From 9fad4b11c21eb0ac06b9bcaaffeeb772a3b7dbce Mon Sep 17 00:00:00 2001 From: PierreQuentel Date: Thu, 10 Oct 2024 11:41:27 +0200 Subject: [PATCH] Update generated scripts --- www/src/brython.js | 6 +- www/src/brython.min.js | 2 +- www/src/brython_stdlib.js | 2 +- www/src/py_flags.js | 10 +- www/src/version_info.js | 4 +- www/tests/test_unicodedata.py | 3368 ++++++++++++++++----------------- 6 files changed, 1674 insertions(+), 1718 deletions(-) diff --git a/www/src/brython.js b/www/src/brython.js index 9f3ac217f..dda5d4fd6 100644 --- a/www/src/brython.js +++ b/www/src/brython.js @@ -209,8 +209,8 @@ $B.unicode_bidi_whitespace=[9,10,11,12,13,28,29,30,31,32,133,5760,8192,8193,8194 ; __BRYTHON__.implementation=[3,13,0,'dev',0] __BRYTHON__.version_info=[3,13,0,'final',0] -__BRYTHON__.compiled_date="2024-10-10 09:35:26.141461" -__BRYTHON__.timestamp=1728545726141 +__BRYTHON__.compiled_date="2024-10-10 09:45:40.204033" +__BRYTHON__.timestamp=1728546340203 __BRYTHON__.builtin_module_names=["_ajax","_ast","_base64","_binascii","_io_classes","_json","_jsre","_locale","_multiprocessing","_posixsubprocess","_profile","_random","_sre","_sre_utils","_string","_strptime","_svg","_symtable","_tokenize","_webcomponent","_webworker","_zlib_utils","_zlib_utils1","_zlib_utils_kozh","array","builtins","dis","encoding_cp932","encoding_cp932_v2","hashlib","html_parser","marshal","math","modulefinder","posix","pyexpat","python_re","python_re_new","unicodedata","xml_helpers","xml_parser","xml_parser_backup"] ; @@ -10882,7 +10882,7 @@ throw _b_.TypeError.$factory(`object ${$B.class_name(obj)} `+ `can't be used in 'await' expression`)}})(__BRYTHON__) ; -(function($B){$B.builtin_class_flags={builtins:{1073763586:['ImportError','StopIteration','ArithmeticError','PythonFinalizationError','EnvironmentError','GeneratorExit','RuntimeError','IOError','NotImplementedError','FileNotFoundError','KeyError','UnboundLocalError','WindowsError','TimeoutError','NotADirectoryError','OverflowError','IndexError','AttributeError','ResourceWarning','BaseException','ConnectionResetError','ChildProcessError','Warning','UnicodeDecodeError','UnicodeTranslateError','RuntimeWarning','FutureWarning','BytesWarning','InterruptedError','BaseExceptionGroup','TabError','AssertionError','ImportWarning','ConnectionError','OSError','ConnectionAbortedError','ConnectionRefusedError','EncodingWarning','EOFError','TypeError','UserWarning','Exception','PermissionError','UnicodeEncodeError','FloatingPointError','ModuleNotFoundError','SyntaxWarning','MemoryError','SystemExit','ReferenceError','SyntaxError','_IncompleteInputError','PendingDeprecationWarning','SystemError','DeprecationWarning','IsADirectoryError','ValueError','FileExistsError','BufferError','RecursionError','ProcessLookupError','LookupError','BlockingIOError','BrokenPipeError','IndentationError','StopAsyncIteration','NameError','UnicodeError','UnicodeWarning','KeyboardInterrupt','ZeroDivisionError'],1073763848:['ExceptionGroup'],20975874:['bool'],4199682:['float','bytearray'],138417410:['bytes'],21762:['super','enumerate','staticmethod','classmethod','property','zip','map','reversed','filter'],5378:['object','complex'],541087042:['dict'],4216066:['frozenset','set'],20976898:['int'],37770530:['list'],20770:['memoryview'],4386:['range'],20738:['slice'],272635138:['str'],71324962:['tuple'],2155896066:['type'],},types:{20866:['generator','member_descriptor','method-wrapper','classmethod_descriptor','async_generator','coroutine','frame','getset_descriptor'],22914:['builtin_function_or_method'],20738:['cell','traceback'],4354:['ellipsis','NoneType','code','NotImplementedType'],153858:['function'],20802:['mappingproxy'],153986:['method_descriptor'],22786:['method'],21762:['module'],151938:['wrapper_descriptor'],}}})(__BRYTHON__) +(function($B){$B.builtin_class_flags={builtins:{1073763586:['ReferenceError','BaseExceptionGroup','InterruptedError','ConnectionRefusedError','RecursionError','KeyError','ImportError','UserWarning','BufferError','AttributeError','OverflowError','Exception','ChildProcessError','SystemError','ConnectionError','FutureWarning','TypeError','FileNotFoundError','IsADirectoryError','NotImplementedError','IndentationError','PythonFinalizationError','FloatingPointError','EOFError','TabError','ValueError','ConnectionResetError','ImportWarning','ConnectionAbortedError','PermissionError','FileExistsError','EnvironmentError','NameError','_IncompleteInputError','NotADirectoryError','WindowsError','SyntaxError','ArithmeticError','RuntimeWarning','BaseException','MemoryError','StopIteration','ZeroDivisionError','UnboundLocalError','UnicodeWarning','UnicodeEncodeError','ModuleNotFoundError','StopAsyncIteration','UnicodeTranslateError','GeneratorExit','LookupError','BlockingIOError','IOError','AssertionError','IndexError','ProcessLookupError','UnicodeError','KeyboardInterrupt','BytesWarning','ResourceWarning','TimeoutError','PendingDeprecationWarning','Warning','BrokenPipeError','OSError','SyntaxWarning','RuntimeError','UnicodeDecodeError','SystemExit','EncodingWarning','DeprecationWarning'],1073763848:['ExceptionGroup'],20975874:['bool'],4199682:['float','bytearray'],138417410:['bytes'],21762:['filter','zip','property','reversed','staticmethod','super','classmethod','map','enumerate'],5378:['complex','object'],541087042:['dict'],4216066:['frozenset','set'],20976898:['int'],37770530:['list'],20770:['memoryview'],4386:['range'],20738:['slice'],272635138:['str'],71324962:['tuple'],2155896066:['type'],},types:{20866:['getset_descriptor','member_descriptor','classmethod_descriptor','generator','coroutine','method-wrapper','async_generator','frame'],22914:['builtin_function_or_method'],20738:['cell','traceback'],4354:['code','ellipsis','NoneType','NotImplementedType'],153858:['function'],20802:['mappingproxy'],153986:['method_descriptor'],22786:['method'],21762:['module'],151938:['wrapper_descriptor'],}}})(__BRYTHON__) ; (function($B){var _b_=$B.builtins var update=$B.update_obj=function(mod,data){for(let attr in data){mod[attr]=data[attr]}} diff --git a/www/src/brython.min.js b/www/src/brython.min.js index 650b404af..e5a9fc733 100644 --- a/www/src/brython.min.js +++ b/www/src/brython.min.js @@ -1 +1 @@ -var __BRYTHON__=globalThis.__BRYTHON__||{};try{eval("async function* f(){}")}catch(err){console.warn("Your browser is not fully supported. If you are using "+"Microsoft Edge, please upgrade to the latest version")}(function($B){$B.isWebWorker="undefined"!==typeof WorkerGlobalScope&&"function"===typeof importScripts&&navigator instanceof WorkerNavigator;$B.isNode=typeof process!=="undefined"&&process.release.name==="node"&&process.__nwjs!==1;var _window=globalThis;_window.location||={href:"",origin:"",pathname:""};_window.navigator||={userLanguage:""};_window.document||={getElementsByTagName:()=>[{src:"http://localhost/"}],currentScript:{src:"http://localhost/"},querySelectorAll:()=>[]};_window.HTMLElement||=class HTMLElement{};_window.MutationObserver||=function(){this.observe=()=>{}};_window.customElements||={define:()=>{}};var href=_window.location.href;$B.protocol=href.split(":")[0];$B.BigInt=_window.BigInt;$B.indexedDB=_window.indexedDB;if($B.brython_path===undefined){var this_url;if($B.isWebWorker){this_url=_window.location.href;if(this_url.startsWith("blob:")){this_url=this_url.substr(5)}}else{this_url=document.currentScript.src}var elts=this_url.split("/");elts.pop();$B.brython_path=elts.join("/")+"/"}else{if(!$B.brython_path.endsWith("/")){$B.brython_path+="/"}}var parts_re=new RegExp("(.*?)://(.*?)/(.*)"),mo=parts_re.exec($B.brython_path);if(mo){$B.full_url={protocol:mo[1],host:mo[2],address:mo[3]};if(["http","https"].includes(mo[1])){$B.domain=mo[1]+"://"+mo[2]}}var path=_window.location.origin+_window.location.pathname,path_elts=path.split("/");path_elts.pop();$B.script_dir=path_elts.join("/");mo=parts_re.exec($B.script_dir);if(mo){if(["http","https"].includes(mo[1])){$B.script_domain=mo[1]+"://"+mo[2]}}else{var parts_re_root=new RegExp("(.*?)://(.*?)"),mo=parts_re_root.exec($B.script_dir);if(mo&&["http","https"].includes(mo[1])){$B.script_domain=$B.script_dir}}$B.strip_host=function(url){var parts_re=new RegExp("(.*?)://([^/]*)?[/#]?(.*)"),mo=parts_re.exec(url);if(mo){return mo[3]}console.log(Error().stack);throw Error("not a url: "+url)};$B.webworkers={};$B.file_cache={};$B.url2name={};$B.scripts={};$B.import_info={};$B.imported={};$B.precompiled={};$B.frame_obj=null;$B.builtins=Object.create(null);$B.builtins_scope={id:"__builtins__",module:"__builtins__",binding:{}};$B.builtin_funcs={};$B.builtin_classes=[];$B.__getattr__=function(attr){return this[attr]};$B.__setattr__=function(attr,value){if(["debug","stdout","stderr"].indexOf(attr)>-1){$B[attr]=value}else{throw $B.builtins.AttributeError.$factory("__BRYTHON__ object has no attribute "+attr)}};$B.language=_window.navigator.userLanguage||_window.navigator.language;$B.locale="C";var date=new Date;var formatter=new Intl.DateTimeFormat($B.language,{timeZoneName:"short"}),short=formatter.format(date);formatter=new Intl.DateTimeFormat($B.language,{timeZoneName:"long"});var long=formatter.format(date);var ix=0,minlen=Math.min(short.length,long.length);while(ix>":"rshift","+":"add","-":"sub","*":"mul","/":"truediv","%":"mod","@":"matmul"},augmented_assigns:{"//=":"ifloordiv",">>=":"irshift","<<=":"ilshift","**=":"ipow","+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv","%=":"imod","&=":"iand","|=":"ior","^=":"ixor","@=":"imatmul"},binary:{"&":"and","|":"or","~":"invert","^":"xor"},comparisons:{"<":"lt",">":"gt","<=":"le",">=":"ge","==":"eq","!=":"ne"},boolean:{or:"or",and:"and",in:"in",not:"not",is:"is"},subset:function(){var res={},keys=[];if(arguments[0]=="all"){keys=Object.keys($B.op2method);keys.splice(keys.indexOf("subset"),1)}else{for(var arg of arguments){keys.push(arg)}}for(var key of keys){var ops=$B.op2method[key];if(ops===undefined){throw Error(key)}for(var attr in ops){res[attr]=ops[attr]}}return res}};$B.method_to_op={};for(var category in $B.op2method){for(var op in $B.op2method[category]){var method=`__${$B.op2method[category][op]}__`;$B.method_to_op[method]=op}}$B.special_string_repr={8:"\\x08",9:"\\t",10:"\\n",11:"\\x0b",12:"\\x0c",13:"\\r",92:"\\\\",160:"\\xa0"};$B.$py_next_hash=Math.pow(2,53)-1;$B.$py_UUID=Math.floor(Math.random()*2**50);$B.lambda_magic=Math.random().toString(36).substr(2,8);$B.set_func_names=function(klass,module){for(var attr in klass){if(typeof klass[attr]=="function"){klass[attr].$infos={__doc__:klass[attr].__doc__||"",__module__:module,__qualname__:klass.__qualname__+"."+attr,__name__:attr};if(klass[attr].$type=="classmethod"){klass[attr].__class__=$B.method}}}klass.__module__=module};var has_storage=typeof Storage!=="undefined";if(has_storage){$B.has_local_storage=false;try{if(localStorage){$B.local_storage=localStorage;$B.has_local_storage=true}}catch(err){}$B.has_session_storage=false;try{if(sessionStorage){$B.session_storage=sessionStorage;$B.has_session_storage=true}}catch(err){}}else{$B.has_local_storage=false;$B.has_session_storage=false}$B.globals=function(){return $B.frame_obj.frame[3]};$B.scripts={};$B.$options={};$B.builtins_repr_check=function(builtin,args){var $=$B.args("__repr__",1,{self:null},["self"],args,{},null,null),self=$.self;if(!$B.$isinstance(self,builtin)){var _b_=$B.builtins;throw _b_.TypeError.$factory("descriptor '__repr__' requires a "+`'${builtin.__name__}' object but received a `+`'${$B.class_name(self)}'`)}};$B.update_VFS=function(scripts){$B.VFS=$B.VFS||{};var vfs_timestamp=scripts.$timestamp;if(vfs_timestamp!==undefined){delete scripts.$timestamp}for(var script in scripts){if($B.VFS.hasOwnProperty(script)){console.warn("Virtual File System: duplicate entry "+script)}$B.VFS[script]=scripts[script];$B.VFS[script].timestamp=vfs_timestamp}$B.stdlib_module_names=Object.keys($B.VFS)};$B.add_files=function(files){$B.files=$B.files||{};for(var file in files){$B.files[file]=files[file]}};$B.has_file=function(file){return $B.files&&$B.files.hasOwnProperty(file)};$B.show_tokens=function(src,mode){for(var token of $B.tokenizer(src,"",mode||"file")){console.log(token.type,$B.builtins.repr(token.string),token.start,token.end,token.line)}};function from_py(src,script_id){if(!$B.options_parsed){$B.parse_options()}script_id=script_id||"python_script_"+$B.UUID();var filename=$B.script_path+"#"+script_id;$B.url2name[filename]=script_id;$B.imported[script_id]={};var root=__BRYTHON__.py2js({src:src,filename:filename},script_id,script_id,__BRYTHON__.builtins_scope);return root.to_js()}$B.getPythonModule=function(name){return $B.imported[name]};$B.python_to_js=function(src,script_id){return"(function() {\n"+from_py(src,script_id)+"\nreturn locals}())"};$B.pythonToJS=$B.python_to_js;var fakeScript=$B.fakeScript=function(filename){this.options={}};fakeScript.prototype.getAttribute=function(key){return this.options[key]??null};fakeScript.prototype.dispatchEvent=function(){};$B.runPythonSource=function(src,options){var script_id;if(options){if(typeof options=="string"){script_id=options}else if(options.constructor===Object){if(options.hasOwnProperty("id")){script_id=options.id;delete options.id}}else{console.debug("invalid options argument:",options)}}var script=new fakeScript,url=$B.script_path=globalThis.location.href.split("#")[0];if(options){for(var[key,value]of Object.entries(options)){script.options[key]=value}}script_id=script_id??"python_script_"+$B.UUID();$B.run_script(script,src,script_id,url,true);return $B.imported[script_id]}})(__BRYTHON__);__BRYTHON__.ast_classes={Add:"",And:"",AnnAssign:"target,annotation,value?,simple",Assert:"test,msg?",Assign:"targets*,value,type_comment?",AsyncFor:"target,iter,body*,orelse*,type_comment?",AsyncFunctionDef:"name,args,body*,decorator_list*,returns?,type_comment?,type_params*",AsyncWith:"items*,body*,type_comment?",Attribute:"value,attr,ctx",AugAssign:"target,op,value",Await:"value",BinOp:"left,op,right",BitAnd:"",BitOr:"",BitXor:"",BoolOp:"op,values*",Break:"",Call:"func,args*,keywords*",ClassDef:"name,bases*,keywords*,body*,decorator_list*,type_params*",Compare:"left,ops*,comparators*",Constant:"value,kind?",Continue:"",Del:"",Delete:"targets*",Dict:"keys*,values*",DictComp:"key,value,generators*",Div:"",Eq:"",ExceptHandler:"type?,name?,body*",Expr:"value",Expression:"body",FloorDiv:"",For:"target,iter,body*,orelse*,type_comment?",FormattedValue:"value,conversion,format_spec?",FunctionDef:"name,args,body*,decorator_list*,returns?,type_comment?,type_params*",FunctionType:"argtypes*,returns",GeneratorExp:"elt,generators*",Global:"names*",Gt:"",GtE:"",If:"test,body*,orelse*",IfExp:"test,body,orelse",Import:"names*",ImportFrom:"module?,names*,level?",In:"",Interactive:"body*",Invert:"",Is:"",IsNot:"",JoinedStr:"values*",LShift:"",Lambda:"args,body",List:"elts*,ctx",ListComp:"elt,generators*",Load:"",Lt:"",LtE:"",MatMult:"",Match:"subject,cases*",MatchAs:"pattern?,name?",MatchClass:"cls,patterns*,kwd_attrs*,kwd_patterns*",MatchMapping:"keys*,patterns*,rest?",MatchOr:"patterns*",MatchSequence:"patterns*",MatchSingleton:"value",MatchStar:"name?",MatchValue:"value",Mod:"",Module:"body*,type_ignores*",Mult:"",Name:"id,ctx",NamedExpr:"target,value",Nonlocal:"names*",Not:"",NotEq:"",NotIn:"",Or:"",ParamSpec:"name,default_value?",Pass:"",Pow:"",RShift:"",Raise:"exc?,cause?",Return:"value?",Set:"elts*",SetComp:"elt,generators*",Slice:"lower?,upper?,step?",Starred:"value,ctx",Store:"",Sub:"",Subscript:"value,slice,ctx",Try:"body*,handlers*,orelse*,finalbody*",TryStar:"body*,handlers*,orelse*,finalbody*",Tuple:"elts*,ctx",TypeAlias:"name,type_params*,value",TypeIgnore:"lineno,tag",TypeVar:"name,bound?,default_value?",TypeVarTuple:"name,default_value?",UAdd:"",USub:"",UnaryOp:"op,operand",While:"test,body*,orelse*",With:"items*,body*,type_comment?",Yield:"value?",YieldFrom:"value",alias:"name,asname?",arg:"arg,annotation?,type_comment?",arguments:"posonlyargs*,args*,vararg?,kwonlyargs*,kw_defaults*,kwarg?,defaults*",boolop:["And","Or"],cmpop:["Eq","NotEq","Lt","LtE","Gt","GtE","Is","IsNot","In","NotIn"],comprehension:"target,iter,ifs*,is_async",excepthandler:["ExceptHandler"],expr:["BoolOp","NamedExpr","BinOp","UnaryOp","Lambda","IfExp","Dict","Set","ListComp","SetComp","DictComp","GeneratorExp","Await","Yield","YieldFrom","Compare","Call","FormattedValue","JoinedStr","Constant","Attribute","Subscript","Starred","Name","List","Tuple","Slice"],expr_context:["Load","Store","Del"],keyword:"arg?,value",match_case:"pattern,guard?,body*",mod:["Module","Interactive","Expression","FunctionType"],operator:["Add","Sub","Mult","MatMult","Div","Mod","Pow","LShift","RShift","BitOr","BitXor","BitAnd","FloorDiv"],pattern:["MatchValue","MatchSingleton","MatchSequence","MatchMapping","MatchClass","MatchStar","MatchAs","MatchOr"],stmt:["FunctionDef","AsyncFunctionDef","ClassDef","Return","Delete","Assign","TypeAlias","AugAssign","AnnAssign","For","AsyncFor","While","If","With","AsyncWith","Match","Raise","Try","TryStar","Assert","Import","ImportFrom","Global","Nonlocal","Expr","Pass","Break","Continue"],type_ignore:["TypeIgnore"],type_param:["TypeVar","ParamSpec","TypeVarTuple"],unaryop:["Invert","Not","UAdd","USub"],withitem:"context_expr,optional_vars?"};(function($B){$B.stdlib={};var pylist=["VFS_import","__future__","_aio","_codecs","_codecs_jp","_collections","_collections_abc","_colorize","_compat_pickle","_compression","_contextvars","_csv","_dummy_thread","_frozen_importlib","_functools","_imp","_io","_markupbase","_multibytecodec","_operator","_py_abc","_pydatetime","_pydecimal","_queue","_signal","_socket","_sre","_struct","_sysconfigdata","_sysconfigdata_0_brython_","_testcapi","_thread","_threading_local","_typing","_weakref","_weakrefset","abc","antigravity","argparse","ast","asyncio","atexit","base64","bdb","binascii","bisect","browser.ajax","browser.highlight","browser.idbcache","browser.indexed_db","browser.local_storage","browser.markdown","browser.object_storage","browser.session_storage","browser.svg","browser.template","browser.timer","browser.ui","browser.webcomponent","browser.websocket","browser.worker","calendar","cmath","cmd","code","codecs","codeop","colorsys","configparser","contextlib","contextvars","copy","copyreg","csv","dataclasses","datetime","decimal","difflib","doctest","enum","errno","external_import","faulthandler","fnmatch","formatter","fractions","functools","gc","genericpath","getopt","getpass","gettext","glob","gzip","heapq","hmac","imp","inspect","interpreter","io","ipaddress","itertools","keyword","linecache","locale","mimetypes","ntpath","numbers","opcode","operator","optparse","os","pathlib","pdb","pickle","pkgutil","platform","posixpath","pprint","profile","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","re1","reprlib","secrets","select","selectors","shlex","shutil","signal","site","site-packages.__future__","site-packages.docs","site-packages.header","site-packages.test_sp","socket","sre_compile","sre_constants","sre_parse","stat","statistics","string","stringprep","struct","subprocess","symtable","sys","sysconfig","tabnanny","tarfile","tb","tempfile","test.namespace_pkgs.module_and_namespace_package.a_test","textwrap","this","threading","time","timeit","token","tokenize","traceback","turtle","types","typing","uuid","warnings","weakref","webbrowser","zipfile","zipimport","zlib"];for(var i=0;i":"RARROW",".":"DOT","...":"ELLIPSIS","/":"SLASH","//":"DOUBLESLASH","//=":"DOUBLESLASHEQUAL","/=":"SLASHEQUAL",":":"COLON",":=":"COLONEQUAL",";":"SEMI","<":"LESS","<<":"LEFTSHIFT","<<=":"LEFTSHIFTEQUAL","<=":"LESSEQUAL","=":"EQUAL","==":"EQEQUAL",">":"GREATER",">=":"GREATEREQUAL",">>":"RIGHTSHIFT",">>=":"RIGHTSHIFTEQUAL","@":"AT","@=":"ATEQUAL","[":"LSQB","]":"RSQB","^":"CIRCUMFLEX","^=":"CIRCUMFLEXEQUAL","{":"LBRACE","|":"VBAR","|=":"VBAREQUAL","}":"RBRACE","~":"TILDE"};function ISTERMINAL(x){return x=NT_OFFSET}function ISEOF(x){return x==ENDMARKER}})(__BRYTHON__);(function($B){var _b_=$B.builtins;function is_whitespace(char){return" \n\r\t\f".includes(char)}var unprintable_re=/\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}|\p{Zl}|\p{Zp}|\p{Zs}/u;const Other_ID_Start=[6277,6278,8472,8494,12443,12444].map((x=>String.fromCodePoint(x)));function is_ID_Start(char){return/\p{Letter}/u.test(char)||/\p{Nl}/u.test(char)||char=="_"||Other_ID_Start.includes(char)}const Other_ID_Continue=[183,903,4969,4976,4977,6618,8204,8205,12539,65381].map((x=>String.fromCodePoint(x)));function is_ID_Continue(char){return is_ID_Start(char)||/\p{Mn}|\p{Mc}|\p{Nd}|\p{Pc}/u.test(char)||Other_ID_Continue.includes(char)}$B.is_XID_Start=function(cp){let char=String.fromCodePoint(cp);if(!is_ID_Start(char)){return false}var norm=char.normalize("NFKC");if(!is_ID_Start(norm[0])){return false}for(let char of norm.substr(1)){if(!is_ID_Continue(char)){return false}}return true};$B.is_XID_Continue=function(cp){let char=String.fromCodePoint(cp);if(!is_ID_Continue(char)){return false}var norm=char.normalize("NFKC");for(let char of norm.substr(1)){if(!is_ID_Continue(char)){return false}}return true};$B.in_unicode_category=function(category,cp){if(isNaN(cp)){return false}try{var re=new RegExp("\\p{"+category+"}","u");return re.test(String.fromCodePoint(cp))}catch(err){return in_unicode_category(category,cp)}};function in_unicode_category(category,cp){var table=$B.unicode[category],start=0,end=table.length-1,len=table.length,ix=Math.floor(len/2),nb=0;var first=table[start],item=typeof first=="number"?first:first[0];if(cplast){return false}}else if(last[0]+last[1]100){console.log("infinite loop for",cp);alert()}item=table[ix];if(typeof item!="number"){item=item[0]}if(item==cp){return true}else if(item>cp){end=ix}else{start=ix}len=Math.floor((end-start)/2);if(end-start==1){break}ix=start+len}var step=table[start][2];if(step===undefined){return table[start][0]+table[start][1]>cp}return table[start][0]+step*table[start][1]>cp&&(cp-table[start][0])%step==0}const FSTRING_START="FSTRING_START",FSTRING_MIDDLE="FSTRING_MIDDLE",FSTRING_END="FSTRING_END";function ord(char){if(char.length==1){return char.charCodeAt(0)}var code=65536;code+=(char.charCodeAt(0)&1023)<<10;code+=char.charCodeAt(1)&1023;return code}function $last(array){return array[array.length-1]}var ops=".,:;+-*/%~^|&=<>[](){}@",op2=["**","//",">>","<<"],augm_op="+-*/%^|&=<>@",closing={"}":"{","]":"[",")":"("};function Token(type,string,lineno,col_offset,end_lineno,end_col_offset,line){var res={type:type,string:string,line:line,lineno:lineno,col_offset:col_offset,end_lineno:end_lineno,end_col_offset:end_col_offset};res.num_type=$B.py_tokens[type];if(type=="OP"){res.num_type=$B.py_tokens[$B.EXACT_TOKEN_TYPES[string]]}else if(type=="ENCODING"){res.num_type=$B.py_tokens.ENCODING}res.bytes=res.string;return res}function get_comment(parser,src,pos,line_num,line_start,token_name,line){var start=pos,ix;var t=[];while(true){if(pos>=src.length||(ix="\r\n".indexOf(src[pos]))>-1){if(parser&&parser.flags&$B.PyCF_TYPE_COMMENTS){var comment=src.substring(start-1,pos),mo=/^#\s*type\s*:(.*)/.exec(comment);if(mo){var is_type_ignore=false;if(mo[1].startsWith("ignore")){if(mo[1].length==6){is_type_ignore=true}else{var char=mo[1][6];if(char.charCodeAt(0)<=128&&/[a-zA-Z0-9]/.exec(char)===null){is_type_ignore=true}}}if(is_type_ignore){t.push(Token("TYPE_IGNORE",comment,line_num,start-line_start,line_num,pos-line_start+1,line))}else{t.push(Token("TYPE_COMMENT",comment,line_num,start-line_start,line_num,pos-line_start+1,line))}return{t:t,pos:pos}}}t.push(Token("COMMENT",src.substring(start-1,pos),line_num,start-line_start,line_num,pos-line_start+1,line));if(ix!==undefined){var nb=1;if(src[pos]=="\r"&&src[pos+1]=="\n"){nb++}else if(src[pos]===undefined){nb=0}t.push(Token(token_name,src.substr(pos,nb),line_num,pos-line_start+1,line_num,pos-line_start+nb+1,line));if(src[pos]===undefined){t.push(Token("NEWLINE","\n",line_num,pos-line_start+1,line_num,pos-line_start+2,""))}pos+=nb}return{t:t,pos:pos}}pos++}}function test_num(num_type,char){switch(num_type){case"":return $B.in_unicode_category("Nd",ord(char));case"x":return"0123456789abcdef".includes(char.toLowerCase());case"b":return"01".includes(char);case"o":return"01234567".includes(char);default:throw Error("unknown num type "+num_type)}}function nesting_level(token_modes){var ix=token_modes.length-1;while(ix>=0){var mode=token_modes[ix];if(mode.nesting!==undefined){return mode.nesting}ix--}}$B.tokenizer=function*(src,filename,mode,parser){var string_prefix=/^(r|u|R|U|f|F|fr|Fr|fR|FR|rf|rF|Rf|RF)$/,bytes_prefix=/^(b|B|br|Br|bR|BR|rb|rB|Rb|RB)$/;src=src.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(mode!="eval"&&!src.endsWith("\n")){src+="\n"}var lines=src.split("\n"),linenum=0,line_at={};for(let i=0,len=src.length;i=55296&&cp<=56319){cp=ord(src.substr(pos,2));char=src.substr(pos,2);pos++}pos++;if(token_mode!=save_mode){if(token_mode=="fstring"){fstring_buffer="";fstring_escape=false}else if(token_mode=="format_specifier"){format_specifier=""}}save_mode=token_mode;if(token_mode=="fstring"){if(char==token_mode.quote){if(fstring_escape){fstring_buffer+="\\"+char;fstring_escape=false;continue}if(token_mode.triple_quote){if(src.substr(pos,2)!=token_mode.quote.repeat(2)){fstring_buffer+=char;continue}char=token_mode.quote.repeat(3);pos+=2}if(fstring_buffer.length>0){yield Token(FSTRING_MIDDLE,fstring_buffer,line_num,fstring_start,line_num,fstring_start+fstring_buffer.length,line)}yield Token(FSTRING_END,char,line_num,pos-line_start,line_num,pos-line_start+1,line);token_modes.pop();token_mode=$B.last(token_modes);state=null;continue}else if(char=="{"){if(src.charAt(pos)=="{"){fstring_buffer+=char;pos++;continue}else{if(fstring_buffer.length>0){yield Token(FSTRING_MIDDLE,fstring_buffer,line_num,fstring_start,line_num,fstring_start+fstring_buffer.length,line)}token_mode="regular_within_fstring";fstring_expr_start=pos-line_start;state=null;token_modes.push(token_mode)}}else if(char=="}"){if(src.charAt(pos)=="}"){fstring_buffer+=char;pos++;continue}else{yield Token("OP",char,line_num,pos-line_start,line_num,pos-line_start+1,line);continue}}else if(char=="\\"){if(token_mode.raw){fstring_buffer+=char+char}else{if(fstring_escape){fstring_buffer+="\\"+char}fstring_escape=!fstring_escape}continue}else{if(fstring_escape){fstring_buffer+="\\"}fstring_buffer+=char;fstring_escape=false;if(char=="\n"){line_num++}continue}}else if(token_mode=="format_specifier"){if(char==quote){if(format_specifier.length>0){yield Token(FSTRING_MIDDLE,format_specifier,line_num,fstring_start,line_num,fstring_start+format_specifier.length,line);token_modes.pop();token_mode=$B.last(token_modes);continue}}else if(char=="{"){yield Token(FSTRING_MIDDLE,format_specifier,line_num,fstring_start,line_num,fstring_start+format_specifier.length,line);token_mode="regular_within_fstring";fstring_expr_start=pos-line_start;state=null;token_modes.push(token_mode)}else if(char=="}"){yield Token(FSTRING_MIDDLE,format_specifier,line_num,fstring_start,line_num,fstring_start+format_specifier.length,line);yield Token("OP",char,line_num,pos-line_start,line_num,pos-line_start+1,line);if(braces.length==0||$B.last(braces).char!=="{"){throw Error("wrong braces")}braces.pop();token_modes.pop();token_mode=$B.last(token_modes);continue}else{format_specifier+=char;continue}}switch(state){case"line_start":line=get_line_at(pos-1);line_start=pos;line_num++;if(mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos-1))){yield Token("NL",mo[0],line_num,0,line_num,mo[0].length,line);pos+=mo[0].length-1;continue}else if(char=="#"){comment=get_comment(parser,src,pos,line_num,line_start,"NL",line);for(var item of comment.t){yield item}pos=comment.pos;state="line_start";continue}indent=0;if(char==" "){indent=1}else if(char=="\t"){indent=8}if(indent){var broken=false;while(pos0&&" \t".includes(src[pos])){console.log("indentation error 479");$B.raise_error_known_location(_b_.IndentationError,filename,line_num,pos-line_start,line_num,pos-line_start+1,line,"unindent does not match any outer indentation level")}if(src[pos]==" "){indent++}else if(src[pos]=="\t"){indent+=8}else if(src[pos]=="\\"&&src[pos+1]=="\n"){pos++;line_start=pos+2;line_num++;line=get_line_at(pos+2);broken=true}else{break}pos++}if(pos==src.length){line_num--;break}if(src[pos]=="#"){comment=get_comment(parser,src,pos+1,line_num,line_start,"NL",line);for(var item of comment.t){yield item}pos=comment.pos;continue}else if(src[pos]=="\\"){if(/^\f?(\r\n|\r|\n)/.exec(src[pos+1])){line_num++;pos++;continue}else{$B.raise_error_known_location(_b_.SyntaxError,filename,line_num,pos+2-line_start,line_num,pos+3-line_start,line,"unexpected character after line continuation character")}}else if(mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos))){yield Token("NL","",line_num,pos-line_start+1,line_num,pos-line_start+1+mo[0].length,line);pos+=mo[0].length;continue}if(indents.length==0||indent>$last(indents)){indents.push(indent);yield Token("INDENT","",line_num,0,line_num,indent,line)}else if(indent<$last(indents)){var ix=indents.indexOf(indent);if(ix==-1){var message="unindent does not match "+"any outer indentation level";$B.raise_error_known_location(_b_.IndentationError,filename,line_num,0,line_num,0,line,message)}for(var i=indents.length-1;i>ix;i--){indents.pop();yield Token("DEDENT","",line_num,indent,line_num,indent,line)}}state=null}else{while(indents.length>0){indents.pop();yield Token("DEDENT","",line_num,indent,line_num,indent,line)}state=null;pos--}break;case null:switch(char){case'"':case"'":quote=char;triple_quote=src[pos]==char&&src[pos+1]==char;string_start=[line_num,pos-line_start,line_start];if(triple_quote){pos+=2}escaped=false;state="STRING";string="";prefix="";break;case"#":var token_name=braces.length>0?"NL":"NEWLINE";comment=get_comment(parser,src,pos,line_num,line_start,token_name,line);for(var item of comment.t){yield item}pos=comment.pos;if(braces.length==0){state="line_start"}else{state=null;line_num++;line_start=pos+1;line=get_line_at(pos)}break;case"0":state="NUMBER";number=char;num_type="";if(src[pos]&&"xbo".includes(src[pos].toLowerCase())){number+=src[pos];num_type=src[pos].toLowerCase();pos++}else if(src[pos]){var pos1=pos;while(pos1=3){yield Token("OP","...",line_num,dot_pos,line_num,dot_pos+3,line);op=op.substr(3)}for(var i=0;i0?"NL":"NEWLINE";mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos-1));yield Token(token_name,mo[0],line_num,pos-line_start,line_num,pos-line_start+mo[0].length,line);pos+=mo[0].length-1;if(token_name=="NEWLINE"){state="line_start"}else{line_num++;line_start=pos+1;line=get_line_at(pos)}break;default:if($B.is_XID_Start(ord(char))){state="NAME";name=char}else if($B.in_unicode_category("Nd",ord(char))){state="NUMBER";num_type="";number=char}else if(ops.includes(char)){if(token_mode=="regular_within_fstring"&&(char==":"||char=="}")){if(char==":"){if(nesting_level(token_modes)==braces.length-1){let colon=Token("OP",char,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line);colon.metadata=src.substr(line_start+fstring_expr_start,pos-line_start-fstring_expr_start-1);yield colon;token_modes.pop();token_mode="format_specifier";token_modes.push(token_mode);continue}}else{let closing_brace=Token("OP",char,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line);closing_brace.metadata=src.substring(line_start+fstring_expr_start,pos-1);yield closing_brace;token_modes.pop();token_mode=token_modes[token_modes.length-1];if(braces.length==0||$B.last(braces).char!=="{"){throw Error("wrong braces")}braces.pop();continue}}var op=char;if(op2.includes(char+src[pos])){op=char+src[pos];pos++}if(src[pos]=="="&&(op.length==2||augm_op.includes(op))){op+=src[pos];pos++}else if(char=="-"&&src[pos]==">"||char==":"&&src[pos]=="="){op+=src[pos];pos++}if("[({".includes(char)){braces.push({char:char,pos:pos,line_num:line_num,line_start:line_start,line:line})}else if("])}".includes(char)){if(braces.length&&$last(braces).char==closing[char]){braces.pop()}else{braces.push({char:char,pos:pos,line_num:line_num,line_start:line_start,line:line})}}yield Token("OP",op,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line)}else if(char=="!"){if(src[pos]=="="){yield Token("OP","!=",line_num,pos-line_start,line_num,pos-line_start+2,line);pos++}else{let token=Token("OP",char,line_num,pos-line_start,line_num,pos-line_start+1,line);token.metadata=src.substring(line_start+fstring_start+2,pos-1);yield token}}else if(char==" "||char=="\t"){}else{var cp=char.codePointAt(0),err_msg="invalid";if(unprintable_re.exec(char)){err_msg+=" non-printable"}var unicode=cp.toString(16).toUpperCase();while(unicode.length<4){unicode="0"+unicode}err_msg+=` character '${char}' (U+${unicode})`;if(char=="$"||char=="`"){err_msg="invalid syntax"}var err_token=Token("ERRORTOKEN",char,line_num,pos-line_start,line_num,pos-line_start+1,line);$B.raise_error_known_token(_b_.SyntaxError,filename,err_token,err_msg)}}break;case"NAME":if($B.is_XID_Continue(ord(char))){name+=char}else if(char=='"'||char=="'"){if(string_prefix.exec(name)||bytes_prefix.exec(name)){state="STRING";quote=char;triple_quote=src[pos]==quote&&src[pos+1]==quote;prefix=name;if(triple_quote){pos+=2}if(prefix.toLowerCase().includes("f")){fstring_start=pos-line_start-name.length;token_mode=new String("fstring");token_mode.nesting=braces.length;token_mode.quote=quote;token_mode.triple_quote=triple_quote;token_mode.raw=prefix.toLowerCase().includes("r");token_modes.push(token_mode);var s=triple_quote?quote.repeat(3):quote;var end_col=fstring_start+name.length+s.length;yield Token(FSTRING_START,prefix+s,line_num,fstring_start,line_num,end_col,line);continue}escaped=false;string_start=[line_num,pos-line_start-name.length,line_start];string=""}else{yield Token("NAME",name,line_num,pos-line_start-name.length,line_num,pos-line_start,line);state=null;pos--}}else{yield Token("NAME",name,line_num,pos-line_start-name.length,line_num,pos-line_start,line);state=null;pos--}break;case"STRING":switch(char){case quote:if(!escaped){var string_line=line;if(line_num>string_start[0]){string_line=src.substring(string_start[2]-1,pos+2)}var full_string;if(!triple_quote){full_string=prefix+quote+string+quote;yield Token("STRING",full_string,string_start[0],string_start[1],line_num,pos-line_start+1,string_line);state=null}else if(char+src.substr(pos,2)==quote.repeat(3)){full_string=prefix+quote.repeat(3)+string+quote.repeat(3);yield Token("STRING",full_string,string_start[0],string_start[1],line_num,pos-line_start+3,string_line);pos+=2;state=null}else{string+=char}}else{string+=char}escaped=false;break;case"\r":case"\n":if(!escaped&&!triple_quote){var msg=`unterminated string literal `+`(detected at line ${line_num})`,line_num=string_start[0],col_offset=string_start[1];$B.raise_error_known_location(_b_.SyntaxError,filename,line_num,col_offset,line_num,col_offset,line,msg)}string+=char;line_num++;line_start=pos+1;if(char=="\r"&&src[pos]=="\n"){string+=src[pos];line_start++;pos++}line=get_line_at(pos);escaped=false;break;case"\\":string+=char;escaped=!escaped;break;default:escaped=false;string+=char;break}break;case"NUMBER":if(test_num(num_type,char)){number+=char}else if(char=="_"&&!number.endsWith(".")){if(number.endsWith("_")){throw SyntaxError("consecutive _ in number")}else if(src[pos]===undefined||!test_num(num_type,src[pos])){yield Token("NUMBER",number,line_num,pos-line_start-number.length,line_num,pos-line_start,line);state=null;pos--}else{number+=char}}else if(char=="."&&!number.includes(char)){number+=char}else if(char.toLowerCase()=="e"&&!number.toLowerCase().includes("e")){if("+-".includes(src[pos])||$B.in_unicode_category("Nd",ord(src[pos]))){number+=char}else{yield Token("NUMBER",number,line_num,pos-line_start-number.length,line_num,pos-line_start,line);state=null;pos--}}else if((char=="+"||char=="-")&&number.toLowerCase().endsWith("e")){number+=char}else if(char.toLowerCase()=="j"){number+=char;yield Token("NUMBER",number,line_num,pos-line_start-number.length+1,line_num,pos-line_start+1,line);state=null}else if(char.match(/\p{Letter}/u)){$B.raise_error_known_location(_b_.SyntaxError,filename,line_num,pos-line_start-number.length,line_num,pos-line_start,line,"invalid decimal literal")}else{yield Token("NUMBER",number,line_num,pos-line_start-number.length,line_num,pos-line_start,line);state=null;pos--}break}}switch(state){case"line_start":line_num++;break;case"NAME":yield Token("NAME",name,line_num,pos-line_start-name.length+1,line_num,pos-line_start+1,line);break;case"NUMBER":yield Token("NUMBER",number,line_num,pos-line_start-number.length+1,line_num,pos-line_start+1,line);break;case"STRING":line_num=string_start[0];line=lines[line_num-1];var msg=`unterminated ${triple_quote?"triple-quoted ":""}`+`string literal (detected at line ${line_num})`,col_offset=string_start[1];$B.raise_error_known_location(_b_.SyntaxError,filename,line_num,col_offset,line_num,col_offset,line,msg)}if(!src.endsWith("\n")&&state!=line_start){yield Token("NEWLINE","",line_num,pos-line_start+1,line_num,pos-line_start+1,line+"\n");line_num++}while(indents.length>0){indents.pop();yield Token("DEDENT","",line_num,0,line_num,0,"")}yield Token("ENDMARKER","",line_num,0,line_num,0,"")}})(__BRYTHON__);(function($B){var binary_ops={"+":"Add","-":"Sub","*":"Mult","/":"Div","//":"FloorDiv","%":"Mod","**":"Pow","<<":"LShift",">>":"RShift","|":"BitOr","^":"BitXor","&":"BitAnd","@":"MatMult"};var boolean_ops={and:"And",or:"Or"};var comparison_ops={"==":"Eq","!=":"NotEq","<":"Lt","<=":"LtE",">":"Gt",">=":"GtE",is:"Is",is_not:"IsNot",in:"In",not_in:"NotIn"};var unary_ops={unary_inv:"Invert",unary_pos:"UAdd",unary_neg:"USub",unary_not:"Not"};var op_types=$B.op_types=[binary_ops,boolean_ops,comparison_ops,unary_ops];var _b_=$B.builtins;var ast=$B.ast={};for(var kl in $B.ast_classes){var args=$B.ast_classes[kl],body="";if(typeof args=="string"){if(args.length>0){for(var arg of args.split(",")){if(arg.endsWith("*")){arg=arg.substr(0,arg.length-1);body+=` this.${arg} = $B.$list(${arg} === undefined ? [] : ${arg})\n`}else if(arg.endsWith("?")){arg=arg.substr(0,arg.length-1);body+=` this.${arg} = ${arg}\n`}else{body+=` this.${arg} = ${arg}\n`}}}var arg_list=args.replace(/[*?]/g,"").split(",");ast[kl]=Function(...arg_list,body);ast[kl]._fields=args.split(",")}else{ast[kl]=args.map((x=>ast[x]))}ast[kl].$name=kl}$B.ast_js_to_py=function(obj){$B.create_python_ast_classes();if(obj===undefined){return _b_.None}else if(Array.isArray(obj)){return $B.$list(obj.map($B.ast_js_to_py))}else{var class_name=obj.constructor.$name,py_class=$B.python_ast_classes[class_name],py_ast_obj={__class__:py_class};if(py_class===undefined){return obj}for(var field of py_class._fields){py_ast_obj[field]=$B.ast_js_to_py(obj[field])}py_ast_obj._attributes=$B.fast_tuple([]);for(var loc of["lineno","col_offset","end_lineno","end_col_offset"]){if(obj[loc]!==undefined){py_ast_obj[loc]=obj[loc];py_ast_obj._attributes.push(loc)}}return py_ast_obj}};$B.ast_py_to_js=function(obj){if(obj===undefined||obj===_b_.None){return undefined}else if(Array.isArray(obj)){return obj.map($B.ast_py_to_js)}else if(typeof obj=="string"){return obj}else{var class_name=$B.class_name(obj),js_class=$B.ast[class_name];if(js_class===undefined){return obj}var js_ast_obj=new js_class;for(var field of js_class._fields){if(field.endsWith("?")||field.endsWith("*")){field=field.substr(0,field.length-1)}js_ast_obj[field]=$B.ast_py_to_js(obj[field])}for(var loc of["lineno","col_offset","end_lineno","end_col_offset"]){if(obj[loc]!==undefined){js_ast_obj[loc]=obj[loc]}}return js_ast_obj}};$B.create_python_ast_classes=function(){if($B.python_ast_classes){return}$B.python_ast_classes={};for(var klass in $B.ast_classes){$B.python_ast_classes[klass]=function(kl){var _fields,raw_fields;if(typeof $B.ast_classes[kl]=="string"){if($B.ast_classes[kl]==""){raw_fields=_fields=[]}else{raw_fields=$B.ast_classes[kl].split(",");_fields=raw_fields.map((x=>x.endsWith("*")||x.endsWith("?")?x.substr(0,x.length-1):x))}}var cls=$B.make_class(kl),$defaults={},slots={},nb_args=0;if(raw_fields){for(let i=0,len=_fields.length;i2){console.log("wrong js indent");console.log(res)}level=0}try{res+=(add_spaces?indentation.repeat(level):"")+line+"\n"}catch(err){console.log(res);throw err}if(line.endsWith("{")){level++}else if(add_closing_brace){level--;if(level<0){level=0}try{res+=indentation.repeat(level)+"}\n"}catch(err){console.log(res);throw err}}last_is_backslash=line.endsWith("\\");last_is_var_and_comma=line.endsWith(",")&&(line.startsWith("var ")||last_is_var_and_comma)}return res};function get_docstring(node){var doc_string=_b_.None;if(node.body.length>0){var firstchild=node.body[0];if(firstchild instanceof $B.ast.Constant&&typeof firstchild.value=="string"){doc_string=firstchild.value}}return doc_string}var s_escaped='abfnrtvxuU"0123456789'+"'"+"\\",is_escaped={};for(var i=0;i>10)+String.fromCharCode(56320|value&1023)}function test_escape(text,antislash_pos){var seq_end,mo;mo=/^[0-7]{1,3}/.exec(text.substr(antislash_pos+1));if(mo){return[String.fromCharCode(parseInt(mo[0],8)),1+mo[0].length]}switch(text[antislash_pos+1]){case"x":mo=/^[0-9A-F]{0,2}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=2){seq_end=antislash_pos+mo[0].length+1;$token.value.start[1]=seq_end;throw Error("(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\xXX escape")}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]}break;case"u":mo=/^[0-9A-F]{0,4}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=4){seq_end=antislash_pos+mo[0].length+1;$token.value.start[1]=seq_end;throw Error("(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\uXXXX escape")}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]}break;case"U":mo=/^[0-9A-F]{0,8}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=8){seq_end=antislash_pos+mo[0].length+1;$token.value.start[1]=seq_end;throw Error("(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\uXXXX escape")}else{let value=parseInt(mo[0],16);if(value>1114111){throw Error("invalid unicode escape "+mo[0])}else if(value>=65536){return[SurrogatePair(value),2+mo[0].length]}else{return[String.fromCharCode(value),2+mo[0].length]}}}}$B.test_escape=test_escape;function unindent(src){var lines=src.split("\n"),line,global_indent,indent,first,unindented_lines=[];var min_indent;for(var line of lines){if(/^\s*$/.exec(line)){continue}indent=line.match(/^\s*/)[0].length;if(indent==0){return src}if(min_indent===undefined){min_indent=indent}if(indent0;options.python_extension=options.python_extension||".py";if($B.$options.args){$B.__ARGV=$B.$options.args}else{$B.__ARGV=_b_.list.$factory([])}$B.options_parsed=true;return options};if(!($B.isWebWorker||$B.isNode)){var startup_observer=new MutationObserver((function(mutations){for(var mutation of mutations){for(var addedNode of mutation.addedNodes){addPythonScript(addedNode)}}}));startup_observer.observe(document.documentElement,{childList:true,subtree:true})}var brython_options=$B.brython_options={};var python_scripts=[];if(!$B.isWebWorker){python_scripts=python_scripts.concat(Array.from(document.querySelectorAll('script[type="text/python"]'))).concat(Array.from(document.querySelectorAll('script[type="text/python3"]')));var onload;addEventListener("DOMContentLoaded",(function(ev){if(ev.target.body){onload=ev.target.body.onload}if(!onload){ev.target.body.onload=function(){return brython()}}else{ev.target.body.onload=function(){onload();if(!status.brython_called){brython()}}}}));class BrythonOptions extends HTMLElement{constructor(){super()}connectedCallback(){for(var attr of this.getAttributeNames()){brython_options[attr]=convert_option(attr,this.getAttribute(attr))}}}customElements.define("brython-options",BrythonOptions)}var defined_ids={},script_to_id=new Map,id_to_script={};function addPythonScript(addedNode){if(addedNode.tagName=="SCRIPT"&&(addedNode.type=="text/python"||addedNode.type=="text/python3")){python_scripts.push(addedNode)}}var status={brython_called:false,first_unnamed_script:true};$B.dispatch_load_event=function(script){script.dispatchEvent(new Event("load"))};function injectPythonScript(addedNode){if(addedNode.tagName=="SCRIPT"&&addedNode.type=="text/python"){set_script_id(addedNode);run_scripts([addedNode])}}function set_script_id(script){if(script_to_id.has(script)){}else if(script.id){if(defined_ids[script.id]){throw Error("Brython error : Found 2 scripts with the "+"same id '"+script.id+"'")}else{defined_ids[script.id]=true}script_to_id.set(script,script.id)}else{if(script.className==="webworker"){throw _b_.AttributeError.$factory("webworker script has no attribute 'id'")}if(status.first_unnamed_script){script_to_id.set(script,"__main__");status.first_unnamed_script=false}else{script_to_id.set(script,"__main__"+$B.UUID())}}var id=script_to_id.get(script);id_to_script[id]=script;return id}var brython=$B.parser.brython=function(options){$B.$options=$B.parse_options(options);if(!($B.isWebWorker||$B.isNode)){if(!status.brython_called){status.brython_called=true;startup_observer.disconnect();var inject_observer=new MutationObserver((function(mutations){for(var mutation of mutations){for(var addedNode of mutation.addedNodes){injectPythonScript(addedNode)}}}));inject_observer.observe(document.documentElement,{childList:true,subtree:true})}}else if($B.isNode){return}for(var python_script of python_scripts){set_script_id(python_script)}var scripts=[];$B.script_path=_window.location.href.split("#")[0];var $href=$B.script_path=_window.location.href.split("#")[0],$href_elts=$href.split("/");$href_elts.pop();if($B.isWebWorker||$B.isNode){$href_elts.pop()}$B.curdir=$href_elts.join("/");var kk=Object.keys(_window);var ids=$B.get_page_option("ids");if(ids!==undefined){if(!Array.isArray(ids)){throw _b_.ValueError.$factory("ids is not a list")}if(ids.length==0){}for(var id of ids){var script=document.querySelector(`script[id="${id}"]`);if(script){set_script_id(script);scripts.push(script)}else{console.log(`no script with id '${id}'`);throw _b_.KeyError.$factory(`no script with id '${id}'`)}}}else if($B.isWebWorker){}else{scripts=python_scripts.slice()}run_scripts(scripts)};function convert_option(option,value){if(option=="debug"){if(typeof value=="string"&&value.match(/^\d+$/)){return parseInt(value)}else if(typeof value=="number"){return value}else{if(value!==null&&value!==undefined){console.debug(`Invalid value for debug: ${value}`)}}}else if(option=="cache"||option=="indexeddb"||option=="static_stdlib_import"){if(value=="1"||value.toLowerCase()=="true"){return true}else if(value=="0"||value.toLowerCase()=="false"){return false}else{console.debug(`Invalid value for ${option}: ${value}`)}}else if(option=="ids"||option=="pythonpath"||option=="args"){if(typeof value=="string"){if(value.trim().length==0){return[]}return value.trim().split(/\s+/)}}return value}const default_option={args:[],cache:false,debug:1,indexeddb:true,python_extension:".py",static_stdlib_import:true};$B.get_filename=function(){if($B.count_frames()>0){return $B.get_frame_at(0).__file__}};$B.get_filename_for_import=function(){var filename=$B.get_filename();if($B.import_info[filename]===undefined){$B.make_import_paths(filename)}return filename};$B.get_page_option=function(option){option=option.toLowerCase();if($B.$options.hasOwnProperty(option)){return $B.$options[option]}else if(brython_options.hasOwnProperty(option)){return brython_options[option]}else{return default_option[option]}};$B.get_option=function(option,err){var filename=$B.script_filename;if(err&&err.$frame_obj){filename=$B.get_frame_at(0,err.$frame_obj).__file__}else{filename=$B.get_filename()}return $B.get_option_from_filename(option,filename)};$B.get_option_from_filename=function(option,filename){if(filename===undefined||!$B.scripts[filename]){return $B.get_page_option(option)}var value=$B.scripts[filename].getAttribute(option);if(value!==null){return convert_option(option,value)}else{return $B.get_page_option(option)}};function run_scripts(_scripts){var webworkers=_scripts.filter((script=>script.className==="webworker")),scripts=_scripts.filter((script=>script.className!=="webworker"));var module_name,filename;if(scripts.length>0||$B.isWebWorker){if($B.get_page_option("indexedDB")&&$B.has_indexedDB&&$B.hasOwnProperty("VFS")){$B.tasks.push([$B.idb_open])}}var src;for(var worker of webworkers){if(worker.src){$B.tasks.push([$B.ajax_load_script,{script:worker,name:worker.id,url:worker.src,is_ww:true}])}else{$B.webworkers[worker.id]=worker;filename=$B.script_filename=$B.strip_host($B.script_path+"#"+worker.id);var source=worker.innerText||worker.textContent;source=unindent(source);source=source.replace(/^\n/,"");$B.url2name[filename]=worker.id;$B.file_cache[filename]=source;$B.scripts[filename]=worker;$B.dispatch_load_event(worker)}}for(var script of scripts){module_name=script_to_id.get(script);if(script.src){$B.tasks.push([$B.ajax_load_script,{script:script,name:module_name,url:script.src,id:script.id}])}else{filename=$B.script_filename=$B.strip_host($B.script_path+"#"+module_name);src=script.innerHTML||script.textContent;src=unindent(src);src=src.replace(/^\n/,"");if(src.endsWith("\n")){src=src.substr(0,src.length-1)}$B.tasks.push([$B.run_script,script,src,module_name,$B.script_path,true])}}$B.loop()}$B.run_script=function(script,src,name,url,run_loop){var filename=$B.script_filename=$B.strip_host(url+"#"+name);var script_elts=url.split("/");script_elts.pop();$B.script_dir=script_elts.join("/");$B.file_cache[filename]=src;$B.url2name[filename]=name;$B.scripts[filename]=script;$B.make_import_paths(filename);_b_.__debug__=$B.get_option("debug")>0;var root,js;try{root=$B.py2js({src:src,filename:filename},name,name);js=root.to_js();if($B.get_option_from_filename("debug",filename)>1){console.log($B.format_indent(js,0))}}catch(err){console.log("err",err);return $B.handle_error($B.exception(err))}var _script={__doc__:get_docstring(root._ast),js:js,__name__:name,__file__:url,script_element:script};$B.tasks.push(["execute",_script]);if(run_loop){$B.loop()}};$B.brython=brython})(__BRYTHON__);globalThis.brython=__BRYTHON__.brython;if(__BRYTHON__.isNode){global.__BRYTHON__=__BRYTHON__;module.exports={__BRYTHON__:__BRYTHON__}}(function($B){var _b_=$B.builtins;if($B.VFS_timestamp&&$B.VFS_timestamp>$B.timestamp){$B.timestamp=$B.VFS_timestamp}function idb_load(evt,module){var res=evt.target.result;var debug=$B.get_page_option("debug");if(res===undefined||res.timestamp!=$B.timestamp||$B.VFS[module]&&res.source_ts!==$B.VFS[module].timestamp){if($B.VFS[module]!==undefined){var elts=$B.VFS[module],ext=elts[0],source=elts[1];if(ext==".py"){var is_package=elts.length==4,__package__;if(is_package){__package__=module}else{var parts=module.split(".");parts.pop();__package__=parts.join(".")}$B.imported[module]=$B.module.$factory(module,"",__package__);$B.url2name[module]=module;try{$B.py2js({src:source,filename:module},module,module)}catch(err){$B.handle_error(err)}delete $B.imported[module];if(debug>1){console.log("precompile",module)}}else{console.log("bizarre",module,ext)}}else{}}else{if(res.is_package){$B.precompiled[module]=[res.content]}else{$B.precompiled[module]=res.content}if(res.imports.length>0){if(debug>1){console.log(module,"imports",res.imports)}var subimports=res.imports.split(",");for(var i=0;i0){let module=outdated.pop(),req=store.delete(module);req.onsuccess=function(mod){return function(){if($B.get_page_option("debug")>1){console.info("delete outdated",mod)}report_remove_outdated(mod);remove_outdated(db,outdated,callback)}}(module)}else{report_close();callback()}}$B.idb_open_promise=function(){return new Promise((function(resolve,reject){$B.idb_name="brython-cache";var idb_cx=$B.idb_cx=indexedDB.open($B.idb_name);idb_cx.onsuccess=function(){var db=idb_cx.result;var tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),record,outdated=[];var openCursor=store.openCursor();openCursor.onerror=function(){reject("open cursor error")};openCursor.onsuccess=function(evt){var cursor=evt.target.result;if(cursor){record=cursor.value;if(record.timestamp==$B.timestamp){if(!$B.VFS||!$B.VFS[record.name]||$B.VFS[record.name].timestamp==record.source_ts){if(record.is_package){$B.precompiled[record.name]=[record.content]}else{$B.precompiled[record.name]=record.content}}else{outdated.push(record.name)}}else{outdated.push(record.name)}cursor.continue()}else{remove_outdated(db,outdated,resolve)}}};idb_cx.onupgradeneeded=function(){var db=idb_cx.result,store=db.createObjectStore("modules",{keyPath:"name"});store.onsuccess=resolve};idb_cx.onerror=function(){$B.idb_cx=null;$B.idb_name=null;$B.$options.indexeddb=false;reject("could not open indexedDB database")}}))};$B.idb_open=function(){$B.idb_name="brython-cache";var idb_cx=$B.idb_cx=indexedDB.open($B.idb_name);idb_cx.onsuccess=function(){var db=idb_cx.result;if($B.get_page_option("debug")>1){console.info("using indexedDB for stdlib modules cache")}var tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),record,outdated=[];var openCursor=store.openCursor();openCursor.onerror=function(evt){console.log("open cursor error",evt)};openCursor.onsuccess=function(evt){var cursor=evt.target.result;if(cursor){record=cursor.value;if(record.timestamp==$B.timestamp){if(!$B.VFS||!$B.VFS[record.name]||$B.VFS[record.name].timestamp==record.source_ts){if(record.is_package){$B.precompiled[record.name]=[record.content]}else{$B.precompiled[record.name]=record.content}if($B.get_page_option("debug")>1){console.info("load from cache",record.name)}}else{outdated.push(record.name)}}else{outdated.push(record.name)}cursor.continue()}else{if($B.get_page_option("debug")>1){console.log("done")}remove_outdated(db,outdated,loop)}}};idb_cx.onupgradeneeded=function(){console.info("upgrade needed");var db=idb_cx.result,store=db.createObjectStore("modules",{keyPath:"name"});store.onsuccess=loop};idb_cx.onerror=function(){console.info("could not open indexedDB database");$B.idb_cx=null;$B.idb_name=null;$B.$options.indexeddb=false;loop()};idb_cx.onversionchange=function(){console.log("version change")}};$B.ajax_load_script=function(s){var script=s.script,url=s.url,name=s.name,rel_path=url.substr($B.script_dir.length+1);if($B.files&&$B.files.hasOwnProperty(rel_path)){var src=atob($B.files[rel_path].content);$B.tasks.splice(0,0,[$B.run_script,script,src,name,url,true]);loop()}else if($B.protocol!="file"){var filename=$B.script_filename=$B.strip_host(url);$B.scripts[filename]=script;var req=new XMLHttpRequest,cache=$B.get_option("cache"),qs=cache?"":(url.search(/\?/)>-1?"&":"?")+Date.now();req.open("GET",url+qs,true);req.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){var src=this.responseText;if(s.is_ww){$B.webworkers[name]=script;$B.file_cache[filename]=src;$B.dispatch_load_event(script)}else{$B.tasks.splice(0,0,[$B.run_script,script,src,name,url,true])}loop()}else if(this.status==404){throw Error(url+" not found")}}};req.send()}else{throw _b_.IOError.$factory("can't load external script at "+script.url+" (Ajax calls not supported with protocol file:///)")}};function add_jsmodule(module,source){source+="\nvar $locals_"+module.replace(/\./g,"_")+" = $module";$B.precompiled[module]=source}$B.inImported=function(module){if($B.imported.hasOwnProperty(module)){}else if(__BRYTHON__.VFS&&__BRYTHON__.VFS.hasOwnProperty(module)){var elts=__BRYTHON__.VFS[module];var ext=elts[0],source=elts[1];if(ext==".py"){if($B.idb_cx){$B.tasks.splice(0,0,[idb_get,module])}}else{add_jsmodule(module,source)}}else{console.log("bizarre",module)}loop()};function report_remove_outdated(mod){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent("precompile",{detail:`remove outdated ${mod} from cache`}))}}function report_close(){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent("precompile",{detail:"close"}))}}function report_done(){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent("brython_done",{detail:_b_.dict.$from_js($B.$options)}))}}var loop=$B.loop=function(){if($B.tasks.length==0){report_done();return}var task=$B.tasks.shift(),func=task[0],args=task.slice(1);if(func=="execute"){let script=task[1],script_id=script.__name__.replace(/\./g,"_"),module=$B.module.$factory(script.__name__);module.__file__=script.__file__;module.__doc__=script.__doc__;$B.imported[script_id]=module;try{var modobj=new Function(script.js+`\nreturn locals`)();for(var key in modobj){if(!key.startsWith("$")){module[key]=modobj[key]}}$B.dispatch_load_event(script.script_element)}catch(err){if(err.__class__===undefined){if(err.$py_exc){err=err.$py_exc}else{$B.freeze(err);var stack=err.$stack,frame_obj=err.$frame_obj,linenums=err.$linenums;var lineNumber=err.lineNumber;if(lineNumber!==undefined){console.log("around line",lineNumber);console.log(script.js.split("\n").slice(lineNumber-4,lineNumber).join("\n"))}$B.print_stack();err=_b_.RuntimeError.$factory(err+"");err.$stack=stack;err.$frame_obj=frame_obj;err.$linenums=linenums}}$B.handle_error(err)}loop()}else{try{func.apply(null,args)}catch(err){$B.handle_error(err)}}};$B.tasks=[];$B.has_indexedDB=self.indexedDB!==undefined})(__BRYTHON__);(function($B){var _b_=$B.builtins,_window=globalThis,isWebWorker="undefined"!==typeof WorkerGlobalScope&&"function"===typeof importScripts&&navigator instanceof WorkerNavigator;function missing_required_kwonly(fname,args){var plural=args.length==1?"":"s",arg_list;args=args.map((x=>`'${x}'`));if(args.length==1){arg_list=args[0]}else if(args.length==2){arg_list=args[0]+" and "+args[1]}else{arg_list=args.slice(0,args.length-1).join(", ")+", and "+args[args.length-1]}throw _b_.TypeError.$factory(fname+"() "+`missing ${args.length} required keyword-only argument${plural}: `+arg_list)}function missing_required_pos(fname,args){var plural=args.length==1?"":"s",arg_list;args=args.map((x=>`'${x}'`));if(args.length==1){arg_list=args[0]}else if(args.length==2){arg_list=args[0]+" and "+args[1]}else{arg_list=args.slice(0,args.length-1).join(", ")+", and "+args[args.length-1]}throw _b_.TypeError.$factory(fname+"() "+`missing ${args.length} required positional argument${plural}: `+arg_list)}function multiple_values(fname,arg){throw _b_.TypeError.$factory(fname+"() "+`got multiple values for argument '${arg}'`)}function pos_only_passed_as_keyword(fname,arg){return _b_.TypeError.$factory(fname+`() got some positional-only arguments passed as keyword arguments:`+` '${arg}'`)}function too_many_pos_args(fname,kwarg,arg_names,nb_kwonly,defaults,args,slots){var nb_pos=args.length,last=$B.last(args);if(last!==null&&last!==undefined&&last.$kw){if(!kwarg){var kw=$B.parse_kwargs(last.$kw,fname);for(var k in kw){if(!slots.hasOwnProperty(k)){var suggestion=$B.offer_suggestions_for_unexpected_keyword_error(arg_names,k);throw unexpected_keyword(fname,k,suggestion)}}}nb_pos--}var nb_def=defaults.length;var expected=arg_names.length-nb_kwonly,plural=expected==1?"":"s";if(nb_def){expected=`from ${expected-nb_def} to ${expected}`;plural="s"}var verb=nb_pos==1?"was":"were";return _b_.TypeError.$factory(fname+"() takes "+`${expected} positional argument${plural} but ${nb_pos} ${verb} given`)}function unexpected_keyword(fname,k,suggestion){var msg=`${fname}() got an unexpected keyword argument '${k}'`;if(suggestion!==_b_.None){msg+=`. Did you mean: '${suggestion}'?`}return _b_.TypeError.$factory(msg)}var empty={};function args0(f,args){var arg_names=f.$infos.arg_names,code=f.$infos.__code__,slots={};for(var arg_name of arg_names){slots[arg_name]=empty}return $B.parse_args(args,f.$infos.__name__,code.co_argcount,slots,arg_names,f.$infos.__defaults__,f.$infos.__kwdefaults__,f.$infos.vararg,f.$infos.kwarg,code.co_posonlyargcount,code.co_kwonlyargcount)}function args0_NEW(fct,args){const LAST_ARGS=args[args.length-1];const HAS_KW=LAST_ARGS!==undefined&&LAST_ARGS!==null&&LAST_ARGS.$kw!==undefined;let ARGS_POS_COUNT=args.length,ARGS_NAMED=null;if(HAS_KW){--ARGS_POS_COUNT;ARGS_NAMED=LAST_ARGS.$kw}const result={};const $INFOS=fct.$infos,$CODE=$INFOS.__code__,PARAMS_NAMES=$INFOS.arg_names,PARAMS_POS_COUNT=$CODE.co_argcount,PARAMS_NAMED_COUNT=$CODE.co_kwonlyargcount,PARAMS_VARARGS_NAME=$INFOS.vararg,PARAMS_KWARGS_NAME=$INFOS.kwarg,PARAMS_POS_DEFAULTS=$INFOS.__defaults__,PARAMS_POS_DEFAULTS_COUNT=PARAMS_POS_DEFAULTS.length,PARAMS_POS_DEFAULTS_OFFSET=PARAMS_POS_COUNT-PARAMS_POS_DEFAULTS_COUNT;const min=Math.min(ARGS_POS_COUNT,PARAMS_POS_COUNT);let offset=0;for(;offsetPARAMS_POS_COUNT){args0(fct,args);throw new Error("Too much positional arguments given (args0 should have raised an error) !")}if(ARGS_NAMED===null){if(offset=nb_pos_or_kw){if(vararg){varargs.push(arg)}else{throw too_many_pos_args(fname,kwarg,arg_names,nb_kwonly,defaults,args,slots)}}else{if(i0){throw missing_required_kwonly(fname,missing_kwonly)}if(!kwarg){for(var k in kw){if(!slots.hasOwnProperty(k)){var suggestion=$B.offer_suggestions_for_unexpected_keyword_error(arg_names,k);throw unexpected_keyword(fname,k,suggestion)}}}for(var k in kw){if(kw[k]===empty){continue}if(!slots.hasOwnProperty(k)){if(kwarg){extra_kw[k]=kw[k]}}else if(slots[k]!==empty){if(posonly_set[k]&&kwarg){extra_kw[k]=kw[k]}else{throw multiple_values(fname,k)}}else{slots[k]=kw[k]}}if(kwarg){slots[kwarg]=_b_.dict.$from_js(extra_kw)}if(vararg){slots[vararg]=$B.fast_tuple(varargs)}return slots};$B.parse_kwargs=function(kw_args,fname){var kwa=kw_args[0];for(var i=1,len=kw_args.length;i0||y!==undefined&&y.$kw){throw _b_.TypeError.$factory(name+"() takes no keyword arguments")}};$B.check_nb_args_no_kw=function(name,expected,args){var len=args.length,last=args[len-1];if(last&&last.$kw){if(last.$kw.length==2&&Object.keys(last.$kw[0]).length==0){len--}else{throw _b_.TypeError.$factory(name+"() takes no keyword arguments")}}if(len!=expected){if(expected==0){throw _b_.TypeError.$factory(name+"() takes no argument"+" ("+len+" given)")}else{throw _b_.TypeError.$factory(name+"() takes exactly "+expected+" argument"+(expected<2?"":"s")+" ("+len+" given)")}}};$B.get_class=function(obj){if(obj===null){return $B.imported.javascript.NullType}if(obj===undefined){return $B.imported.javascript.UndefinedType}var klass=obj.__class__||obj.$tp_class;if(klass===undefined){switch(typeof obj){case"number":if(Number.isInteger(obj)){return _b_.int}break;case"string":return _b_.str;case"boolean":return _b_.bool;case"function":if(!obj.$js_func){return $B.function}case"object":if(Array.isArray(obj)){return $B.js_array}else if(obj instanceof $B.str_dict){return _b_.dict}else if(typeof Node!=="undefined"&&obj instanceof Node){if(obj.tagName){return $B.imported["browser.html"][obj.tagName]||$B.DOMNode}return $B.DOMNode}else if(obj instanceof Event){return $B.DOMEvent}break}}if(klass===undefined){return $B.get_jsobj_class(obj)}return klass};$B.class_name=function(obj){var klass=$B.get_class(obj);if(klass===$B.JSObj){return"Javascript "+obj.constructor.name}else{return klass.__name__}};$B.unpack_mapping=function*(func,obj){var klass=$B.get_class(obj);var getitem=$B.$getattr(klass,"__getitem__",null);if(getitem===null){throw _b_.TypeError.$factory(`'${$B.class_name(obj)}' object `+"is not subscriptable")}getitem=$B.$call(getitem);var key_func=$B.$getattr(klass,"keys",null);if(key_func===null){var f=`${func.$infos.__module__}.${func.$infos.__name__}`;throw _b_.TypeError.$factory(`${f}() argument after **`+` must be a mapping, not ${$B.class_name(obj)}`)}var keys=$B.$call($B.$getattr(klass,"keys"))(obj);for(var key of $B.make_js_iterator(keys)){if(!_b_.isinstance(key,_b_.str)){throw _b_.TypeError.$factory("keywords must be strings")}yield{key:key,value:getitem(obj,key)}}};$B.make_js_iterator=function(iterator,frame,lineno){var set_lineno=$B.set_lineno;if(frame===undefined){if($B.frame_obj===null){set_lineno=function(){}}else{frame=$B.frame_obj.frame;lineno=frame.$lineno}}if(iterator.__class__===_b_.range){var obj={ix:iterator.start};if(iterator.step>0){return{[Symbol.iterator](){return this},next(){set_lineno(frame,lineno);if(obj.ix>=iterator.stop){return{done:true,value:null}}var value=obj.ix;obj.ix+=iterator.step;return{done:false,value:value}}}}else{return{[Symbol.iterator](){return this},next(){set_lineno(frame,lineno);if(obj.ix<=iterator.stop){return{done:true,value:null}}var value=obj.ix;obj.ix+=iterator.step;return{done:false,value:value}}}}}if(iterator[Symbol.iterator]&&!iterator.$is_js_array){var it=iterator[Symbol.iterator]();return{[Symbol.iterator](){return this},next(){set_lineno(frame,lineno);return it.next()}}}var next_func=$B.$getattr(_b_.iter(iterator),"__next__",null);if(next_func!==null){next_func=$B.$call(next_func);return{[Symbol.iterator](){return this},next(){set_lineno(frame,lineno);try{var value=next_func();return{done:false,value:value}}catch(err){if($B.is_exc(err,[_b_.StopIteration])){return{done:true,value:null}}throw err}}}}};$B.unpacker=function(obj,nb_targets,has_starred){var position,position_rank=3;if(has_starred){var nb_after_starred=arguments[3];position_rank++}position=$B.decode_position(arguments[position_rank]);var t=_b_.list.$factory(obj),right_length=t.length,left_length=nb_targets+(has_starred?nb_after_starred-1:0);if(!has_starred&&right_lengthleft_length){var exc=_b_.ValueError.$factory("too many values to unpack "+`(expected ${left_length})`);if(position){$B.set_exception_offsets(exc,position)}throw exc}t.index=-1;t.read_one=function(){t.index++;return t[t.index]};t.read_rest=function(){t.index++;var res=t.slice(t.index,t.length-nb_after_starred);t.index=t.length-nb_after_starred-1;return $B.$list(res)};return t};$B.set_lineno=function(frame,lineno){frame.$lineno=lineno;if(frame.$f_trace!==_b_.None){$B.trace_line()}return true};$B.get_method_class=function(method,ns,qualname,refs){var klass=ns;if(method.$infos&&method.$infos.$class){return method.$infos.$class}for(var ref of refs){if(klass[ref]===undefined){return $B.make_class(qualname)}klass=klass[ref]}return klass};$B.warn=function(klass,message,filename,token){var warning=klass.$factory(message);warning.filename=filename;if(klass===_b_.SyntaxWarning){warning.lineno=token.lineno;warning.offset=token.col_offset;warning.end_lineno=token.end_lineno;warning.end_offset=token.end_coloffset;warning.text=token.line;warning.args[1]=$B.fast_tuple([filename,warning.lineno,warning.offset,warning.text,warning.end_lineno,warning.end_offset])}$B.imported._warnings.warn(warning)};function index_error(obj){var type=typeof obj=="string"?"string":"list";throw _b_.IndexError.$factory(type+" index out of range")}$B.$getitem=function(obj,item,position){var is_list=Array.isArray(obj)&&obj.__class__===_b_.list,is_dict=obj.__class__===_b_.dict&&!obj.$jsobj;if(typeof item=="number"){if(is_list||typeof obj=="string"){item=item>=0?item:obj.length+item;if(obj[item]!==undefined){return obj[item]}else{index_error(obj)}}}else if(item.valueOf&&typeof item.valueOf()=="string"&&is_dict){return _b_.dict.$getitem(obj,item)}if(obj.$is_class){if(!Array.isArray(item)){item=$B.fast_tuple([item])}if(obj===_b_.type){return $B.$class_getitem(obj,item)}var class_gi=$B.$getattr(obj,"__class_getitem__",_b_.None);if(class_gi!==_b_.None){return $B.$call(class_gi)(item)}else if(obj.__class__){class_gi=$B.$getattr(obj.__class__,"__getitem__",_b_.None);if(class_gi!==_b_.None){return class_gi(obj,item)}else{throw _b_.TypeError.$factory("type '"+$B.$getattr(obj,"__qualname__")+"' is not subscriptable")}}}if(is_list){return _b_.list.$getitem(obj,item)}if(is_dict){return _b_.dict.$getitem(obj,item)}var gi=$B.$getattr(obj.__class__||$B.get_class(obj),"__getitem__",_b_.None);if(gi!==_b_.None){return gi(obj,item)}var exc=_b_.TypeError.$factory("'"+$B.class_name(obj)+"' object is not subscriptable");if(position){$B.set_exception_offsets(exc,$B.decode_position(position))}throw exc};$B.getitem_slice=function(obj,slice){var res;if(Array.isArray(obj)&&obj.__class__===_b_.list){if(slice.start===_b_.None&&slice.stop===_b_.None){if(slice.step===_b_.None||slice.step==1){res=obj.slice()}else if(slice.step==-1){res=obj.slice().reverse()}}else if(slice.step===_b_.None){if(slice.start===_b_.None){slice.start=0}if(slice.stop===_b_.None){slice.stop=obj.length}if(typeof slice.start=="number"&&typeof slice.stop=="number"){if(slice.start<0){slice.start+=obj.length}if(slice.stop<0){slice.stop+=obj.length}res=obj.slice(slice.start,slice.stop)}}if(res){res.__class__=obj.__class__;return res}else{return _b_.list.$getitem(obj,slice)}}else if(typeof obj=="string"){return _b_.str.__getitem__(obj,slice)}return $B.$getattr($B.get_class(obj),"__getitem__")(obj,slice)};$B.$getattr_pep657=function(obj,attr,position){try{return $B.$getattr(obj,attr)}catch(err){$B.set_exception_offsets(err,$B.decode_position(position));throw err}};$B.set_list_slice=function(obj,start,stop,value){if(start===null){start=0}else{start=$B.$GetInt(start);if(start<0){start=Math.max(0,start+obj.length)}}if(stop===null){stop=obj.length}stop=$B.$GetInt(stop);if(stop<0){stop=Math.max(0,stop+obj.length)}var res=_b_.list.$factory(value);obj.splice.apply(obj,[start,stop-start].concat(res))};$B.set_list_slice_step=function(obj,start,stop,step,value){if(step===null||step==1){return $B.set_list_slice(obj,start,stop,value)}if(step==0){throw _b_.ValueError.$factory("slice step cannot be zero")}step=$B.$GetInt(step);if(start===null){start=step>0?0:obj.length-1}else{start=$B.$GetInt(start)}if(stop===null){stop=step>0?obj.length:-1}else{stop=$B.$GetInt(stop)}var repl=_b_.list.$factory(value),j=0,test,nb=0;if(step>0){test=function(i){return istop}}for(var i=start;test(i);i+=step){nb++}if(nb!=repl.length){throw _b_.ValueError.$factory("attempt to assign sequence of size "+repl.length+" to extended slice of size "+nb)}for(var i=start;test(i);i+=step){obj[i]=repl[j];j++}};$B.$setitem=function(obj,item,value){if(Array.isArray(obj)&&obj.__class__===undefined&&!obj.$is_js_array&&typeof item=="number"&&!$B.$isinstance(obj,_b_.tuple)){if(item<0){item+=obj.length}if(obj[item]===undefined){throw _b_.IndexError.$factory("list assignment index out of range")}obj[item]=value;return}else if(obj.__class__===_b_.dict){_b_.dict.$setitem(obj,item,value);return}else if(obj.__class__===_b_.list){return _b_.list.$setitem(obj,item,value)}var si=$B.$getattr(obj.__class__||$B.get_class(obj),"__setitem__",null);if(si===null||typeof si!="function"){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object does not support item assignment")}return si(obj,item,value)};$B.$delitem=function(obj,item){if(Array.isArray(obj)&&obj.__class__===_b_.list&&typeof item=="number"&&!$B.$isinstance(obj,_b_.tuple)){if(item<0){item+=obj.length}if(obj[item]===undefined){throw _b_.IndexError.$factory("list deletion index out of range")}obj.splice(item,1);return}else if(obj.__class__===_b_.dict){if(obj.$is_namespace){Object.defineProperty(obj.$jsobj,item,{get(){throw $B.name_error(item)},set(value){Object.defineProperty(obj.$jsobj,item,{value:value});return _b_.None}})}else{_b_.dict.__delitem__(obj,item)}return}else if(obj.__class__===_b_.list){return _b_.list.__delitem__(obj,item)}var di=$B.$getattr(obj.__class__||$B.get_class(obj),"__delitem__",null);if(di===null){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object doesn't support item deletion")}return di(obj,item)};function num_result_type(x,y){var is_int,is_float,x_num,y_num;if(typeof x=="number"){x_num=x;if(typeof y=="number"){is_int=true;y_num=y}else if(y.__class__===_b_.float){is_float=true;y_num=y.value}}else if(x.__class__===_b_.float){x_num=x.value;if(typeof y=="number"){y_num=y;is_float=true}else if(y.__class__===_b_.float){is_float=true;y_num=y.value}}return{is_int:is_int,is_float:is_float,x:x_num,y:y_num}}$B.augm_assign=function(left,op,right){var res_type=num_result_type(left,right);if(res_type.is_int||res_type.is_float){var z;switch(op){case"+=":z=res_type.x+res_type.y;break;case"-=":z=res_type.x-res_type.y;break;case"*=":z=res_type.x*res_type.y;break;case"/=":z=res_type.x/res_type.y;break}if(z){if(res_type.is_int&&Number.isSafeInteger(z)){return z}else if(res_type.res_is_float){return $B.fast_float(z)}}}else if(op=="*="){if(typeof left=="number"&&typeof right=="string"){return left<=0?"":right.repeat(left)}else if(typeof left=="string"&&typeof right=="number"){return right<=0?"":left.repeat(right)}}else if(op=="+="){if(typeof left=="string"&&typeof right=="string"){return left+right}}var op1=op.substr(0,op.length-1),method=$B.op2method.augmented_assigns[op],augm_func=$B.$getattr(left,"__"+method+"__",null);if(augm_func!==null){var res=$B.$call(augm_func)(right);if(res===_b_.NotImplemented){throw _b_.TypeError.$factory(`unsupported operand type(s)`+` for ${op}: '${$B.class_name(left)}' `+`and '${$B.class_name(right)}'`)}return res}else{var method1=$B.op2method.operations[op1];if(method1===undefined){method1=$B.op2method.binary[op1]}return $B.rich_op(`__${method1}__`,left,right)}};$B.$is=function(a,b){if((a===undefined||a===$B.Undefined)&&(b===undefined||b===$B.Undefined)){return true}if(a===null){return b===null}if(b===null){return a===null}if(a.__class__===_b_.float&&b.__class__===_b_.float){if(isNaN(a.value)&&isNaN(b.value)){return true}return a.value==b.value}if(a===_b_.int&&b==$B.long_int||a===$B.long_int&&b===_b_.int){return true}return a===b};$B.is_or_equals=function(x,y){return $B.$is(x,y)||$B.rich_comp("__eq__",x,y)};$B.member_func=function(obj){var klass=$B.get_class(obj),contains=$B.$getattr(klass,"__contains__",null);if(contains!==null){contains=$B.$call(contains);return contains.bind(null,obj)}try{var iterator=$B.make_js_iterator(obj);return function(key){try{for(var item of iterator){if($B.is_or_equals(key,item)){return true}}return false}catch(err){return false}}}catch(err){var getitem=$B.$getattr(klass,"__getitem__",null);if(getitem!==null){return function(key){var i=-1;while(true){i++;try{var item=getitem(obj,i);if($B.is_or_equals(key,item)){return true}}catch(err){if($B.$is_exc(err,[_b_.StopIteration])){return false}throw err}}}}else{throw _b_.TypeError.$factory("argument of type "+`'${$B.class_name(obj)}' is not iterable`)}}};$B.$is_member=function(item,_set){return $B.member_func(_set)(item)};$B.$call=function(callable,position){callable=$B.$call1(callable);if(position){return function(){try{return callable.apply(null,arguments)}catch(exc){position=$B.decode_position(position);$B.set_exception_offsets(exc,position);throw exc}}}return callable};$B.$call1=function(callable){if(callable.__class__===$B.method){return callable}else if(callable.__class__===_b_.staticmethod){return callable.__func__}else if(callable.$factory){return callable.$factory}else if(callable.$is_class){return callable.$factory=$B.$instance_creator(callable)}else if(callable.$is_js_class){return callable.$factory=function(){return new callable(...arguments)}}else if(callable.$in_js_module){return function(){var res=callable(...arguments);return res===undefined?_b_.None:res}}else if(callable.$is_func||typeof callable=="function"){if(callable.$infos&&callable.$infos.__code__&&callable.$infos.__code__.co_flags&32){$B.frame_obj.frame.$has_generators=true}if(callable.$is_async){if($B.frame_obj!==null){var frame=$B.frame_obj.frame;frame.$async=callable}}return callable}try{return $B.$getattr(callable,"__call__")}catch(err){throw _b_.TypeError.$factory("'"+$B.class_name(callable)+"' object is not callable")}};var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or"];var ropsigns=["+","-","*","/","//","%","**","<<",">>","&","^","|"];$B.make_rmethods=function(klass){for(var r_opname of r_opnames){if(klass["__r"+r_opname+"__"]===undefined&&klass["__"+r_opname+"__"]){klass["__r"+r_opname+"__"]=function(name){return function(self,other){return klass["__"+name+"__"](other,self)}}(r_opname)}}};$B.UUID=function(){return $B.$py_UUID++};$B.$GetInt=function(value){if(typeof value=="number"||value.constructor===Number){return value}else if(typeof value==="boolean"){return value?1:0}else if($B.$isinstance(value,_b_.int)){return value}else if($B.$isinstance(value,_b_.float)){return value.valueOf()}if(!value.$is_class){try{var v=$B.$getattr(value,"__int__")();return v}catch(e){}try{var v=$B.$getattr(value,"__index__")();return v}catch(e){}}throw _b_.TypeError.$factory("'"+$B.class_name(value)+"' object cannot be interpreted as an integer")};$B.to_num=function(obj,methods){var expected_class={__complex__:_b_.complex,__float__:_b_.float,__index__:_b_.int,__int__:_b_.int};var klass=obj.__class__||$B.get_class(obj);for(var i=0;i$B.recursion_limit){var exc=_b_.RecursionError.$factory("maximum recursion depth exceeded");$B.set_exc(exc,frame);throw exc}frame.__class__=$B.frame;frame.__file__=__file__;frame.$lineno=lineno;frame.$f_trace=_b_.None;frame.$has_generators=!!frame[1].$has_generators;$B.frame_obj={prev:$B.frame_obj,frame:frame,count:count+1};if($B.tracefunc!==_b_.None){if(frame[4]===$B.tracefunc||$B.tracefunc.$infos&&frame[4]&&frame[4]===$B.tracefunc.$infos.__func__){$B.tracefunc.$frame_id=frame[0];frame.$f_trace=_b_.None;return}else{var frame_obj=$B.frame_obj;while(frame_obj!==null){if(frame_obj.frame[0]==$B.tracefunc.$frame_id){frame.$f_trace=_b_.None;return}frame_obj=frame_obj.prev}try{var res=$B.tracefunc(frame,"call",_b_.None);var frame_obj=$B.frame_obj;while(frame_obj!==null){if(frame_obj.frame[4]==res){return _b_.None}frame_obj=frame_obj.prev}frame.$f_trace=res;return}catch(err){$B.set_exc(err,frame);$B.frame_obj=$B.frame_obj.prev;err.$in_trace_func=true;throw err}}}};$B.trace_exception=function(){var frame=$B.frame_obj.frame;if(frame[0]==$B.tracefunc.$current_frame_id){return _b_.None}var trace_func=frame.$f_trace,exc=frame[1].$current_exception;return trace_func(frame,"exception",$B.fast_tuple([exc.__class__,exc,$B.traceback.$factory(exc)]))};$B.trace_line=function(){var frame=$B.frame_obj.frame;if(frame[0]==$B.tracefunc.$current_frame_id){return _b_.None}var trace_func=frame.$f_trace;if(trace_func===undefined){console.log("trace line, frame",frame)}return trace_func(frame,"line",_b_.None)};$B.trace_return=function(value){var frame=$B.frame_obj.frame,trace_func=frame.$f_trace;if(frame[0]==$B.tracefunc.$current_frame_id){return _b_.None}trace_func(frame,"return",value)};$B.leave_frame=function(arg){if($B.frame_obj===null){return}if(arg&&arg.value!==undefined&&$B.tracefunc!==_b_.None){if($B.frame_obj.frame.$f_trace===undefined){$B.frame_obj.frame.$f_trace=$B.tracefunc}if($B.frame_obj.frame.$f_trace!==_b_.None){$B.trace_return(arg.value)}}var frame=$B.frame_obj.frame;if(frame.$coroutine){if(!frame.$coroutine.$sent){var cname=frame.$coroutine.$func.$infos.__name__;var message=_b_.RuntimeWarning.$factory(`coroutine '${cname}' was never awaited`);message.lineno=frame.$coroutine.$lineno;$B.imported._warnings.warn(message)}}$B.frame_obj=$B.frame_obj.prev;if(frame.$has_generators){for(var key in frame[1]){if(frame[1][key]&&frame[1][key].__class__===$B.generator){var gen=frame[1][key];if(gen.$frame===undefined){continue}var ctx_managers=gen.$frame[1].$context_managers;if(ctx_managers){for(var cm of ctx_managers){$B.$call($B.$getattr(cm,"__exit__"))(_b_.None,_b_.None,_b_.None)}}}}}delete frame[1].$current_exception;return _b_.None};$B.trace_return_and_leave=function(frame,return_value){if(frame.$f_trace!==_b_.None){$B.trace_return(return_value)}return $B.leave_frame()};$B.push_frame=function(frame){var count=$B.frame_obj===null?0:$B.frame_obj.count;return{prev:$B.frame_obj,frame:frame,count:count+1}};var reversed_op={__lt__:"__gt__",__le__:"__ge__",__gt__:"__lt__",__ge__:"__le__"};var method2comp={__lt__:"<",__le__:"<=",__gt__:">",__ge__:">="};$B.rich_comp=function(op,x,y){if(x===undefined){throw _b_.RuntimeError.$factory("error in rich comp")}var x1=x!==null&&x.valueOf?x.valueOf():x,y1=y!==null&&y.valueOf?y.valueOf():y;if(typeof x1=="number"&&typeof y1=="number"&&x.__class__===undefined&&y.__class__===undefined){switch(op){case"__eq__":return x1==y1;case"__ne__":return x1!=y1;case"__le__":return x1<=y1;case"__lt__":return x1=y1;case"__gt__":return x1>y1}}var res;if(x!==null&&(x.$is_class||x.$factory)){if(op=="__eq__"){return x===y}else if(op=="__ne__"){return!(x===y)}else{throw _b_.TypeError.$factory("'"+method2comp[op]+"' not supported between instances of '"+$B.class_name(x)+"' and '"+$B.class_name(y)+"'")}}var x_class_op=$B.$call($B.$getattr($B.get_class(x),op)),rev_op=reversed_op[op]||op,y_rev_func;if(x!==null&&x.__class__&&y!==null&&y.__class__){if(y.__class__.__mro__.indexOf(x.__class__)>-1){y_rev_func=$B.$getattr(y,rev_op);res=$B.$call(y_rev_func)(x);if(res!==_b_.NotImplemented){return res}}}res=x_class_op(x,y);if(res!==_b_.NotImplemented){return res}if(y_rev_func===undefined){y_rev_func=$B.$call($B.$getattr($B.get_class(y),rev_op));res=y_rev_func(y,x);if(res!==_b_.NotImplemented){return res}}if(op=="__eq__"){return _b_.False}else if(op=="__ne__"){return _b_.True}throw _b_.TypeError.$factory("'"+method2comp[op]+"' not supported between instances of '"+$B.class_name(x)+"' and '"+$B.class_name(y)+"'")};var opname2opsign={__sub__:"-",__xor__:"^",__mul__:"*",__and__:"&",__or__:"|"};$B.rich_op=function(op,x,y,position){try{return $B.rich_op1(op,x,y)}catch(exc){if(position){$B.set_exception_offsets(exc,$B.decode_position(position))}throw exc}};$B.rich_op1=function(op,x,y){var res_is_int,res_is_float,x_num,y_num;if(typeof x=="number"){x_num=x;if(typeof y=="number"){res_is_int=true;y_num=y}else if(y.__class__===_b_.float){res_is_float=true;y_num=y.value}}else if(x.__class__===_b_.float){x_num=x.value;if(typeof y=="number"){y_num=y;res_is_float=true}else if(y.__class__===_b_.float){res_is_float=true;y_num=y.value}}if(res_is_int||res_is_float){var z;switch(op){case"__add__":z=x_num+y_num;break;case"__sub__":z=x_num-y_num;break;case"__mul__":z=x_num*y_num;break;case"__pow__":if(res_is_int&&y_num>=0){return _b_.int.$int_or_long(BigInt(x_num)**BigInt(y_num))}break;case"__truediv__":if(y_num==0){throw _b_.ZeroDivisionError.$factory("division by zero")}z=x_num/y_num;return{__class__:_b_.float,value:z}}if(z){if(res_is_int&&Number.isSafeInteger(z)){return z}else if(res_is_float){return{__class__:_b_.float,value:z}}}}else if(typeof x=="string"&&typeof y=="string"&&op=="__add__"){return x+y}var x_class=x.__class__||$B.get_class(x),y_class=y.__class__||$B.get_class(y),rop="__r"+op.substr(2),method;if(x_class===y_class){if(x_class===_b_.int){return _b_.int[op](x,y)}else if(x_class===_b_.bool){return(_b_.bool[op]||_b_.int[op])(x,y)}try{method=$B.$call($B.$getattr(x_class,op))}catch(err){if(err.__class__===_b_.AttributeError){var kl_name=$B.class_name(x);throw _b_.TypeError.$factory("unsupported operand type(s) "+"for "+opname2opsign[op]+": '"+kl_name+"' and '"+kl_name+"'")}throw err}return method(x,y)}if(_b_.issubclass(y_class,x_class)){var reflected_left=$B.$getattr(x_class,rop,false),reflected_right=$B.$getattr(y_class,rop,false);if(reflected_right&&reflected_left&&reflected_right!==reflected_left){return reflected_right(y,x)}}var res;try{var attr=$B.$getattr(x,op);method=$B.$getattr(x_class,op)}catch(err){if(err.__class__!==_b_.AttributeError){throw err}res=$B.$call($B.$getattr(y,rop))(x);if(res!==_b_.NotImplemented){return res}throw _b_.TypeError.$factory(`unsupported operand type(s) for ${$B.method_to_op[op]}:`+` '${$B.class_name(x)}' and '${$B.class_name(y)}'`)}res=method(x,y);if(res===_b_.NotImplemented){try{method=$B.$getattr(y_class,rop)}catch(err){if(err.__class__!==_b_.AttributeError){throw err}throw _b_.TypeError.$factory(`unsupported operand type(s) for ${$B.method_to_op[op]}:`+` '${$B.class_name(x)}' and '${$B.class_name(y)}'`)}res=method(y,x);if(res===_b_.NotImplemented){throw _b_.TypeError.$factory(`unsupported operand type(s) for ${$B.method_to_op[op]}:`+` '${$B.class_name(x)}' and '${$B.class_name(y)}'`)}return res}else{return res}};$B.is_none=function(o){return o===undefined||o===null||o==_b_.None};var repr_stack=new Set;$B.repr={enter:function(obj){var obj_id=_b_.id(obj);if(repr_stack.has(obj_id)){return true}else{repr_stack.add(obj_id);if(repr_stack.size>$B.recursion_limit){repr_stack.clear();throw _b_.RecursionError.$factory("maximum recursion depth "+"exceeded while getting the repr of an object")}}},leave:function(obj){repr_stack.delete(_b_.id(obj))}}})(__BRYTHON__);(function($B){var _b_=$B.builtins;var object={__name__:"object",__qualname__:"object",$is_class:true,$native:true};object.__delattr__=function(self,attr){if(self.__dict__&&$B.$isinstance(self.__dict__,_b_.dict)&&_b_.dict.$contains_string(self.__dict__,attr)){_b_.dict.$delete_string(self.__dict__,attr);return _b_.None}else if(self.__dict__===undefined&&self[attr]!==undefined){delete self[attr];return _b_.None}else{var klass=self.__class__;if(klass){var prop=$B.$getattr(klass,attr);if(prop.__class__===_b_.property){if(prop.__delete__!==undefined){prop.__delete__(self);return _b_.None}}}}throw $B.attr_error(attr,self)};object.__dir__=function(self){var objects;if(self.$is_class){objects=[self].concat(self.__mro__)}else{var klass=self.__class__||$B.get_class(self);objects=[self,klass].concat(klass.__mro__)}var res=[];for(var i=0,len=objects.length;i2){console.log("error in get.apply",err);console.log("get attr",attr,"of",obj);console.log("res",res);console.log("__get__",__get__);console.log(__get__+"")}throw err}}if(__get__===null&&typeof res=="function"){__get__=function(x){return x}}if(__get__!==null){res.__name__=attr;if(attr=="__new__"||res.__class__===$B.builtin_function_or_method){res.$type="staticmethod"}var res1=__get__.apply(null,[res,obj,klass]);if($test){console.log("res",res,"res1",res1)}if(typeof res1=="function"){if(res1.__class__===$B.method){return res}if(res.$type=="staticmethod"){return res}else{var self=res.__class__===$B.method?klass:obj,method=function(){var args=[self];for(var i=0,len=arguments.length;i0||_b_.dict.__len__($.kwargs)>0){throw _b_.TypeError.$factory("object() takes no parameters")}var res=Object.create(null);res.__class__=cls;res.__dict__=$B.obj_dict({});return res}};object.$no_new_init=function(cls){var res=Object.create(null);res.__class__=cls;res.__dict__=$B.obj_dict({});return res};object.__new__=function(cls,...args){if(cls===undefined){throw _b_.TypeError.$factory("object.__new__(): not enough arguments")}var init_func=$B.$getattr(cls,"__init__");if(init_func===object.__init__){if(args.length>0){throw _b_.TypeError.$factory("object() takes no parameters")}}var res=Object.create(null);$B.update_obj(res,{__class__:cls,__dict__:$B.obj_dict({})});return res};object.__ne__=function(self,other){if(self===other){return false}var eq=$B.$getattr(self.__class__||$B.get_class(self),"__eq__",null);if(eq!==null){var res=$B.$call(eq)(self,other);if(res===_b_.NotImplemented){return res}return!$B.$bool(res)}return _b_.NotImplemented};object.__reduce__=function(self){if(!self.__dict__){throw _b_.TypeError.$factory(`cannot pickle '${$B.class_name(self)}' object`)}if($B.imported.copyreg===undefined){$B.$import("copyreg")}var res=[$B.imported.copyreg._reconstructor];var D=$B.get_class(self),B=object;for(var klass of D.__mro__){if(klass.__module__=="builtins"){B=klass;break}}var args=$B.$list([D,B]);if(B===object){args.push(_b_.None)}else{args.push($B.$call(B)(self))}res.push($B.fast_tuple(args));var d=$B.empty_dict();for(var attr of _b_.dict.$keys_string(self.__dict__)){_b_.dict.$setitem(d,attr,_b_.dict.$getitem_string(self.__dict__,attr))}res.push(d);return _b_.tuple.$factory(res)};function getNewArguments(self,klass){var newargs_ex=$B.$getattr(self,"__getnewargs_ex__",null);if(newargs_ex!==null){let newargs=newargs_ex();if(!newargs||newargs.__class__!==_b_.tuple){throw _b_.TypeError.$factory("__getnewargs_ex__ should "+`return a tuple, not '${$B.class_name(newargs)}'`)}if(newargs.length!=2){throw _b_.ValueError.$factory("__getnewargs_ex__ should "+`return a tuple of length 2, not ${newargs.length}`)}let args=newargs[0],kwargs=newargs[1];if(!args||args.__class__!==_b_.tuple){throw _b_.TypeError.$factory("first item of the tuple returned "+`by __getnewargs_ex__ must be a tuple, not '${$B.class_name(args)}'`)}if(!kwargs||kwargs.__class__!==_b_.dict){throw _b_.TypeError.$factory("second item of the tuple returned "+`by __getnewargs_ex__ must be a dict, not '${$B.class_name(kwargs)}'`)}return{args:args,kwargs:kwargs}}let newargs=klass.$getnewargs,args;if(!newargs){newargs=$B.$getattr(klass,"__getnewargs__",null)}if(newargs){args=newargs(self);if(!args||args.__class__!==_b_.tuple){throw _b_.TypeError.$factory("__getnewargs__ should "+`return a tuple, not '${$B.class_name(args)}'`)}return{args:args}}}object.__reduce_ex__=function(self,protocol){var klass=$B.get_class(self);if($B.imported.copyreg===undefined){$B.$import("copyreg")}if(protocol<2){return $B.$call($B.imported.copyreg._reduce_ex)(self,protocol)}var reduce=$B.$getattr(klass,"__reduce__");if(reduce!==object.__reduce__){return $B.$call(reduce)(self)}var res=[$B.imported.copyreg.__newobj__];var arg2=[klass];var newargs=getNewArguments(self,klass);if(newargs){arg2=arg2.concat(newargs.args)}res.push($B.fast_tuple(arg2));var d=$B.empty_dict(),nb=0;if(self.__dict__){for(var item of _b_.dict.$iter_items(self.__dict__)){if(item.key=="__class__"||item.key.startsWith("$")){continue}_b_.dict.$setitem(d,item.key,item.value);nb++}}if(nb==0){d=_b_.None}res.push(d);var list_like_iterator=_b_.None;if($B.$getattr(klass,"append",null)!==null&&$B.$getattr(klass,"extend",null)!==null){list_like_iterator=_b_.iter(self)}res.push(list_like_iterator);var key_value_iterator=_b_.None;if($B.$isinstance(self,_b_.dict)){key_value_iterator=_b_.dict.items(self)}res.push(key_value_iterator);return _b_.tuple.$factory(res)};object.__repr__=function(self){if(self===object){return""}if(self.__class__===_b_.type){return""}var module=self.__class__.__module__;if(module!==undefined&&!module.startsWith("$")&&module!=="builtins"){return"<"+self.__class__.__module__+"."+$B.class_name(self)+" object>"}else{return"<"+$B.class_name(self)+" object>"}};object.__setattr__=function(self,attr,val){if(val===undefined){throw _b_.TypeError.$factory("can't set attributes of built-in/extension type 'object'")}else if(self.__class__===object){if(object[attr]===undefined){throw $B.attr_error(attr,self)}else{throw _b_.AttributeError.$factory("'object' object attribute '"+attr+"' is read-only")}}if(self.__dict__){_b_.dict.$setitem(self.__dict__,attr,val)}else{self[attr]=val}return _b_.None};object.__setattr__.__get__=function(obj){return function(attr,val){object.__setattr__(obj,attr,val)}};object.__setattr__.__str__=function(){return"method object.setattr"};object.__str__=function(self){if(self===undefined||self.$kw){throw _b_.TypeError.$factory("descriptor '__str__' of 'object' "+"object needs an argument")}var klass=self.__class__||$B.get_class(self);var repr_func=$B.$getattr(klass,"__repr__");return $B.$call(repr_func).apply(null,arguments)};object.__subclasshook__=function(){return _b_.NotImplemented};object.$factory=function(){if(arguments.length>0||arguments.length==1&&arguments[0].$kw&&Object.keys(arguments[0].$kw).length>0){throw _b_.TypeError.$factory("object() takes no arguments")}var res={__class__:object},args=[res];object.__init__.apply(null,args);return res};$B.set_func_names(object,"builtins");_b_.object=object})(__BRYTHON__);(function($B){var _b_=$B.builtins;const TPFLAGS={STATIC_BUILTIN:1<<1,MANAGED_WEAKREF:1<<3,MANAGED_DICT:1<<4,SEQUENCE:1<<5,MAPPING:1<<6,DISALLOW_INSTANTIATION:1<<7,IMMUTABLETYPE:1<<8,HEAPTYPE:1<<9,BASETYPE:1<<10,HAVE_VECTORCALL:1<<11,READY:1<<12,READYING:1<<13,HAVE_GC:1<<14,METHOD_DESCRIPTOR:1<<17,VALID_VERSION_TAG:1<<19,IS_ABSTRACT:1<<20,MATCH_SELF:1<<22,LONG_SUBCLASS:1<<24,LIST_SUBCLASS:1<<25,TUPLE_SUBCLASS:1<<26,BYTES_SUBCLASS:1<<27,UNICODE_SUBCLASS:1<<28,DICT_SUBCLASS:1<<29,BASE_EXC_SUBCLASS:1<<30,TYPE_SUBCLASS:1<<31,HAVE_FINALIZE:1<<0,HAVE_VERSION_TAG:1<<18};$B.$class_constructor=function(class_name,class_obj_proxy,metaclass,resolved_bases,bases,kwargs,static_attributes,firstlineno){var dict;if(class_obj_proxy instanceof $B.str_dict){dict=$B.empty_dict();dict.$strings=class_obj_proxy}else{dict=class_obj_proxy.$target}var module=class_obj_proxy.__module__;for(var base of bases){if(base.__flags__!==undefined&&!(base.__flags__&TPFLAGS.BASETYPE)){throw _b_.TypeError.$factory("type 'bool' is not an acceptable base type")}}var extra_kwargs={};if(kwargs){for(let i=0;i0){if(bases[0].__class__===undefined){if(typeof bases[0]=="function"){if(bases.length!=1){throw _b_.TypeError.$factory("A Brython class "+"can inherit at most 1 Javascript constructor")}$B.set_func_names(bases[0],module);return $B.JSMeta}else{throw _b_.TypeError.$factory("Argument of "+class_name+" is not a class (type '"+$B.class_name(bases[0])+"')")}}for(var base of bases){var mc=base.__class__;if(metaclass===undefined){metaclass=mc}else if(mc===metaclass||_b_.issubclass(metaclass,mc)){}else if(_b_.issubclass(mc,metaclass)){metaclass=mc}else if(metaclass.__bases__&&metaclass.__bases__.indexOf(mc)==-1){throw _b_.TypeError.$factory("metaclass conflict: the "+"metaclass of a derived class must be a (non-"+"strict) subclass of the metaclasses of all its bases")}}}else{metaclass=metaclass||_b_.type}return metaclass};function set_attr_if_absent(dict,attr,value){try{$B.$getitem(dict,attr)}catch(err){$B.$setitem(dict,attr,value)}}$B.make_class_namespace=function(metaclass,class_name,module,qualname,bases){var class_dict=_b_.dict.$literal([["__module__",module],["__qualname__",qualname]]);if(metaclass!==_b_.type){var prepare=$B.$getattr(metaclass,"__prepare__",_b_.None);if(prepare!==_b_.None){class_dict=$B.$call(prepare)(class_name,bases);set_attr_if_absent(class_dict,"__module__",module);set_attr_if_absent(class_dict,"__qualname__",qualname)}}if(class_dict.__class__===_b_.dict){if(class_dict.$all_str){return class_dict.$strings}return new Proxy(class_dict,{get:function(target,prop){if(prop=="__class__"){return _b_.dict}else if(prop=="$target"){return target}if(_b_.dict.$contains_string(target,prop)){return _b_.dict.$getitem_string(target,prop)}return undefined},set:function(target,prop,value){_b_.dict.$setitem(target,prop,value)}})}else{var setitem=$B.$getattr(class_dict,"__setitem__"),getitem=$B.$getattr(class_dict,"__getitem__");return new Proxy(class_dict,{get:function(target,prop){if(prop=="__class__"){return $B.get_class(target)}else if(prop=="$target"){return target}try{return getitem(prop)}catch(err){return undefined}},set:function(target,prop,value){setitem(prop,value);return _b_.None}})}};$B.resolve_mro_entries=function(bases){var new_bases=[],has_mro_entries=false;for(var base of bases){if(!$B.$isinstance(base,_b_.type)){var mro_entries=$B.$getattr(base,"__mro_entries__",_b_.None);if(mro_entries!==_b_.None){has_mro_entries=true;var entries=_b_.list.$factory(mro_entries(bases));new_bases=new_bases.concat(entries)}else{new_bases.push(base)}}else{new_bases.push(base)}}return has_mro_entries?new_bases:bases};$B.make_class=function(qualname,factory){var A={__class__:type,__bases__:[_b_.object],__mro__:[_b_.object],__name__:qualname,__qualname__:qualname,$is_class:true};A.$factory=factory;return A};var type=$B.make_class("type",(function(){var missing={},$=$B.args("type",3,{kls:null,bases:null,cl_dict:null},["kls","bases","cl_dict"],arguments,{bases:missing,cl_dict:missing},null,"kw"),kls=$.kls,bases=$.bases,cl_dict=$.cl_dict,kw=$.kw;var kwarg={};for(var item of _b_.dict.$iter_items(kw)){kwarg[item.key]=item.value}var kwargs={$kw:[kwarg]};if(cl_dict===missing){if(bases!==missing){throw _b_.TypeError.$factory("type() takes 1 or 3 arguments")}var res=$B.get_class(kls);if(res===$B.long_int){return _b_.int}return res}else{var module=$B.frame_obj.frame[2],resolved_bases=$B.resolve_mro_entries(bases),metaclass=$B.get_metaclass(kls,module,resolved_bases);return type.__call__(metaclass,kls,resolved_bases,cl_dict,kwargs)}}));type.__class__=type;var classmethod=_b_.classmethod=$B.make_class("classmethod",(function(func){$B.check_nb_args_no_kw("classmethod",1,arguments);return{__class__:classmethod,__func__:func}}));classmethod.__get__=function(){var $=$B.args("classmethod",3,{self:null,obj:null,cls:null},["self","obj","cls"],arguments,{cls:_b_.None},null,null),self=$.self,obj=$.obj,cls=$.cls;if(cls===_b_.None||cls===undefined){cls=$B.get_class(obj)}var func_class=$B.get_class(self.__func__),candidates=[func_class].concat(func_class.__mro__);for(var candidate of candidates){if(candidate===$B.function){break}if(candidate.__get__){return candidate.__get__(self.__func__,cls,cls)}}return $B.method.$factory(self.__func__,cls)};$B.set_func_names(classmethod,"builtins");var staticmethod=_b_.staticmethod=$B.make_class("staticmethod",(function(func){return{__class__:staticmethod,__func__:func}}));staticmethod.__call__=function(self){return $B.$call(self.__func__)};staticmethod.__get__=function(self){return self.__func__};$B.set_func_names(staticmethod,"builtins");$B.getset_descriptor=$B.make_class("getset_descriptor",(function(klass,attr,getter,setter){var res={__class__:$B.getset_descriptor,__doc__:_b_.None,cls:klass,attr:attr,getter:getter,setter:setter};return res}));$B.getset_descriptor.__get__=function(self,obj,klass){if(obj===_b_.None){return self}return self.getter(self,obj,klass)};$B.getset_descriptor.__set__=function(self,klass,value){return self.setter(self,klass,value)};$B.getset_descriptor.__repr__=function(self){return``};$B.set_func_names($B.getset_descriptor,"builtins");type.$call=function(klass,new_func,init_func){return function(){var instance=new_func.bind(null,klass).apply(null,arguments);if($B.$isinstance(instance,klass)){init_func.bind(null,instance).apply(null,arguments)}return instance}};type.$call_no_new_init=function(klass,init_func){return function(){var instance=_b_.object.$no_new_init(klass);init_func(instance,...arguments);return instance}};type.$call_no_init=function(klass,new_func){return new_func.bind(null,klass)};type.__call__=function(){var extra_args=[],klass=arguments[0];for(var i=1,len=arguments.length;i1){console.log("warning: no attribute $infos for",res,"klass",klass,"attr",attr)}if($test){console.log("res is function",res)}if(attr=="__new__"||res.__class__===$B.builtin_function_or_method){res.$type="staticmethod"}if((attr=="__class_getitem__"||attr=="__init_subclass__")&&res.__class__!==_b_.classmethod){res=_b_.classmethod.$factory(res);return _b_.classmethod.__get__(res,_b_.None,klass)}if(res.__class__===$B.method){return res.__get__(null,klass)}else{if($test){console.log("return res",res)}return res}}else{return res}}};type.__hash__=function(cls){return _b_.hash(cls)};type.__init__=function(){if(arguments.length==0){throw _b_.TypeError.$factory("descriptor '__init__' of 'type' "+"object needs an argument")}};type.__init_subclass__=function(){var $=$B.args("__init_subclass__",1,{cls:null},["cls"],arguments,{},"args","kwargs");if($.args.length>0){throw _b_.TypeError.$factory(`${$.cls.__qualname__}.__init_subclass__ takes no arguments `+`(${$.args.length} given)`)}if(_b_.dict.__len__($.kwargs)>0){throw _b_.TypeError.$factory(`${$.cls.__qualname__}.__init_subclass__() `+`takes no keyword arguments`)}return _b_.None};_b_.object.__init_subclass__=type.__init_subclass__;type.__instancecheck__=function(cls,instance){var kl=instance.__class__||$B.get_class(instance);if(kl===cls){return true}else{for(var i=0;i"};type.__ror__=function(){var len=arguments.length;if(len!=1){throw _b_.TypeError.$factory(`expected 1 argument, got ${len}`)}return _b_.NotImplemented};function update_subclasses(kls,name,alias,value){for(var subclass of kls.$subclasses){if(!subclass.hasOwnProperty(name)){subclass[alias]=value;update_subclasses(subclass,name,alias,value)}}}type.__setattr__=function(kls,attr,value){var $test=false;if($test){console.log("kls is class",type)}if(type[attr]&&type[attr].__get__&&type[attr].__set__){type[attr].__set__(kls,value);return _b_.None}if(kls.__module__=="builtins"){throw _b_.TypeError.$factory(`cannot set '${attr}' attribute of immutable type '`+kls.__qualname__+"'")}kls[attr]=value;var mp=kls.__dict__||$B.$getattr(kls,"__dict__");_b_.dict.$setitem(mp,attr,value);switch(attr){case"__init__":case"__new__":kls.$factory=$B.$instance_creator(kls);break;case"__bases__":kls.__mro__=_b_.type.mro(kls);break;case"__setattr__":var initial_value=kls.$tp_setattr;kls.$tp_setattr=value;update_subclasses(kls,"__setattr__","$tp_setattr",value);break}if($test){console.log("after setattr",kls)}return _b_.None};type.$mro=function(cls){if(cls===undefined){throw _b_.TypeError.$factory("unbound method type.mro() needs an argument")}var bases=cls.__bases__,seqs=[],pos1=0;for(var base of bases){let bmro=[],pos=0;if(base===undefined||base.__mro__===undefined){if(base.__class__===undefined){return[_b_.object]}else{console.log("error for base",base);console.log("cls",cls)}}bmro[pos++]=base;var _tmp=base.__mro__;if(_tmp){if(_tmp[0]===base){_tmp.splice(0,1)}for(var k=0;k<_tmp.length;k++){bmro[pos++]=_tmp[k]}}seqs[pos1++]=bmro}seqs[pos1++]=bases.slice();var mro=[cls],mpos=1;while(1){let non_empty=[],pos=0;for(let i=0;i0){non_empty[pos++]=seqs[i]}}if(non_empty.length==0){break}let candidate;for(let i=0;i-1){not_head[pos++]=s}}if(not_head.length>0){candidate=null}else{break}}if(candidate===null){throw _b_.TypeError.$factory("inconsistent hierarchy, no C3 MRO is possible")}mro[mpos++]=candidate;for(let i=0;i-1};$B.set_func_names(type,"builtins");type.__init_subclass__=_b_.classmethod.$factory(type.__init_subclass__);_b_.type=type;var property=_b_.property=$B.make_class("property",(function(fget,fset,fdel,doc){var res={__class__:property};property.__init__(res,fget,fset,fdel,doc);return res}));property.__init__=function(){var $=$B.args("__init__",5,{self:null,fget:null,fset:null,fdel:null,doc:null},["self","fget","fset","fdel","doc"],arguments,{fget:_b_.None,fset:_b_.None,fdel:_b_.None,doc:_b_.None},null,null),self=$.self,fget=$.fget,fset=$.fset,fdel=$.fdel,doc=$.doc;self.__doc__=doc;if($B.$getattr&&doc===_b_.None){self.__doc__=$B.$getattr(fget,"__doc__",doc)}self.$type=fget.$type;self.fget=fget;self.fset=fset;self.fdel=fdel;self.$is_property=true;if(fget&&fget.$attrs){for(var key in fget.$attrs){self[key]=fget.$attrs[key]}}self.__delete__=fdel;self.getter=function(fget){return property.$factory(fget,self.fset,self.fdel,self.__doc__)};self.setter=function(fset){return property.$factory(self.fget,fset,self.fdel,self.__doc__)};self.deleter=function(fdel){return property.$factory(self.fget,self.fset,fdel,self.__doc__)}};property.__get__=function(self,kls){if(self.fget===undefined){throw _b_.AttributeError.$factory("unreadable attribute")}return $B.$call(self.fget)(kls)};property.__new__=function(cls){return{__class__:cls}};property.__set__=function(self,obj,value){if(self.fset===undefined){var name=self.fget.$infos.__name__;var msg=`property '${name}' of '${$B.class_name(obj)}' object `+"has no setter";throw _b_.AttributeError.$factory(msg)}$B.$getattr(self.fset,"__call__")(obj,value)};$B.set_func_names(property,"builtins");var wrapper_descriptor=$B.wrapper_descriptor=$B.make_class("wrapper_descriptor");wrapper_descriptor.__text_signature__={__get__:function(){return"(self, /, *args, **kwargs)"}};$B.set_func_names(wrapper_descriptor,"builtins");type.__call__.__class__=wrapper_descriptor;$B.$instance_creator=function(klass){var test=false;if(test){console.log("instance creator of",klass)}if(klass.prototype&&klass.prototype.constructor==klass){return function(){return new klass(...arguments)}}if(klass.__abstractmethods__&&$B.$bool(klass.__abstractmethods__)){return function(){var ams=Array.from($B.make_js_iterator(klass.__abstractmethods__));ams.sort();var msg=(ams.length>1?"s ":" ")+ams.join(", ");throw _b_.TypeError.$factory("Can't instantiate abstract class interface "+"with abstract method"+msg)}}var metaclass=klass.__class__||$B.get_class(klass),call_func,factory;if(metaclass===_b_.type){var new_func=type.__getattribute__(klass,"__new__"),init_func=type.__getattribute__(klass,"__init__");if(init_func===_b_.object.__init__){if(new_func===_b_.object.__new__){factory=_b_.object.$new(klass)}else{factory=new_func.bind(null,klass)}}else if(new_func===_b_.object.__new__){factory=type.$call_no_new_init(klass,init_func)}else{factory=type.$call(klass,new_func,init_func)}}else{call_func=_b_.type.__getattribute__(metaclass,"__call__");if(call_func.$is_class){factory=$B.$call(call_func)}else{factory=call_func.bind(null,klass)}}factory.__class__=$B.function;factory.$infos={__name__:klass.__name__,__module__:klass.__module__};return factory};var method_wrapper=$B.method_wrapper=$B.make_class("method_wrapper",(function(attr,klass,method){var f=function(){return method.apply(null,arguments)};f.$infos={__name__:attr,__module__:klass.__module__};return f}));method_wrapper.__str__=method_wrapper.__repr__=function(self){return""};var member_descriptor=$B.member_descriptor=$B.make_class("member_descriptor",(function(attr,cls){return{__class__:member_descriptor,cls:cls,attr:attr}}));member_descriptor.__delete__=function(self,kls){if(kls.$slot_values===undefined||!kls.$slot_values.hasOwnProperty(self.attr)){throw _b_.AttributeError.$factory(self.attr)}kls.$slot_values.delete(self.attr)};member_descriptor.__get__=function(self,kls){if(kls===_b_.None){return self}if(kls.$slot_values===undefined||!kls.$slot_values.has(self.attr)){throw $B.attr_error(self.attr,kls)}return kls.$slot_values.get(self.attr)};member_descriptor.__set__=function(self,kls,value){if(kls.$slot_values===undefined){kls.$slot_values=new Map}kls.$slot_values.set(self.attr,value)};member_descriptor.__str__=member_descriptor.__repr__=function(self){return""};$B.set_func_names(member_descriptor,"builtins");var method=$B.method=$B.make_class("method",(function(func,cls){var f=function(){return $B.$call(func).bind(null,cls).apply(null,arguments)};f.__class__=method;if(typeof func!=="function"){console.log("method from func w-o $infos",func,"all",$B.$call(func))}f.$infos=func.$infos||{};f.$infos.__func__=func;f.$infos.__self__=cls;f.$infos.__dict__=$B.empty_dict();return f}));method.__eq__=function(self,other){return self.$infos!==undefined&&other.$infos!==undefined&&self.$infos.__func__===other.$infos.__func__&&self.$infos.__self__===other.$infos.__self__};method.__ne__=function(self,other){return!$B.method.__eq__(self,other)};method.__get__=function(self){var f=function(){return self(...arguments)};f.__class__=$B.method_wrapper;f.$infos=method.$infos;return f};method.__getattribute__=function(self,attr){var infos=self.$infos;if(infos&&infos[attr]){if(attr=="__code__"){var res={__class__:$B.Code};for(var key in infos.__code__){res[key]=infos.__code__[key]}return res}else{return infos[attr]}}else if(method.hasOwnProperty(attr)){return _b_.object.__getattribute__(self,attr)}else{return $B.function.__getattribute__(self.$infos.__func__,attr)}};method.__repr__=method.__str__=function(self){return""};method.__setattr__=function(self,key){if(key=="__class__"){throw _b_.TypeError.$factory("__class__ assignment only supported "+"for heap types or ModuleType subclasses")}throw $B.attr_error(key,self)};$B.set_func_names(method,"builtins");$B.method_descriptor=$B.make_class("method_descriptor");$B.classmethod_descriptor=$B.make_class("classmethod_descriptor");_b_.object.__class__=type;$B.make_iterator_class=function(name){var klass={__class__:_b_.type,__mro__:[_b_.object],__name__:name,__qualname__:name,$factory:function(items){return{__class__:klass,__dict__:$B.empty_dict(),counter:-1,items:items,len:items.length,$builtin_iterator:true}},$is_class:true,$iterator_class:true,__iter__:function(self){self.counter=self.counter===undefined?-1:self.counter;self.len=self.items.length;return self},__len__:function(self){return self.items.length},__next__:function(self){if(typeof self.test_change=="function"){var message=self.test_change();if(message){throw _b_.RuntimeError.$factory(message)}}self.counter++;if(self.counter$B.fast_tuple(self.items)));$B.GenericAlias.__call__=function(self,...args){return self.origin_class.$factory.apply(null,args)};$B.GenericAlias.__eq__=function(self,other){if(!$B.$isinstance(other,$B.GenericAlias)){return false}return $B.rich_comp("__eq__",self.origin_class,other.origin_class)&&$B.rich_comp("__eq__",self.items,other.items)};$B.GenericAlias.__getitem__=function(self,item){throw _b_.TypeError.$factory("descriptor '__getitem__' for '"+self.origin_class.__name__+"' objects doesn't apply to a '"+$B.class_name(item)+"' object")};$B.GenericAlias.__mro_entries__=function(self){return $B.fast_tuple([self.origin_class])};$B.GenericAlias.__new__=function(origin_class,items){var res={__class__:$B.GenericAlias,__mro__:[origin_class],origin_class:origin_class,items:items,$is_class:true};return res};$B.GenericAlias.__or__=function(){var $=$B.args("__or__",2,{self:null,other:null},["self","other"],arguments,{},null,null);return $B.UnionType.$factory([$.self,$.other])};$B.GenericAlias.__origin__=_b_.property.$factory((self=>self.origin_class));$B.GenericAlias.__parameters__=_b_.property.$factory((function(){return $B.fast_tuple([])}));$B.GenericAlias.__repr__=function(self){var items=Array.isArray(self.items)?self.items:[self.items];var reprs=[];for(var item of items){if(item===_b_.Ellipsis){reprs.push("...")}else{if(item.$is_class){reprs.push(item.__name__)}else{reprs.push(_b_.repr(item))}}}var iv=$B.$getattr(self.origin_class,"__infer_variance__",true);var prefix=iv?"":"~";return prefix+$B.$getattr(self.origin_class,"__qualname__")+"["+reprs.join(", ")+"]"};$B.GenericAlias.__type_params__=_b_.property.$factory((function(self){return $B.$getattr(self.origin_class,"__type_params__")}));$B.set_func_names($B.GenericAlias,"types");$B.UnionType=$B.make_class("UnionType",(function(items){return{__class__:$B.UnionType,items:items}}));$B.UnionType.__args__=_b_.property.$factory((self=>$B.fast_tuple(self.items)));$B.UnionType.__eq__=function(self,other){if(!$B.$isinstance(other,$B.UnionType)){return _b_.NotImplemented}return _b_.list.__eq__(self.items,other.items)};$B.UnionType.__or__=function(self,other){var items=self.items.slice();if(!items.includes(other)){items.push(other)}return $B.UnionType.$factory(items)};$B.UnionType.__parameters__=_b_.property.$factory((()=>$B.fast_tuple([])));$B.UnionType.__repr__=function(self){var t=[];for(var item of self.items){if(item.$is_class){var s=item.__name__;if(item.__module__!=="builtins"){s=item.__module__+"."+s}t.push(s)}else{t.push(_b_.repr(item))}}return t.join(" | ")};$B.set_func_names($B.UnionType,"types")})(__BRYTHON__);(function($B){var _b_=$B.builtins;_b_.__debug__=false;$B.$comps={">":"gt",">=":"ge","<":"lt","<=":"le"};$B.$inv_comps={">":"lt",">=":"le","<":"gt","<=":"ge"};var check_nb_args=$B.check_nb_args,check_no_kw=$B.check_no_kw,check_nb_args_no_kw=$B.check_nb_args_no_kw;var NoneType=$B.NoneType={$factory:function(){return None},__bool__:function(){return False},__class__:_b_.type,__hash__:function(){return 0},__module__:"builtins",__mro__:[_b_.object],__name__:"NoneType",__qualname__:"NoneType",__repr__:function(){return"None"},__str__:function(){return"None"},$is_class:true};NoneType.__setattr__=function(self,attr){return no_set_attr(NoneType,attr)};var None=_b_.None={__class__:NoneType};None.__doc__=None;NoneType.__doc__=None;for(var $op in $B.$comps){var key=$B.$comps[$op];switch(key){case"ge":case"gt":case"le":case"lt":NoneType["__"+key+"__"]=function(){return function(){return _b_.NotImplemented}}($op)}}for(var $func in None){if(typeof None[$func]=="function"){None[$func].__str__=function(f){return function(){return""}}($func)}}$B.set_func_names(NoneType,"builtins");_b_.__build_class__=function(){throw _b_.NotImplementedError.$factory("__build_class__")};_b_.abs=function(obj){check_nb_args_no_kw("abs",1,arguments);var klass=obj.__class__||$B.get_class(obj);try{var method=$B.$getattr(klass,"__abs__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("Bad operand type for abs(): '"+$B.class_name(obj)+"'")}throw err}return $B.$call(method)(obj)};_b_.aiter=function(async_iterable){return $B.$call($B.$getattr(async_iterable,"__aiter__"))()};_b_.all=function(obj){check_nb_args_no_kw("all",1,arguments);var iterable=iter(obj);while(1){try{var elt=next(iterable);if(!$B.$bool(elt)){return false}}catch(err){return true}}};_b_.anext=function(){var missing={},$=$B.args("anext",2,{async_iterator:null,_default:null},["async_iterator","_default"],arguments,{_default:missing},null,null);var awaitable=$B.$call($B.$getattr($.async_iterator,"__anext__"))();return awaitable.catch((function(err){if($B.is_exc(err,[_b_.StopAsyncIteration])){if($._default!==missing){return $._default}}throw err}))};_b_.any=function(obj){check_nb_args_no_kw("any",1,arguments);for(var elt of $B.make_js_iterator(obj)){if($B.$bool(elt)){return true}}return false};_b_.ascii=function(obj){check_nb_args_no_kw("ascii",1,arguments);var res=repr(obj),res1="",cp;for(var i=0;i=0){return prefix+value.toString(base)}return"-"+prefix+(-value).toString(base)}function bin_hex_oct(base,obj){if($B.$isinstance(obj,_b_.int)){return $builtin_base_convert_helper(obj,base)}else{try{var klass=obj.__class__||$B.get_class(obj),method=$B.$getattr(klass,"__index__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object cannot be interpreted as an integer")}throw err}var res=$B.$call(method)(obj);return $builtin_base_convert_helper(res,base)}}_b_.bin=function(obj){check_nb_args_no_kw("bin",1,arguments);return bin_hex_oct(2,obj)};_b_.breakpoint=function(){$B.$import("sys",[]);var missing={},hook=$B.$getattr($B.imported.sys,"breakpointhook",missing);if(hook===missing){throw _b_.RuntimeError.$factory("lost sys.breakpointhook")}return $B.$call(hook).apply(null,arguments)};_b_.callable=function(obj){check_nb_args_no_kw("callable",1,arguments);return _b_.hasattr(obj,"__call__")};_b_.chr=function(i){check_nb_args_no_kw("chr",1,arguments);i=$B.PyNumber_Index(i);if(i<0||i>1114111){throw _b_.ValueError.$factory("Outside valid range")}else if(i>=65536&&i<=1114111){var code=i-65536,s=String.fromCodePoint(55296|code>>10)+String.fromCodePoint(56320|code&1023);return $B.make_String(s,[0])}else{return String.fromCodePoint(i)}};var code=_b_.code=$B.make_class("code");code.__repr__=code.__str__=function(_self){return``};code.__getattribute__=function(self,attr){if(attr=="co_positions"){return()=>$B.$list([$B.$list([0,0,0,0])])}return self[attr]};$B.set_func_names(code,"builtins");_b_.compile=function(){var $=$B.args("compile",7,{source:null,filename:null,mode:null,flags:null,dont_inherit:null,optimize:null,_feature_version:null},["source","filename","mode","flags","dont_inherit","optimize","_feature_version"],arguments,{flags:0,dont_inherit:false,optimize:-1,_feature_version:0},null,null);var module_name="$exec_"+$B.UUID();$.__class__=code;$.co_flags=$.flags;$.co_name="";var filename=$.co_filename=$.filename;var interactive=$.mode=="single"&&$.flags&512;$B.file_cache[filename]=$.source;$B.url2name[filename]=module_name;if($.flags&$B.PyCF_TYPE_COMMENTS){}if($B.$isinstance($.source,_b_.bytes)){var encoding="utf-8",lfpos=$.source.source.indexOf(10),first_line,second_line;if(lfpos==-1){first_line=$.source}else{first_line=_b_.bytes.$factory($.source.source.slice(0,lfpos))}first_line=_b_.bytes.decode(first_line,"latin-1");var encoding_re=/^[\t\f]*#.*?coding[:=][\t]*([-_.a-zA-Z0-9]+)/;var mo=first_line.match(encoding_re);if(mo){encoding=mo[1]}else if(lfpos>-1){var rest=$.source.source.slice(lfpos+1);lfpos=rest.indexOf(10);if(lfpos>-1){second_line=_b_.bytes.$factory(rest.slice(0,lfpos))}else{second_line=_b_.bytes.$factory(rest)}second_line=_b_.bytes.decode(second_line,"latin-1");mo=second_line.match(encoding_re);if(mo){encoding=mo[1]}}$.source=_b_.bytes.decode($.source,encoding)}if(!$B.$isinstance(filename,[_b_.bytes,_b_.str])){$B.warn(_b_.DeprecationWarning,`path should be string, bytes, or os.PathLike, `+`not ${$B.class_name(filename)}`)}if(interactive&&!$.source.endsWith("\n")){var lines=$.source.split("\n"),last_line=$B.last(lines);if(last_line.startsWith(" ")){var msg="unexpected EOF while parsing",exc=_b_.SyntaxError.$factory();exc.filename=filename;exc.lineno=exc.end_lineno=lines.length-1;exc.offset=0;exc.end_offset=last_line.length-1;exc.text=last_line;exc.args=[msg,$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset])];throw exc}}if($.source.__class__&&$.source.__class__.__module__=="ast"){$B.imported._ast._validate($.source);$._ast=$.source;delete $.source;return $}var _ast,parser;try{var parser_mode=$.mode=="eval"?"eval":"file";parser=new $B.Parser($.source,filename,parser_mode);parser.flags=$.flags;_ast=$B._PyPegen.run_parser(parser)}catch(err){if($.mode=="single"){var tester=parser.tokens[parser.tokens.length-2];if(tester&&(tester.type=="NEWLINE"&&$.flags&$B.PyCF_ALLOW_INCOMPLETE_INPUT||tester.type=="DEDENT"&&$.flags&512)){err.__class__=_b_._IncompleteInputError;err.args[0]="incomplete input"}}throw err}if($.mode=="single"&&_ast.body.length==1&&_ast.body[0]instanceof $B.ast.Expr){parser=new $B.Parser($.source,filename,"eval");_ast=$B._PyPegen.run_parser(parser);$.single_expression=true}if($.flags==$B.PyCF_ONLY_AST){delete $B.url2name[filename];let res=$B.ast_js_to_py(_ast);res.$js_ast=_ast;return res}delete $B.url2name[filename];$._ast=$B.ast_js_to_py(_ast);$._ast.$js_ast=_ast;var future=$B.future_features(_ast,filename);var symtable=$B._PySymtable_Build(_ast,filename,future);$B.js_from_root({ast:_ast,symtable:symtable,filename:filename,src:$.source});return $};_b_.debug=$B.debug>0;_b_.delattr=function(obj,attr){check_nb_args_no_kw("delattr",2,arguments);if(typeof attr!="string"){throw _b_.TypeError.$factory("attribute name must be string, not '"+$B.class_name(attr)+"'")}return $B.$getattr(obj,"__delattr__")(attr)};$B.$delete=function(name,is_global){function del(obj){if(obj.__class__===$B.generator){obj.js_gen.return()}}var found=false,frame=$B.frame_obj.frame;if(!is_global){if(frame[1][name]!==undefined){found=true;del(frame[1][name]);delete frame[1][name]}}else{if(frame[2]!=frame[0]&&frame[3][name]!==undefined){found=true;del(frame[3][name]);delete frame[3][name]}}if(!found){throw $B.name_error(name)}};_b_.dir=function(obj){if(obj===undefined){var locals=_b_.locals();return _b_.sorted(locals)}check_nb_args_no_kw("dir",1,arguments);var klass=obj.__class__||$B.get_class(obj);if(obj.$is_class){var dir_func=$B.$getattr(obj.__class__,"__dir__");return $B.$call(dir_func)(obj)}try{let res=$B.$call($B.$getattr(klass,"__dir__"))(obj);res=_b_.list.$factory(res);return res}catch(err){if($B.get_option("debug")>2){console.log("error in dir, obj",obj,"klass",klass,$B.$getattr(klass,"__dir__"),err.message)}throw err}};_b_.divmod=function(x,y){check_nb_args_no_kw("divmod",2,arguments);try{return $B.rich_op("__divmod__",x,y)}catch(err){if($B.is_exc(err,[_b_.TypeError])){return _b_.tuple.$factory([$B.rich_op("__floordiv__",x,y),$B.rich_op("__mod__",x,y)])}throw err}};var enumerate=_b_.enumerate=$B.make_class("enumerate",(function(){var $ns=$B.args("enumerate",2,{iterable:null,start:null},["iterable","start"],arguments,{start:0},null,null),_iter=iter($ns["iterable"]),start=$ns["start"];return{__class__:enumerate,__name__:"enumerate iterator",counter:start-1,iter:_iter,start:start}}));enumerate.__class_getitem__=$B.$class_getitem;enumerate.__iter__=function(self){self.counter=self.start-1;return self};enumerate.__next__=function(self){self.counter++;return $B.fast_tuple([self.counter,next(self.iter)])};$B.set_func_names(enumerate,"builtins");$B.LOCALS_PROXY=Symbol("locals_proxy");enumerate.__class_getitem__=_b_.classmethod.$factory(enumerate.__class_getitem__);var $$eval=_b_.eval=function(){var $=$B.args("eval",4,{src:null,globals:null,locals:null,mode:null},["src","globals","locals","mode"],arguments,{globals:_b_.None,locals:_b_.None,mode:"eval"},null,null,4),src=$.src,_globals=$.globals,_locals=$.locals,mode=$.mode;if($.src.mode&&$.src.mode=="single"&&["",""].indexOf($.src.filename)>-1){_b_.print(">",$.src.source.trim())}var filename="";if(src.__class__===code){filename=src.filename}else if(!src.valueOf||typeof src.valueOf()!=="string"){throw _b_.TypeError.$factory(`${mode}() arg 1 must be a string,`+" bytes or code object")}else{src=src.valueOf()}var __name__="exec";if(_globals!==_b_.None&&_globals.__class__==_b_.dict&&_b_.dict.$contains_string(_globals,"__name__")){__name__=_b_.dict.$getitem_string(_globals,"__name__")}$B.url2name[filename]=__name__;var frame=$B.frame_obj.frame;$B.exec_scope=$B.exec_scope||{};if(typeof src=="string"&&src.endsWith("\\\n")){var exc=_b_.SyntaxError.$factory("unexpected EOF while parsing");var lines=src.split("\n"),line=lines[lines.length-2];exc.args=["unexpected EOF while parsing",[filename,lines.length-1,1,line]];exc.filename=filename;exc.text=line;throw exc}var local_name=("locals_"+__name__).replace(/\./g,"_"),global_name=("globals_"+__name__).replace(/\./g,"_"),exec_locals={},exec_globals={};if(_globals===_b_.None){if(frame[1]===frame[3]){global_name+="_globals";exec_locals=exec_globals=frame[3]}else{if(mode=="exec"){exec_locals=$B.clone(frame[1]);for(var attr in frame[3]){exec_locals[attr]=frame[3][attr]}exec_globals=exec_locals}else{exec_locals=frame[1];exec_globals=frame[3]}}}else{if(_globals.__class__!==_b_.dict){throw _b_.TypeError.$factory(`${mode}() globals must be `+"a dict, not "+$B.class_name(_globals))}exec_globals={};if(_globals.$jsobj){exec_globals=_globals.$jsobj}else{exec_globals=_globals.$jsobj={};for(var key of _b_.dict.$keys_string(_globals)){_globals.$jsobj[key]=_b_.dict.$getitem_string(_globals,key);if(key=="__name__"){__name__=_globals.$jsobj[key]}}_globals.$all_str=false}if(exec_globals.__builtins__===undefined){exec_globals.__builtins__=_b_.__builtins__}if(_locals===_b_.None){exec_locals=exec_globals}else{if(_locals===_globals){global_name+="_globals";exec_locals=exec_globals}else if(_locals.$jsobj){for(let key in _locals.$jsobj){exec_globals[key]=_locals.$jsobj[key]}}else{if(_locals.$jsobj){exec_locals=_locals.$jsobj}else{var klass=$B.get_class(_locals),getitem=$B.$call($B.$getattr(klass,"__getitem__")),setitem=$B.$call($B.$getattr(klass,"__setitem__"));exec_locals=new Proxy(_locals,{get(target,prop){if(prop=="$target"){return target}else if(prop==$B.LOCALS_PROXY){return true}try{return getitem(target,prop)}catch(err){return undefined}},set(target,prop,value){return setitem(target,prop,value)}})}}}}var save_frame_obj=$B.frame_obj;var _ast;frame=[__name__,exec_locals,__name__,exec_globals];frame.is_exec_top=true;$B.enter_frame(frame,filename,1);var _frame_obj=$B.frame_obj;if(src.__class__===code){_ast=src._ast;if(_ast.$js_ast){_ast=_ast.$js_ast}else{_ast=$B.ast_py_to_js(_ast)}}try{if(!_ast){var _mode=mode=="eval"?"eval":"file";var parser=new $B.Parser(src,filename,_mode);_ast=$B._PyPegen.run_parser(parser)}var future=$B.future_features(_ast,filename),symtable=$B._PySymtable_Build(_ast,filename,future),js_obj=$B.js_from_root({ast:_ast,symtable:symtable,filename:filename,src:src,namespaces:{local_name:local_name,exec_locals:exec_locals,global_name:global_name,exec_globals:exec_globals}}),js=js_obj.js}catch(err){if(err.args){if(err.args[1]){exec_locals.$lineno=err.args[1][1]}}else{console.log("JS Error",err.message)}$B.frame_obj=save_frame_obj;throw err}if(mode=="eval"){js=`var __file__ = '${filename}'\n`+`var locals = ${local_name}\nreturn ${js}`}else if(src.single_expression){js=`var __file__ = '${filename}'\n`+`var result = ${js}\n`+`if(result !== _b_.None){\n`+`_b_.print(result)\n`+`}`}try{var exec_func=new Function("$B","_b_",local_name,global_name,"frame","_frame_obj",js)}catch(err){if($B.get_option("debug")>1){console.log("eval() error\n",$B.format_indent(js,0));console.log("-- python source\n",src)}$B.frame_obj=save_frame_obj;throw err}try{var res=exec_func($B,_b_,exec_locals,exec_globals,frame,_frame_obj)}catch(err){if($B.get_option("debug")>2){console.log("Python code\n",src,"\nexec func",$B.format_indent(exec_func+"",0),"\n filename",filename,"\n name from filename",$B.url2name[filename],"\n local_name",local_name,"\n exec_locals",exec_locals,"\n global_name",global_name,"\n exec_globals",exec_globals,"\n frame",frame,"\n _ast",_ast,"\n js",js,"\n err",err.__class__,err.args,err.$frame_obj)}$B.frame_obj=save_frame_obj;throw err}if(_globals!==_b_.None&&!_globals.$jsobj){for(var _key in exec_globals){if(!_key.startsWith("$")){_b_.dict.$setitem(_globals,_key,exec_globals[_key])}}}$B.frame_obj=save_frame_obj;return res};$$eval.$is_func=true;var exec=_b_.exec=function(){var $=$B.args("exec",3,{src:null,globals:null,locals:null},["src","globals","locals"],arguments,{globals:_b_.None,locals:_b_.None},null,null,1),src=$.src,globals=$.globals,locals=$.locals;$$eval(src,globals,locals,"exec");return _b_.None};exec.$is_func=true;var exit=_b_.exit=function(){throw _b_.SystemExit};exit.__repr__=exit.__str__=function(){return"Use exit() or Ctrl-Z plus Return to exit"};var filter=_b_.filter=$B.make_class("filter",(function(func,iterable){check_nb_args_no_kw("filter",2,arguments);iterable=iter(iterable);if(func===_b_.None){func=$B.$bool}return{__class__:filter,func:func,iterable:iterable}}));filter.__iter__=function(self){return self};filter.__next__=function(self){while(true){var _item=next(self.iterable);if(self.func(_item)){return _item}}};$B.set_func_names(filter,"builtins");_b_.format=function(){var $=$B.args("format",2,{value:null,format_spec:null},["value","format_spec"],arguments,{format_spec:""},null,null),value=$.value;var klass=value.__class__||$B.get_class(value);try{var method=$B.$getattr(klass,"__format__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.NotImplementedError("__format__ is not implemented "+"for object '"+_b_.str.$factory(value)+"'")}throw err}return $B.$call(method)(value,$.format_spec)};function attr_error(attr,obj){var cname=$B.get_class(obj);var msg="bad operand type for unary #: '"+cname+"'";switch(attr){case"__neg__":throw _b_.TypeError.$factory(msg.replace("#","-"));case"__pos__":throw _b_.TypeError.$factory(msg.replace("#","+"));case"__invert__":throw _b_.TypeError.$factory(msg.replace("#","~"));case"__call__":throw _b_.TypeError.$factory("'"+cname+"'"+" object is not callable");default:throw $B.attr_error(attr,obj)}}_b_.getattr=function(){var missing={};var $=$B.args("getattr",3,{obj:null,attr:null,_default:null},["obj","attr","_default"],arguments,{_default:missing},null,null);if(!$B.$isinstance($.attr,_b_.str)){throw _b_.TypeError.$factory("attribute name must be string, "+`not '${$B.class_name($.attr)}'`)}return $B.$getattr($.obj,_b_.str.$to_string($.attr),$._default===missing?undefined:$._default)};$B.search_in_mro=function(klass,attr){if(klass.hasOwnProperty(attr)){return klass[attr]}var mro=klass.__mro__;for(var i=0,len=mro.length;i-1}))}break;case"__mro__":if(obj.__mro__){return _b_.tuple.$factory([obj].concat(obj.__mro__))}else if(obj.__dict__&&_b_.dict.$contains_string(obj.__dict__,"__mro__")){return _b_.dict.$getitem_string(obj.__dict__,"__mro__")}throw $B.attr_error(attr,obj);case"__subclasses__":if(klass.$factory||klass.$is_class){var subclasses=obj.$subclasses||[];return function(){return $B.$list(subclasses)}}break}if(typeof obj=="function"){var value=obj[attr];if(value!==undefined){if(attr=="__module__"){return value}}}if(!is_class&&klass.$native){if(obj.$method_cache&&obj.$method_cache[attr]){return obj.$method_cache[attr]}if($test){console.log("native class",klass,klass[attr])}if(klass[attr]===undefined){var object_attr=_b_.object[attr];if($test){console.log("object attr",object_attr)}if(object_attr!==undefined){klass[attr]=object_attr}else{if($test){console.log("obj[attr]",obj[attr])}var attrs=obj.__dict__;if(attrs&&_b_.dict.$contains_string(attrs,attr)){return _b_.dict.$getitem_string(attrs,attr)}if(_default===undefined){throw $B.attr_error(attr,obj)}return _default}}else if(["__name__","__qualname__"].includes(attr)){attr_error(attr,obj)}if(klass.$descriptors&&klass.$descriptors[attr]!==undefined){return klass[attr](obj)}if(typeof klass[attr]=="function"){var func=klass[attr];if(attr=="__new__"){func.$type="staticmethod"}if(func.$type=="staticmethod"){return func}var self=klass[attr].__class__==$B.method?klass:obj,method=klass[attr].bind(null,self);method.__class__=$B.method;method.$infos={__func__:func,__name__:attr,__self__:self,__qualname__:klass.__qualname__+"."+attr};if(typeof obj=="object"){obj.__class__=klass;obj.$method_cache=obj.$method_cache||{};if(obj.$method_cache){obj.$method_cache[attr]=method}}return method}else if(klass[attr].__class__===_b_.classmethod){return _b_.classmethod.__get__(klass[attr],obj,klass)}else if(klass[attr]!==undefined){return klass[attr]}attr_error(rawname,klass)}var attr_func;if(is_class){if($test){console.log("obj is class",obj);console.log("is a type ?",_b_.isinstance(klass,_b_.type));console.log("is type",klass===_b_.type)}if(klass===_b_.type){attr_func=_b_.type.__getattribute__}else{attr_func=$B.$call($B.$getattr(klass,"__getattribute__"))}if($test){console.log("attr func",attr_func)}}else{attr_func=klass.__getattribute__;if(attr_func===undefined){for(var cls of klass.__mro__){attr_func=cls["__getattribute__"];if(attr_func!==undefined){break}}}if($test){console.log("attr func",attr_func)}}if(typeof attr_func!=="function"){console.log(attr+" is not a function "+attr_func,klass)}var odga=_b_.object.__getattribute__;if($test){console.log("attr_func is odga ?",attr_func,attr_func===odga,"\n","\nobj[attr]",obj[attr])}if(attr_func===odga){res=obj[attr];if(Array.isArray(obj)&&Array.prototype[attr]!==undefined){res=undefined}else if(res===null){return null}else if(res!==undefined){if($test){console.log(obj,attr,obj[attr],res.__set__||res.$is_class)}if(res.$is_property){return _b_.property.__get__(res)}if(res.__set__===undefined||res.$is_class){if($test){console.log("return",res,res+"",res.__set__,res.$is_class)}return res}}}var getattr;try{res=attr_func(obj,attr);if($test){console.log("result of attr_func",res)}}catch(err){if($test){console.log("attr_func raised error",err.__class__,err.args,err.name)}if(klass===$B.module){getattr=obj.__getattr__;if($test){console.log("use module getattr",getattr);console.log(getattr+"")}if(getattr){try{return getattr(attr)}catch(err){if($test){console.log("encore erreur",err)}if(_default!==undefined){return _default}throw err}}}getattr=$B.search_in_mro(klass,"__getattr__");if($test){console.log("try getattr",getattr)}if(getattr){if($test){console.log("try with getattr",getattr)}try{return getattr(obj,attr)}catch(err){if(_default!==undefined){return _default}throw err}}if(_default!==undefined){return _default}throw err}if(res!==undefined){return res}if(_default!==undefined){return _default}attr_error(rawname,is_class?obj:klass)};_b_.globals=function(){check_nb_args_no_kw("globals",0,arguments);var res=$B.obj_dict($B.frame_obj.frame[3]);res.$jsobj.__BRYTHON__=$B.jsobj2pyobj($B);res.$is_namespace=true;return res};_b_.hasattr=function(obj,attr){check_nb_args_no_kw("hasattr",2,arguments);try{$B.$getattr(obj,attr);return true}catch(err){return false}};_b_.hash=function(obj){check_nb_args_no_kw("hash",1,arguments);return $B.$hash(obj)};$B.$hash=function(obj){if(obj.__hashvalue__!==undefined){return obj.__hashvalue__}if(typeof obj==="boolean"){return obj?1:0}if(obj.$is_class||obj.__class__===_b_.type||obj.__class__===$B.function){return obj.__hashvalue__=$B.$py_next_hash--}if(typeof obj=="string"){return _b_.str.__hash__(obj)}else if(typeof obj=="number"){return obj}else if(typeof obj=="boolean"){return obj?1:0}else if(obj.__class__===_b_.float){return _b_.float.$hash_func(obj)}var klass=obj.__class__||$B.get_class(obj);if(klass===undefined){throw _b_.TypeError.$factory("unhashable type: '"+_b_.str.$factory($B.jsobj2pyobj(obj))+"'")}var hash_method=_b_.type.__getattribute__(klass,"__hash__",_b_.None);if(hash_method===_b_.None){throw _b_.TypeError.$factory("unhashable type: '"+$B.class_name(obj)+"'")}function check_int(v){if(!Number.isInteger(v)&&!$B.$isinstance(v,_b_.int)){throw _b_.TypeError.$factory("__hash__ method should return an integer")}return v}var res;if(hash_method.$infos.__func__===_b_.object.__hash__){if(_b_.type.__getattribute__(klass,"__eq__")!==_b_.object.__eq__){throw _b_.TypeError.$factory("unhashable type: '"+$B.class_name(obj)+"'","hash")}else{return obj.__hashvalue__=check_int(_b_.object.__hash__(obj))}}else{return check_int($B.$call(hash_method)(obj))}};var help=_b_.help=function(obj){if(obj===undefined){obj="help"}if(typeof obj=="string"){var lib_url="https://docs.python.org/3/library";var parts=obj.split("."),head=[],url;while(parts.length>0){head.push(parts.shift());if($B.stdlib[head.join(".")]){url=head.join(".")}else{break}}if(url){var doc_url;if(["browser","javascript","interpreter"].indexOf(obj.split(".")[0])>-1){doc_url="/static_doc/"+($B.language=="fr"?"fr":"en")}else{doc_url=lib_url}window.open(`${doc_url}/${url}.html#`+obj);return}if(_b_[obj]){if(obj==obj.toLowerCase()){url=lib_url+`/functions.html#${obj}`}else if(["False","True","None","NotImplemented","Ellipsis","__debug__"].indexOf(obj)>-1){url=lib_url+`/constants.html#${obj}`}else if(_b_[obj].$is_class&&_b_[obj].__bases__.indexOf(_b_.Exception)>-1){url=lib_url+`/exceptions.html#${obj}`}if(url){window.open(url);return}}$B.$import("pydoc");return $B.$call($B.$getattr($B.imported.pydoc,"help"))(obj)}if(obj.__class__===$B.module){return help(obj.__name__)}try{_b_.print($B.$getattr(obj,"__doc__"))}catch(err){return""}};help.__repr__=help.__str__=function(){return"Type help() for interactive help, or help(object) "+"for help about object."};_b_.hex=function(obj){check_nb_args_no_kw("hex",1,arguments);return bin_hex_oct(16,obj)};_b_.id=function(obj){check_nb_args_no_kw("id",1,arguments);if(obj.$id!==undefined){return obj.$id}else if($B.$isinstance(obj,[_b_.str,_b_.int,_b_.float])&&!$B.$isinstance(obj,$B.long_int)){return $B.$getattr(_b_.str.$factory(obj),"__hash__")()}else{return obj.$id=$B.UUID()}};_b_.__import__=function(){var $=$B.args("__import__",5,{name:null,globals:null,locals:null,fromlist:null,level:null},["name","globals","locals","fromlist","level"],arguments,{globals:None,locals:None,fromlist:_b_.tuple.$factory(),level:0},null,null);return $B.$__import__($.name,$.globals,$.locals,$.fromlist)};_b_.input=function(msg){var res=prompt(msg||"")||"";if($B.imported["sys"]&&$B.imported["sys"].ps1){var ps1=$B.imported["sys"].ps1,ps2=$B.imported["sys"].ps2;if(msg==ps1||msg==ps2){console.log(msg,res)}}return res};_b_.isinstance=function(obj,cls){check_nb_args_no_kw("isinstance",2,arguments);return $B.$isinstance(obj,cls)};$B.$isinstance=function(obj,cls){if(obj===null){return cls===$B.imported.javascript.NullType}if(obj===undefined){return false}var kls;if(Array.isArray(cls)){for(kls of cls){if($B.$isinstance(obj,kls)){return true}}return false}if(cls.__class__===$B.UnionType){for(kls of cls.items){if($B.$isinstance(obj,kls)){return true}}return false}if(cls.__class__===$B.GenericAlias){throw _b_.TypeError.$factory("isinstance() arg 2 cannot be a parameterized generic")}if(!cls.__class__&&!cls.$is_class){if(!$B.$getattr(cls,"__instancecheck__",false)){throw _b_.TypeError.$factory("isinstance() arg 2 must be a type "+"or tuple of types")}}if(cls===_b_.int&&(obj===True||obj===False)){return true}if(cls===_b_.bool){switch(typeof obj){case"string":return false;case"number":return false;case"boolean":return true}}var klass=obj.__class__;if(klass==undefined){if(typeof obj=="string"){if(cls==_b_.str){return true}else if($B.builtin_classes.includes(cls)){return false}}else if(typeof obj=="number"&&Number.isFinite(obj)){if(Number.isFinite(obj)&&cls==_b_.int){return true}}klass=$B.get_class(obj)}if(klass===undefined){return false}if(klass===cls){return true}var mro=klass.__mro__;for(var i=0;i-1){return true}var sch=$B.$getattr(classinfo.__class__||$B.get_class(classinfo),"__subclasscheck__",_b_.None);if(sch==_b_.None){return false}return sch(classinfo,klass)};var iterator_class=$B.make_class("iterator",(function(getitem){return{__class__:iterator_class,getitem:getitem,counter:-1}}));iterator_class.__next__=function(self){self.counter++;try{return self.getitem(self.counter)}catch(err){throw _b_.StopIteration.$factory("")}};$B.set_func_names(iterator_class,"builtins");const callable_iterator=$B.make_class("callable_iterator",(function(func,sentinel){return{__class__:callable_iterator,func:func,sentinel:sentinel}}));callable_iterator.__iter__=function(self){return self};callable_iterator.__next__=function(self){var res=self.func();if($B.rich_comp("__eq__",res,self.sentinel)){throw _b_.StopIteration.$factory()}return res};$B.set_func_names(callable_iterator,"builtins");$B.$iter=function(obj,sentinel){if(sentinel===undefined){var klass=obj.__class__||$B.get_class(obj);try{var _iter=$B.$call($B.$getattr(klass,"__iter__"))}catch(err){if(err.__class__===_b_.AttributeError){try{var gi_method=$B.$call($B.$getattr(klass,"__getitem__")),gi=function(i){return gi_method(obj,i)},len;return iterator_class.$factory(gi)}catch(err){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object is not iterable")}}throw err}var res=$B.$call(_iter)(obj);try{$B.$getattr(res,"__next__")}catch(err){if($B.$isinstance(err,_b_.AttributeError)){throw _b_.TypeError.$factory("iter() returned non-iterator of type '"+$B.class_name(res)+"'")}}return res}else{return callable_iterator.$factory(obj,sentinel)}};var iter=_b_.iter=function(){var $=$B.args("iter",1,{obj:null},["obj"],arguments,{},"args","kw"),sentinel;if($.args.length>0){sentinel=$.args[0]}return $B.$iter($.obj,sentinel)};var len=_b_.len=function(obj){check_nb_args_no_kw("len",1,arguments);var klass=obj.__class__||$B.get_class(obj);try{var method=$B.$getattr(klass,"__len__")}catch(err){throw _b_.TypeError.$factory("object of type '"+$B.class_name(obj)+"' has no len()")}let res=$B.$call(method)(obj);if(!$B.$isinstance(res,_b_.int)){throw _b_.TypeError.$factory(`'${$B.class_name(res)}' object cannot be interpreted as an integer`)}if(!$B.rich_comp("__ge__",res,0)){throw _b_.ValueError.$factory("ValueError: __len__() should return >= 0")}return res};_b_.locals=function(){check_nb_args("locals",0,arguments);var locals_obj=$B.frame_obj.frame[1];var class_locals=locals_obj.$target;if(class_locals){return class_locals}var res=$B.obj_dict($B.clone(locals_obj),(function(key){return key.startsWith("$")}));res.$is_namespace=true;return res};var map=_b_.map=$B.make_class("map",(function(){var $=$B.args("map",2,{func:null,it1:null},["func","it1"],arguments,{},"args",null),func=$B.$call($.func);var iter_args=[$B.make_js_iterator($.it1)];for(var arg of $.args){iter_args.push($B.make_js_iterator(arg))}return{__class__:map,args:iter_args,func:func}}));map.__iter__=function(self){return self};map.__next__=function(self){var args=[];for(var iter of self.args){var arg=iter.next();if(arg.done){throw _b_.StopIteration.$factory("")}args.push(arg.value)}return self.func.apply(null,args)};$B.set_func_names(map,"builtins");function $extreme(args,op){var $op_name="min";if(op==="__gt__"){$op_name="max"}var $=$B.args($op_name,0,{},[],args,{},"args","kw");var has_default=false,func=false;for(var item of _b_.dict.$iter_items($.kw)){switch(item.key){case"key":func=item.value;func=func===_b_.None?func:$B.$call(func);break;case"default":var default_value=item.value;has_default=true;break;default:throw _b_.TypeError.$factory("'"+item.key+"' is an invalid keyword argument for this function")}}if(!func||func===_b_.None){func=x=>x}if($.args.length==0){throw _b_.TypeError.$factory($op_name+" expected 1 arguments, got 0")}else if($.args.length==1){var $iter=$B.make_js_iterator($.args[0]),res=null,x_value,extr_value;for(var x of $iter){if(res===null){extr_value=func(x);res=x}else{x_value=func(x);if($B.rich_comp(op,x_value,extr_value)){res=x;extr_value=x_value}}}if(res===null){if(has_default){return default_value}else{throw _b_.ValueError.$factory($op_name+"() arg is an empty sequence")}}else{return res}}else{if(has_default){throw _b_.TypeError.$factory("Cannot specify a default for "+$op_name+"() with multiple positional arguments")}var _args;if($B.last(args).$kw){_args=[$.args].concat($B.last(args))}else{_args=[$.args]}return $extreme.call(null,_args,op)}}_b_.max=function(){return $extreme(arguments,"__gt__")};var memoryview=_b_.memoryview=$B.make_class("memoryview",(function(obj){check_nb_args_no_kw("memoryview",1,arguments);if(obj.__class__===memoryview){return obj}if($B.get_class(obj).$buffer_protocol){return{__class__:memoryview,obj:obj,format:"B",itemsize:1,ndim:1,shape:_b_.tuple.$factory([_b_.len(obj)]),strides:_b_.tuple.$factory([1]),suboffsets:_b_.tuple.$factory([]),c_contiguous:true,f_contiguous:true,contiguous:true}}else{throw _b_.TypeError.$factory("memoryview: a bytes-like object "+"is required, not '"+$B.class_name(obj)+"'")}}));memoryview.$match_sequence_pattern=true,memoryview.$buffer_protocol=true;memoryview.$not_basetype=true;memoryview.__eq__=function(self,other){if(other.__class__!==memoryview){return false}return $B.$getattr(self.obj,"__eq__")(other.obj)};memoryview.__getitem__=function(self,key){var res;if($B.$isinstance(key,_b_.int)){var start=key*self.itemsize;if(self.format=="I"){res=self.obj.source[start];var coef=256;for(var i=1;i<4;i++){res+=self.obj.source[start+i]*coef;coef*=256}return res}else if("B".indexOf(self.format)>-1){if(key>self.obj.source.length-1){throw _b_.KeyError.$factory(key)}return self.obj.source[key]}else{return self.obj.source[key]}}res=self.obj.__class__.__getitem__(self.obj,key);if(key.__class__===_b_.slice){return memoryview.$factory(res)}};memoryview.__len__=function(self){return len(self.obj)/self.itemsize};memoryview.__setitem__=function(self,key,value){try{$B.$setitem(self.obj,key,value)}catch(err){throw _b_.TypeError.$factory("cannot modify read-only memory")}};memoryview.cast=function(self,format){switch(format){case"B":return memoryview.$factory(self.obj);case"I":var res=memoryview.$factory(self.obj),objlen=len(self.obj);res.itemsize=4;res.format="I";if(objlen%4!=0){throw _b_.TypeError.$factory("memoryview: length is not "+"a multiple of itemsize")}return res}};memoryview.hex=function(self){var res="",bytes=_b_.bytes.$factory(self);bytes.source.forEach((function(item){res+=item.toString(16)}));return res};memoryview.tobytes=function(self){return{__class__:_b_.bytes,source:self.obj.source}};memoryview.tolist=function(self){if(self.itemsize==1){return _b_.list.$factory(_b_.bytes.$factory(self.obj))}else if(self.itemsize==4){if(self.format=="I"){var res=[];for(var i=0;i=65536&&code<=131071||code>=131072&&code<=196607||code>=196608&&code<=262143||code>=851968&&code<=917503||code>=917504&&code<=1048575){return code}}throw _b_.TypeError.$factory("ord() expected a character, but "+"string of length "+c.length+" found")}switch($B.get_class(c)){case _b_.str:if(c.length==1){return c.charCodeAt(0)}throw _b_.TypeError.$factory("ord() expected a character, but "+"string of length "+c.length+" found");case _b_.bytes:case _b_.bytearray:if(c.source.length==1){return c.source[0]}throw _b_.TypeError.$factory("ord() expected a character, but "+"string of length "+c.source.length+" found");default:throw _b_.TypeError.$factory("ord() expected a character, but "+$B.class_name(c)+" was found")}};var complex_modulo=()=>_b_.ValueError.$factory("complex modulo");var all_ints=()=>_b_.TypeError.$factory("pow() 3rd argument not "+"allowed unless all arguments are integers");_b_.pow=function(){var $=$B.args("pow",3,{x:null,y:null,mod:null},["x","y","mod"],arguments,{mod:None},null,null),x=$.x,y=$.y,z=$.mod;if(z===_b_.None){return $B.rich_op("__pow__",x,y)}else{if($B.$isinstance(x,_b_.int)){if($B.$isinstance(y,_b_.float)){throw all_ints()}else if($B.$isinstance(y,_b_.complex)){throw complex_modulo()}else if($B.$isinstance(y,_b_.int)){if($B.$isinstance(z,_b_.complex)){throw complex_modulo()}else if(!$B.$isinstance(z,_b_.int)){throw all_ints()}}return _b_.int.__pow__(x,y,z)}else if($B.$isinstance(x,_b_.float)){throw all_ints()}else if($B.$isinstance(x,_b_.complex)){throw complex_modulo()}}};var $print=_b_.print=function(){var $ns=$B.args("print",0,{},[],arguments,{},"args","kw");var kw=$ns["kw"],end=_b_.dict.get(kw,"end","\n"),sep=_b_.dict.get(kw,"sep"," "),file=_b_.dict.get(kw,"file",$B.get_stdout());var args=$ns["args"],writer=$B.$getattr(file,"write");for(var i=0,len=args.length;i-1){has_slot=true;break}}}if(!has_slot){throw $B.attr_error(attr,klass)}}}if($test){console.log("attr",attr,"use _setattr",_setattr)}if(!_setattr){if(obj[attr]!==undefined){obj[attr]=value}else if(obj.__dict__===undefined){throw _b_.AttributeError.$factory(`'${$B.class_name(obj)}' `+`object has no attribute '${attr}' and no __dict__ for `+`setting new attributes`)}else{_b_.dict.$setitem(obj.__dict__,attr,value)}if($test){console.log("no setattr, obj",obj)}}else{if($test){console.log("apply _setattr",obj,attr)}_setattr(obj,attr,value)}return None};_b_.sorted=function(){var $=$B.args("sorted",1,{iterable:null},["iterable"],arguments,{},null,"kw");var _list=_b_.list.$factory($.iterable),args=[_list].concat(Array.from(arguments).slice(1));_b_.list.sort.apply(null,args);return _list};_b_.sum=function(){var $=$B.args("sum",2,{iterable:null,start:null},["iterable","start"],arguments,{start:0},null,null),iterable=$.iterable,start=$.start;if($B.$isinstance(start,[_b_.str,_b_.bytes])){throw _b_.TypeError.$factory("sum() can't sum bytes"+" [use b''.join(seq) instead]")}var res=start;iterable=iter(iterable);while(true){try{var _item=next(iterable);res=$B.rich_op("__add__",res,_item)}catch(err){if(err.__class__===_b_.StopIteration){break}else{throw err}}}return res};$B.missing_super2=function(obj){obj.$missing=true;return obj};var $$super=_b_.super=$B.make_class("super",(function(_type,object_or_type){var no_object_or_type=object_or_type===undefined;if(_type===undefined&&object_or_type===undefined){var frame=$B.frame_obj.frame,pyframe=$B.imported["_sys"]._getframe(),code=$B.frame.f_code.__get__(pyframe),co_varnames=code.co_varnames;if(co_varnames.length>0){_type=frame[1].__class__;if(_type===undefined){throw _b_.RuntimeError.$factory("super(): no arguments")}object_or_type=frame[1][code.co_varnames[0]]}else{throw _b_.RuntimeError.$factory("super(): no arguments")}}if(!no_object_or_type&&Array.isArray(object_or_type)){object_or_type=object_or_type[0]}var $arg2;if(object_or_type!==undefined){if(object_or_type===_type||object_or_type.$is_class&&_b_.issubclass(object_or_type,_type)){$arg2="type"}else if($B.$isinstance(object_or_type,_type)){$arg2="object"}else{throw _b_.TypeError.$factory("super(type, obj): obj must be an instance "+"or subtype of type")}}return{__class__:$$super,__thisclass__:_type,__self_class__:object_or_type,$arg2:$arg2}}));$$super.__get__=function(self,instance){return $$super.$factory(self.__thisclass__,instance)};$$super.__getattribute__=function(self,attr){if(self.__thisclass__.$is_js_class){if(attr=="__init__"){return function(){mro[0].$js_func.call(self.__self_class__,...arguments)}}}var object_or_type=self.__self_class__,mro=self.$arg2=="type"?object_or_type.__mro__:$B.get_class(object_or_type).__mro__;var search_start=mro.indexOf(self.__thisclass__)+1,search_classes=mro.slice(search_start);var $test=attr=="new";if($test){console.log("super.__ga__, self",self,"search classes",search_classes)}var f;for(var klass of search_classes){if(klass===undefined){console.log("klass undef in super",self);console.log("mro",mro)}if(klass[attr]!==undefined){f=klass[attr];break}}if(f===undefined){if($$super[attr]!==undefined){return function(x){return function(){var args=[x];for(var i=0,len=arguments.length;i";if(self.__self_class__!==undefined){res+=", <"+self.__self_class__.__class__.__name__+" object>"}else{res+=", NULL"}return res+">"};$B.set_func_names($$super,"builtins");_b_.vars=function(){var def={},$=$B.args("vars",1,{obj:null},["obj"],arguments,{obj:def},null,null);if($.obj===def){return _b_.locals()}else{try{return $B.$getattr($.obj,"__dict__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("vars() argument must have __dict__ attribute")}throw err}}};var $Reader=$B.make_class("Reader");$Reader.__bool__=function(){return true};$Reader.__enter__=function(self){return self};$Reader.__exit__=function(self){$Reader.close(self)};$Reader.__init__=function(_self,initial_value=""){_self.$content=initial_value;_self.$counter=0};$Reader.__iter__=function(self){return iter($Reader.readlines(self))};$Reader.__len__=function(self){return self.lines.length};$Reader.__new__=function(cls){return{__class__:cls}};$Reader.close=function(self){self.closed=true};$Reader.flush=function(){return None};$Reader.read=function(){var $=$B.args("read",2,{self:null,size:null},["self","size"],arguments,{size:-1},null,null),self=$.self,size=$B.$GetInt($.size);if(self.closed===true){throw _b_.ValueError.$factory("I/O operation on closed file")}var len=_b_.len(self.$content);if(size<0){size=len-self.$counter}var res;if(self.$binary){res=_b_.bytes.$factory(self.$content.source.slice(self.$counter,self.$counter+size))}else{res=self.$content.substr(self.$counter,size)}self.$counter+=size;return res};$Reader.readable=function(){return true};function make_lines(self){if(self.$lines===undefined){if(!self.$binary){self.$lines=self.$content.split("\n");if($B.last(self.$lines)==""){self.$lines.pop()}self.$lines=self.$lines.map((x=>x+"\n"))}else{var lines=[],pos=0,source=self.$content.source,len=source.length;while(pos-1){rest=rest.slice(0,size)}self.$counter=self.$content.source.length;return _b_.bytes.$factory(rest)}else{var line_source=self.$content.source.slice(self.$counter,ix+1);if(size>-1){line_source=line_source.slice(0,size)}result={__class__:_b_.bytes,source:line_source};self.$counter=ix+1;return result}}else{if(self.$counter==self.$content.length){return""}ix=self.$content.indexOf("\n",self.$counter);if(ix==-1){rest=self.$content.substr(self.$counter);if(size>-1){rest=rest.substr(0,size)}self.$counter=self.$content.length;return rest}else{result=self.$content.substring(self.$counter,ix+1);if(size>-1){result=result.substr(0,size)}self.$counter=ix+1;self.$lc+=1;return result}}};$Reader.readlines=function(){var $=$B.args("readlines",2,{self:null,hint:null},["self","hint"],arguments,{hint:-1},null,null),self=$.self,hint=$B.$GetInt($.hint);var nb_read=0;if(self.closed===true){throw _b_.ValueError.$factory("I/O operation on closed file")}self.$lc=self.$lc===undefined?-1:self.$lc;make_lines(self);var lines;if(hint<0){lines=self.$lines.slice(self.$lc+1)}else{lines=[];while(self.$lc-1;if(mode.search("w")>-1){result={$binary:is_binary,$content:is_binary?_b_.bytes.$factory():"",$encoding:encoding,closed:False,mode:mode,name:file};result.__class__=is_binary?$BufferedReader:$TextIOWrapper;$B.file_cache[file]=result.$content;return result}else if(["r","rb"].indexOf(mode)==-1){throw _b_.ValueError.$factory("Invalid mode '"+mode+"'")}if($B.$isinstance(file,_b_.str)){if($B.file_cache.hasOwnProperty($.file)){var f=$B.file_cache[$.file];result.content=f;if(is_binary&&typeof f=="string"){result.content=_b_.str.encode(f,"utf-8")}else if(f.__class__===_b_.bytes&&!is_binary){result.content=_b_.bytes.decode(f,encoding)}}else if($B.files&&$B.files.hasOwnProperty($.file)){var $res=atob($B.files[$.file].content);var source=[];for(const char of $res){source.push(char.charCodeAt(0))}result.content=_b_.bytes.$factory(source);if(!is_binary){try{result.content=_b_.bytes.decode(result.content,encoding)}catch(error){result.error=error}}}else if($B.protocol!="file"){var req=new XMLHttpRequest;req.overrideMimeType("text/plain;charset=x-user-defined");req.onreadystatechange=function(){if(this.readyState!=4){return}var status=this.status;if(status==404){result.error=_b_.FileNotFoundError.$factory(file)}else if(status!=200){result.error=_b_.IOError.$factory("Could not open file "+file+" : status "+status)}else{var bytes=[];for(var codePoint of this.response){var cp=codePoint.codePointAt(0);if(cp>63232){cp-=63232}bytes[bytes.length]=cp}result.content=_b_.bytes.$factory(bytes);if(!is_binary){try{result.content=_b_.bytes.decode(result.content,encoding)}catch(error){result.error=error}}}};var cache=$B.get_option("cache"),fake_qs=cache?"":"?foo="+(new Date).getTime();req.open("GET",encodeURI(file+fake_qs),false);req.send()}else{throw _b_.FileNotFoundError.$factory("cannot use 'open()' with protocol 'file'")}if(result.error!==undefined){throw result.error}var res={$binary:is_binary,$content:result.content,$counter:0,$encoding:encoding,$length:is_binary?result.content.source.length:result.content.length,closed:False,mode:mode,name:file};res.__class__=is_binary?$BufferedReader:$TextIOWrapper;return res}else{throw _b_.TypeError.$factory("invalid argument for open(): "+_b_.str.$factory(file))}};var zip=_b_.zip=$B.make_class("zip",(function(){var res={__class__:zip,items:[]};if(arguments.length==0){return res}var $ns=$B.args("zip",0,{},[],arguments,{},"args","kw");var _args=$ns["args"],strict=$B.$bool(_b_.dict.get($ns.kw,"strict",false));var iters=[];for(var arg of _args){iters.push($B.make_js_iterator(arg))}return{__class__:zip,iters:iters,strict:strict}}));zip.__iter__=function(self){return self};zip.__next__=function(self){var res=[],len=self.iters.length;for(var i=0;i0){throw _b_.ValueError.$factory(`zip() argument ${i+1} is longer than argument ${i}`)}else{for(var j=1;j!x.startsWith("$"))))};$B.function.__get__=function(self,obj){if(obj===_b_.None){return self}return $B.method.$factory(self,obj)};$B.function.__getattribute__=function(self,attr){if(self.$infos&&self.$infos[attr]!==undefined){if(attr=="__code__"){var res={__class__:code};for(var _attr in self.$infos.__code__){res[_attr]=self.$infos.__code__[_attr]}res.name=self.$infos.__name__;res.filename=self.$infos.__code__.co_filename;res.co_code=self+"";return res}else if(attr=="__annotations__"){return $B.obj_dict(self.$infos[attr])}else if(self.$infos.hasOwnProperty(attr)){return self.$infos[attr]}}else if(self.$infos&&self.$infos.__dict__&&_b_.dict.$contains_string(self.$infos.__dict__,attr)){return _b_.dict.$getitem_string(self.$infos.__dict__,attr)}else if(attr=="__closure__"){var free_vars=self.$infos.__code__.co_freevars;if(free_vars.length==0){return None}var cells=[];for(var i=0;i"}else{return""}};$B.function.__mro__=[_b_.object];$B.make_function_infos=function(f,__module__,__defaults__,__kwdefaults__,__doc__,arg_names,vararg,kwarg,co_argcount,co_filename,co_firstlineno,co_flags,co_freevars,co_kwonlyargcount,co_name,co_posonlyargcount,co_qualname,co_varnames){f.$is_func=true;f.$args_parser=$B.make_args_parser_and_parse;if(co_flags&$B.COMPILER_FLAGS.COROUTINE){f.$is_async=true}f.$infos={__module__:__module__,__defaults__:__defaults__,__kwdefaults__:__kwdefaults__,__doc__:__doc__,arg_names:arg_names,vararg:vararg,kwarg:kwarg};f.$infos.__name__=co_name;f.$infos.__qualname__=co_qualname;co_freevars.__class__=_b_.tuple;co_varnames.__class__=_b_.tuple;f.$infos.__code__={co_argcount:co_argcount,co_filename:co_filename,co_firstlineno:co_firstlineno,co_flags:co_flags,co_freevars:co_freevars,co_kwonlyargcount:co_kwonlyargcount,co_name:co_name,co_nlocals:co_varnames.length,co_posonlyargcount:co_posonlyargcount,co_qualname:co_qualname,co_varnames:co_varnames,co_positions:{}}};$B.make_args_parser=function(f){if(f.$infos===undefined||f.$infos.__code__===undefined){throw _b_.AttributeError.$factory(`cannot set defauts to ${_b_.str.$factory(f)}`)}const varnames=f.$infos.__code__.co_varnames,value=f.$infos.__defaults__,offset=f.$infos.__code__.co_argcount-value.length,$kwdefaults=new Map;var nb_kw_defaults=f.$infos.__kwdefaults__===_b_.None?0:_b_.dict.__len__(f.$infos.__kwdefaults__);if(f.$infos.__kwdefaults__!==_b_.None){const kwdef=f.$infos.__kwdefaults__;for(let kw of $B.make_js_iterator(kwdef)){$kwdefaults.set(kw,$B.$getitem(kwdef,kw))}}f.$kwdefaults=$kwdefaults;f.$kwdefaults_values=[...$kwdefaults.values()];f.$hasParams=new Set;var nb_args=f.$infos.__code__.co_argcount+f.$infos.__code__.co_kwonlyargcount+(f.$infos.kwargs?1:0);for(let i=0;i0){named_defaults=PARAMS_NAMED_DEFAULTS_COUNT>=PARAMS_NAMED_COUNT?DEFAULTS.ALL:DEFAULTS.SOME}const PARAMS_POSONLY_COUNT=$CODE.co_posonlyargcount;const PARAMS_POS_COUNT=$CODE.co_argcount-PARAMS_POSONLY_COUNT;let pos_defaults=DEFAULTS.NONE;if(PARAMS_POS_COUNT!==0&&value.length>0){pos_defaults=value.length>=PARAMS_POS_COUNT?DEFAULTS.ALL:DEFAULTS.SOME}let posonly_defaults=DEFAULTS.NONE;if(value.length>PARAMS_POS_COUNT){posonly_defaults=value.length>=$CODE.co_argcount?DEFAULTS.ALL:DEFAULTS.SOME}f.$args_parser=f.$infos.args_parser=$B.getArgs0(PARAMS_POSONLY_COUNT!==0,posonly_defaults,PARAMS_POS_COUNT!==0,pos_defaults,$INFOS.vararg!==null,PARAMS_NAMED_COUNT!==0,named_defaults,$INFOS.kwarg!==null);return f.$args_parser};$B.function.__setattr__=function(self,attr,value){if(attr=="__closure__"){throw _b_.AttributeError.$factory("readonly attribute")}else if(attr=="__defaults__"){if(value===_b_.None){value=[]}else if(!$B.$isinstance(value,_b_.tuple)){throw _b_.TypeError.$factory("__defaults__ must be set to a tuple object")}if(self.$infos){self.$infos.__defaults__=value;$B.make_args_parser(self)}else{throw _b_.AttributeError.$factory("cannot set attribute "+attr+" of "+_b_.str.$factory(self))}}else if(attr=="__kwdefaults__"){if(value===_b_.None){value=$B.empty_dict}else if(!$B.$isinstance(value,_b_.dict)){throw _b_.TypeError.$factory("__kwdefaults__ must be set to a dict object")}if(self.$infos){self.$infos.__kwdefaults__=value;$B.make_args_parser(self)}else{throw _b_.AttributeError.$factory("cannot set attribute "+attr+" of "+_b_.str.$factory(self))}}if(self.$infos[attr]!==undefined){self.$infos[attr]=value}else{self.$attrs=self.$attrs||{};self.$attrs[attr]=value}};$B.function.$factory=function(){};$B.set_func_names($B.function,"builtins");_b_.__BRYTHON__=__BRYTHON__;$B.builtin_funcs=["__build_class__","abs","aiter","all","anext","any","ascii","bin","breakpoint","callable","chr","compile","delattr","dir","divmod","eval","exec","exit","format","getattr","globals","hasattr","hash","help","hex","id","input","isinstance","issubclass","iter","len","locals","max","min","next","oct","open","ord","pow","print","quit","repr","round","setattr","sorted","sum","vars"];var builtin_function=$B.builtin_function_or_method=$B.make_class("builtin_function_or_method",(function(f){f.__class__=builtin_function;return f}));builtin_function.__getattribute__=$B.function.__getattribute__;builtin_function.__reduce_ex__=builtin_function.__reduce__=function(self){return self.$infos.__name__};builtin_function.__repr__=builtin_function.__str__=function(self){return""};$B.set_func_names(builtin_function,"builtins");var method_wrapper=$B.make_class("method_wrapper");method_wrapper.__repr__=method_wrapper.__str__=function(self){return""};$B.set_func_names(method_wrapper,"builtins");$B.builtin_classes=["bool","bytearray","bytes","classmethod","complex","dict","enumerate","filter","float","frozenset","int","list","map","memoryview","object","property","range","reversed","set","slice","staticmethod","str","super","tuple","type","zip"];var other_builtins=["Ellipsis","False","None","True","__debug__","__import__","copyright","credits","license","NotImplemented"];var builtin_names=$B.builtin_funcs.concat($B.builtin_classes).concat(other_builtins);for(var name of builtin_names){try{if($B.builtin_funcs.indexOf(name)>-1){_b_[name].__class__=builtin_function;_b_[name].$infos={__module__:"builtins",__name__:name,__qualname__:name}}}catch(err){}}_b_.object.__init__.__class__=$B.wrapper_descriptor;_b_.object.__new__.__class__=builtin_function})(__BRYTHON__);(function($B){var _b_=$B.builtins;var DEFAULT_MIN_MERGE=32;var DEFAULT_MIN_GALLOPING=7;var DEFAULT_TMP_STORAGE_LENGTH=256;var POWERS_OF_TEN=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9];function log10(x){if(x<1e5){if(x<100){return x<10?0:1}if(x<1e4){return x<1e3?2:3}return 4}if(x<1e7){return x<1e6?5:6}if(x<1e9){return x<1e8?7:8}return 9}function alphabeticalCompare(a,b){if(a===b){return 0}if(~~a===a&&~~b===b){if(a===0||b===0){return a=0){return-1}if(a>=0){return 1}a=-a;b=-b}var al=log10(a),bl=log10(b);var t=0;if(albl){b*=POWERS_OF_TEN[al-bl-1];a/=10;t=1}if(a===b){return t}return a=DEFAULT_MIN_MERGE){r|=n&1;n>>=1}return n+r}function makeAscendingRun(array,lo,hi,compare){var runHi=lo+1;if(runHi===hi){return 1}if(compare(array[runHi++],array[lo])<0){while(runHi=0){runHi++}}return runHi-lo}function reverseRun(array,lo,hi){hi--;while(lo>>1;if(compare(pivot,array[mid])<0){right=mid}else{left=mid+1}}var n=start-left;switch(n){case 3:array[left+3]=array[left+2];case 2:array[left+2]=array[left+1];case 1:array[left+1]=array[left];break;default:while(n>0){array[left+n]=array[left+n-1];n--}}array[left]=pivot}}function gallopLeft(value,array,start,length,hint,compare){var lastOffset=0,maxOffset=0,offset=1;if(compare(value,array[start+hint])>0){maxOffset=length-hint;while(offset0){lastOffset=offset;offset=(offset<<1)+1;if(offset<=0){offset=maxOffset}}if(offset>maxOffset){offset=maxOffset}lastOffset+=hint;offset+=hint}else{maxOffset=hint+1;while(offsetmaxOffset){offset=maxOffset}var tmp=lastOffset;lastOffset=hint-offset;offset=hint-tmp}lastOffset++;while(lastOffset>>1);if(compare(value,array[start+m])>0){lastOffset=m+1}else{offset=m}}return offset}function gallopRight(value,array,start,length,hint,compare){var lastOffset=0,maxOffset=0,offset=1;if(compare(value,array[start+hint])<0){maxOffset=hint+1;while(offsetmaxOffset){offset=maxOffset}var tmp=lastOffset;lastOffset=hint-offset;offset=hint-tmp}else{maxOffset=length-hint;while(offset=0){lastOffset=offset;offset=(offset<<1)+1;if(offset<=0){offset=maxOffset}}if(offset>maxOffset){offset=maxOffset}lastOffset+=hint;offset+=hint}lastOffset++;while(lastOffset>>1);if(compare(value,array[start+m])<0){offset=m}else{lastOffset=m+1}}return offset}var TIM_SORT_ASSERTION="TimSortAssertion";var TimSortAssertion=function(message){this.name=TIM_SORT_ASSERTION;this.message=message};var TimSort=function(array,compare){var self={array:array,compare:compare,minGallop:DEFAULT_MIN_GALLOPING,length:array.length,tmpStorageLength:DEFAULT_TMP_STORAGE_LENGTH,stackLength:0,runStart:null,runLength:null,stackSize:0,pushRun:function(runStart,runLength){this.runStart[this.stackSize]=runStart;this.runLength[this.stackSize]=runLength;this.stackSize+=1},mergeRuns:function(){while(this.stackSize>1){var n=this.stackSize-2;if(n>=1&&this.runLength[n-1]<=this.runLength[n]+this.runLength[n+1]||n>=2&&this.runLength[n-2]<=this.runLength[n]+this.runLength[n-1]){if(this.runLength[n-1]this.runLength[n+1]){break}this.mergeAt(n)}},forceMergeRuns:function(){while(this.stackSize>1){var n=this.stackSize-2;if(n>0&&this.runLength[n-1]=DEFAULT_MIN_GALLOPING||count2>=DEFAULT_MIN_GALLOPING);if(exit){break}if(minGallop<0){minGallop=0}minGallop+=2}this.minGallop=minGallop;if(minGallop<1){this.minGallop=1}if(length1===1){for(let i=0;i=0;i--){array[customDest+i]=array[customCursor+i]}array[dest]=tmp[cursor2];return}var minGallop=this.minGallop;while(true){let count1=0,count2=0,exit=false;do{if(compare(tmp[cursor2],array[cursor1])<0){array[dest--]=array[cursor1--];count1++;count2=0;if(--length1===0){exit=true;break}}else{array[dest--]=tmp[cursor2--];count2++;count1=0;if(--length2===1){exit=true;break}}}while((count1|count2)=0;i--){array[customDest+i]=array[customCursor+i]}if(length1===0){exit=true;break}}array[dest--]=tmp[cursor2--];if(--length2===1){exit=true;break}count2=length2-gallopLeft(array[cursor1],tmp,0,length2,length2-1,compare);if(count2!==0){dest-=count2;cursor2-=count2;length2-=count2;customDest=dest+1;customCursor=cursor2+1;for(let i=0;i=DEFAULT_MIN_GALLOPING||count2>=DEFAULT_MIN_GALLOPING);if(exit){break}if(minGallop<0){minGallop=0}minGallop+=2}this.minGallop=minGallop;if(minGallop<1){this.minGallop=1}if(length2===1){dest-=length1;cursor1-=length1;customDest=dest+1;customCursor=cursor1+1;for(let i=length1-1;i>=0;i--){array[customDest+i]=array[customCursor+i]}array[dest]=tmp[cursor2]}else if(length2==0){throw new TimSortAssertion("mergeHigh preconditions were not respected")}else{customCursor=dest-(length2-1);for(let i=0;i>>1}self.tmp=new Array(self.tmpStorageLength);self.stackLength=self.length<120?5:self.length<1542?10:self.length<119151?19:40;self.runStart=new Array(self.stackLength);self.runLength=new Array(self.stackLength);return self};function tim_sort(array,compare,lo,hi){if(!Array.isArray(array)){throw _b_.TypeError.$factory("Can only sort arrays")}if(!compare){compare=alphabeticalCompare}else if(typeof compare!=="function"){hi=lo;lo=compare;compare=alphabeticalCompare}if(!lo){lo=0}if(!hi){hi=array.length}var remaining=hi-lo;if(remaining<2){return}var runLength=0;if(remainingminRun){force=minRun}binaryInsertionSort(array,lo,lo+force,lo+runLength,compare);runLength=force}ts.pushRun(lo,runLength);ts.mergeRuns();remaining-=runLength;lo+=runLength}while(remaining!==0);ts.forceMergeRuns()}function tim_sort_safe(array,compare){try{tim_sort(array,compare,0,array.length)}catch(e){if(e.name==TIM_SORT_ASSERTION){array.sort(compare)}else{throw e}}}$B.$TimSort=tim_sort_safe;$B.$AlphabeticalCompare=alphabeticalCompare})(__BRYTHON__);(function($B){var _b_=$B.builtins;$B.del_exc=function(frame){delete frame[1].$current_exception};$B.set_exc=function(exc,frame){if(frame===undefined){var msg="Internal error: no frame for exception "+_b_.repr(exc);console.error(["Traceback (most recent call last):",$B.print_stack(exc.$frame_obj),msg].join("\n"));if($B.get_option("debug",exc)>1){console.log(exc.args);console.log(exc.stack)}throw Error(msg)}else{frame[1].$current_exception=$B.exception(exc)}};$B.set_exc_and_trace=function(frame,exc){$B.set_exc(exc,frame);if(!exc.$in_trace_func&&frame.$f_trace!==_b_.None){frame.$f_trace=$B.trace_exception()}};$B.set_exc_and_leave=function(frame,exc){$B.set_exc_and_trace(frame,exc);$B.leave_frame()};$B.get_exc=function(){var frame=$B.frame_obj.frame;return frame[1].$current_exception};$B.set_exception_offsets=function(exc,position){exc.$positions=exc.$positions||{};exc.$positions[$B.frame_obj.count-1]=position;return exc};$B.$raise=function(arg,cause){var active_exc=$B.get_exc();if(arg===undefined){if(active_exc!==undefined){throw active_exc}throw _b_.RuntimeError.$factory("No active exception to reraise")}else{if($B.$isinstance(arg,_b_.BaseException)){if(arg.__class__===_b_.StopIteration&&$B.frame_obj.frame.$is_generator){arg=_b_.RuntimeError.$factory("generator raised StopIteration")}arg.__context__=active_exc===undefined?_b_.None:active_exc;arg.__cause__=cause||_b_.None;arg.__suppress_context__=cause!==undefined;throw arg}else if(arg.$is_class&&_b_.issubclass(arg,_b_.BaseException)){if(arg===_b_.StopIteration){if($B.frame_obj.frame[1].$is_generator){throw _b_.RuntimeError.$factory("generator raised StopIteration")}}var exc=$B.$call(arg)();exc.__context__=active_exc===undefined?_b_.None:active_exc;exc.__cause__=cause||_b_.None;exc.__suppress_context__=cause!==undefined;throw exc}else{throw _b_.TypeError.$factory("exceptions must derive from BaseException")}}};$B.print_stack=function(frame_obj){var stack=make_frames_stack(frame_obj||$B.frame_obj);var trace=[];for(var frame of stack){var lineno=frame.$lineno,filename=frame.__file__;if(lineno!==undefined){var local=frame[0]==frame[2]?"":frame[0];trace.push(` File "${filename}" line ${lineno}, in ${local}`);var src=$B.file_cache[filename];if(src){var lines=src.split("\n"),line=lines[lineno-1];trace.push(" "+line.trim())}}}return trace.join("\n")};$B.last_frame=function(){var frame=$B.frame_obj.frame;return`file ${frame.__file__} line ${frame.$lineno}`};$B.count_frames=function(frame_obj){frame_obj=frame_obj||$B.frame_obj;return frame_obj==null?0:frame_obj.count};$B.get_frame_at=function(pos,frame_obj){frame_obj=frame_obj||$B.frame_obj;var nb=frame_obj.count-pos-1;for(var i=0;i"};frame.f_builtins={__get__:function(_self){return $B.$getattr(_self[3].__builtins__,"__dict__")}};frame.f_code={__get__:function(_self){var res;if(_self[4]){res=_self[4].$infos.__code__}else if(_self.f_code){res=_self.f_code}else{res={co_name:_self[0]==_self[2]?"":_self[0],co_filename:_self.__file__,co_varnames:$B.fast_tuple([])};res.co_qualname=res.co_name}res.__class__=_b_.code;return res}};frame.f_globals={__get__:function(_self){if(_self.f_globals){return _self.f_globals}else if(_self.f_locals&&_self[1]==_self[3]){return _self.f_globals=_self.f_locals}else{return _self.f_globals=$B.obj_dict(_self[3])}}};frame.f_lineno={__get__:function(_self){return _self.$lineno}};frame.f_locals={__get__:function(_self){if(_self.f_locals){return _self.f_locals}else if(_self.f_globals&&_self[1]==_self[3]){return _self.f_locals=_self.f_globals}else{return _self.f_locals=$B.obj_dict(_self[1])}}};frame.f_trace={__get__:function(_self){return _self.$f_trace}};$B.set_func_names(frame,"builtins");$B._frame=frame;$B.deep_copy=function(stack){var res=[];for(const s of stack){var item=[s[0],{},s[2],{}];if(s[4]!==undefined){item.push(s[4])}for(const i of[1,3]){for(var key in s[i]){item[i][key]=s[i][key]}}res.push(item)}return res};$B.restore_frame_obj=function(frame_obj,locals){$B.frame_obj=frame_obj;$B.frame_obj.frame[1]=locals};$B.make_linenums=function(frame_obj){var res=[];frame_obj=frame_obj||$B.frame_obj;while(frame_obj!==null){res.push(frame_obj.frame.$lineno);frame_obj=frame_obj.prev}return res.reverse()};var make_frames_stack=$B.make_frames_stack=function(frame_obj){var stack=[];while(frame_obj!==null){stack[stack.length]=frame_obj.frame;frame_obj=frame_obj.prev}stack.reverse();return stack};$B.freeze=function(err){if(err.$frame_obj===undefined){err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums()}err.__traceback__=traceback.$factory(err)};$B.exception=function(js_exc){var exc;if(!js_exc.__class__){if(js_exc.$py_exc){return js_exc.$py_exc}if($B.get_option("debug",exc)>1){console.log("Javascript error",js_exc)}var msg=js_exc.name+": "+js_exc.message;exc=_b_.JavascriptError.$factory(msg);exc.$js_exc=js_exc;if($B.is_recursion_error(js_exc)){msg="maximum recursion depth exceeded";exc=_b_.RecursionError.$factory(msg)}exc.__cause__=_b_.None;exc.__context__=_b_.None;exc.__suppress_context__=false;exc.args=_b_.tuple.$factory([msg]);exc.$py_error=true;js_exc.$py_exc=exc;$B.freeze(exc)}else{exc=js_exc;$B.freeze(exc)}return exc};$B.is_exc=function(exc,exc_list){if(exc.__class__===undefined){exc=$B.exception(exc)}var this_exc_class=exc.$is_class?exc:exc.__class__;for(var i=0;i1){res+=", "+_b_.repr($B.fast_tuple(self.args.slice(1)))}return res+")"};_b_.BaseException.__str__=function(self){if(self.args.length>0&&self.args[0]!==_b_.None){return _b_.str.$factory(self.args[0])}return""};_b_.BaseException.__new__=function(cls){var err=_b_.BaseException.$factory();err.__class__=cls;err.__dict__=$B.empty_dict();return err};_b_.BaseException.__getattr__=function(self,attr){if(attr=="__context__"){var frame=$B.frame_obj.frame,ctx=frame[1].$current_exception;return ctx||_b_.None}else{throw $B.attr_error(attr,self)}};_b_.BaseException.add_note=function(self,note){if(!$B.$isinstance(note,_b_.str)){throw _b_.TypeError.$factory("note must be a str, not "+`'${$B.class_name(note)}'`)}if(self.__notes__!==undefined){self.__notes__.push(note)}else{self.__notes__=$B.$list([note])}};_b_.BaseException.with_traceback=function(_self,tb){_self.__traceback__=tb;return _self};$B.set_func_names(_b_.BaseException,"builtins");make_builtin_exception(["SystemExit","KeyboardInterrupt","GeneratorExit","Exception"],_b_.BaseException);make_builtin_exception("JavascriptError",_b_.Exception);make_builtin_exception(["ArithmeticError","AssertionError","BufferError","EOFError","LookupError","MemoryError","OSError","ReferenceError","RuntimeError","SystemError","TypeError","ValueError","Warning"],_b_.Exception);make_builtin_exception("StopIteration",_b_.Exception,"value");make_builtin_exception("StopAsyncIteration",_b_.Exception,"value");make_builtin_exception("ImportError",_b_.Exception,"name");make_builtin_exception("SyntaxError",_b_.Exception,"msg");make_builtin_exception(["FloatingPointError","OverflowError","ZeroDivisionError"],_b_.ArithmeticError);make_builtin_exception("ModuleNotFoundError",_b_.ImportError,"name");make_builtin_exception(["IndexError","KeyError"],_b_.LookupError);make_builtin_exception(["BlockingIOError","ChildProcessError","ConnectionError","FileExistsError","FileNotFoundError","InterruptedError","IsADirectoryError","NotADirectoryError","PermissionError","ProcessLookupError","TimeoutError"],_b_.OSError);make_builtin_exception(["BrokenPipeError","ConnectionAbortedError","ConnectionRefusedError","ConnectionResetError"],_b_.ConnectionError);make_builtin_exception(["NotImplementedError","RecursionError","PythonFinalizationError"],_b_.RuntimeError);make_builtin_exception(["IndentationError","_IncompleteInputError"],_b_.SyntaxError,"msg");make_builtin_exception("TabError",_b_.IndentationError);make_builtin_exception("UnicodeError",_b_.ValueError);make_builtin_exception(["UnicodeDecodeError","UnicodeEncodeError","UnicodeTranslateError"],_b_.UnicodeError);make_builtin_exception(["DeprecationWarning","PendingDeprecationWarning","RuntimeWarning","SyntaxWarning","UserWarning","FutureWarning","ImportWarning","UnicodeWarning","BytesWarning","ResourceWarning","EncodingWarning"],_b_.Warning);make_builtin_exception(["EnvironmentError","IOError","VMSError","WindowsError"],_b_.OSError);_b_.AttributeError=$B.make_class("AttributeError",(function(){var $=$B.args("AttributeError",3,{msg:null,name:null,obj:null},["msg","name","obj"],arguments,{msg:_b_.None,name:_b_.None,obj:_b_.None},"*",null);var err=Error();err.__class__=_b_.AttributeError;err.__traceback__=_b_.None;err.$py_error=true;err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums();err.args=$B.fast_tuple($.msg===_b_.None?[]:[$.msg]);err.name=$.name;err.obj=$.obj;if(err.obj===undefined){console.log("pas de obj",$)}err.__cause__=_b_.None;err.__context__=_b_.None;err.__suppress_context__=false;return err}));_b_.AttributeError.__bases__=[_b_.Exception];_b_.AttributeError.__mro__=_b_.type.$mro(_b_.AttributeError);_b_.AttributeError.__str__=function(self){return self.args[0]};$B.set_func_names(_b_.AttributeError,"builtins");$B.attr_error=function(name,obj){var msg;if(obj.$is_class){msg=`type object '${obj.__name__}'`}else{msg=`'${$B.class_name(obj)}' object`}msg+=` has no attribute '${name}'`;return _b_.AttributeError.$factory({$kw:[{name:name,obj:obj,msg:msg}]})};_b_.NameError=$B.make_class("NameError",(function(){var $=$B.args("NameError",2,{message:null,name:null},["message","name"],arguments,{message:_b_.None,name:_b_.None},"*",null,1);var err=Error();err.__class__=_b_.NameError;err.__traceback__=_b_.None;err.$py_error=true;err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums();err.args=$B.fast_tuple($.message===_b_.None?[]:[$.message]);err.name=$.name;err.__cause__=_b_.None;err.__context__=_b_.None;err.__suppress_context__=false;return err}));_b_.NameError.__bases__=[_b_.Exception];_b_.NameError.__mro__=_b_.type.$mro(_b_.NameError).slice(1);_b_.NameError.__str__=function(self){return self.args[0]};$B.set_func_names(_b_.NameError,"builtins");make_builtin_exception("UnboundLocalError",_b_.NameError);_b_.UnboundLocalError.__str__=function(self){return self.args[0]};$B.set_func_names(_b_.UnboundLocalError,"builtins");$B.name_error=function(name){var exc=_b_.NameError.$factory(`name '${name}' is not defined`);exc.name=name;exc.$frame_obj=$B.frame_obj;return exc};$B.recursion_error=function(frame){var exc=_b_.RecursionError.$factory("maximum recursion depth exceeded");$B.set_exc(exc,frame);$B.freeze(exc);return exc};var MAX_CANDIDATE_ITEMS=750,MOVE_COST=2,CASE_COST=1,SIZE_MAX=65535;function LEAST_FIVE_BITS(n){return n&31}function levenshtein_distance(a,b,max_cost){if(a==b){return 0}if(a.lengthmax_cost){return max_cost+1}var buffer=[];for(var i=0;imax_cost){return max_cost+1}}return result}function substitution_cost(a,b){if(LEAST_FIVE_BITS(a)!=LEAST_FIVE_BITS(b)){return MOVE_COST}if(a==b){return 0}if(a.toLowerCase()==b.toLowerCase()){return CASE_COST}return MOVE_COST}function calculate_suggestions(dir,name){if(dir.length>=MAX_CANDIDATE_ITEMS){return null}var suggestion_distance=2**52,suggestion=null;for(var item of dir){var max_distance=(name.length+item.length+3)*MOVE_COST/6;max_distance=Math.min(max_distance,suggestion_distance-1);var current_distance=levenshtein_distance(name,item,max_distance);if(current_distance>max_distance){continue}if(!suggestion||current_distance!x.startsWith("$")));var suggestion=calculate_suggestions(locals,name);if(suggestion){return suggestion}if(frame[2]!=frame[0]){var globals=Object.keys(frame[3]).filter((x=>!x.startsWith("$")));suggestion=calculate_suggestions(globals,name);if(suggestion){return suggestion}}if(frame[4]&&frame[4].$is_method){var instance_name=frame[4].$infos.__code__.co_varnames[0],instance=frame[1][instance_name];if(_b_.hasattr(instance,name)){return`self.${name}`}}return _b_.None};$B.offer_suggestions_for_unexpected_keyword_error=function(arg_names,key){if(key===_b_.None){return _b_.None}var suggestions=calculate_suggestions(arg_names,key);return suggestions||_b_.None};_b_.BaseExceptionGroup=$B.make_class("BaseExceptionGFroup",(function(){var missing={},$=$B.args("BaseExceptionGroup",2,{message:null,exceptions:null},["message","exceptions"],arguments,{exceptions:missing},null,null);var err=Error();err.args=$B.fast_tuple(Array.from(arguments));err.__class__=_b_.BaseExceptionGroup;err.__traceback__=_b_.None;err.$py_error=true;err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums();err.message=$.message;err.exceptions=$.exceptions===missing?[]:$.exceptions;if(err.exceptions!==_b_.None){var exc_list=_b_.list.$factory(err.exceptions);var all_exceptions=true;for(var exc of exc_list){if(!$B.$isinstance(exc,_b_.Exception)){all_exceptions=false;break}}if(all_exceptions){err.__class__=_b_.ExceptionGroup}}err.__cause__=_b_.None;err.__context__=_b_.None;err.__suppress_context__=false;return err}));_b_.BaseExceptionGroup.__bases__=[_b_.BaseException];_b_.BaseExceptionGroup.__class_getitem__=$B.$class_getitem;_b_.BaseExceptionGroup.__mro__=_b_.type.$mro(_b_.BaseExceptionGroup);_b_.BaseExceptionGroup.__str__=function(self){return`${self.message} (${self.exceptions.length} sub-exception`+`${self.exceptions.length>1?"s":""})`};_b_.BaseExceptionGroup.split=function(self,condition){var matching_excs=[],non_matching_excs=[];for(var exc of self.exceptions){if($B.$isinstance(exc,_b_.BaseExceptionGroup)){var subsplit=_b_.BaseExceptionGroup.split(exc,condition),matching=subsplit[0],non_matching=subsplit[1];if(matching===_b_.None){non_matching_excs.push(exc)}else if(matching.exceptions.length==exc.exceptions.length){matching_excs.push(exc)}else{if(matching.exceptions.length>0){matching_excs=matching_excs.concat(matching)}if(non_matching.exceptions.length>0){non_matching_excs=non_matching_excs.concat(non_matching)}}}else if(condition(exc)){matching_excs.push(exc)}else{non_matching_excs.push(exc)}}if(matching_excs.length==0){matching_excs=_b_.None}if(non_matching_excs.length==0){non_matching_excs=_b_.None}var res=[];for(var item of[matching_excs,non_matching_excs]){var eg=_b_.BaseExceptionGroup.$factory(self.message,item);eg.__cause__=self.__cause__;eg.__context__=self.__context__;eg.__traceback__=self.__traceback__;res.push(eg)}return $B.fast_tuple(res)};_b_.BaseExceptionGroup.subgroup=function(self,condition){return _b_.BaseExceptionGroup.split(self,condition)[0]};$B.set_func_names(_b_.BaseExceptionGroup,"builtins");_b_.BaseExceptionGroup.__class_getitem__=_b_.classmethod.$factory(_b_.BaseExceptionGroup.__class_getitem__);_b_.ExceptionGroup=$B.make_class("ExceptionGFroup",(function(){var missing={},$=$B.args("ExceptionGroup",2,{message:null,exceptions:null},["message","exceptions"],arguments,{exceptions:missing},null,null);var err=Error();err.args=$B.fast_tuple(Array.from(arguments));err.__class__=_b_.ExceptionGroup;err.__traceback__=_b_.None;err.$py_error=true;err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums();err.message=$.message;err.exceptions=$.exceptions===missing?[]:$.exceptions;if(err.exceptions!==_b_.None){var exc_list=_b_.list.$factory(err.exceptions);for(var exc of exc_list){if(!$B.$isinstance(exc,_b_.Exception)){throw _b_.TypeError.$factory("Cannot nest BaseExceptions in an ExceptionGroup")}}}err.__cause__=_b_.None;err.__context__=_b_.None;err.__suppress_context__=false;return err}));_b_.ExceptionGroup.__bases__=[_b_.BaseExceptionGroup,_b_.Exception];_b_.ExceptionGroup.__mro__=_b_.type.$mro(_b_.ExceptionGroup);$B.set_func_names(_b_.ExceptionGroup,"builtins");function trace_from_stack(err){function handle_repeats(src,count_repeats){if(count_repeats>0){var len=trace.length;for(var i=0;i<2;i++){if(src){trace.push(trace[len-2]);trace.push(trace[len-1])}else{trace.push(trace[len-1])}count_repeats--;if(count_repeats==0){break}}if(count_repeats>0){trace.push(`[Previous line repeated ${count_repeats} more`+` time${count_repeats>1?"s":""}]`)}}}var trace=[],save_filename,save_lineno,save_scope,count_repeats=0,stack=err.$frame_obj===undefined?[]:make_frames_stack(err.$frame_obj),linenos=err.$linenums;for(let frame_num=0,len=stack.length;frame_num":frame[0];if(filename==save_filename&&scope==save_scope&&lineno==save_lineno){count_repeats++;continue}handle_repeats(src,count_repeats);save_filename=filename;save_lineno=lineno;save_scope=scope;count_repeats=0;var src=$B.file_cache[filename];trace.push(` File "${filename}", line ${lineno}, in `+(frame[0]==frame[2]?"":frame[0]));if(src){var lines=src.split("\n"),line=lines[lineno-1];if(line){trace.push(" "+line.trim())}else{console.log("no line",line);console.log("lineno",lineno);console.log("filename",filename)}if(err.$positions!==undefined&&line){var position=err.$positions[frame_num],trace_line="";if(position&&(position[1]!=position[0]||position[2]-position[1]!=line.trim().length||position[3])){var indent=line.length-line.trimLeft().length;var paddings=[position[0]-indent,position[1]-position[0],position[2]-position[1]];for(var padding in paddings){if(padding<0){console.log("wrong values, position",position,"indent",indent);paddings[paddings.indexOf(padding)]=0}}trace_line+=" "+" ".repeat(paddings[0])+"~".repeat(paddings[1])+"^".repeat(paddings[2]);if(position[3]!==undefined){trace_line+="~".repeat(position[3]-position[2])}trace.push(trace_line)}}}else{console.log("no src for filename",filename)}}if(count_repeats>1){let len=trace.length;for(let i=0;i<2;i++){if(src){trace.push(trace[len-2]);trace.push(trace[len-1])}else{trace.push(trace[len-1])}}trace.push(`[Previous line repeated ${count_repeats-2} more times]`)}return trace.join("\n")+"\n"}$B.error_trace=function(err){var trace="",stack=err.$frame_obj===undefined?[]:make_frames_stack(err.$frame_obj);if($B.get_option("debug",err)>1){console.log("handle error",err.__class__,err.args);console.log("stack",stack);console.log(err.stack)}if(stack.length>0){trace="Traceback (most recent call last):\n"}if(err.__class__===_b_.SyntaxError||err.__class__===_b_.IndentationError){err.$frame_obj=err.$frame_obj===null?null:err.$frame_obj.prev;trace+=trace_from_stack(err);var filename=err.filename,line=err.text,indent=line.length-line.trimLeft().length;trace+=` File "${filename}", line ${err.args[1][1]}\n`+` ${line.trim()}\n`;if(err.__class__!==_b_.IndentationError&&err.text){if($B.get_option("debug",err)>1){console.log("error args",err.args[1]);console.log("err line",line);console.log("indent",indent)}var start=err.offset-indent-1,end_offset=err.end_offset-1+(err.end_offset==err.offset?1:0),marks=" "+" ".repeat(Math.max(0,start)),nb_marks=1;if(err.end_lineno){if(err.end_lineno>err.lineno){nb_marks=line.length-start-indent}else{nb_marks=end_offset-start-indent}if(nb_marks==0&&err.end_offset==line.substr(indent).length){nb_marks=1}}marks+="^".repeat(nb_marks)+"\n";trace+=marks}trace+=`${err.__class__.__name__}: ${err.args[0]}`}else if(err.__class__!==undefined){var name=$B.class_name(err);trace+=trace_from_stack(err);var args_str=_b_.str.$factory(err);trace+=name+(args_str?": "+args_str:"");var save_frame_obj=$B.frame_obj;$B.frame_obj=err.$frame_obj;if(err.__class__===_b_.NameError){let suggestion=$B.offer_suggestions_for_name_error(err);if(suggestion!==_b_.None&&suggestion!==err.name){trace+=`. Did you mean: '${suggestion}'?`}if($B.stdlib_module_names.indexOf(err.name)>-1){trace+=`. Did you forget to import '${err.name}'?`}}else if(err.__class__===_b_.AttributeError){let suggestion=$B.offer_suggestions_for_attribute_error(err);if(suggestion!==_b_.None){trace+=`. Did you mean: '${suggestion}'?`}}else if(err.__class__===_b_.ImportError){if(err.$suggestion!==_b_.None){trace+=`. Did you mean: '${err.$suggestion}'?`}}$B.frame_obj=save_frame_obj}else{trace=err+""}if(err.$js_exc){trace+="\n";if($B.get_option("debug",err)>1){trace+=err.$js_exc.stack}}return trace};$B.get_stderr=function(){return $B.imported.sys?$B.imported.sys.stderr:$B.imported._sys.stderr};$B.get_stdout=function(){return $B.imported.sys?$B.imported.sys.stdout:$B.imported._sys.stdout};$B.show_error=function(err){var trace=$B.error_trace($B.exception(err));try{var stderr=$B.get_stderr();$B.$getattr(stderr,"write")(trace);var flush=$B.$getattr(stderr,"flush",_b_.None);if(flush!==_b_.None){flush()}}catch(print_exc_err){console.debug(trace)}};$B.handle_error=function(err){if(err.$handled){return}err.$handled=true;$B.show_error(err);throw err}})(__BRYTHON__);(function($B){var _b_=$B.builtins,None=_b_.None,range={__class__:_b_.type,__mro__:[_b_.object],__qualname__:"range",$is_class:true,$native:true,$match_sequence_pattern:true,$not_basetype:true,$descriptors:{start:true,step:true,stop:true}};range.__contains__=function(self,other){if(range.__len__(self)==0){return false}try{other=$B.int_or_bool(other)}catch(err){try{range.index(self,other);return true}catch(err){return false}}var start=_b_.int.$to_bigint(self.start),stop=_b_.int.$to_bigint(self.stop),step=_b_.int.$to_bigint(self.step);other=_b_.int.$to_bigint(other);var sub=other-start,fl=sub/step,res=step*fl;if(res==sub){if(stop>start){return other>=start&&stop>other}else{return start>=other&&other>stop}}else{return false}};range.__delattr__=function(){throw _b_.AttributeError.$factory("readonly attribute")};range.__eq__=function(self,other){if($B.$isinstance(other,range)){var len=range.__len__(self);if(!$B.rich_comp("__eq__",len,range.__len__(other))){return false}if(len==0){return true}if(!$B.rich_comp("__eq__",self.start,other.start)){return false}if(len==1){return true}return $B.rich_comp("__eq__",self.step,other.step)}return false};function compute_item(r,i){var len=range.__len__(r);if(len==0){return r.start}else if(i>len){return r.stop}return $B.rich_op("__add__",r.start,$B.rich_op("__mul__",r.step,i))}range.__getitem__=function(self,rank){if($B.$isinstance(rank,_b_.slice)){var norm=_b_.slice.$conv_for_seq(rank,range.__len__(self)),substep=$B.rich_op("__mul__",self.step,norm.step),substart=compute_item(self,norm.start),substop=compute_item(self,norm.stop);return range.$factory(substart,substop,substep)}if(typeof rank!="number"){rank=$B.$GetInt(rank)}if($B.rich_comp("__gt__",0,rank)){rank=$B.rich_op("__add__",rank,range.__len__(self))}var res=$B.rich_op("__add__",self.start,$B.rich_op("__mul__",rank,self.step));if($B.rich_comp("__gt__",self.step,0)&&($B.rich_comp("__ge__",res,self.stop)||$B.rich_comp("__gt__",self.start,res))||$B.rich_comp("__gt__",0,self.step)&&($B.rich_comp("__ge__",self.stop,res)||$B.rich_comp("__gt__",res,self.start))){throw _b_.IndexError.$factory("range object index out of range")}return res};range.__hash__=function(self){var len=range.__len__(self);if(len==0){return _b_.hash(_b_.tuple.$factory([0,None,None]))}if(len==1){return _b_.hash(_b_.tuple.$factory([1,self.start,None]))}return _b_.hash(_b_.tuple.$factory([len,self.start,self.step]))};var RangeIterator=$B.make_class("range_iterator",(function(obj){return{__class__:RangeIterator,obj:obj}}));RangeIterator.__iter__=function(self){return self};RangeIterator.__next__=function(self){return _b_.next(self.obj)};$B.set_func_names(RangeIterator,"builtins");range.__iter__=function(self){var res={__class__:range,start:self.start,stop:self.stop,step:self.step};if(self.$safe){res.$counter=self.start-self.step}else{res.$counter=$B.rich_op("__sub__",self.start,self.step)}return RangeIterator.$factory(res)};range.__len__=function(self){var len,start=_b_.int.$to_bigint(self.start),stop=_b_.int.$to_bigint(self.stop),step=_b_.int.$to_bigint(self.step);if(self.step>0){if(self.start>=self.stop){return 0}len=1n+(stop-start-1n)/step}else{if(self.stop>=self.start){return 0}len=1n+(start-stop-1n)/-step}return _b_.int.$int_or_long(len)};range.__next__=function(self){if(self.$safe){self.$counter+=self.step;if(self.step>0&&self.$counter>=self.stop||self.step<0&&self.$counter<=self.stop){throw _b_.StopIteration.$factory("")}}else{self.$counter=$B.rich_op("__add__",self.$counter,self.step);if($B.rich_comp("__gt__",self.step,0)&&$B.rich_comp("__ge__",self.$counter,self.stop)||$B.rich_comp("__gt__",0,self.step)&&$B.rich_comp("__ge__",self.stop,self.$counter)){throw _b_.StopIteration.$factory("")}}return self.$counter};range.__reversed__=function(self){var n=$B.rich_op("__sub__",range.__len__(self),1);return range.$factory($B.rich_op("__add__",self.start,$B.rich_op("__mul__",n,self.step)),$B.rich_op("__sub__",self.start,self.step),$B.rich_op("__mul__",-1,self.step))};range.__repr__=function(self){$B.builtins_repr_check(range,arguments);var res="range("+_b_.str.$factory(self.start)+", "+_b_.str.$factory(self.stop);if(self.step!=1){res+=", "+_b_.str.$factory(self.step)}return res+")"};range.__setattr__=function(){throw _b_.AttributeError.$factory("readonly attribute")};range.start=function(self){return self.start};range.step=function(self){return self.step},range.stop=function(self){return self.stop};range.count=function(self,ob){if($B.$isinstance(ob,[_b_.int,_b_.float,_b_.bool])){return _b_.int.$factory(range.__contains__(self,ob))}else{var comp=function(other){return $B.rich_comp("__eq__",ob,other)},it=range.__iter__(self),_next=RangeIterator.__next__,nb=0;while(true){try{if(comp(_next(it))){nb++}}catch(err){if($B.$isinstance(err,_b_.StopIteration)){return nb}throw err}}}};range.index=function(){var $=$B.args("index",2,{self:null,other:null},["self","other"],arguments,{},null,null),self=$.self,other=$.other;try{other=$B.int_or_bool(other)}catch(err){var comp=function(x){return $B.rich_comp("__eq__",other,x)},it=range.__iter__(self),_next=RangeIterator.__next__,nb=0;while(true){try{if(comp(_next(it))){return nb}nb++}catch(err){if($B.$isinstance(err,_b_.StopIteration)){throw _b_.ValueError.$factory(_b_.str.$factory(other)+" not in range")}throw err}}}var sub=$B.rich_op("__sub__",other,self.start),fl=$B.rich_op("__floordiv__",sub,self.step),res=$B.rich_op("__mul__",self.step,fl);if($B.rich_comp("__eq__",res,sub)){if($B.rich_comp("__gt__",self.stop,self.start)&&$B.rich_comp("__ge__",other,self.start)&&$B.rich_comp("__gt__",self.stop,other)||$B.rich_comp("__ge__",self.start,self.stop)&&$B.rich_comp("__ge__",self.start,other)&&$B.rich_comp("__gt__",other,self.stop)){return fl}else{throw _b_.ValueError.$factory(_b_.str.$factory(other)+" not in range")}}else{throw _b_.ValueError.$factory(_b_.str.$factory(other)+" not in range")}};range.$factory=function(){var $=$B.args("range",3,{start:null,stop:null,step:null},["start","stop","step"],arguments,{start:null,stop:null,step:null},null,null),start=$.start,stop=$.stop,step=$.step,safe;if(stop===null&&step===null){if(start==null){throw _b_.TypeError.$factory("range expected 1 arguments, got 0")}stop=$B.PyNumber_Index(start);safe=typeof stop==="number";return{__class__:range,start:0,stop:stop,step:1,$is_range:true,$safe:safe}}if(step===null){step=1}start=$B.PyNumber_Index(start);stop=$B.PyNumber_Index(stop);step=$B.PyNumber_Index(step);if(step==0){throw _b_.ValueError.$factory("range arg 3 must not be zero")}safe=typeof start=="number"&&typeof stop=="number"&&typeof step=="number";return{__class__:range,start:start,stop:stop,step:step,$is_range:true,$safe:safe}};$B.set_func_names(range,"builtins");var slice={__class__:_b_.type,__mro__:[_b_.object],__qualname__:"slice",$is_class:true,$native:true,$not_basetype:true,$descriptors:{start:true,step:true,stop:true}};slice.__eq__=function(self,other){var conv1=conv_slice(self),conv2=conv_slice(other);return conv1[0]==conv2[0]&&conv1[1]==conv2[1]&&conv1[2]==conv2[2]};slice.__repr__=function(self){$B.builtins_repr_check(slice,arguments);return"slice("+_b_.str.$factory(self.start)+", "+_b_.str.$factory(self.stop)+", "+_b_.str.$factory(self.step)+")"};slice.__setattr__=function(){throw _b_.AttributeError.$factory("readonly attribute")};function conv_slice(self){var attrs=["start","stop","step"],res=[];for(var i=0;i=0;i--){if(cars.indexOf(self.source[i])==-1){break}}return bytes.$factory(self.source.slice(0,i+1))}function invalid(other){return!$B.$isinstance(other,[bytes,bytearray])}var bytearray={__class__:_b_.type,__mro__:[_b_.object],__qualname__:"bytearray",$buffer_protocol:true,$is_class:true};var mutable_methods=["__delitem__","clear","copy","count","index","pop","remove","reverse"];for(var method of mutable_methods){bytearray[method]=function(m){return function(self){var args=[self.source],pos=1;for(var i=1,len=arguments.length;i255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}var pos=arg;if(arg<0){pos=self.source.length+pos}if(pos>=0&&pos=0;i--){if(!$B.$isinstance($temp[i],_b_.int)){throw _b_.TypeError.$factory("an integer is required")}else if($temp[i]>255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}self.source.splice(start,0,$temp[i])}}catch(err){throw _b_.TypeError.$factory("can only assign an iterable")}}else{throw _b_.TypeError.$factory("list indices must be integer, not "+$B.class_name(arg))}};bytearray.append=function(self,b){if(arguments.length!=2){throw _b_.TypeError.$factory("append takes exactly one argument ("+(arguments.length-1)+" given)")}if(!$B.$isinstance(b,_b_.int)){throw _b_.TypeError.$factory("an integer is required")}if(b>255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}self.source[self.source.length]=b};bytearray.extend=function(self,b){if(self.in_iteration){throw _b_.BufferError.$factory("Existing exports of data: object "+"cannot be re-sized")}if(b.__class__===bytearray||b.__class__===bytes){self.source=self.source.concat(b.source);return _b_.None}for(var item of $B.make_js_iterator(b)){bytearray.append(self,$B.PyNumber_Index(item))}return _b_.None};bytearray.insert=function(self,pos,b){if(arguments.length!=3){throw _b_.TypeError.$factory("insert takes exactly 2 arguments ("+(arguments.length-1)+" given)")}if(!$B.$isinstance(b,_b_.int)){throw _b_.TypeError.$factory("an integer is required")}if(b>255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}_b_.list.insert(self.source,pos,b)};bytearray.$factory=function(){var args=[bytearray];for(var i=0,len=arguments.length;i-1}if(self.source.length=0&&pos0){stop=Math.min(stop,self.source.length);if(stop<=start){return bytes.$factory([])}for(let i=start;i=start){return bytes.$factory([])}stop=Math.max(0,stop);for(let i=start;i>=stop;i+=step){res[pos++]=self.source[i]}}return bytes.$factory(res)}else if($B.$isinstance(arg,_b_.bool)){return self.source.__getitem__(_b_.int.$factory(arg))}};bytes.$getnewargs=function(self){return $B.fast_tuple([bytes_value(self)])};bytes.__getnewargs__=function(){return bytes.$getnewargs($B.single_arg("__getnewargs__","self",arguments))};bytes.__gt__=function(self,other){if(invalid(other)){return _b_.NotImplemented}return _b_.list.__gt__(self.source,other.source)};bytes.__hash__=function(self){if(self===undefined){return bytes.__hashvalue__||$B.$py_next_hash--}var hash=1;for(var i=0,len=self.source.length;i=0&&item<256){source.push(item)}else{throw _b_.ValueError.$factory("bytes must be in range (0, 256)")}}}return{__class__:$.cls,source:source}};bytes.$new=function(cls,source,encoding,errors){var self={__class__:cls},int_list=[],pos=0;if(source===undefined){}else if(typeof source=="number"||$B.$isinstance(source,_b_.int)){let i=source;while(i--){int_list[pos++]=0}}else{if(typeof source=="string"||$B.$isinstance(source,_b_.str)){if(encoding===undefined){throw _b_.TypeError.$factory("string argument without an encoding")}int_list=encode(source,encoding||"utf-8",errors||"strict")}else{if(encoding!==undefined){console.log("encoding",encoding);throw _b_.TypeError.$factory("encoding without a string argument")}if(Array.isArray(source)){int_list=source}else{try{int_list=_b_.list.$factory(source)}catch(err){var bytes_method=$B.$getattr(source,"__bytes__",_b_.None);if(bytes_method===_b_.None){throw _b_.TypeError.$factory("cannot convert "+`'${$B.class_name(source)}' object to bytes`)}var res=$B.$call(bytes_method)();if(!$B.$isinstance(res,_b_.bytes)){throw _b_.TypeError.$factory(`__bytes__ returned `+`non-bytes (type ${$B.class_name(res)})`)}return res}for(let i=0;i255){throw _b_.ValueError.$factory("bytes must be in range"+"(0, 256)")}}}}}self.source=int_list;self.encoding=encoding;self.errors=errors;return self};bytes.__repr__=bytes.__str__=function(self){var t=$B.special_string_repr,res="";for(var i=0,len=self.source.length;i=128){var hx=s.toString(16);hx=(hx.length==1?"0":"")+hx;res+="\\x"+hx}else if(s=="\\".charCodeAt(0)){res+="\\\\"}else{res+=String.fromCharCode(s)}}if(res.indexOf("'")>-1&&res.indexOf('"')==-1){return'b"'+res+'"'}else{return"b'"+res.replace(new RegExp("'","g"),"\\'")+"'"}};bytes.capitalize=function(self){var src=self.source,len=src.length,buffer=src.slice();if(buffer[0]>96&&buffer[0]<123){buffer[0]-=32}for(var i=1;i64&&buffer[i]<91){buffer[i]+=32}}return bytes.$factory(buffer)};bytes.center=function(){var $=$B.args("center",3,{self:null,width:null,fillbyte:null},["self","width","fillbyte"],arguments,{fillbyte:bytes.$factory([32])},null,null);var diff=$.width-$.self.source.length;if(diff<=0){return bytes.$factory($.self.source)}var ljust=bytes.ljust($.self,$.self.source.length+Math.floor(diff/2),$.fillbyte);return bytes.rjust(ljust,$.width,$.fillbyte)};bytes.count=function(){var $=$B.args("count",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:-1},null,null);var n=0,index=-1,len=0;if(typeof $.sub=="number"){if($.sub<0||$.sub>255)throw _b_.ValueError.$factory("byte must be in range(0, 256)");len=1}else if(!$.sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.sub)+"'")}else if(!$.sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.sub)+"'")}else{len=$.sub.source.length}do{index=bytes.find($.self,$.sub,Math.max(index+len,$.start),$.end);if(index!=-1){n++}}while(index!=-1);return n};bytes.decode=function(){var $=$B.args("decode",3,{self:null,encoding:null,errors:null},["self","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null);switch($.errors){case"strict":case"ignore":case"replace":case"surrogateescape":case"surrogatepass":case"xmlcharrefreplace":case"backslashreplace":return decode($.self,$.encoding,$.errors);default:}};bytes.endswith=function(){var $=$B.args("endswith",4,{self:null,suffix:null,start:null,end:null},["self","suffix","start","end"],arguments,{start:-1,end:-1},null,null);if($B.$isinstance($.suffix,bytes)){var end=$.end==-1?$.self.source.length:$.end;var res=true;for(let i=$.suffix.source.length-1,len=$.suffix.source.length;i>=0&&res;--i){res=$.self.source[end-len+i]==$.suffix.source[i]}return res}else if($B.$isinstance($.suffix,_b_.tuple)){for(let i=0;i<$.suffix.length;++i){if($B.$isinstance($.suffix[i],bytes)){if(bytes.endswith($.self,$.suffix[i],$.start,$.end)){return true}}else{throw _b_.TypeError.$factory("endswith first arg must be "+"bytes or a tuple of bytes, not "+$B.class_name($.suffix))}}return false}else{throw _b_.TypeError.$factory("endswith first arg must be bytes "+"or a tuple of bytes, not "+$B.class_name($.suffix))}};bytes.expandtabs=function(){var $=$B.args("expandtabs",2,{self:null,tabsize:null},["self","tabsize"],arguments,{tabsize:8},null,null);var tab_spaces=[];for(let i=0;i<$.tabsize;++i){tab_spaces.push(32)}var buffer=$.self.source.slice();for(let i=0;i255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}return self.source.slice(0,end==-1?undefined:end).indexOf(sub,start)}else if(!sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name(sub)+"'")}else if(!sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name(sub)+"'")}end=end==-1?self.source.length:Math.min(self.source.length,end);var len=sub.source.length;for(var i=start;i<=end-len;i++){var chunk=self.source.slice(i,i+len),found=true;for(var j=0;jstring.length){throw _b_.ValueError.$factory("non-hexadecimal number found "+"in fromhex() arg")}source.push(_b_.int.$factory(string.substr(i,2),16))}return $.cls.$factory(source)};bytes.hex=function(){var $=$B.args("hex",3,{self:null,sep:null,bytes_per_sep:null},["self","sep","bytes_per_sep"],arguments,{sep:"",bytes_per_sep:1},null,null),self=$.self,sep=$.sep,bytes_per_sep=$.bytes_per_sep,res="",digits="0123456789abcdef",bps=bytes_per_sep,jstart=bps,len=self.source.length;if(bytes_per_sep<0){bps=-bytes_per_sep;jstart=bps}else if(bytes_per_sep==0){sep=""}else{jstart=len%bps;if(jstart==0){jstart=bps}}for(var i=0,j=jstart;i>4];res+=digits[c&15]}return res};bytes.index=function(){var $=$B.args("index",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:-1},null,null);var index=bytes.find($.self,$.sub,$.start,$.end);console.log("index",index);if(index==-1){throw _b_.ValueError.$factory("subsection not found")}return index};bytes.isalnum=function(){var $=$B.args("isalnum",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,res=len>0;for(var i=0;i96&&src[i]<123||src[i]>64&&src[i]<91||src[i]>47&&src[i]<58}return res};bytes.isalpha=function(){var $=$B.args("isalpha",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,res=len>0;for(var i=0;i96&&src[i]<123||src[i]>64&&src[i]<91}return res};bytes.isdigit=function(){var $=$B.args("isdigit",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,res=len>0;for(let i=0;i47&&src[i]<58}return res};bytes.islower=function(){var $=$B.args("islower",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,res=false;for(let i=0;i96&&src[i]<123;if(src[i]>64&&src[i]<91){return false}}return res};bytes.isspace=function(){var $=$B.args("isspace",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length;for(let i=0;i64&&src[i]<91;if(src[i]>96&&src[i]<123){return false}}return res};bytes.istitle=function(){var $=$B.args("istitle",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false;for(var i=0;i96&&src[i]<123;is_uppercase=src[i]>64&&src[i]<91;current_char_is_letter=is_lowercase||is_uppercase;if(current_char_is_letter&&(prev_char_was_letter&&is_uppercase)||!prev_char_was_letter&&is_lowercase){return false}prev_char_was_letter=current_char_is_letter}return true};bytes.join=function(){var $ns=$B.args("join",2,{self:null,iterable:null},["self","iterable"],arguments,{}),self=$ns["self"],iterable=$ns["iterable"];var next_func=$B.$getattr(_b_.iter(iterable),"__next__"),res=self.__class__.$factory(),empty=true;while(true){try{var item=next_func();if(empty){empty=false}else{res=bytes.__add__(res,self)}res=bytes.__add__(res,item)}catch(err){if($B.$isinstance(err,_b_.StopIteration)){break}throw err}}return res};var _lower=function(char_code){if(char_code>=65&&char_code<=90){return char_code+32}else{return char_code}};bytes.lower=function(self){var _res=[],pos=0;for(var i=0,len=self.source.length;i=0?$.count:src.length;if(!$.old.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.old)+"'")}else if(!$.old.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.sep)+"'")}if(!$.new.__class__){throw _b_.TypeError.$factory("second argument must be a bytes-like "+"object, not '"+$B.class_name($.old)+"'")}else if(!$.new.__class__.$buffer_protocol){throw _b_.TypeError.$factory("second argument must be a bytes-like "+"object, not '"+$B.class_name($.sep)+"'")}for(var i=0;i255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}return $.self.source.slice(start,$.end==-1?undefined:$.end).lastIndexOf(sub)+start}else if(!sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.sub)+"'")}else if(!sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name(sub)+"'")}end=end==-1?self.source.length:Math.min(self.source.length,end);var len=sub.source.length;for(var i=end-len;i>=start;--i){var chunk=self.source.slice(i,i+len),found=true;for(var j=0;jstart){res.push(bytes.$factory(src.slice(start,stop)))}return $B.$list(res)};bytes.splitlines=function(){var $=$B.args("splitlines",2,{self:null,keepends:null},["self","keepends"],arguments,{keepends:false},null,null);if(!$B.$isinstance($.keepends,[_b_.bool,_b_.int])){throw _b_.TypeError("integer argument expected, got "+$B.get_class($.keepends).__name)}var keepends=_b_.int.$factory($.keepends),res=$B.$list([]),source=$.self.source,start=0,pos=0;if(!source.length){return res}while(pos96&&buffer[i]<123){buffer[i]-=32}else if(buffer[i]>64&&buffer[i]<91){buffer[i]+=32}}return bytes.$factory(buffer)};bytes.title=function(self){var src=self.source,len=src.length,buffer=src.slice(),current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false;for(var i=0;i96&&buffer[i]<123;is_uppercase=buffer[i]>64&&buffer[i]<91;current_char_is_letter=is_lowercase||is_uppercase;if(current_char_is_letter){if(prev_char_was_letter&&is_uppercase){buffer[i]+=32}else if(!prev_char_was_letter&&is_lowercase){buffer[i]-=32}}prev_char_was_letter=current_char_is_letter}return bytes.$factory(buffer)};bytes.translate=function(self,table,_delete){if(_delete===undefined){_delete=[]}else if($B.$isinstance(_delete,bytes)){_delete=_delete.source}else{throw _b_.TypeError.$factory("Type "+$B.get_class(_delete).__name+" doesn't support the buffer API")}var res=[],pos=0;if($B.$isinstance(table,bytes)&&table.source.length==256){for(var i=0,len=self.source.length;i-1){continue}res[pos++]=table.source[self.source[i]]}}return bytes.$factory(res)};var _upper=function(char_code){if(char_code>=97&&char_code<=122){return char_code-32}else{return char_code}};bytes.upper=function(self){var _res=[],pos=0;for(var i=0,len=self.source.length;i>5==6){if(b[pos+1]===undefined){err_info=[byte,pos,"end"]}else if((b[pos+1]&192)!=128){err_info=[byte,pos,"continuation"]}if(err_info!==null){if(errors=="ignore"){pos++}else{throw _b_.UnicodeDecodeError.$factory("'utf-8' codec can't decode byte 0x"+err_info[0].toString(16)+" in position "+err_info[1]+(err_info[2]=="end"?": unexpected end of data":": invalid continuation byte"))}}else{let cp=byte&31;cp<<=6;cp+=b[pos+1]&63;s+=String.fromCodePoint(cp);pos+=2}}else if(byte>>4==14){if(b[pos+1]===undefined){err_info=[byte,pos,"end",pos+1]}else if((b[pos+1]&192)!=128){err_info=[byte,pos,"continuation",pos+2]}else if(b[pos+2]===undefined){err_info=[byte,pos+"-"+(pos+1),"end",pos+2]}else if((b[pos+2]&192)!=128){err_info=[byte,pos,"continuation",pos+3]}if(err_info!==null){if(errors=="ignore"){pos=err_info[3]}else if(errors=="surrogateescape"){for(let i=pos;i>3==30){if(b[pos+1]===undefined){err_info=[byte,pos,"end",pos+1]}else if((b[pos+1]&192)!=128){err_info=[byte,pos,"continuation",pos+2]}else if(b[pos+2]===undefined){err_info=[byte,pos+"-"+(pos+1),"end",pos+2]}else if((b[pos+2]&192)!=128){err_info=[byte,pos,"continuation",pos+3]}else if(b[pos+3]===undefined){err_info=[byte,pos+"-"+(pos+1)+"-"+(pos+2),"end",pos+3]}if(err_info!==null){if(errors=="ignore"){pos=err_info[3]}else if(errors=="surrogateescape"){for(let i=pos;i")}}return decoded}return s};var encode=$B.encode=function(){var $=$B.args("encode",3,{s:null,encoding:null,errors:null},["s","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null),s=$.s,encoding=$.encoding,errors=$.errors;var t=[],pos=0,enc=normalise(encoding);switch(enc){case"utf-8":case"utf_8":case"utf8":if(globalThis.TextEncoder){var encoder=new TextEncoder("utf-8",{fatal:true});try{var array=encoder.encode(s);return fast_bytes(Array.from(array))}catch(err){}}for(let i=0,len=s.length;i>6),128+(cp&63))}else if(cp<=65535){t.push(224+(cp>>12),128+((cp&4095)>>6),128+(cp&63))}else{console.log("4 bytes")}}break;case"latin":case"latin1":case"latin-1":case"latin_1":case"L1":case"iso8859_1":case"iso_8859_1":case"8859":case"cp819":case"windows1252":for(let i=0,len=s.length;i>2>other_size){return set_copy_and_difference(so,other)}var result=make_new_set();if(other_is_dict){for(let entry of set_iter_with_hash(so)){if(!_b_.dict.$lookup_by_key(other,entry.item,entry.hash).found){set_add(result,entry.item,entry.hash)}}return result}for(let entry of set_iter_with_hash(so)){if(!set_contains(other,entry.item,entry.hash)){set_add(result,entry.item,entry.hash)}}result.__class__=so.__class__;return result}function set_difference_update(so,other){if(so===other){return set.clear(so)}if($B.$isinstance(other,[set,frozenset])){for(let entry of set_iter_with_hash(other)){set_discard_entry(so,entry.item,entry.hash)}}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(other)){set_discard_entry(so,entry.key,entry.hash)}}else{var iterator=$B.make_js_iterator(other);for(let key of iterator){set_discard_key(so,key)}}}const DISCARD_NOTFOUND=0;function set_discard_entry(so,key,hash){var entry=set_lookkey(so,key,hash);if(!entry){return DISCARD_NOTFOUND}if(so.$store[entry.hash]!==undefined){set_remove(so,entry.hash,entry.index)}}function set_discard_key(so,key){return set_discard_entry(so,key)}function*set_iter(so){var ordered_keys=Object.keys(so.$store).sort();for(var hash of ordered_keys){if(so.$store[hash]!==undefined){for(var item of so.$store[hash]){yield item}}}}function*set_iter_with_hash(so){for(var hash in so.$store){if(so.$store[hash]!==undefined){for(var item of so.$store[hash]){yield{item:item,hash:hash}}}}}function set_remove(so,hash,index){so.$store[hash].splice(index,1);if(so.$store[hash].length==0){delete so.$store[hash]}so.$used--}function set_intersection(so,other){if(so===other){return set_copy(so)}var result=make_new_set_base_type(so);if($B.$isinstance(other,[set,frozenset])){if(other.$used>so.$used){var tmp=so;so=other;other=tmp}for(let entry of set_iter_with_hash(other)){if(set_contains(so,entry.item,entry.hash)){set_add(result,entry.item,entry.hash)}}}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(other)){if(set_contains(so,entry.key,entry.hash)){set_add(result,entry.key,entry.hash)}}}else{let iterator=$B.make_js_iterator(other);for(var other_item of iterator){var test=set_contains(so,other_item);if(test){set_add(result,other_item)}}}return result}function set_intersection_multi(so,args){var result=set_copy(so);if(args.length==0){return result}for(var other of args){result=set_intersection(result,other)}return result}function set_lookkey(so,key,hash){if(hash===undefined){try{hash=$B.$hash(key)}catch(err){if($B.$isinstance(key,set)){hash=$B.$hash(frozenset.$factory(key))}else{throw err}}}var items=so.$store[hash];if(items===undefined){return false}for(var index=0,len=so.$store[hash].length;index0){set.clear(self)}set.update(self,iterable);return _b_.None};var set_iterator=$B.make_class("set_iterator",(function(so){return{__class__:set_iterator,so:so,it:set_iter(so),version:so.$version}}));set_iterator.__iter__=function(self){return self};set_iterator.__length_hint__=function(self){return self.so.$used};set_iterator.__next__=function(self){var res=self.it.next();if(res.done){throw _b_.StopIteration.$factory()}if(self.so.$version!=self.version){throw _b_.RuntimeError.$factory("Set changed size during iteration")}return res.value};set_iterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([set_make_items(self.so)])])};$B.set_func_names(set_iterator,"builtins");set.__iter__=function(self){return set_iterator.$factory(self)};function set_make_items(so){var items=[];for(var hash in so.$store){items=items.concat(so.$store[hash])}return $B.$list(items)}set.__le__=function(self,other){if($B.$isinstance(other,[set,frozenset])){return set.issubset(self,other)}return _b_.NotImplemented};set.__len__=function(self){return self.$used};set.__lt__=function(self,other){if($B.$isinstance(other,[set,frozenset])){return set.__le__(self,other)&&set.__len__(self)1){throw _b_.TypeError.$factory(`set.pop() takes no arguments`+` (${arguments.length-1} given)`)}for(var hash in self.$store){break}if(hash===undefined){throw _b_.KeyError.$factory("pop from an empty set")}var item;item=self.$store[hash].pop();if(self.$store[hash].length==0){delete self.$store[hash]}self.$used--;self.$version++;return item};set.remove=function(){var $=$B.args("remove",2,{self:null,item:null},["self","item"],arguments,{},null,null),self=$.self,item=$.item;var result=set_discard_entry(self,item);if(result==DISCARD_NOTFOUND){throw _b_.KeyError.$factory(item)}self.$version++;return _b_.None};set.symmetric_difference_update=function(){var $=$B.args("symmetric_difference_update",2,{self:null,s:null},["self","s"],arguments,{},null,null),self=$.self,s=$.s;return set_symmetric_difference_update(self,s)};set.update=function(self){var $=$B.args("update",1,{self:null},["self"],arguments,{},"args",null);for(var iterable of $.args){if(Array.isArray(iterable)){for(let i=0;iset.__len__(other)){return false}for(let entry of set_iter_with_hash(self)){if(!set_lookkey(other,entry.item,entry.hash)){return false}}return true}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(self)){if(!set_lookkey(other,entry.key,entry.hash)){return false}}return true}else{var member_func=$B.member_func(other);for(let entry of set_iter_with_hash(self)){if(!member_func(entry.item)){return false}}return true}};set.issuperset=function(){var $=$B.args("issuperset",2,{self:null,other:null},["self","other"],arguments,{},"args",null),self=$.self,other=$.other;if($B.$isinstance(other,[set,frozenset])){return set.issubset(other,self)}else{return set.issubset(set.$factory(other),self)}};set.__iand__=function(self,other){if(!$B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented}set.intersection_update(self,other);return self};set.__isub__=function(self,other){if(!$B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented}set_difference_update(self,other);return self};set.__ixor__=function(self,other){if(!$B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented}set.symmetric_difference_update(self,other);return self};set.__ior__=function(self,other){if(!$B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented}set.update(self,other);return self};set.$literal=function(items){let res=make_new_set(set);for(let item of items){if(item.constant){set_add(res,item.constant[0],item.constant[1])}else if(item.starred){for(let _item of $B.make_js_iterator(item.starred)){set_add(res,_item)}}else{set_add(res,item.item)}}return res};set.$factory=function(){var args=[set].concat(Array.from(arguments)),self=set.__new__.apply(null,args);set.__init__(self,...arguments);return self};$B.set_func_names(set,"builtins");set.__class_getitem__=_b_.classmethod.$factory(set.__class_getitem__);var frozenset=$B.make_class("frozenset");frozenset.$native=true;for(var attr in set){switch(attr){case"add":case"clear":case"discard":case"pop":case"remove":case"update":break;default:if(frozenset[attr]==undefined){if(typeof set[attr]=="function"){frozenset[attr]=function(x){return function(){return set[x].apply(null,arguments)}}(attr)}else{frozenset[attr]=set[attr]}}}}frozenset.__hash__=function(self){if(self===undefined){return frozenset.__hashvalue__||$B.$py_next_hash--}if(self.__hashvalue__!==undefined){return self.__hashvalue__}var _hash=1927868237;_hash*=self.$used;for(var entry of set_iter_with_hash(self)){var _h=entry.hash;_hash^=(_h^89869747^_h<<16)*3644798167}_hash=_hash*69069+907133923;if(_hash==-1){_hash=590923713}return self.__hashvalue__=_hash};frozenset.__init__=function(){return _b_.None};frozenset.__new__=function(cls,iterable){if(cls===undefined){throw _b_.TypeError.$factory("frozenset.__new__(): not enough arguments")}var self=make_new_set(cls);if(iterable===undefined){return self}$B.check_nb_args_no_kw("__new__",2,arguments);if(cls===frozenset&&iterable.__class__===frozenset){return iterable}set.update(self,iterable);return self};frozenset.__repr__=function(self){$B.builtins_repr_check(frozenset,arguments);return set_repr(self)};frozenset.copy=function(self){if(self.__class__===frozenset){return self}return set_copy(self)};frozenset.$factory=function(){var args=[frozenset].concat(Array.from(arguments)),self=frozenset.__new__.apply(null,args);frozenset.__init__(self,...arguments);return self};$B.set_func_names(frozenset,"builtins");_b_.set=set;_b_.frozenset=frozenset})(__BRYTHON__);(function($B){var _b_=$B.builtins,_window=globalThis;var Module=$B.module=$B.make_class("module",(function(name,doc,$package){return{$tp_class:Module,__builtins__:_b_.__builtins__,__name__:name,__doc__:doc||_b_.None,__package__:$package||_b_.None}}));Module.__dir__=function(self){if(self.__dir__){return $B.$call(self.__dir__)()}var res=[];for(var key in self){if(key.startsWith("$")||key=="__class__"){continue}res[res.length]=key}return $B.$list(res.sort())};Module.__new__=function(cls,name,doc,$package){return{__class__:cls,__builtins__:_b_.__builtins__,__name__:name,__doc__:doc||_b_.None,__package__:$package||_b_.None}};Module.__repr__=Module.__str__=function(self){var res=""};Module.__setattr__=function(self,attr,value){if(self.__name__=="__builtins__"){$B.builtins[attr]=value}else{self[attr]=value}};$B.set_func_names(Module,"builtins");$B.make_import_paths=function(filename){var filepath=$B.script_domain?$B.script_domain+"/"+filename:filename;var elts=filepath.split("/");elts.pop();var script_dir=elts.join("/"),path=[$B.brython_path+"Lib",$B.brython_path+"libs",script_dir,$B.brython_path+"Lib/site-packages"];var meta_path=[],path_hooks=[];if($B.use_VFS){meta_path.push($B.finders.VFS)}var static_stdlib_import=$B.get_option_from_filename("static_stdlib_import",filename);if(static_stdlib_import!==false&&$B.protocol!="file"){meta_path.push($B.finders.stdlib_static);if(path.length>3){path.shift();path.shift()}}var pythonpath=$B.get_option_from_filename("pythonpath",filename);if(pythonpath){var ix=path.indexOf(script_dir);if(ix===-1){console.log("bizarre, script_dir",script_dir,"not in path",path)}else{var fullpaths=[];for(var p of pythonpath){if(p=="."){fullpaths.push(script_dir)}else if(p.startsWith("/")){fullpaths.push($B.script_domain+p)}else if(p.split("://")[0].startsWith("http")){fullpaths.push(p)}else if(!p.startsWith($B.script_domain)){fullpaths.push(script_dir+"/"+p)}else{fullpaths.push(p)}}path.splice(ix,1,...fullpaths)}}if($B.protocol!=="file"){meta_path.push($B.finders.path);path_hooks.push($B.url_hook)}$B.import_info[filename]={meta_path:meta_path,path_hooks:path_hooks,path:path}};function $download_module(mod,url){var xhr=new XMLHttpRequest,fake_qs="?v="+(new Date).getTime(),res=null,mod_name=mod.__name__;if($B.get_option("cache")){xhr.open("GET",url,false)}else{xhr.open("GET",url+fake_qs,false)}var timer=_window.setTimeout((function(){xhr.abort()}),5e3);xhr.send();if($B.$CORS){if(xhr.status==200||xhr.status==0){res=xhr.responseText}else{res=_b_.ModuleNotFoundError.$factory("No module named '"+mod_name+"'")}}else{if(xhr.readyState==4){if(xhr.status==200){res=xhr.responseText;mod.$last_modified=xhr.getResponseHeader("Last-Modified")}else{console.info("Trying to import "+mod_name+", not found at url "+url);res=_b_.ModuleNotFoundError.$factory("No module named '"+mod_name+"'")}}}_window.clearTimeout(timer);if(res==null){throw _b_.ModuleNotFoundError.$factory("No module named '"+mod_name+"' (res is null)")}if(res.constructor===Error){throw res}return res}$B.$download_module=$download_module;$B.addToImported=function(name,modobj){$B.imported[name]=modobj;if(modobj===undefined){throw _b_.ImportError.$factory("imported not set by module")}modobj.__class__=Module;modobj.__name__=name;for(var attr in modobj){if(typeof modobj[attr]=="function"){modobj[attr].$infos={__module__:name,__name__:attr,__qualname__:attr};modobj[attr].$in_js_module=true}else if($B.$isinstance(modobj[attr],_b_.type)&&!modobj[attr].hasOwnProperty("__module__")){modobj[attr].__module__=name}}};function run_js(module_contents,path,_module){try{new Function(module_contents)()}catch(err){throw $B.exception(err)}var modobj=$B.imported[_module.__name__];if(modobj===undefined){throw _b_.ImportError.$factory("imported not set by module")}modobj.__class__=Module;modobj.__name__=_module.__name__;for(var attr in modobj){if(typeof modobj[attr]=="function"){modobj[attr].$infos={__module__:_module.__name__,__name__:attr,__qualname__:attr};modobj[attr].$in_js_module=true}else if($B.$isinstance(modobj[attr],_b_.type)&&!modobj[attr].hasOwnProperty("__module__")){modobj[attr].__module__=_module.__name__}}return true}function run_py(module_contents,path,module,compiled){var filename=module.__file__;$B.file_cache[filename]=module_contents;$B.url2name[filename]=module.__name__;var root,js,mod_name=module.__name__,src;if(!compiled){src={src:module_contents,filename:filename,imported:true};try{root=$B.py2js(src,module,module.__name__,$B.builtins_scope)}catch(err){err.$frame_obj=$B.frame_obj;if($B.get_option("debug",err)>1){console.log("error in imported module",module);console.log("stack",$B.make_frames_stack(err.$frame_obj))}throw err}}try{js=compiled?module_contents:root.to_js();if($B.get_option("debug")==10){console.log("code for module "+module.__name__);console.log($B.format_indent(js,0))}src=js;js="var $module = (function(){\n"+js;var prefix="locals_";js+="return "+prefix;js+=module.__name__.replace(/\./g,"_")+"})(__BRYTHON__)\n"+"return $module";var module_id=prefix+module.__name__.replace(/\./g,"_");var mod=new Function(module_id,js)(module)}catch(err){err.$frame_obj=err.$frame_obj||$B.frame_obj;if($B.get_option("debug",err)>2){console.log(err+" for module "+module.__name__);console.log("module",module);console.log(root);if($B.get_option("debug",err)>1){console.log($B.format_indent(js,0))}for(let attr in err){console.log(attr,err[attr])}console.log("message: "+err.$message);console.log("filename: "+err.fileName);console.log("linenum: "+err.lineNumber);console.log(js.split("\n").slice(err.lineNumber-3,err.lineNumber+3).join("\n"));console.log(err.stack)}throw err}var imports=Object.keys(root.imports).join(",");try{for(let attr in mod){module[attr]=mod[attr]}module.__initializing__=false;$B.imported[module.__name__]=module;return{content:src,name:mod_name,imports:imports,is_package:module.$is_package,path:path,timestamp:$B.timestamp,source_ts:module.__spec__.loader_state.timestamp}}catch(err){console.log(""+err+" "+" for module "+module.__name__);for(let attr in err){console.log(attr+" "+err[attr])}if($B.get_option("debug")>0){console.log("line info "+__BRYTHON__.line_info)}throw err}}$B.run_py=run_py;$B.run_js=run_js;var ModuleSpec=$B.make_class("ModuleSpec",(function(fields){fields.__class__=ModuleSpec;return fields}));ModuleSpec.__str__=ModuleSpec.__repr__=function(self){var res=`ModuleSpec(name='${self.name}', `+`loader=${_b_.str.$factory(self.loader)}, `+`origin='${self.origin}'`;if(self.submodule_search_locations!==_b_.None){res+=`, submodule_search_locations=`+`${_b_.str.$factory(self.submodule_search_locations)}`}return res+")"};$B.set_func_names(ModuleSpec,"builtins");function parent_package(mod_name){var parts=mod_name.split(".");parts.pop();return parts.join(".")}var VFSFinder=$B.make_class("VFSFinder",(function(){return{__class__:VFSFinder}}));VFSFinder.find_spec=function(cls,fullname){var stored,is_package,timestamp;if(!$B.use_VFS){return _b_.None}stored=$B.VFS[fullname];if(stored===undefined){return _b_.None}is_package=stored[3]||false;timestamp=stored.timestamp;if(stored){var is_builtin=$B.builtin_module_names.indexOf(fullname)>-1;return ModuleSpec.$factory({name:fullname,loader:VFSLoader.$factory(),origin:is_builtin?"built-in":"brython_stdlib",submodule_search_locations:is_package?$B.$list([]):_b_.None,loader_state:{stored:stored,timestamp:timestamp},cached:_b_.None,parent:is_package?fullname:parent_package(fullname),has_location:_b_.False})}};$B.set_func_names(VFSFinder,"");for(let method in VFSFinder){if(typeof VFSFinder[method]=="function"){VFSFinder[method]=_b_.classmethod.$factory(VFSFinder[method])}}const VFSLoader=$B.make_class("VFSLoader",(function(){return{__class__:VFSLoader}}));VFSLoader.create_module=function(){return _b_.None};VFSLoader.exec_module=function(self,modobj){var stored=modobj.__spec__.loader_state.stored,timestamp=modobj.__spec__.loader_state.timestamp;var ext=stored[0],module_contents=stored[1],imports=stored[2];modobj.$is_package=stored[3]||false;var path="VFS."+modobj.__name__;path+=modobj.$is_package?"/__init__.py":ext;modobj.__file__=path;$B.file_cache[modobj.__file__]=$B.VFS[modobj.__name__][1];$B.url2name[modobj.__file__]=modobj.__name__;if(ext==".js"){run_js(module_contents,modobj.__path__,modobj)}else if($B.precompiled.hasOwnProperty(modobj.__name__)){if($B.get_option("debug")>1){console.info("load",modobj.__name__,"from precompiled")}var parts=modobj.__name__.split(".");for(var i=0;i";mod.__package__=parent;mod.$is_package=true}else{let elts=parent.split(".");elts.pop();mod.__package__=elts.join(".")}mod.__file__=path;try{var parent_id=parent.replace(/\./g,"_"),prefix="locals_";mod_js+="return "+prefix+parent_id;var $module=new Function(prefix+parent_id,mod_js)(mod)}catch(err){if($B.get_option("debug")>1){console.log("error in module",mod);console.log(err);for(var k in err){console.log(k,err[k])}console.log(Object.keys($B.imported));console.log(modobj,"mod_js",mod_js)}throw err}for(var attr in $module){mod[attr]=$module[attr]}$module.__file__=path;if(i>0){$B.builtins.setattr($B.imported[parts.slice(0,i).join(".")],parts[i],$module)}}return $module}else{var mod_name=modobj.__name__;if($B.get_option("debug")>1){console.log("run Python code from VFS",mod_name)}var path=$B.brython_path+"/"+modobj.__file__;var record=run_py(module_contents,path,modobj);record.imports=imports.join(",");record.is_package=modobj.$is_package;record.timestamp=$B.timestamp;record.source_ts=timestamp;$B.precompiled[mod_name]=record.is_package?[record.content]:record.content;let elts=mod_name.split(".");if(elts.length>1){elts.pop()}if($B.get_page_option("indexeddb")&&$B.indexedDB&&$B.idb_name){var idb_cx=indexedDB.open($B.idb_name);idb_cx.onsuccess=function(evt){var db=evt.target.result,tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),request=store.put(record);request.onsuccess=function(){if($B.get_option("debug")>1){console.info(modobj.__name__,"stored in db")}};request.onerror=function(){console.info("could not store "+modobj.__name__)}}}}};$B.set_func_names(VFSLoader,"builtins");var StdlibStaticFinder=$B.make_class("StdlibStaticFinder",(function(){return{__class__:StdlibStaticFinder}}));StdlibStaticFinder.find_spec=function(self,fullname){if($B.stdlib&&$B.get_option("static_stdlib_import")){var address=$B.stdlib[fullname];if(address===undefined){var elts=fullname.split(".");if(elts.length>1){elts.pop();var $package=$B.stdlib[elts.join(".")];if($package&&$package[1]){address=["py"]}}}if(address!==undefined){var ext=address[0],is_pkg=address[1]!==undefined,path=$B.brython_path+(ext=="py"?"Lib/":"libs/")+fullname.replace(/\./g,"/"),metadata={ext:ext,is_package:is_pkg,path:path+(is_pkg?"/__init__.py":ext=="py"?".py":".js"),address:address},_module=Module.$factory(fullname);metadata.code=$download_module(_module,metadata.path);var res=ModuleSpec.$factory({name:fullname,loader:PathLoader.$factory(),origin:metadata.path,submodule_search_locations:is_pkg?$B.$list([path]):_b_.None,loader_state:metadata,cached:_b_.None,parent:is_pkg?fullname:parent_package(fullname),has_location:_b_.True});return res}}return _b_.None};$B.set_func_names(StdlibStaticFinder,"");for(let method in StdlibStaticFinder){if(typeof StdlibStaticFinder[method]=="function"){StdlibStaticFinder[method]=_b_.classmethod.$factory(StdlibStaticFinder[method])}}StdlibStaticFinder.$factory=function(){return{__class__:StdlibStaticFinder}};var PathFinder=$B.make_class("PathFinder",(function(){return{__class__:PathFinder}}));PathFinder.find_spec=function(cls,fullname,path){if($B.VFS&&$B.VFS[fullname]){return _b_.None}if($B.is_none(path)){path=get_info("path")}for(var i=0,li=path.length;i");for(let method in PathFinder){if(typeof PathFinder[method]=="function"){PathFinder[method]=_b_.classmethod.$factory(PathFinder[method])}}var PathEntryFinder=$B.make_class("PathEntryFinder",(function(path_entry,hint){return{__class__:PathEntryFinder,path_entry:path_entry,hint:hint}}));PathEntryFinder.find_spec=function(self,fullname){var loader_data={},notfound=true,hint=self.hint,base_path=self.path_entry+fullname.match(/[^.]+$/g)[0],modpaths=[],py_ext=$B.get_option("python_extension");var tryall=hint===undefined;if(tryall||hint=="py"){modpaths=modpaths.concat([[base_path+py_ext,"py",false],[base_path+"/__init__"+py_ext,"py",true]])}for(var j=0;notfound&&j-1){meta_path.splice(path_ix,1)}}for(var i=0,len=meta_path.length;i0;if(modobj==_b_.None){import_error(mod_name)}if(modobj===undefined){if($B.is_none(fromlist)){fromlist=[]}for(var i=0,modsep="",_mod_name="",len=parsed_name.length-1,__path__=_b_.None;i<=len;++i){var _parent_name=_mod_name;_mod_name+=modsep+parsed_name[i];modsep=".";modobj=$B.imported[_mod_name];if($test){console.log("iter",i,_mod_name,"\nmodobj",modobj,"\n__path__",__path__,Array.isArray(__path__));alert()}if(modobj==_b_.None){import_error(_mod_name)}else if(modobj===undefined){try{import_engine(_mod_name,__path__,from_stdlib)}catch(err){delete $B.imported[_mod_name];throw err}if($B.is_none($B.imported[_mod_name])){import_error(_mod_name)}else{if(_parent_name){_b_.setattr($B.imported[_parent_name],parsed_name[i],$B.imported[_mod_name])}}}else if($B.imported[_parent_name]&&$B.imported[_parent_name][parsed_name[i]]===undefined){_b_.setattr($B.imported[_parent_name],parsed_name[i],$B.imported[_mod_name])}if(i0){return $B.imported[mod_name]}else{let package_name=mod_name;while(parsed_name.length>1){var module=parsed_name.pop();package_name=parsed_name.join(".");if($B.imported[package_name]===undefined){$B.$import(package_name,[],{},locals);$B.imported[package_name][module]=$B.imported[mod_name];mod_name=module}}return $B.imported[package_name]}};$B.$import=function(mod_name,fromlist,aliases,locals){var test=false;if(test){console.log("import",mod_name,fromlist,aliases)}if(mod_name=="_frozen_importlib_external"){let alias=aliases[mod_name]||mod_name;$B.$import_from("importlib",["_bootstrap_external"],{_bootstrap_external:alias},0,locals);let _bootstrap=$B.imported.importlib._bootstrap,_bootstrap_external=$B.imported.importlib["_bootstrap_external"];_bootstrap_external._set_bootstrap_module(_bootstrap);_bootstrap._bootstap_external=_bootstrap_external;let _frozen_importlib=$B.imported._frozen_importlib;if(_frozen_importlib){_frozen_importlib._bootstrap_external=_bootstrap_external}return}var level=0,frame=$B.frame_obj.frame,current_module=frame[2],parts=current_module.split(".");while(mod_name.length>0&&mod_name.startsWith(".")){level++;mod_name=mod_name.substr(1);if(parts.length==0){throw _b_.ImportError.$factory("Parent module '' not loaded, "+"cannot perform relative import")}current_module=parts.join(".");parts.pop()}if(level>0){mod_name=current_module+(mod_name.length>0?"."+mod_name:"")}parts=mod_name.split(".");if(mod_name[mod_name.length-1]=="."){parts.pop()}var norm_parts=[],prefix=true;for(var p of parts){if(prefix&&p==""){var elt=norm_parts.pop();if(elt===undefined){throw _b_.ImportError.$factory("Parent module '' not loaded, "+"cannot perform relative import")}}else{prefix=false;norm_parts.push(p)}}mod_name=norm_parts.join(".");fromlist=fromlist===undefined?[]:fromlist;aliases=aliases===undefined?{}:aliases;locals=locals===undefined?{}:locals;if(test){console.log("step 2, mod_name",mod_name,"fromlist",fromlist)}if($B.get_option("debug")==10){console.log("$import "+mod_name);console.log("use VFS ? "+$B.use_VFS);console.log("use static stdlib paths ? "+$B.get_option("static_stdlib_import"))}var current_frame=$B.frame_obj.frame,_globals=current_frame[3],__import__=_globals["__import__"],globals=$B.obj_dict(_globals);if(__import__===undefined){__import__=$B.$__import__}var importer=typeof __import__=="function"?__import__:$B.$getattr(__import__,"__call__");if(test){console.log("use importer",importer,"mod_name",mod_name,"fromlist",fromlist)}var modobj=importer(mod_name,globals,undefined,fromlist,0);if(test){console.log("step 3, mod_name",mod_name,"fromlist",fromlist);console.log("modobj",modobj)}if(!fromlist||fromlist.length==0){let alias=aliases[mod_name];if(alias){locals[alias]=$B.imported[mod_name]}else{locals[norm_parts[0]]=modobj}}else{var __all__=fromlist,thunk={};if(fromlist&&fromlist[0]=="*"){if(test){console.log("import *",modobj)}__all__=$B.$getattr(modobj,"__all__",thunk);if(__all__!==thunk){aliases={}}}if(__all__===thunk){for(var attr in modobj){if(attr[0]!=="_"){locals[attr]=modobj[attr]}}}else{for(let name of __all__){var alias=aliases[name]||name;try{locals[alias]=$B.$getattr(modobj,name);if(locals[alias]&&locals[alias].$js_func){locals[alias]=locals[alias].$js_func}}catch($err1){if(!$B.is_exc($err1,[_b_.AttributeError])){throw $err1}try{$B.$getattr(__import__,"__call__")(mod_name+"."+name,globals,undefined,[],0);locals[alias]=$B.$getattr(modobj,name)}catch($err3){if(mod_name==="__future__"){var exc=_b_.SyntaxError.$factory("future feature "+name+" is not defined");throw exc}var $frame=[mod_name,modobj,mod_name,modobj],suggestion=$B.offer_suggestions_for_name_error({name:name},$frame);if($err3.$py_error){$err3.__class__=_b_.ImportError;$err3.args[0]=`cannot import name '${name}' `+`from '${mod_name}'`;if(modobj.__file__){$err3.args[0]+=` (${modobj.__file__})`}$err3.$suggestion=suggestion;throw $err3}if($B.get_option("debug")>1){console.log($err3);console.log($B.frame_obj.frame)}throw _b_.ImportError.$factory("cannot import name '"+name+"'")}}}}return locals}};$B.$import_from=function(module,names,aliases,level,locals){var current_module_name=$B.frame_obj.frame[2],parts=current_module_name.split("."),relative=level>0,current_module;if(relative){current_module=$B.imported[parts.join(".")];if(current_module===undefined){throw _b_.ImportError.$factory("attempted relative import with no known parent package")}if(!current_module.$is_package){if(parts.length==1){throw _b_.ImportError.$factory("attempted relative import with no known parent package")}else{parts.pop();current_module=$B.imported[parts.join(".")]}}while(level>0){current_module=$B.imported[parts.join(".")];if(!current_module.$is_package){throw _b_.ImportError.$factory("attempted relative import with no known parent package")}level--;parts.pop()}if(module){var submodule=current_module.__name__+"."+module;$B.$import(submodule,[],{},{});current_module=$B.imported[submodule]}if(names.length>0&&names[0]=="*"){for(var key in current_module){if(key.startsWith("$")||key.startsWith("_")){continue}locals[key]=current_module[key]}}else{for(var name of names){var alias=aliases[name]||name;if(current_module[name]!==undefined){locals[alias]=current_module[name]}else{var sub_module=current_module.__name__+"."+name;$B.$import(sub_module,[],{},{});locals[alias]=$B.imported[sub_module]}}}}else{$B.$import(module,names,aliases,locals)}};$B.import_all=function(locals,module){for(var attr in module){if("_$".indexOf(attr.charAt(0))==-1){locals[attr]=module[attr]}}};$B.$meta_path=[VFSFinder,StdlibStaticFinder,PathFinder];$B.finders={VFS:VFSFinder,stdlib_static:StdlibStaticFinder,path:PathFinder};function optimize_import_for_path(path,filetype){if(path.slice(-1)!="/"){path=path+"/"}var value=filetype=="none"?_b_.None:url_hook(path,filetype);$B.path_importer_cache[path]=value}var Loader={__class__:$B.$type,__mro__:[_b_.object],__name__:"Loader"};var _importlib_module={__class__:Module,__name__:"_importlib",Loader:Loader,VFSFinder:VFSFinder,StdlibStatic:StdlibStaticFinder,ImporterPath:PathFinder,UrlPathFinder:url_hook,optimize_import_for_path:optimize_import_for_path};_importlib_module.__repr__=_importlib_module.__str__=function(){return""};$B.imported["_importlib"]=_importlib_module})(__BRYTHON__);(function($B){var _b_=$B.builtins;var escape2cp=$B.escape2cp={b:"\b",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v"};$B.surrogates=function(s){var s1="",escaped=false;for(var char of s){if(escaped){var echar=escape2cp[char];if(echar!==undefined){s1+=echar}else{s1+="\\"+char}escaped=false}else if(char=="\\"){escaped=true}else{s1+=char}}var surrogates=[],j=0;for(var i=0,len=s1.length;i=65536){surrogates.push(j);i++}j++}return surrogates};$B.String=function(s){var srg=$B.surrogates(s);return srg.length==0?s:$B.make_String(s,srg)};$B.make_String=function(s,surrogates){var res=new String(s);res.__class__=str;res.surrogates=surrogates;return res};function pypos2jspos(s,pypos){if(s.surrogates===undefined){return pypos}var nb=0;while(s.surrogates[nb]' requires "+"string as left operand, not "+$B.class_name(item))}[_self,item]=to_string([_self,item]);return _self.includes(item)};str.__delitem__=function(){throw _b_.TypeError.$factory("'str' object doesn't support item deletion")};str.__dir__=_b_.object.__dir__;str.__eq__=function(_self,other){if($B.$isinstance(other,str)){[_self,other]=to_string([_self,other]);return _self+""==other+""}return _b_.NotImplemented};function preformat(_self,fmt){if(fmt.empty){return _b_.str.$factory(_self)}if(fmt.type&&fmt.type!="s"){throw _b_.ValueError.$factory("Unknown format code '"+fmt.type+"' for object of type 'str'")}return _self}str.__format__=function(_self,format_spec){[_self,format_spec]=to_string([_self,format_spec]);var fmt=new $B.parse_format_spec(format_spec,_self);if(fmt.sign!==undefined){throw _b_.ValueError.$factory("Sign not allowed in string format specifier")}if(fmt.precision){_self=_self.substr(0,fmt.precision)}fmt.align=fmt.align||"<";return $B.format_width(preformat(_self,fmt),fmt)};str.__getitem__=function(_self,arg){_self=to_string(_self);if($B.$isinstance(arg,_b_.int)){var len=str.__len__(_self);var pos=arg;if(arg<0){pos+=len}if(pos>=0&&pos=65536){return $B.String(_self.substr(jspos,2))}else{return _self[jspos]}}throw _b_.IndexError.$factory("string index out of range")}if($B.$isinstance(arg,_b_.slice)){return _b_.str.$getitem_slice(_self,arg)}if($B.$isinstance(arg,_b_.bool)){return _self.__getitem__(_b_.int.$factory(arg))}throw _b_.TypeError.$factory("string indices must be integers")};str.$getitem_slice=function(_self,slice){var len=str.__len__(_self),s=_b_.slice.$conv_for_seq(slice,len),start=pypos2jspos(_self,s.start),stop=pypos2jspos(_self,s.stop),step=s.step;var res="";if(step>0){if(stop<=start){return""}for(let i=start;i=start){return""}for(let i=start;i>stop;i+=step){res+=_self[i]}}return $B.String(res)};var prefix=2,suffix=3;str.$getnewargs=function(self){return $B.fast_tuple([to_string(self)])};str.__getnewargs__=function(){return str.$getnewargs($B.single_arg("__getnewargs__","self",arguments))};str.__hash__=function(_self){var s=to_string(_self);for(var i=0,h=0,len=s.length;imax_precision){throw _b_.OverflowError.$factory("precision too large")}var s;if(val.__class__===$B.long_int){s=$B.long_int.to_base(val,10)}else{s=val.toString()}if(precision-s.length>max_repeat){throw _b_.OverflowError.$factory("precision too large")}if(s[0]==="-"){return"-"+"0".repeat(Math.max(0,precision-s.length+1))+s.slice(1)}return"0".repeat(Math.max(0,precision-s.length))+s};var format_float_precision=function(val,upper,flags,modifier){var precision=flags.precision;if(isFinite(val)){return modifier(val,precision,flags,upper)}if(val===Infinity){val="inf"}else if(val===-Infinity){val="-inf"}else{val="nan"}if(upper){return val.toUpperCase()}return val};var format_sign=function(val,flags){if(flags.sign){if(val>=0||isNaN(val)||val===Number.POSITIVE_INFINITY){return"+"}}else if(flags.space){if(val>=0||isNaN(val)){return" "}}return""};var str_format=function(val,flags){flags.pad_char=" ";return format_padding(str.$factory(val),flags)};var num_format=function(val,flags){number_check(val,flags);if($B.$isinstance(val,_b_.float)){val=parseInt(val.value)}else if(!$B.$isinstance(val,_b_.int)){val=parseInt(val)}else if($B.$isinstance(val,_b_.bool)){val=val?1:0}var s=format_int_precision(val,flags);if(flags.pad_char==="0"){if(val<0){s=s.substring(1);return"-"+format_padding(s,flags,true)}var sign=format_sign(val,flags);if(sign!==""){return sign+format_padding(s,flags,true)}}return format_padding(format_sign(val,flags)+s,flags)};var repr_format=function(val,flags){flags.pad_char=" ";return format_padding(_b_.repr(val),flags)};var ascii_format=function(val,flags,type){flags.pad_char=" ";var ascii;if(type=="bytes"){var repr=_b_.repr(val);ascii=_b_.str.encode(repr,"ascii","backslashreplace");ascii=_b_.bytes.decode(ascii,"ascii")}else{ascii=_b_.ascii(val)}return format_padding(ascii,flags)};var _float_helper=function(val,flags){number_check(val,flags);if(flags.precision===undefined){if(!flags.decimal_point){flags.precision=6}else{flags.precision=0}}else{flags.precision=parseInt(flags.precision,10);validate_precision(flags.precision)}return $B.$isinstance(val,_b_.int)?val:val.value};var validate_precision=function(precision){if(precision>20){precision=20}};function handle_special_values(value,upper){var special;if(isNaN(value)){special=upper?"NAN":"nan"}else if(value==Number.POSITIVE_INFINITY){special=upper?"INF":"inf"}else if(value==Number.NEGATIVE_INFINITY){special=upper?"-INF":"-inf"}return special}var floating_point_format=function(val,upper,flags){val=_float_helper(val,flags);var special=handle_special_values(val,upper);if(special){return format_padding(format_sign(val,flags)+special,flags)}var p=flags.precision;if(p==0){p=1}var exp_format=val.toExponential(p-1),e_index=exp_format.indexOf("e"),exp=parseInt(exp_format.substr(e_index+1)),res;function remove_zeros(v){if(flags.alternate){return v}if(v.indexOf(".")>-1){while(v.endsWith("0")){v=v.substr(0,v.length-1)}if(v.endsWith(".")){v=v.substr(0,v.length-1)}}return v}if(-4<=exp&&exp-1){return BigInt(v).toString()}const mul=Math.pow(10,d);var is_neg=v<0;if(is_neg){v=-v}var res_floor=(Math.floor(v*mul)/mul).toFixed(d),res_ceil=(Math.ceil(v*mul)/mul).toFixed(d),res;if(v-res_floor==res_ceil-v){var last=res_floor[res_floor.length-1];res=last.match(/[02468]/)?res_floor:res_ceil}else{res=v-res_floor1){mant+="."+parts[0].substr(1)+(parts[1]||"")}else if(parts[1]){mant+="."+parts[1]}}mant=parseFloat(mant);mant=roundDownToFixed(parseFloat(mant),precision);if(parseFloat(mant)==10){parts=mant.split(".");parts[0]="1";mant=parts.join(".");exp=parseInt(exp)+(exp_sign=="+"?1:-1);if(exp==0){exp_sign="+"}}if(flags.alternate&&mant.indexOf(".")==-1){mant+="."}if(exp.toString().length==1){exp="0"+exp}return`${is_neg?"-":""}${mant}${upper?"E":"e"}${exp_sign}${exp}`};var floating_point_exponential_format=function(val,upper,flags){val=_float_helper(val,flags);return format_padding(format_sign(val,flags)+format_float_precision(val,upper,flags,_floating_exp_helper),flags)};$B.formatters={floating_point_format:floating_point_format,floating_point_decimal_format:floating_point_decimal_format,floating_point_exponential_format:floating_point_exponential_format};var signed_hex_format=function(val,upper,flags){var ret;if(!$B.$isinstance(val,_b_.int)){throw _b_.TypeError.$factory(`%X format: an integer is required, not ${$B.class_name(val)}`)}else if($B.$isinstance(val,_b_.bool)){val=val?1:0}if(val.__class__===$B.long_int){ret=val.value.toString(16)}else{ret=parseInt(val);ret=ret.toString(16)}ret=format_int_precision(ret,flags);if(upper){ret=ret.toUpperCase()}if(flags.pad_char==="0"){if(val<0){ret=ret.substring(1);ret="-"+format_padding(ret,flags,true)}var sign=format_sign(val,flags);if(sign!==""){ret=sign+format_padding(ret,flags,true)}}if(flags.alternate){if(ret.charAt(0)==="-"){if(upper){ret="-0X"+ret.slice(1)}else{ret="-0x"+ret.slice(1)}}else{if(upper){ret="0X"+ret}else{ret="0x"+ret}}}return format_padding(format_sign(val,flags)+ret,flags)};var octal_format=function(val,flags){number_check(val,flags);var ret;if(val.__class__===$B.long_int){ret=$B.long_int.to_base(8)}else{ret=parseInt(val);ret=ret.toString(8)}ret=format_int_precision(ret,flags);if(flags.pad_char==="0"){if(val<0){ret=ret.substring(1);ret="-"+format_padding(ret,flags,true)}var sign=format_sign(val,flags);if(sign!==""){ret=sign+format_padding(ret,flags,true)}}if(flags.alternate){if(ret.charAt(0)==="-"){ret="-0o"+ret.slice(1)}else{ret="0o"+ret}}return format_padding(ret,flags)};function series_of_bytes(val,flags){if(val.__class__&&val.__class__.$buffer_protocol){var it=_b_.iter(val),ints=[];while(true){try{ints.push(_b_.next(it))}catch(err){if(err.__class__===_b_.StopIteration){var b=_b_.bytes.$factory(ints);return format_padding(_b_.bytes.decode(b,"ascii"),flags)}throw err}}}else{try{var bytes_obj=$B.$getattr(val,"__bytes__")();return format_padding(_b_.bytes.decode(bytes_obj),flags)}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("%b does not accept '"+$B.class_name(val)+"'")}throw err}}}var single_char_format=function(val,flags,type){if(type=="bytes"){if($B.$isinstance(val,_b_.int)){if(val.__class__===$B.long_int||val<0||val>255){throw _b_.OverflowError.$factory("%c arg not in range(256)")}}else if($B.$isinstance(val,[_b_.bytes,_b_.bytearray])){if(val.source.length>1){throw _b_.TypeError.$factory("%c requires an integer in range(256) or a single byte")}val=val.source[0]}}else{if($B.$isinstance(val,_b_.str)){if(_b_.str.__len__(val)==1){return val}throw _b_.TypeError.$factory("%c requires int or char")}else if(!$B.$isinstance(val,_b_.int)){throw _b_.TypeError.$factory("%c requires int or char")}if(val.__class__===$B.long_int&&(val.value<0||val.value>=1114112)||(val<0||val>=1114112)){throw _b_.OverflowError.$factory("%c arg not in range(0x110000)")}}return format_padding(_b_.chr(val),flags)};var num_flag=function(c,flags){if(c==="0"&&!flags.padding&&!flags.decimal_point&&!flags.left){flags.pad_char="0";return}if(!flags.decimal_point){flags.padding=(flags.padding||"")+c}else{flags.precision=(flags.precision||"")+c}};var decimal_point_flag=function(val,flags){if(flags.decimal_point){throw new UnsupportedChar}flags.decimal_point=true};var neg_flag=function(val,flags){flags.pad_char=" ";flags.left=true};var space_flag=function(val,flags){flags.space=true};var sign_flag=function(val,flags){flags.sign=true};var alternate_flag=function(val,flags){flags.alternate=true};var char_mapping={b:series_of_bytes,s:str_format,d:num_format,i:num_format,u:num_format,o:octal_format,r:repr_format,a:ascii_format,g:function(val,flags){return floating_point_format(val,false,flags)},G:function(val,flags){return floating_point_format(val,true,flags)},f:function(val,flags){return floating_point_decimal_format(val,false,flags)},F:function(val,flags){return floating_point_decimal_format(val,true,flags)},e:function(val,flags){return floating_point_exponential_format(val,false,flags)},E:function(val,flags){return floating_point_exponential_format(val,true,flags)},x:function(val,flags){return signed_hex_format(val,false,flags)},X:function(val,flags){return signed_hex_format(val,true,flags)},c:single_char_format,0:function(val,flags){return num_flag("0",flags)},1:function(val,flags){return num_flag("1",flags)},2:function(val,flags){return num_flag("2",flags)},3:function(val,flags){return num_flag("3",flags)},4:function(val,flags){return num_flag("4",flags)},5:function(val,flags){return num_flag("5",flags)},6:function(val,flags){return num_flag("6",flags)},7:function(val,flags){return num_flag("7",flags)},8:function(val,flags){return num_flag("8",flags)},9:function(val,flags){return num_flag("9",flags)},"-":neg_flag," ":space_flag,"+":sign_flag,".":decimal_point_flag,"#":alternate_flag};var UnsupportedChar=function(){this.name="UnsupportedChar"};const conversion_flags="#0- +",length_modifiers="hlL",conversion_types="diouxXeEfFgGcrsa";function parse_mod_format(s,type,pos){var flags={pad_char:" "},len=s.length,start_pos=pos,mo;pos++;while(pos-1){flags.conversion_flag=char;if(char=="#"){flags.alternate=true}else if(char=="-"){flags.left=true}else if(char=="+"){flags.sign="+"}else if(char=="0"){flags.pad_char="0"}else if(char==" "){flags.space=true}pos++}else if(char=="*"){flags.padding="*";pos++}else if(mo=/^\d+/.exec(s.substr(pos))){flags.padding=mo[0];pos+=mo[0].length}else if(char=="."){pos++;if(s[pos]=="*"){flags.precision="*";pos++}else if(mo=/^\d+/.exec(s.substr(pos))){flags.precision=mo[0];pos+=mo[0].length}else{flags.precision="0"}}else if(length_modifiers.indexOf(char)>-1){flags.length_modifier=char;pos++}else if(conversion_types.indexOf(char)>-1||char=="b"&&type=="bytes"){if(type=="bytes"){if(char=="s"){char="b"}else if(char=="r"){char="a"}}flags.conversion_type=char;flags.end=pos;flags.string=s.substring(start_pos,pos+1);if(flags.left&&flags.pad_char=="0"){flags.pad_char=" "}return flags}else{throw _b_.ValueError.$factory(`invalid character in format: ${char}`)}}throw _b_.ValueError.$factory("invalid format")}function is_mapping(obj){return _b_.hasattr(obj,"keys")&&_b_.hasattr(obj,"__getitem__")}$B.printf_format=function(s,type,args){var argpos=null,getitem;if($B.$isinstance(args,_b_.tuple)){argpos=0}else{getitem=$B.$getattr(args,"__getitem__",_b_.None)}var ret="",nbph=0,pos=0,len=s.length;while(pos1){if(!$B.$isinstance(args,_b_.tuple)&&!is_mapping(args)){throw _b_.TypeError.$factory("not enough arguments for format string")}}var fmt=parse_mod_format(s,type,pos);pos=fmt.end+1;if(fmt.padding=="*"){if(args[argpos]===undefined){throw _b_.ValueError.$factory("no value for field width *")}fmt.padding=args[argpos];argpos++}if(fmt.precision=="*"){if(args[argpos]===undefined){throw _b_.ValueError.$factory("no value for precision *")}fmt.precision=args[argpos];argpos++}var func=char_mapping[fmt.conversion_type],value;if(fmt.mapping_key!==undefined){value=getitem(fmt.mapping_key)}else{if(argpos===null){value=args}else{value=args[argpos];if(value===undefined){throw _b_.TypeError.$factory("not enough arguments for format string")}argpos++}}ret+=func(value,fmt,type)}}if(argpos!==null){if(args.length>argpos){throw _b_.TypeError.$factory("not enough arguments for format string")}else if(args.length=127&&cp<160){cp=cp.toString(16);if(cp.length<2){cp="0"+cp}repl+="\\x"+cp}else if(cp>=768&&cp<=879){repl+="​"+chars[i]+" "}else if(cp.toString(16)=="feff"){repl+="\\ufeff"}else{repl+=chars[i]}}var res=repl;if(res.search('"')==-1&&res.search("'")==-1){return"'"+res+"'"}else if(_self.search('"')==-1){return'"'+res+'"'}var qesc=new RegExp("'","g");res="'"+res.replace(qesc,"\\'")+"'";return res};str.__rmod__=function(){var $=$B.args("__rmod__",2,{self:null,other:null},["self","other"],arguments,{},null,null);if(!$B.$isinstance($.other,str)){return _b_.NotImplemented}return str.__mod__($.other,$.self)};str.__rmul__=function(_self,other){_self=to_string(_self);if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other);var res="";while(other>0){res+=_self;other--}return res}return _b_.NotImplemented};str.__setattr__=function(_self,attr,value){if(typeof _self==="string"){if(str.hasOwnProperty(attr)){throw _b_.AttributeError.$factory("'str' object attribute '"+attr+"' is read-only")}else{throw _b_.AttributeError.$factory("'str' object has no attribute '"+attr+"'")}}_b_.dict.$setitem(_self.__dict__,attr,value);return _b_.None};str.__setitem__=function(){throw _b_.TypeError.$factory("'str' object does not support item assignment")};var combining=[];for(var cp=768;cp<=879;cp++){combining.push(String.fromCharCode(cp))}var combining_re=new RegExp("("+combining.join("|")+")","g");str.__str__=function(_self){_self=to_string(_self);var repl="",chars=to_chars(_self);if(chars.length==_self.length){return _self.replace(combining_re,"​$1")}for(var i=0;i=768&&cp<=879){repl+="​"+chars[i]}else{repl+=chars[i]}}return repl};var body=`var _b_ = __BRYTHON__.builtins\nif(typeof other !== typeof _self){\n return _b_.NotImplemented}else if(typeof _self == "string"){\n return _self > other}else{\n return _self.$brython_value > other.$brython_value}`;var comps={">":"gt",">=":"ge","<":"lt","<=":"le"};for(var op in comps){str[`__${comps[op]}__`]=Function("_self","other",body.replace(/>/gm,op))}str.capitalize=function(){var $=$B.args("capitalize",1,{self:self},["self"],arguments,{},null,null),_self=to_string($.self);if(_self.length==0){return""}return _self.charAt(0).toUpperCase()+_self.substr(1).toLowerCase()};str.casefold=function(){var $=$B.args("casefold",1,{self:self},["self"],arguments,{},null,null),res="",char,cf,_self=to_string($.self),chars=to_chars(_self);for(var i=0,len=chars.length;i=0){n++;pos+=sub.length}else{break}}return n};str.encode=function(){var $=$B.args("encode",3,{self:null,encoding:null,errors:null},["self","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null),_self=to_string($.self);if($.encoding=="rot13"||$.encoding=="rot_13"){var res="";for(var i=0,len=_self.length;i0){res+=" ";col++}break;case"\r":case"\n":res+=car;col=0;break;default:res+=car;col++;break}pos++}return res};str.find=function(){var $=$B.args("str.find",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:null},null,null),_self,sub;check_str($.sub);normalize_start_end($);[_self,sub]=to_string([$.self,$.sub]);var len=str.__len__(_self),sub_len=str.__len__(sub);if(sub_len==0&&$.start==len){return len}if(len+sub_len==0){return-1}var js_start=pypos2jspos(_self,$.start),js_end=pypos2jspos(_self,$.end),ix=_self.slice(js_start,js_end).indexOf(sub);if(ix==-1){return-1}return jspos2pypos(_self,js_start+ix)};$B.parse_format=function(fmt_string){var elts=fmt_string.split(":"),name,conv,spec,name_ext=[];if(elts.length==1){name=fmt_string}else{name=elts[0];spec=elts.splice(1).join(":")}elts=name.split("!");if(elts.length>1){name=elts[0];conv=elts[1]}if(name!==undefined){function name_repl(match){name_ext.push(match);return""}var name_ext_re=/\.[_a-zA-Z][_a-zA-Z0-9]*|\[[_a-zA-Z][_a-zA-Z0-9]*\]|\[[0-9]+\]/g;name=name.replace(name_ext_re,name_repl)}return{name:name,name_ext:name_ext,conv:conv,spec:spec||"",string:fmt_string}};$B.split_format=function(s){var pos=0,_len=s.length,car,text="",parts=[],rank=0;while(pos<_len){car=s.charAt(pos);if(car=="{"&&s.charAt(pos+1)=="{"){text+="{";pos+=2}else if(car=="}"&&s.charAt(pos+1)=="}"){text+="}";pos+=2}else if(car=="{"){parts.push(text);var end=pos+1,nb=1;while(end<_len){if(s.charAt(end)=="{"){nb++;end++}else if(s.charAt(end)=="}"){nb--;end++;if(nb==0){var fmt_string=s.substring(pos+1,end-1);var fmt_obj=$B.parse_format(fmt_string);fmt_obj.raw_name=fmt_obj.name;fmt_obj.raw_spec=fmt_obj.spec;if(!fmt_obj.name){fmt_obj.name=rank+"";rank++}if(fmt_obj.spec!==undefined){function replace_nested(name,key){if(key==""){return"{"+rank+++"}"}return"{"+key+"}"}fmt_obj.spec=fmt_obj.spec.replace(/\{(.*?)\}/g,replace_nested)}parts.push(fmt_obj);text="";break}}else{end++}}if(nb>0){throw _b_.ValueError.$factory("wrong format "+s)}pos=end}else{text+=car;pos++}}if(text){parts.push(text)}return parts};str.format=function(){var last_arg=$B.last(arguments),$,mapping,getitem;if(last_arg.$nat=="mapping"){mapping=last_arg.mapping;getitem=$B.$getattr(mapping,"__getitem__");var args=[];for(let i=0,len=arguments.length-1;i-1){let pos=parseInt(fmt.name);value=_b_.tuple.__getitem__($.$args,pos)}else{value=getitem(fmt.name)}for(var j=0;j-1){key=parseInt(key)}value=$B.$getattr(value,"__getitem__")(key)}}if(fmt.conv=="a"){value=_b_.ascii(value)}else if(fmt.conv=="r"){value=_b_.repr(value)}else if(fmt.conv=="s"){value=_b_.str.$factory(value)}if(value.$is_class||value.$factory){res+=value.__class__.__format__(value,fmt.spec)}else{res+=$B.$getattr(value,"__format__")(fmt.spec)}}return res};str.format_map=function(){var $=$B.args("format_map",2,{self:null,mapping:null},["self","mapping"],arguments,{},null,null),_self=to_string($.self);return str.format(_self,{$nat:"mapping",mapping:$.mapping})};str.index=function(){var res=str.find.apply(null,arguments);if(res===-1){throw _b_.ValueError.$factory("substring not found")}return res};str.isascii=function(){var $=$B.args("isascii",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);for(var i=0,len=_self.length;i127){return false}}return true};var unicode_categories_contain_character=function(categories,cp){for(var cat of categories){console.log(cat,cp);if($B.in_unicode_category(cat,cp)){return true}}return false};var alpha_categories=["Ll","Lu","Lm","Lt","Lo"];var alnum_categories=["Ll","Lu","Lm","Lt","Lo","Nd"];str.isalnum=function(){var $=$B.args("isalnum",1,{self:null},["self"],arguments,{},null,null);var _self=to_string($.self);if(_self.length==0){return false}for(var char of _self){if(!unicode_categories_contain_character(alnum_categories,_b_.ord(char))){return false}}return true};str.isalpha=function(){var $=$B.args("isalpha",1,{self:null},["self"],arguments,{},null,null);var _self=to_string($.self);if(_self.length==0){return false}for(var char of _self){if(!unicode_categories_contain_character(alpha_categories,_b_.ord(char))){return false}}return true};str.isdecimal=function(){var $=$B.args("isdecimal",1,{self:null},["self"],arguments,{},null,null),cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if(!$B.in_unicode_category("Nd",cp)){return false}}return _self.length>0};str.isdigit=function(){var $=$B.args("isdigit",1,{self:null},["self"],arguments,{},null,null),cp,_self=to_string($.self);for(var char of _self){if(/\p{Nd}/u.test(char)){continue}cp=_b_.ord(char);if(!$B.in_unicode_category("No_digits",cp)){return false}}return _self.length>0};str.isidentifier=function(){var $=$B.args("isidentifier",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);if(_self.length==0){return false}var chars=to_chars(_self);if(!$B.is_XID_Start(_b_.ord(chars[0]))){return false}else{for(var char of chars){var cp=_b_.ord(char);if(!$B.is_XID_Continue(cp)){return false}}}return true};str.islower=function(){var $=$B.args("islower",1,{self:null},["self"],arguments,{},null,null),has_cased=false,cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if($B.in_unicode_category("Ll",cp)){has_cased=true;continue}else if($B.in_unicode_category("Lu",cp)||$B.in_unicode_category("Lt",cp)){return false}}return has_cased};const numeric_re=/\p{Nd}|\p{Nl}|\p{No}/u;str.isnumeric=function(){var $=$B.args("isnumeric",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);for(var char of _self){if(!numeric_re.test(char)&&!$B.in_unicode_category("Lo_numeric",_b_.ord(char))){return false}}return _self.length>0};var unprintable_re=/\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}|\p{Zl}|\p{Zp}|\p{Zs}/u;str.isprintable=function(){var $=$B.args("isprintable",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);for(var char of _self){if(char==" "){continue}if(unprintable_re.test(char)){return false}}return true};str.isspace=function(){var $=$B.args("isspace",1,{self:null},["self"],arguments,{},null,null),cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if(!$B.in_unicode_category("Zs",cp)&&$B.unicode_bidi_whitespace.indexOf(cp)==-1){return false}}return _self.length>0};str.istitle=function(){var $=$B.args("istitle",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);return _self.length>0&&str.title(_self)==_self};str.isupper=function(){var $=$B.args("islower",1,{self:null},["self"],arguments,{},null,null),is_upper=false,cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if($B.in_unicode_category("Lu",cp)){is_upper=true;continue}else if($B.in_unicode_category("Ll",cp)||$B.in_unicode_category("Lt",cp)){return false}}return is_upper};str.join=function(){var $=$B.args("join",2,{self:null,iterable:null},["self","iterable"],arguments,{},null,null),_self=to_string($.self);var iterable=_b_.iter($.iterable),res=[],count=0;while(1){try{var obj2=_b_.next(iterable);if(!$B.$isinstance(obj2,str)){throw _b_.TypeError.$factory("sequence item "+count+": expected str instance, "+$B.class_name(obj2)+" found")}res.push(obj2)}catch(err){if($B.$isinstance(err,_b_.StopIteration)){break}else{throw err}}}return res.join(_self)};str.ljust=function(){var $=$B.args("ljust",3,{self:null,width:null,fillchar:null},["self","width","fillchar"],arguments,{fillchar:" "},null,null),_self=to_string($.self),len=str.__len__(_self);if($.width<=len){return _self}return _self+$.fillchar.repeat($.width-len)};str.lower=function(){var $=$B.args("lower",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);return _self.toLowerCase()};str.lstrip=function(){var $=$B.args("lstrip",2,{self:null,chars:null},["self","chars"],arguments,{chars:_b_.None},null,null),_self=$.self,chars=$.chars;if(chars===_b_.None){return _self.trimStart()}[_self,chars]=to_string([_self,chars]);while(_self.length>0){var flag=false;for(var char of chars){if(_self.startsWith(char)){_self=_self.substr(char.length);flag=true;break}}if(!flag){return $.self.surrogates?$B.String(_self):_self}}return""};str.maketrans=function(){var $=$B.args("maketrans",3,{x:null,y:null,z:null},["x","y","z"],arguments,{y:null,z:null},null,null);var _t=$B.empty_dict();if($.y===null&&$.z===null){if(!$B.$isinstance($.x,_b_.dict)){throw _b_.TypeError.$factory("maketrans only argument must be a dict")}var items=_b_.list.$factory(_b_.dict.items($.x));for(let i=0,len=items.length;i0&&str.endswith(_self,suffix)){return _self.substr(0,_self.length-suffix.length)}return _self.substr(0)};str.replace=function(){var $=$B.args("replace",4,{self:null,old:null,new:null,count:null},["self","old","new","count"],arguments,{count:-1},null,null),count=$.count,_self=$.self,old=$.old,_new=$.new;check_str(old,"replace() argument 1 ");check_str(_new,"replace() argument 2 ");if(!$B.$isinstance(count,[_b_.int,_b_.float])){throw _b_.TypeError.$factory("'"+$B.class_name(count)+"' object cannot be interpreted as an integer")}else if($B.$isinstance(count,_b_.float)){throw _b_.TypeError.$factory("integer argument expected, got float")}if(count==0){return _self}if(count.__class__==$B.long_int){count=parseInt(count.value)}[old,_new]=to_string([old,_new]);var elts;if(old==""){if(_new==""){return _self}if(_self==""){return _new}elts=_self.split("");if(count>-1&&elts.length>=count){var rest=elts.slice(count).join("");return _new+elts.slice(0,count).join(_new)+rest}else{return _new+elts.join(_new)+_new}}else{elts=str.split(_self,old,count)}var res=_self,pos=-1;if(old.length==0){res=_new;for(var i=0;i0){pos=res.indexOf(old,pos);if(pos<0){break}res=res.substr(0,pos)+_new+res.substr(pos+old.length);pos=pos+_new.length;count--}return res};str.rfind=function(){var $=$B.args("rfind",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:null},null,null),_self,sub;normalize_start_end($);check_str($.sub);[_self,sub]=to_string([$.self,$.sub]);var len=str.__len__(_self),sub_len=str.__len__(sub);if(sub_len==0){if($.js_start>len){return-1}else{return str.__len__(_self)}}var js_start=pypos2jspos(_self,$.start),js_end=pypos2jspos(_self,$.end),ix=_self.substring(js_start,js_end).lastIndexOf(sub);if(ix==-1){return-1}return jspos2pypos(_self,js_start+ix)-$.start};str.rindex=function(){var res=str.rfind.apply(null,arguments);if(res==-1){throw _b_.ValueError.$factory("substring not found")}return res};str.rjust=function(){var $=$B.args("rjust",3,{self:null,width:null,fillchar:null},["self","width","fillchar"],arguments,{fillchar:" "},null,null),_self=to_string($.self);var len=str.__len__(_self);if($.width<=len){return _self}return $B.String($.fillchar.repeat($.width-len)+_self)};str.rpartition=function(self,sep){var $=$B.args("rpartition",2,{self:null,sep:null},["self","sep"],arguments,{},null,null),_self;check_str($.sep);[_self,sep]=[$.self,$.sep];_self=reverse(_self),sep=reverse(sep);var items=str.partition(_self,sep).reverse();for(var i=0;i0){var flag=false;for(var char of chars){if(_self.endsWith(char)){_self=_self.substr(0,_self.length-char.length);flag=true;break}}if(!flag){return _self.surrogates?$B.String(_self):_self}}return""};str.split=function(){var $=$B.args("split",3,{self:null,sep:null,maxsplit:null},["self","sep","maxsplit"],arguments,{sep:_b_.None,maxsplit:-1},null,null),maxsplit=$.maxsplit,sep=$.sep,pos=0,_self=to_string($.self);if(maxsplit.__class__===$B.long_int){maxsplit=parseInt(maxsplit.value)}if(sep==""){throw _b_.ValueError.$factory("empty separator")}if(sep===_b_.None){let res=[];while(pos<_self.length&&_self.charAt(pos).search(/\s/)>-1){pos++}if(pos===_self.length-1){return $B.$list([_self])}let name="";while(1){if(_self.charAt(pos).search(/\s/)==-1){if(name==""){name=_self.charAt(pos)}else{name+=_self.charAt(pos)}}else{if(name!==""){res.push(name);if(maxsplit!==-1&&res.length==maxsplit+1){res.pop();res.push(name+_self.substr(pos));return res}name=""}}pos++;if(pos>_self.length-1){if(name){res.push(name)}break}}return $B.$list(res.map($B.String))}else{sep=to_string(sep);let res=[],s="",seplen=sep.length;if(maxsplit==0){return $B.$list([$.self])}while(pos<_self.length){if(_self.substr(pos,seplen)==sep){res.push(s);pos+=seplen;if(maxsplit>-1&&res.length>=maxsplit){res.push(_self.substr(pos));return res.map($B.String)}s=""}else{s+=_self.charAt(pos);pos++}}res.push(s);return $B.$list(res.map($B.String))}};str.splitlines=function(){var $=$B.args("splitlines",2,{self:null,keepends:null},["self","keepends"],arguments,{keepends:false},null,null);if(!$B.$isinstance($.keepends,[_b_.bool,_b_.int])){throw _b_.TypeError("integer argument expected, got "+$B.get_class($.keepends).__name)}var keepends=_b_.int.$factory($.keepends),res=$B.$list([]),start=0,pos=0,_self=to_string($.self);if(!_self.length){return res}while(pos<_self.length){if(_self.substr(pos,2)=="\r\n"){res.push(_self.slice(start,keepends?pos+2:pos));start=pos=pos+2}else if(_self[pos]=="\r"||_self[pos]=="\n"){res.push(_self.slice(start,keepends?pos+1:pos));start=pos=pos+1}else{pos++}}if(start<_self.length){res.push(_self.slice(start))}return $B.$list(res.map($B.String))};str.startswith=function(){var $=$B.args("startswith",4,{self:null,prefix:null,start:null,end:null},["self","prefix","start","end"],arguments,{start:0,end:null},null,null),_self;normalize_start_end($);var prefixes=$.prefix;if(!$B.$isinstance(prefixes,_b_.tuple)){prefixes=[prefixes]}_self=to_string($.self);prefixes=to_string(prefixes);var s=_self.substring($.start,$.end);for(var prefix of prefixes){if(!$B.$isinstance(prefix,str)){throw _b_.TypeError.$factory("endswith first arg must be str "+"or a tuple of str, not int")}if(s.substr(0,prefix.length)==prefix){return true}}return false};str.strip=function(){var $=$B.args("strip",2,{self:null,chars:null},["self","chars"],arguments,{chars:_b_.None},null,null);if($.chars===_b_.None){return $.self.trim()}return str.rstrip(str.lstrip($.self,$.chars),$.chars)};str.swapcase=function(self){var $=$B.args("swapcase",1,{self:self},["self"],arguments,{},null,null),res="",cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if($B.in_unicode_category("Ll",cp)){res+=char.toUpperCase()}else if($B.in_unicode_category("Lu",cp)){res+=char.toLowerCase()}else{res+=char}}return res};str.title=function(self){var $=$B.args("title",1,{self:self},["self"],arguments,{},null,null),state,cp,res="",_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if($B.in_unicode_category("Ll",cp)){if(!state){res+=char.toUpperCase();state="word"}else{res+=char}}else if($B.in_unicode_category("Lu",cp)||$B.in_unicode_category("Lt",cp)){res+=state?char.toLowerCase():char;state="word"}else{state=null;res+=char}}return res};str.translate=function(){var $=$B.args("translate",2,{self:null,table:null},["self","table"],arguments,{},null,null),table=$.table,res=[],getitem=$B.$getattr(table,"__getitem__"),cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);try{var repl=getitem(cp);if(repl!==_b_.None){if(typeof repl=="string"){res.push(repl)}else if(typeof repl=="number"){res.push(String.fromCharCode(repl))}}}catch(err){res.push(char)}}return res.join("")};str.upper=function(){var $=$B.args("upper",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);return _self.toUpperCase()};str.zfill=function(){var $=$B.args("zfill",2,{self:null,width:null},["self","width"],arguments,{},null,null),_self=to_string($.self);var len=str.__len__(_self);if($.width<=len){return _self}switch(_self.charAt(0)){case"+":case"-":return _self.charAt(0)+"0".repeat($.width-len)+_self.substr(1);default:return"0".repeat($.width-len)+_self}};str.$factory=function(arg,encoding){if(arguments.length==0){return""}if(arg===undefined){return $B.UndefinedType.__str__()}else if(arg===null){return""}if(encoding!==undefined){var $=$B.args("str",3,{arg:null,encoding:null,errors:null},["arg","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null);encoding=$.encoding}if(typeof arg=="string"||arg instanceof String){return arg.toString()}else if(typeof arg=="number"&&Number.isInteger(arg)){return arg.toString()}try{if(arg.__class__&&arg.__class__===_b_.bytes&&encoding!==undefined){return _b_.bytes.decode(arg,$.encoding,$.errors)}var klass=arg.__class__||$B.get_class(arg);if(klass===undefined){return $B.JSObj.__str__($B.jsobj2pyobj(arg))}var method=$B.$getattr(klass,"__str__",null);if(method===null){method=$B.$getattr(klass,"__repr__")}}catch(err){console.log("no __str__ for",arg);console.log("err ",err);if($B.get_option("debug")>1){console.log(err)}console.log("Warning - no method __str__ or __repr__, "+"default to toString",arg);throw err}var res=$B.$call(method)(arg);if(typeof res=="string"||$B.$isinstance(res,str)){return res}throw _b_.TypeError.$factory("__str__ returned non-string "+`(type ${$B.class_name(res)})`)};$B.set_func_names(str,"builtins");_b_.str=str;$B.parse_format_spec=function(spec,obj){if(spec==""){this.empty=true}else{var pos=0,aligns="<>=^",digits="0123456789",types="bcdeEfFgGnosxX%",align_pos=aligns.indexOf(spec.charAt(0));if(align_pos!=-1){if(spec.charAt(1)&&aligns.indexOf(spec.charAt(1))!=-1){this.fill=spec.charAt(0);this.align=spec.charAt(1);pos=2}else{this.align=aligns[align_pos];this.fill=" ";pos++}}else{align_pos=aligns.indexOf(spec.charAt(1));if(spec.charAt(1)&&align_pos!=-1){this.align=aligns[align_pos];this.fill=spec.charAt(0);pos=2}}var car=spec.charAt(pos);if(car=="+"||car=="-"||car==" "){this.sign=car;pos++;car=spec.charAt(pos)}if(car=="z"){this.z=true;pos++;car=spec.charAt(pos)}if(car=="#"){this.alternate=true;pos++;car=spec.charAt(pos)}if(car=="0"){this.fill="0";if(align_pos==-1){this.align="="}pos++;car=spec.charAt(pos)}while(car&&digits.indexOf(car)>-1){if(this.width===undefined){this.width=car}else{this.width+=car}pos++;car=spec.charAt(pos)}if(this.width!==undefined){this.width=parseInt(this.width)}if(this.width===undefined&&car=="{"){var end_param_pos=spec.substr(pos).search("}");this.width=spec.substring(pos,end_param_pos);pos+=end_param_pos+1}if(car==","||car=="_"){this.comma=true;this.grouping_option=car;pos++;car=spec.charAt(pos);if(car==","||car=="_"){if(car==this.grouping_option){throw _b_.ValueError.$factory(`Cannot specify '${car}' with '${car}'.`)}else{throw _b_.ValueError.$factory("Cannot specify both ',' and '_'.")}}}if(car=="."){if(digits.indexOf(spec.charAt(pos+1))==-1){throw _b_.ValueError.$factory("Missing precision in format spec")}this.precision=spec.charAt(pos+1);pos+=2;car=spec.charAt(pos);while(car&&digits.indexOf(car)>-1){this.precision+=car;pos++;car=spec.charAt(pos)}this.precision=parseInt(this.precision)}if(car&&types.indexOf(car)>-1){this.type=car;pos++;car=spec.charAt(pos)}if(pos!==spec.length){var err_msg=`Invalid format specifier '${spec}'`;if(obj){err_msg+=` for object of type '${$B.class_name(obj)}'`}throw _b_.ValueError.$factory(err_msg)}}this.toString=function(){return(this.fill===undefined?"":_b_.str.$factory(this.fill))+(this.align||"")+(this.sign||"")+(this.alternate?"#":"")+(this.sign_aware?"0":"")+(this.width||"")+(this.comma?",":"")+(this.precision?"."+this.precision:"")+(this.type||"")}};$B.format_width=function(s,fmt){if(fmt.width&&s.length":return fill.repeat(missing)+s;case"=":if("+-".indexOf(s.charAt(0))>-1){return s.charAt(0)+fill.repeat(missing)+s.substr(1)}else{return fill.repeat(missing)+s}case"^":var left=parseInt(missing/2);return fill.repeat(left)+s+fill.repeat(missing-left)}}return s};function fstring_expression(start){this.type="expression";this.start=start;this.expression="";this.conversion=null;this.fmt=null}function fstring_error(msg,pos){var error=Error(msg);error.position=pos;throw error}$B.parse_fstring=function(string){var elts=[],pos=0,current="",ctype=null,nb_braces=0,expr_start,car;while(pos-1){if(current.expression.length==0){throw Error("f-string: empty expression not allowed")}if("ars".indexOf(string.charAt(i+1))==-1){throw Error("f-string: invalid conversion character:"+" expected 's', 'r', or 'a'")}else{current.conversion=string.charAt(i+1);i+=2}}else if(car=="("||car=="["){nb_paren++;current.expression+=car;i++}else if(car==")"||car=="]"){nb_paren--;current.expression+=car;i++}else if(car=='"'){if(string.substr(i,3)=='"""'){let end=string.indexOf('"""',i+3);if(end==-1){fstring_error("f-string: unterminated string",pos)}else{var trs=string.substring(i,end+3);trs=trs.replace("\n","\\n\\");current.expression+=trs;i=end+3}}else{let end=string.indexOf('"',i+1);if(end==-1){fstring_error("f-string: unterminated string",pos)}else{current.expression+=string.substring(i,end+1);i=end+1}}}else if(nb_paren==0&&car==":"){current.fmt=true;var cb=0,fmt_complete=false;for(var j=i+1;j-1?"\\":"")+last_char;if(ce.length==0||nb_paren>0||string.charAt(i+1)=="="||"=!<>:".search(last_char_re)>-1){current.expression+=car;i+=1}else{var tail=car;while(string.charAt(i+1).match(/\s/)){tail+=string.charAt(i+1);i++}elts.push(current.expression+tail);while(ce.match(/\s$/)){ce=ce.substr(0,ce.length-1)}current.expression=ce;ctype="debug";i++}}else{current.expression+=car;i++}}if(nb_braces>0){fstring_error("f-string: expected '}'",pos)}}}if(current.length>0){elts.push(current)}for(var elt of elts){if(typeof elt=="object"){if(elt.fmt_pos!==undefined&&elt.expression.charAt(elt.fmt_pos)!=":"){throw Error()}}}return elts};$B.codepoint2jsstring=function(i){if(i>=65536&&i<=1114111){var code=i-65536;return String.fromCodePoint(55296|code>>10)+String.fromCodePoint(56320|code&1023)}else{return String.fromCodePoint(i)}};$B.jsstring2codepoint=function(c){if(c.length==1){return c.charCodeAt(0)}var code=65536;code+=(c.charCodeAt(0)&1023)<<10;code+=c.charCodeAt(1)&1023;return code}})(__BRYTHON__);(function($B){var _b_=$B.builtins;function $err(op,other){var msg="unsupported operand type(s) for "+op+" : 'int' and '"+$B.class_name(other)+"'";throw _b_.TypeError.$factory(msg)}function int_value(obj){if(typeof obj=="boolean"){return obj?1:0}return obj.$brython_value!==undefined?obj.$brython_value:obj}function bigint_value(obj){if(typeof obj=="boolean"){return obj?1n:0n}else if(typeof obj=="number"){return BigInt(obj)}else if(obj.__class__===$B.long_int){return obj.value}else if($B.$isinstance(obj,_b_.int)){return bigint_value(obj.$brython_value)}}var int={__class__:_b_.type,__dir__:_b_.object.__dir__,__mro__:[_b_.object],__qualname__:"int",$is_class:true,$native:true,$descriptors:{numerator:true,denominator:true,imag:true,real:true},$is_int_subclass:true};var int_or_long=int.$int_or_long=function(bigint){var res=Number(bigint);return Number.isSafeInteger(res)?res:$B.fast_long_int(bigint)};int.$to_js_number=function(obj){if(typeof obj=="number"){return obj}else if(obj.__class__===$B.long_int){return Number(obj.value)}else if($B.$isinstance(obj,_b_.int)){return int.$to_js_value(obj.$brython_value)}return null};int.$to_bigint=bigint_value;int.$int_value=int_value;int.as_integer_ratio=function(){var $=$B.args("as_integer_ratio",1,{self:null},["self"],arguments,{},null,null);return $B.fast_tuple([$.self,1])};int.from_bytes=function(){var $=$B.args("from_bytes",3,{bytes:null,byteorder:null,signed:null},["bytes","byteorder","signed"],arguments,{byteorder:"big",signed:false},null,null);var x=$.bytes,byteorder=$.byteorder,signed=$.signed,_bytes,_len;if($B.$isinstance(x,[_b_.bytes,_b_.bytearray])){_bytes=x.source;_len=x.source.length}else{_bytes=_b_.list.$factory(x);_len=_bytes.length;for(let i=0;i<_len;i++){_b_.bytes.$factory([_bytes[i]])}}if(byteorder=="big"){_bytes.reverse()}else if(byteorder!="little"){throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")}var num=_bytes[0];if(signed&&num>=128){num=num-256}num=BigInt(num);var _mult=256n;for(let i=1;i<_len;i++){num+=_mult*BigInt(_bytes[i]);_mult*=256n}if(!signed){return int_or_long(num)}if(_bytes[_len-1]<128){return int_or_long(num)}return int_or_long(num-_mult)};int.to_bytes=function(){var $=$B.args("to_bytes",3,{self:null,len:null,byteorder:null,signed:null},["self","len","byteorder","signed"],arguments,{len:1,byteorder:"big",signed:false},null,null),self=$.self,len=$.len,byteorder=$.byteorder,signed=$.signed;if(!$B.$isinstance(len,_b_.int)){throw _b_.TypeError.$factory("integer argument expected, got "+$B.class_name(len))}if(["little","big"].indexOf(byteorder)==-1){throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")}if($B.$isinstance(self,$B.long_int)){return $B.long_int.to_bytes(self,len,byteorder,signed)}if(self<0){if(!signed){throw _b_.OverflowError.$factory("can't convert negative int to unsigned")}self=Math.pow(256,len)+self}var res=[],value=self;while(value>0){var quotient=Math.floor(value/256),rest=value-256*quotient;res.push(rest);if(res.length>len){throw _b_.OverflowError.$factory("int too big to convert")}value=quotient}while(res.length=0){res=fmt.sign+res}}return res}int.__format__=function(self,format_spec){var fmt=new $B.parse_format_spec(format_spec,self);if(fmt.type&&"eEfFgG%".indexOf(fmt.type)!=-1){return _b_.float.__format__($B.fast_float(self),format_spec)}fmt.align=fmt.align||">";var res=preformat(self,fmt);if(fmt.comma){var sign=res[0]=="-"?"-":"",rest=res.substr(sign.length),len=rest.length,nb=Math.ceil(rest.length/3),chunks=[];for(var i=0;iint_value(self);int.__init__=()=>_b_.None;int.__int__=self=>self;int.__invert__=function(self){if(Math.abs(self)<2**31){return~self}return $B.rich_op("__sub__",$B.rich_op("__mul__",self,-1),1)};int.__mod__=function(self,other){if($B.$isinstance(other,_b_.tuple)&&other.length==1){other=other[0]}if(other.__class__===$B.long_int){self=BigInt(self);other=other.value;if(other==0){throw _b_.ZeroDivisionError.$factory("integer division or modulo by zero")}return int_or_long((self%other+other)%other)}if($B.$isinstance(other,int)){other=int_value(other);if(other===false){other=0}else if(other===true){other=1}if(other==0){throw _b_.ZeroDivisionError.$factory("integer division or modulo by zero")}return(self%other+other)%other}return _b_.NotImplemented};int.__mul__=Function("self","other",op_model.replace(/\+/g,"*").replace(/add/g,"mul"));int.__ne__=function(self,other){var res=int.__eq__(self,other);return res===_b_.NotImplemented?res:!res};int.__neg__=function(self){var self_as_int=int_value(self);if(self_as_int.__class__===$B.long_int){return $B.long_int.__neg__(self_as_int)}return-self};int.__new__=function(cls,value,base){if(cls===undefined){throw _b_.TypeError.$factory("int.__new__(): not enough arguments")}else if(!$B.$isinstance(cls,_b_.type)){throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")}if(cls===int){return int.$factory(value,base)}if(cls===bool){throw _b_.TypeError.$factory("int.__new__(bool) is not safe, use bool.__new__()")}return{__class__:cls,__dict__:$B.empty_dict(),$brython_value:int.$factory(value,base),toString:function(){return value}}};int.__pos__=function(self){return self};function extended_euclidean(a,b){var d,u,v;if(b==0){return[a,1n,0n]}else{[d,u,v]=extended_euclidean(b,a%b);return[d,v,u-a/b*v]}}int.__pow__=function(self,other,z){if(!$B.$isinstance(other,int)){return _b_.NotImplemented}if(typeof other=="boolean"){other=other?1:0}if(typeof other=="number"||$B.$isinstance(other,int)){if(z!==undefined&&z!==_b_.None){self=bigint_value(self);other=bigint_value(other);z=bigint_value(z);if(z==1){return 0}var result=1n,exponent=other,base=self%z;if(base<0){base+=z}if(exponent<0){var gcd,inv,_;[gcd,inv,_]=extended_euclidean(self,z);if(gcd!=1){throw _b_.ValueError.$factory("not relative primes: "+self+" and "+z)}return int.__pow__(int_or_long(inv),int_or_long(-exponent),int_or_long(z))}while(exponent>0){if(exponent%2n==1n){result=result*base%z}exponent=exponent>>1n;base=base*base%z}return int_or_long(result)}else{if(typeof other=="number"){if(other>=0){return int_or_long(BigInt(self)**BigInt(other))}else{return $B.fast_float(Math.pow(self,other))}}else if(other.__class__===$B.long_int){if(other.value>=0){return int_or_long(BigInt(self)**other.value)}else{return $B.fast_float(Math.pow(self,other))}}else if($B.$isinstance(other,_b_.int)){return int_or_long(int.__pow__(self,other.$brython_value))}return _b_.NotImplemented}}if($B.$isinstance(other,_b_.float)){other=_b_.float.numerator(other);if(self>=0){return $B.fast_float(Math.pow(self,other))}else{return _b_.complex.__pow__($B.make_complex(self,0),other)}}else if($B.$isinstance(other,_b_.complex)){var preal=Math.pow(self,other.$real),ln=Math.log(self);return $B.make_complex(preal*Math.cos(ln),preal*Math.sin(ln))}var rpow=$B.$getattr(other,"__rpow__",_b_.None);if(rpow!==_b_.None){return rpow(self)}$err("**",other)};int.__repr__=function(self){$B.builtins_repr_check(int,arguments);var value=int_value(self),x=value.__class__===$B.long_int?value.value:value;if($B.int_max_str_digits!=0&&x>=10n**BigInt($B.int_max_str_digits)){throw _b_.ValueError.$factory(`Exceeds the limit `+`(${$B.int_max_str_digits}) for integer string conversion`)}return x.toString()};int.__setattr__=function(self,attr,value){if(typeof self=="number"||typeof self=="boolean"){var cl_name=$B.class_name(self);if(_b_.dir(self).indexOf(attr)>-1){throw _b_.AttributeError.$factory("attribute '"+attr+`' of '${cl_name}' objects is not writable`)}else{throw _b_.AttributeError.$factory(`'${cl_name}' object`+` has no attribute '${attr}'`)}}_b_.dict.$setitem(self.__dict__,attr,value);return _b_.None};int.__sub__=Function("self","other",op_model.replace(/\+/g,"-").replace(/__add__/g,"__sub__"));int.__truediv__=function(self,other){if($B.$isinstance(other,int)){other=int_value(other);if(other==0){throw _b_.ZeroDivisionError.$factory("division by zero")}if(other.__class__===$B.long_int){return $B.fast_float(self/parseInt(other.value))}return $B.fast_float(self/other)}return _b_.NotImplemented};int.bit_count=function(self){var s=_b_.bin(_b_.abs(self)),nb=0;for(var x of s){if(x=="1"){nb++}}return nb};int.bit_length=function(self){var s=_b_.bin(self);s=$B.$getattr(s,"lstrip")("-0b");return s.length};int.numerator=self=>int_value(self);int.denominator=()=>1;int.imag=()=>0;int.real=self=>self;for(var attr of["numerator","denominator","imag","real"]){int[attr].setter=function(x){return function(self){throw _b_.AttributeError.$factory(`attribute '${x}' of `+`'${$B.class_name(self)}' objects is not writable`)}}(attr)}var model=`var _b_ = __BRYTHON__.builtins\nif(typeof other == "number"){\n // transform into BigInt: JS converts numbers to 32 bits\n return _b_.int.$int_or_long(BigInt(self) & BigInt(other))}else if(typeof other == "boolean"){\n return self & (other ? 1 : 0)}else if(other.__class__ === $B.long_int){\n return _b_.int.$int_or_long(BigInt(self) & other.value)}else if($B.$isinstance(other, _b_.int)){\n // int subclass\n return _b_.int.__and__(self, other.$brython_value)}\nreturn _b_.NotImplemented`;int.__and__=Function("self","other",model);int.__lshift__=Function("self","other",model.replace(/&/g,"<<").replace(/__and__/g,"__lshift__"));int.__rshift__=Function("self","other",model.replace(/&/g,">>").replace(/__and__/g,"__rshift__"));int.__or__=Function("self","other",model.replace(/&/g,"|").replace(/__and__/g,"__or__"));int.__xor__=Function("self","other",model.replace(/&/g,"^").replace(/__and__/g,"__xor__"));int.__ge__=function(self,other){self=int_value(self);if(typeof other=="number"){return self>=other}else if(other!==null&&other.__class__===$B.long_int){return self>=other.value}else if(typeof other=="boolean"){return self>=other?1:0}else if($B.$isinstance(other,_b_.int)){return self>=other.$brython_value}return _b_.NotImplemented};int.__gt__=function(self,other){var res=int.__le__(self,other);return res===_b_.NotImplemented?res:!res};int.__le__=function(self,other){self=int_value(self);if(typeof other=="number"){return self<=other}else if(other!==null&&other.__class__===$B.long_int){return self<=other.value}else if(typeof other=="boolean"){return self<=other?1:0}else if($B.$isinstance(other,_b_.int)){return self<=other.$brython_value}return _b_.NotImplemented};int.__lt__=function(self,other){var res=int.__ge__(self,other);return res===_b_.NotImplemented?res:!res};var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or","divmod"];for(var r_opname of r_opnames){if(int["__r"+r_opname+"__"]===undefined&&int["__"+r_opname+"__"]){int["__r"+r_opname+"__"]=function(name){return function(self,other){if($B.$isinstance(other,int)){other=int_value(other);return int["__"+name+"__"](other,self)}return _b_.NotImplemented}}(r_opname)}}var $valid_digits=function(base){var digits="";if(base===0){return"0"}if(base<10){for(let i=0;i=2&&base<=36)){if(base!=0){throw _b_.ValueError.$factory("invalid base")}}function invalid(base){throw _b_.ValueError.$factory("invalid literal for int() with base "+base+": "+_b_.repr(initial_value))}if(typeof value!="string"){value=_b_.str.$to_string(value)}var _value=value.trim(),sign="";if(_value.startsWith("+")||_value.startsWith("-")){sign=_value[0];_value=_value.substr(1)}if(_value.length==2&&base==0&&(_value=="0b"||_value=="0o"||_value=="0x")){throw _b_.ValueError.$factory("invalid value")}if(_value.endsWith("_")){invalid(base)}if(value.indexOf("__")>-1){invalid(base)}if(_value.length>2){let _pre=_value.substr(0,2).toUpperCase();if(base==0){if(_pre=="0B"){base=2}else if(_pre=="0O"){base=8}else if(_pre=="0X"){base=16}else if(_value.startsWith("0")){_value=_value.replace(/_/g,"");if(_value.match(/^0+$/)){return 0}invalid(base)}}else if(_pre=="0X"&&base!=16){invalid(base)}else if(_pre=="0O"&&base!=8){invalid(base)}if(_pre=="0B"&&base==2||_pre=="0O"||_pre=="0X"){_value=_value.substr(2);if(_value.startsWith("_")){_value=_value.substr(1)}}}if(base==0){base=10}var _digits=$valid_digits(base),_re=new RegExp("^[+-]?["+_digits+"]"+"["+_digits+"_]*$","i"),match=_re.exec(_value),res;if(match===null){res=0;var digit;for(var char of _value){if(/\p{Nd}/u.test(char)){let cp=char.codePointAt(0);for(let start of $B.digits_starts){if(cp-start<10){digit=cp-start;break}}}else{if(base>10&&_digits.indexOf(char.toUpperCase())>-1){digit=char.toUpperCase().charCodeAt(0)-55}else{invalid(base)}}if(digit$B.int_max_str_digits){throw _b_.ValueError.$factory("Exceeds the limit "+`(${$B.int_max_str_digits}) for integer string conversion: `+`value has ${value.length} digits; use `+"sys.set_int_max_str_digits() to increase the limit.")}if(base==10){res=BigInt(_value)}else{base=BigInt(base);res=0n;let coef=1n,char;for(let i=_value.length-1;i>=0;i--){char=_value[i].toUpperCase();res+=coef*BigInt(_digits.indexOf(char));coef*=base}}}if(sign=="-"){res=-res}return int_or_long(res)};$B.set_func_names(int,"builtins");_b_.int=int;$B.$bool=function(obj,bool_class){if(obj===null||obj===undefined){return false}switch(typeof obj){case"boolean":return obj;case"number":case"string":if(obj){return true}return false;default:if(obj.$is_class){return true}var klass=$B.get_class(obj),missing={},bool_method=bool_class?$B.$getattr(klass,"__bool__",missing):$B.$getattr(obj,"__bool__",missing);var test=false;if(test){console.log("bool(obj)",obj,"bool_class",bool_class,"klass",klass,"apply bool method",bool_method);console.log("$B.$call(bool_method)",bool_method+"")}if(bool_method===missing){var len_method=$B.$getattr(klass,"__len__",missing);if(len_method===missing){return true}return _b_.len(obj)>0}else{var res=bool_class?$B.$call(bool_method)(obj):$B.$call(bool_method)();if(res!==true&&res!==false){throw _b_.TypeError.$factory("__bool__ should return "+"bool, returned "+$B.class_name(res))}if(test){console.log("bool method returns",res)}return res}}};var bool={__bases__:[int],__class__:_b_.type,__mro__:[int,_b_.object],__qualname__:"bool",$is_class:true,$not_basetype:true,$native:true,$descriptors:{numerator:true,denominator:true,imag:true,real:true}};bool.__and__=function(self,other){if($B.$isinstance(other,bool)){return self&&other}else if($B.$isinstance(other,int)){return int.__and__(bool.__index__(self),int.__index__(other))}return _b_.NotImplemented};bool.__float__=function(self){return self?$B.fast_float(1):$B.fast_float(0)};bool.__hash__=bool.__index__=bool.__int__=function(self){if(self.valueOf())return 1;return 0};bool.__neg__=function(self){return-$B.int_or_bool(self)};bool.__or__=function(self,other){if($B.$isinstance(other,bool)){return self||other}else if($B.$isinstance(other,int)){return int.__or__(bool.__index__(self),int.__index__(other))}return _b_.NotImplemented};bool.__pos__=$B.int_or_bool;bool.__repr__=function(self){$B.builtins_repr_check(bool,arguments);return self?"True":"False"};bool.__xor__=function(self,other){if($B.$isinstance(other,bool)){return self^other?true:false}else if($B.$isinstance(other,int)){return int.__xor__(bool.__index__(self),int.__index__(other))}return _b_.NotImplemented};bool.__invert__=function(self){$B.warn(_b_.DeprecationWarning,`Bitwise inversion '~' on bool is deprecated.This returns the bitwise inversion of the underlying int object and is usually not what you expect from negating a bool.Use the 'not' operator for boolean negation or ~int(x) if you really want the bitwise inversion of the underlying int.`);return int.__invert__(self)};bool.$factory=function(){var $=$B.args("bool",1,{x:null},["x"],arguments,{x:false},null,null,1);return $B.$bool($.x,true)};bool.__new__=function(cls,value){if(cls===undefined){throw _b_.TypeError.$factory("bool.__new__(): not enough arguments")}else if(!$B.$isinstance(cls,_b_.type)){throw _b_.TypeError.$factory(`bool.__new__(X): X is not a type object (${$B.class_name(cls)})`)}else if(!_b_.issubclass(cls,bool)){let class_name=$B.class_name(cls);throw _b_.TypeError.$factory(`bool.__new__(${class_name}): ${class_name} is not a subtype of bool`)}if(arguments.length>2){throw _b_.TypeError.$factory(`bool expected at most 1 argument, got ${arguments.length-1}`)}return bool.$factory(value)};bool.from_bytes=function(){var $=$B.args("from_bytes",3,{bytes:null,byteorder:null,signed:null},["bytes","byteorder","signed"],arguments,{byteorder:"big",signed:false},null,null);let int_result=int.from_bytes($.bytes,$.byteorder,$.signed);return bool.$factory(int_result)};bool.numerator=int.numerator;bool.denominator=int.denominator;bool.real=self=>self?1:0;bool.imag=int.imag;for(var attr of["real"]){bool[attr].setter=function(x){return function(self){throw _b_.AttributeError.$factory(`attribute '${x}' of `+`'${$B.class_name(self)}' objects is not writable`)}}(attr)}_b_.bool=bool;$B.set_func_names(bool,"builtins")})(__BRYTHON__);(function($B){var _b_=$B.builtins;var long_int={__class__:_b_.type,__mro__:[_b_.int,_b_.object],__qualname__:"int",$infos:{__module__:"builtins",__name__:"int"},$is_class:true,$native:true,$descriptors:{numerator:true,denominator:true,imag:true,real:true}};var int_or_long=_b_.int.$int_or_long;function preformat(self,fmt){if(fmt.empty){return _b_.str.$factory(self)}if(fmt.type&&"bcdoxXn".indexOf(fmt.type)==-1){throw _b_.ValueError.$factory("Unknown format code '"+fmt.type+"' for object of type 'int'")}var res;switch(fmt.type){case undefined:case"d":res=self.toString();break;case"b":res=(fmt.alternate?"0b":"")+BigInt(self.value).toString(2);break;case"c":res=_b_.chr(self);break;case"o":res=(fmt.alternate?"0o":"")+BigInt(self.value).toString(8);break;case"x":res=(fmt.alternate?"0x":"")+BigInt(self.value).toString(16);break;case"X":res=(fmt.alternate?"0X":"")+BigInt(self.value).toString(16).toUpperCase();break;case"n":return self}if(fmt.sign!==undefined){if((fmt.sign==" "||fmt.sign=="+")&&self>=0){res=fmt.sign+res}}return res}long_int.$to_js_number=function(self){return Number(self.value)};long_int.__format__=function(self,format_spec){var fmt=new $B.parse_format_spec(format_spec,self);if(fmt.type&&"eEfFgG%".indexOf(fmt.type)!=-1){return _b_.float.__format__(self,format_spec)}fmt.align=fmt.align||">";var res=preformat(self,fmt);if(fmt.comma){var sign=res[0]=="-"?"-":"",rest=res.substr(sign.length),len=rest.length,nb=Math.ceil(rest.length/3),chunks=[];for(var i=0;i0?self.value:-self.value)};long_int.__add__=function(self,other){if(typeof other=="number"){return int_or_long(self.value+BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value+other.value)}else if(typeof other=="boolean"){return int_or_long(self.value+(other?1n:0n))}else if($B.$isinstance(other,_b_.int)){return long_int.__add__(self,other.$brython_value)}return _b_.NotImplemented};long_int.__divmod__=function(self,other){var a=self.value,b=_b_.int.$to_bigint(other),quotient;if(a>=0&&b>0||a<=0&&b<0){quotient=a/b}else{quotient=a/b-1n}var rest=a-quotient*b;return $B.fast_tuple([int_or_long(quotient),int_or_long(rest)])};long_int.__eq__=function(self,other){if(other.__class__===$B.long_int){return self.value==other.value}else if(typeof other=="number"||typeof other=="boolean"){return false}else if($B.$isinstance(other,_b_.int)){return long_int.__eq__(self,other.$brython_value)}return _b_.NotImplemented};long_int.__float__=function(self){if(!isFinite(Number(self.value))){throw _b_.OverflowError.$factory("int too large to convert to float")}return $B.fast_float(Number(self.value))};long_int.__floordiv__=function(self,other){if(typeof other=="number"){return int_or_long(self.value/BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value/other.value)}else if(typeof other=="boolean"){return int_or_long(self.value/(other?1n:0n))}else if($B.$isinstance(other,_b_.int)){return int_or_long(self.value/other.$brython_value)}return _b_.NotImplemented};long_int.__ge__=function(self,other){if(typeof other=="number"){return self.value>=other}else if(other.__class__===$B.long_int){return self.value>=other.value}else if(typeof other=="boolean"){return self.value>=(other?1:0)}else if($B.$isinstance(other,_b_.int)){return self.value>=other.$brython_value}return _b_.NotImplemented};long_int.__gt__=function(self,other){var res=long_int.__le__(self,other);return res===_b_.NotImplemented?res:!res};long_int.__hash__=function(self){var modulus=2305843009213693951n,sign=self.value>=0?1n:-1n,self_pos=self.value*sign;var _hash=sign*(self_pos%modulus);return self.__hashvalue__=int_or_long(_hash)};long_int.__index__=function(self){return self};long_int.__invert__=function(self){return int_or_long(-1n-self.value)};long_int.__le__=function(self,other){if(typeof other=="number"){return self.value<=other}else if(other.__class__===$B.long_int){return self.value<=other.value}else if(typeof other=="boolean"){return self.value<=(other?1:0)}else if($B.$isinstance(other,_b_.int)){return self.value<=other.$brython_value}return _b_.NotImplemented};long_int.__lt__=function(self,other){var res=long_int.__ge__(self,other);return res===_b_.NotImplemented?res:!res};long_int.__lshift__=function(self,other){if(typeof other=="number"){return int_or_long(self.value<>BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value>>other.value)}else if(typeof other=="boolean"){return int_or_long(self.value>>(other?1n:0n))}else if($B.$isinstance(other,_b_.int)){return long_int.__rshift__(self,other.$brython_value)}return _b_.NotImplemented};long_int.__repr__=function(self){$B.builtins_repr_check($B.long_int,arguments);if($B.int_max_str_digits!=0&&self.value>=10n**BigInt($B.int_max_str_digits)){throw _b_.ValueError.$factory(`Exceeds the limit `+`(${$B.int_max_str_digits}) for integer string conversion`)}return self.value.toString()};long_int.__sub__=function(self,other){if(typeof other=="number"){return int_or_long(self.value-BigInt(other))}else if(typeof other=="boolean"){return int_or_long(self.value-(other?1n:0n))}else if(other.__class__===$B.long_int){return int_or_long(self.value-other.value)}else if($B.$isinstance(other,_b_.int)){return long_int.__sub__(self,other.$brython_value)}return _b_.NotImplemented};long_int.__truediv__=function(self,other){if(typeof other=="number"){return $B.fast_float(Number(self.value)/other)}else if(typeof other=="boolean"){return $B.fast_float(Number(self.value)*(other?1:0))}else if(other.__class__===$B.long_int){return $B.fast_float(Number(self.value)/Number(other.value))}else if($B.$isinstance(other,_b_.int)){return long_int.__truediv__(self,other.$brython_value)}return _b_.NotImplemented};long_int.bit_count=function(self){var s=self.value.toString(2),nb=0;for(var x of s){if(x=="1"){nb++}}return nb};long_int.bit_length=function(self){return self.value.toString(2).length};function _infos(self){var nbits=$B.long_int.bit_length(self),pow2=2n**BigInt(nbits-1),rest=BigInt(self.value)-pow2,relative_rest=new Number(rest/pow2);return{nbits:nbits,pow2:pow2,rest:rest,relative_rest:relative_rest}}long_int.$log2=function(x){if(x.value<0){throw _b_.ValueError.$factory("math domain error")}var infos=_infos(x);return _b_.float.$factory(infos.nbits-1+Math.log(1+infos.relative_rest/Math.LN2))};long_int.$log10=function(x){if(x.value<0){throw _b_.ValueError.$factory("math domain error")}var x_string=x.value.toString(),exp=x_string.length-1,mant=parseFloat(x_string[0]+"."+x_string.substr(1));return _b_.float.$factory(exp+Math.log10(mant))};long_int.numerator=self=>self;long_int.denominator=()=>1;long_int.imag=()=>0;long_int.real=self=>self;var body=`var $B = __BRYTHON__,\n _b_ = $B.builtins\nif(typeof other == "number"){\n return _b_.int.$int_or_long(self.value & BigInt(other))}else if(typeof other == "boolean"){\n return _b_.int.$int_or_long(self.value & (other ? 1n : 0n))}else if(other.__class__ === $B.long_int){\n return _b_.int.$int_or_long(self.value & other.value)}else if($B.$isinstance(other, _b_.int)){\n // int subclass\n return $B.long_int.__and__(self, other.$brython_value)}\nreturn _b_.NotImplemented`;long_int.__and__=Function("self","other",body);long_int.__or__=Function("self","other",body.replace(/&/g,"|").replace(/__and__/g,"__or__"));long_int.__xor__=Function("self","other",body.replace(/&/g,"^").replace(/__and__/g,"__xor__"));long_int.to_bytes=function(self,len,byteorder,signed){var res=[],v=self.value;if(!$B.$bool(signed)&&v<0){throw _b_.OverflowError.$factory("can't convert negative int to unsigned")}while(v>0){var quot=v/256n,rest=v-quot*256n;v=quot;res.push(Number(rest));if(res.length>len){throw _b_.OverflowError.$factory("int too big to convert")}}while(res.length10){for(let i=0;i0}};long_int.$factory=function(value,base){var is_digits=digits(base);for(let i=0;i=0;i--){char=value[i].toUpperCase();res+=coef*BigInt(is_digits[char]);coef*=base}}return{__class__:$B.long_int,value:res}};function extended_euclidean_algorithm(a,b){var s=0,old_s=1,t=1,old_t=0,r=b,old_r=a,quotient,tmp;while($B.rich_comp("__ne__",r,0)){quotient=$B.rich_op("__floordiv__",old_r,r);tmp=$B.rich_op("__sub__",old_r,$B.rich_op("__mul__",quotient,r));old_r=r;r=tmp;tmp=$B.rich_op("__sub__",old_s,$B.rich_op("__mul__",quotient,s));old_s=s;s=tmp;tmp=$B.rich_op("__sub__",old_t,$B.rich_op("__mul__",quotient,t));old_t=t;t=tmp}return[old_r,old_s,old_t]}function inverse_of(n,p){var gcd,x,y;[gcd,x,y]=extended_euclidean_algorithm(n,p);if($B.rich_comp("__ne__",gcd,1)){throw Error(`${n} has no multiplicative inverse '\n 'modulo ${p}`)}else{return $B.rich_op("__mod__",x,p)}}$B.inverse_of=inverse_of;$B.set_func_names(long_int,"builtins");$B.long_int=long_int;$B.fast_long_int=function(value){if(typeof value!=="bigint"){console.log("expected bigint, got",value);throw Error("not a big int")}return{__class__:$B.long_int,value:value}}})(__BRYTHON__);(function($B){var _b_=$B.builtins;function float_value(obj){return obj.__class__===float?obj:fast_float(obj.value)}var float={__class__:_b_.type,__dir__:_b_.object.__dir__,__qualname__:"float",$is_class:true,$native:true,$descriptors:{numerator:true,denominator:true,imag:true,real:true}};float.$float_value=float_value;float.$to_js_number=function(self){if(self.__class__===float){return self.value}else{return float.$to_js_number(self.value)}};float.numerator=self=>self;float.denominator=()=>1;float.imag=()=>0;float.real=self=>self;float.__float__=function(self){return self};$B.shift1_cache={};float.as_integer_ratio=function(self){if(isinf(self)){throw _b_.OverflowError.$factory("Cannot pass infinity to "+"float.as_integer_ratio.")}if(isnan(self)){throw _b_.ValueError.$factory("Cannot pass NaN to "+"float.as_integer_ratio.")}var tmp=frexp(self),fp=tmp[0],exponent=tmp[1];for(var i=0;i<300;i++){if(fp==Math.floor(fp)){break}else{fp*=2;exponent--}}var numerator=_b_.int.$factory(fp),py_exponent=_b_.abs(exponent),denominator=1,x;if($B.shift1_cache[py_exponent]!==undefined){x=$B.shift1_cache[py_exponent]}else{x=$B.$getattr(1,"__lshift__")(py_exponent);$B.shift1_cache[py_exponent]=x}py_exponent=x;if(exponent>0){numerator=$B.rich_op("__mul__",numerator,py_exponent)}else{denominator=py_exponent}return $B.fast_tuple([_b_.int.$factory(numerator),_b_.int.$factory(denominator)])};function check_self_is_float(x,method){if(x.__class__===_b_.float||$B.$isinstance(x,_b_.float)){return true}throw _b_.TypeError.$factory(`descriptor '${method}' requires a `+`'float' object but received a '${$B.class_name(x)}'`)}float.__abs__=function(self){check_self_is_float(self,"__abs__");return fast_float(Math.abs(self.value))};float.__bool__=function(self){check_self_is_float(self,"__bool__");return _b_.bool.$factory(self.value)};float.__ceil__=function(self){check_self_is_float(self,"__ceil__");if(isnan(self)){throw _b_.ValueError.$factory("cannot convert float NaN to integer")}else if(isinf(self)){throw _b_.OverflowError.$factory("cannot convert float infinity to integer")}return Math.ceil(self.value)};float.__divmod__=function(self,other){check_self_is_float(self,"__divmod__");if(!$B.$isinstance(other,[_b_.int,float])){return _b_.NotImplemented}return $B.fast_tuple([float.__floordiv__(self,other),float.__mod__(self,other)])};float.__eq__=function(self,other){check_self_is_float(self,"__eq__");if(isNaN(self.value)&&($B.$isinstance(other,float)&&isNaN(other.value))){return false}if($B.$isinstance(other,_b_.int)){return self.value==other}if($B.$isinstance(other,float)){return self.value==other.value}if($B.$isinstance(other,_b_.complex)){if(!$B.rich_comp("__eq__",0,other.$imag)){return false}return float.__eq__(self,other.$real)}return _b_.NotImplemented};float.__floor__=function(self){check_self_is_float(self,"__floor__");if(isnan(self)){throw _b_.ValueError.$factory("cannot convert float NaN to integer")}else if(isinf(self)){throw _b_.OverflowError.$factory("cannot convert float infinity to integer")}return Math.floor(self.value)};float.__floordiv__=function(self,other){check_self_is_float(self,"__floordiv__");if($B.$isinstance(other,float)){if(other.value==0){throw _b_.ZeroDivisionError.$factory("division by zero")}return fast_float(Math.floor(self.value/other.value))}if($B.$isinstance(other,_b_.int)){if(other.valueOf()==0){throw _b_.ZeroDivisionError.$factory("division by zero")}return fast_float(Math.floor(self.value/other))}return _b_.NotImplemented};const DBL_MANT_DIG=53,LONG_MAX=$B.MAX_VALUE,DBL_MAX_EXP=2**10,LONG_MIN=$B.MIN_VALUE,DBL_MIN_EXP=-1021;float.fromhex=function(klass,s){function hex_from_char(char){return parseInt(char,16)}function finished(){while(s[pos]&&s[pos].match(/\s/)){pos++}if(pos!=s.length){throw parse_error()}if(negate){x=float.__neg__(x)}return klass===_b_.float?x:$B.$call(klass)(x)}function overflow_error(){throw _b_.OverflowError.$factory("hexadecimal value too large to represent as a float")}function parse_error(){throw _b_.ValueError.$factory("invalid hexadecimal floating-point string")}function insane_length_error(){throw _b_.ValueError.$factory("hexadecimal string too long to convert")}s=s.trim();if(s.match(/^\+?inf(inity)?$/i)){return INF}else if(s.match(/^-inf(inity)?$/i)){return NINF}else if(s.match(/^[+-]?nan$/i)){return NAN}var pos=0,negate,ldexp=_b_.float.$funcs.ldexp;if(s[pos]=="-"){pos++;negate=1}else if(s[pos]=="+"){pos++}if(s.substr(pos,2).toLowerCase()=="0x"){pos+=2}var coeff_start=pos,coeff_end;while(hex_from_char(s[pos])>=0){pos++}var save_pos=pos;if(s[pos]=="."){pos++;while(hex_from_char(s[pos])>=0){pos++}coeff_end=pos-1}else{coeff_end=pos}var ndigits=coeff_end-coeff_start,fdigits=coeff_end-save_pos;if(ndigits==0){throw parse_error()}if(ndigits>Math.min(DBL_MIN_EXP-DBL_MANT_DIG-LONG_MIN/2,LONG_MAX/2+1-DBL_MAX_EXP)/4){throw insane_length_error()}var exp;if(s[pos]=="p"||s[pos]=="P"){pos++;var exp_start=pos;if(s[pos]=="-"||s[pos]=="+"){pos++}if(!("0"<=s[pos]&&s[pos]<="9")){throw parse_error()}pos++;while("0"<=s[pos]&&s[pos]<="9"){pos++}exp=parseInt(s.substr(exp_start))}else{exp=0}function HEX_DIGIT(j){if(!Number.isInteger(j)){throw Error("j pas entier")}return hex_from_char(s[j0&&HEX_DIGIT(ndigits-1)==0){ndigits--}if(ndigits==0||expLONG_MAX/2){console.log("overflow, exp",exp);throw overflow_error()}exp=exp-4*fdigits;var top_exp=exp+4*(ndigits-1);for(let digit=BigInt(HEX_DIGIT(ndigits-1));digit!=0;digit/=2n){top_exp++}if(top_expDBL_MAX_EXP){throw overflow_error()}var lsb=Math.max(top_exp,DBL_MIN_EXP)-DBL_MANT_DIG;var x=0;if(exp>=lsb){for(let i=ndigits-1;i>=0;i--){x=16*x+HEX_DIGIT(i)}x=ldexp($B.fast_float(x),exp);return finished()}var half_eps=1<<(lsb-exp-1)%4,key_digit=parseInt((lsb-exp-1)/4);for(let i=ndigits-1;i>key_digit;i--){x=16*x+HEX_DIGIT(i)}let digit=HEX_DIGIT(key_digit);x=16*x+(digit&16-2*half_eps);if((digit&half_eps)!=0){var round_up=0;if((digit&3*half_eps-1)!=0||half_eps==8&&key_digit+1=0;i--){if(HEX_DIGIT(i)!=0){round_up=1;break}}}if(round_up){x+=2*half_eps;if(top_exp==DBL_MAX_EXP&&x==ldexp(2*half_eps,DBL_MANT_DIG).value){throw overflow_error()}}}x=ldexp(x,exp+4*key_digit);return finished()};float.__getformat__=function(arg){if(arg=="double"||arg=="float"){return"IEEE, little-endian"}if(typeof arg!=="string"){throw _b_.TypeError.$factory(" __getformat__() argument must be str, not "+$B.class_name(arg))}throw _b_.ValueError.$factory("__getformat__() argument 1 must be "+"'double' or 'float'")};var format_sign=function(val,flags){switch(flags.sign){case"+":return val>=0||isNaN(val)?"+":"";case"-":return"";case" ":return val>=0||isNaN(val)?" ":""}if(flags.space){if(val>=0){return" "}}return""};function preformat(self,fmt){var value=self.value;if(fmt.empty){return _b_.str.$factory(self)}if(fmt.type&&"eEfFgGn%".indexOf(fmt.type)==-1){throw _b_.ValueError.$factory("Unknown format code '"+fmt.type+"' for object of type 'float'")}var special;if(isNaN(value)){special="efg".indexOf(fmt.type)>-1?"nan":"NAN"}else if(value==Number.POSITIVE_INFINITY){special="efg".indexOf(fmt.type)>-1?"inf":"INF"}else if(value==Number.NEGATIVE_INFINITY){special="efg".indexOf(fmt.type)>-1?"-inf":"-INF"}if(special){return format_sign(value,fmt)+special}if(fmt.precision===undefined&&fmt.type!==undefined){fmt.precision=6}if(fmt.type=="%"){value*=100}if(fmt.type=="e"){let res=value.toExponential(fmt.precision),exp=parseInt(res.substr(res.search("e")+1));if(Math.abs(exp)<10){res=res.substr(0,res.length-1)+"0"+res.charAt(res.length-1)}return res}var res;if(fmt.precision!==undefined){let prec=fmt.precision;if(prec==0){return Math.round(value)+""}res=$B.roundDownToFixed(value,prec);let pt_pos=res.indexOf(".");if(fmt.type!==undefined&&(fmt.type=="%"||fmt.type.toLowerCase()=="f")){if(pt_pos==-1){res+="."+"0".repeat(fmt.precision)}else{var missing=fmt.precision-res.length+pt_pos+1;if(missing>0){res+="0".repeat(missing)}}}else if(fmt.type&&fmt.type.toLowerCase()=="g"){let exp_fmt=preformat(self,{type:"e"}).split("e"),exp=parseInt(exp_fmt[1]);if(-4<=exp&&exp0){while(signif.endsWith("0")){signif=signif.substr(0,signif.length-1)}}if(signif.endsWith(".")){signif=signif.substr(0,signif.length-1)}parts[0]=signif}res=parts.join("e");if(fmt.type=="G"){res=res.toUpperCase()}return res}else if(fmt.type===undefined){fmt.type="g";res=preformat(self,fmt);if(res.indexOf(".")==-1){let exp=res.length-1;exp=exp<10?"0"+exp:exp;let is_neg=res.startsWith("-"),point_pos=is_neg?2:1,mant=res.substr(0,point_pos)+"."+res.substr(point_pos);return`${mant}e+${exp}`}fmt.type=undefined}else{let res1=value.toExponential(fmt.precision-1),exp=parseInt(res1.substr(res1.search("e")+1));if(exp<-4||exp>=fmt.precision-1){var elts=res1.split("e");while(elts[0].endsWith("0")){elts[0]=elts[0].substr(0,elts[0].length-1)}res=elts.join("e")}}}else{res=_b_.str.$factory(self)}if(fmt.type===undefined||"gGn".indexOf(fmt.type)!=-1){if(res.search("e")==-1){while(res.charAt(res.length-1)=="0"){res=res.substr(0,res.length-1)}}if(res.charAt(res.length-1)=="."){if(fmt.type===undefined){res+="0"}else{res=res.substr(0,res.length-1)}}}if(fmt.sign!==undefined){if((fmt.sign==" "||fmt.sign=="+")&&value>0){res=fmt.sign+res}}if(fmt.type=="%"){res+="%"}return res}float.__format__=function(self,format_spec){check_self_is_float(self,"__format__");var fmt=new $B.parse_format_spec(format_spec,self);return float.$format(self,fmt)};float.$format=function(self,fmt){fmt.align=fmt.align||">";var pf=preformat(self,fmt);if(fmt.z&&Object.is(parseFloat(pf),-0)){pf=pf.substr(1)}var raw=pf.split("."),_int=raw[0];if(fmt.comma){var len=_int.length,nb=Math.ceil(_int.length/3),chunks=[];for(var i=0;i1e4){$B.float_hash_cache.clear()}return self.__hashvalue__=x};function isninf(x){var x1=float_value(x).value;return x1==-Infinity||x1==Number.NEGATIVE_INFINITY}function isinf(x){var x1=float_value(x).value;return x1==Infinity||x1==-Infinity||x1==Number.POSITIVE_INFINITY||x1==Number.NEGATIVE_INFINITY}function isnan(x){var x1=float_value(x).value;return isNaN(x1)}function fabs(x){if(x==0){return fast_float(0)}return x>0?float.$factory(x):float.$factory(-x)}function frexp(x){var x1=x;if($B.$isinstance(x,float)){if(isnan(x)||isinf(x)){return[x,0]}x1=float_value(x).value}else if($B.$isinstance(x,$B.long_int)){var exp=x.value.toString(2).length,power=2n**BigInt(exp);return[$B.fast_float(Number(x.value)/Number(power)),exp]}if(x1==0){return[0,0]}var sign=1,ex=0,man=x1;if(man<0){sign=-sign;man=-man}while(man<.5){man*=2;ex--}while(man>=1){man*=.5;ex++}man*=sign;return[man,ex]}function ldexp(mantissa,exponent){if(isninf(mantissa)){return NINF}else if(isinf(mantissa)){return INF}if($B.$isinstance(mantissa,_b_.float)){mantissa=mantissa.value}if(mantissa==0){return ZERO}else if(isNaN(mantissa)){return NAN}if($B.$isinstance(exponent,$B.long_int)){if(exponent.value<0){return ZERO}else{throw _b_.OverflowError.$factory("overflow")}}else if(!isFinite(mantissa*Math.pow(2,exponent))){throw _b_.OverflowError.$factory("overflow")}var steps=Math.min(3,Math.ceil(Math.abs(exponent)/1023));var result=mantissa;for(var i=0;i=0){if(Number.isInteger(other)&&other%2==1){return self}return fast_float(0)}else if(self.value==Number.NEGATIVE_INFINITY&&!isNaN(other)){if(other%2==-1){return fast_float(-0)}else if(other<0){return fast_float(0)}else if(other%2==1){return fast_float(Number.NEGATIVE_INFINITY)}else{return fast_float(Number.POSITIVE_INFINITY)}}else if(self.value==Number.POSITIVE_INFINITY&&!isNaN(other)){return other>0?self:fast_float(0)}if(other==Number.NEGATIVE_INFINITY&&!isNaN(self.value)){return Math.abs(self.value)<1?fast_float(Number.POSITIVE_INFINITY):fast_float(0)}else if(other==Number.POSITIVE_INFINITY&&!isNaN(self.value)){return Math.abs(self.value)<1?fast_float(0):fast_float(Number.POSITIVE_INFINITY)}if(self.value<0&&!Number.isInteger(other)){return _b_.complex.__pow__($B.make_complex(self.value,0),fast_float(other))}return fast_float(Math.pow(self.value,other))}return _b_.NotImplemented};float.__repr__=function(self){$B.builtins_repr_check(float,arguments);self=self.value;if(self==Infinity){return"inf"}else if(self==-Infinity){return"-inf"}else if(isNaN(self)){return"nan"}else if(self===0){if(1/self===-Infinity){return"-0.0"}return"0.0"}var res=self+"";if(res.search(/[.eE]/)==-1){res+=".0"}var split_e=res.split(/e/i);if(split_e.length==2){let mant=split_e[0],exp=split_e[1];if(exp.startsWith("-")){let exp_str=parseInt(exp.substr(1))+"";if(exp_str.length<2){exp_str="0"+exp_str}return mant+"e-"+exp_str}}var x,y;[x,y]=res.split(".");var sign="";if(x[0]=="-"){x=x.substr(1);sign="-"}if(x.length>16){let exp=x.length-1,int_part=x[0],dec_part=x.substr(1)+y;while(dec_part.endsWith("0")){dec_part=dec_part.substr(0,dec_part.length-1)}let mant=int_part;if(dec_part.length>0){mant+="."+dec_part}return sign+mant+"e+"+exp}else if(x=="0"){let exp=0;while(exp3){let rest=y.substr(exp);exp=(exp+1).toString();while(rest.endsWith("0")){rest=rest.substr(0,res.length-1)}let mant=rest[0];if(rest.length>1){mant+="."+rest.substr(1)}if(exp.length==1){exp="0"+exp}return sign+mant+"e-"+exp}}return _b_.str.$factory(res)};float.__round__=function(){var $=$B.args("__round__",2,{self:null,ndigits:null},["self","ndigits"],arguments,{ndigits:_b_.None},null,null);return float.$round($.self,$.ndigits)};float.$round=function(x,ndigits){function overflow(){throw _b_.OverflowError.$factory("cannot convert float infinity to integer")}var no_digits=ndigits===_b_.None;if(isnan(x)){if(ndigits===_b_.None){throw _b_.ValueError.$factory("cannot convert float NaN to integer")}return NAN}else if(isninf(x)){return ndigits===_b_.None?overflow():NINF}else if(isinf(x)){return ndigits===_b_.None?overflow():INF}x=float_value(x);ndigits=ndigits===_b_.None?0:ndigits;if(ndigits==0){var res=Math.round(x.value);if(Math.abs(x.value-res)==.5){if(res%2){return res-1}}if(no_digits){return res}return $B.fast_float(res)}if(ndigits.__class__===$B.long_int){ndigits=Number(ndigits.value)}var pow1,pow2,y,z;if(ndigits>=0){if(ndigits>22){pow1=10**(ndigits-22);pow2=1e22}else{pow1=10**ndigits;pow2=1}y=x.value*pow1*pow2;if(!isFinite(y)){return x}}else{pow1=10**-ndigits;pow2=1;if(isFinite(pow1)){y=x.value/pow1}else{return ZERO}}z=Math.round(y);if(fabs(y-z).value==.5){z=2*Math.round(y/2)}if(ndigits>=0){z=z/pow2/pow1}else{z*=pow1}if(!isFinite(z)){throw _b_.OverflowError.$factory("overflow occurred during round")}return fast_float(z)};float.__setattr__=function(self,attr,value){if(self.__class__===float){if(float[attr]===undefined){throw _b_.AttributeError.$factory("'float' object has no attribute '"+attr+"'")}else{throw _b_.AttributeError.$factory("'float' object attribute '"+attr+"' is read-only")}}self[attr]=value;return _b_.None};float.__truediv__=function(self,other){if($B.$isinstance(other,_b_.int)){if(other.valueOf()==0){throw _b_.ZeroDivisionError.$factory("division by zero")}else if($B.$isinstance(other,$B.long_int)){return float.$factory(self.value/Number(other.value))}return float.$factory(self.value/other)}else if($B.$isinstance(other,float)){if(other.value==0){throw _b_.ZeroDivisionError.$factory("division by zero")}return float.$factory(self.value/other.value)}return _b_.NotImplemented};var op_func_body=`var $B = __BRYTHON__,\n _b_ = __BRYTHON__.builtins\n if($B.$isinstance(other, _b_.int)){\n if(typeof other == "boolean"){\n return other ? $B.fast_float(self.value - 1) : self\n }else if(other.__class__ === $B.long_int){\n return _b_.float.$factory(self.value - parseInt(other.value))\n }else{\n return $B.fast_float(self.value - other)\n }\n }\n if($B.$isinstance(other, _b_.float)){\n return $B.fast_float(self.value - other.value)\n }\n return _b_.NotImplemented`;var ops={"+":"add","-":"sub"};for(let op in ops){let body=op_func_body.replace(/-/gm,op);float[`__${ops[op]}__`]=Function("self","other",body)}var comp_func_body=`\nvar $B = __BRYTHON__,\n _b_ = $B.builtins\nif($B.$isinstance(other, _b_.int)){\n if(other.__class__ === $B.long_int){\n return self.value > parseInt(other.value)\n }\n return self.value > other.valueOf()}\nif($B.$isinstance(other, _b_.float)){\n return self.value > other.value}\nif($B.$isinstance(other, _b_.bool)) {\n return self.value > _b_.bool.__hash__(other)}\nif(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")) {\n return _b_.int.__gt__(self.value, $B.$GetInt(other))}\n// See if other has the opposite operator, eg <= for >\nvar inv_op = $B.$getattr(other, "__le__", _b_.None)\nif(inv_op !== _b_.None){\n return inv_op(self)}\nthrow _b_.TypeError.$factory(\n "unorderable types: float() > " + $B.class_name(other) + "()")\n`;for(let op in $B.$comps){let body=comp_func_body.replace(/>/gm,op).replace(/__gt__/gm,`__${$B.$comps[op]}__`).replace(/__le__/,`__${$B.$inv_comps[op]}__`);float[`__${$B.$comps[op]}__`]=Function("self","other",body)}var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or","divmod"];for(var r_opname of r_opnames){if(float["__r"+r_opname+"__"]===undefined&&float["__"+r_opname+"__"]){float["__r"+r_opname+"__"]=function(name){return function(self,other){var other_as_num=_b_.int.$to_js_number(other);if(other_as_num!==null){var other_as_float=$B.fast_float(other_as_num);return float["__"+name+"__"](other_as_float,self)}return _b_.NotImplemented}}(r_opname)}}function to_digits(s){var arabic_digits="٠١٢٣٤٥٦٧٨٩",res="";for(var i=0;i-1){res+=x}else{res+=s[i]}}return res}const fast_float=$B.fast_float=function(value){return{__class__:_b_.float,value:value}};float.$factory=function(value){if(value===undefined){return fast_float(0)}$B.check_nb_args_no_kw("float",1,arguments);switch(value){case true:return fast_float(1);case false:return fast_float(0)}var original_value=value;if(typeof value=="number"){return fast_float(value)}if(value.__class__===float){return value}if($B.$isinstance(value,_b_.memoryview)){value=_b_.memoryview.tobytes(value)}if($B.$isinstance(value,_b_.bytes)){try{value=$B.$getattr(value,"decode")("utf-8")}catch(err){throw _b_.ValueError.$factory("could not convert string to float: "+_b_.repr(original_value))}}if(typeof value=="string"){if(value.trim().length==0){throw _b_.ValueError.$factory(`could not convert string to float: ${_b_.repr(value)}`)}value=value.trim();switch(value.toLowerCase()){case"+inf":case"inf":case"+infinity":case"infinity":return fast_float(Number.POSITIVE_INFINITY);case"-inf":case"-infinity":return fast_float(Number.NEGATIVE_INFINITY);case"+nan":case"nan":return fast_float(Number.NaN);case"-nan":return fast_float(-Number.NaN);default:var parts=value.split("e");if(parts[1]){if(parts[1].startsWith("+")||parts[1].startsWith("-")){parts[1]=parts[1].substr(1)}}parts=parts[0].split(".").concat(parts.splice(1));for(var part of parts){if(part.startsWith("_")||part.endsWith("_")){throw _b_.ValueError.$factory("invalid float literal "+value)}}if(value.indexOf("__")>-1){throw _b_.ValueError.$factory("invalid float literal "+value)}value=value.charAt(0)+value.substr(1).replace(/_/g,"");value=to_digits(value);if(isFinite(value)){return fast_float(parseFloat(value))}else{throw _b_.TypeError.$factory("could not convert string to float: "+_b_.repr(original_value))}}}let klass=$B.get_class(value),float_method=$B.$getattr(klass,"__float__",null);if(float_method===null){var index_method=$B.$getattr(klass,"__index__",null);if(index_method===null){throw _b_.TypeError.$factory("float() argument must be a string or a "+"real number, not '"+$B.class_name(value)+"'")}let index=$B.$call(index_method)(value),index_klass=$B.get_class(index);if(index_klass===_b_.int){return fast_float(index)}else if(index_klass===$B.long_int){return $B.long_int.__float__(index)}else if(index_klass.__mro__.indexOf(_b_.int)>-1){let msg=`${$B.class_name(value)}.__index__ returned `+`non-int (type ${$B.class_name(index)}). The `+"ability to return an instance of a strict subclass"+" of int is deprecated, and may be removed in a "+"future version of Python.";$B.warn(_b_.DeprecationWarning,msg);return fast_float(index)}throw _b_.TypeError.$factory("__index__ returned non-int"+` (type ${$B.class_name(index)})`)}let res=$B.$call(float_method)(value);klass=$B.get_class(res);if(klass!==_b_.float){if(klass.__mro__.indexOf(_b_.float)>-1){let msg=`${$B.class_name(value)}.__float__ returned `+`non-float (type ${$B.class_name(res)}). The `+"ability to return an instance of a strict subclass"+" of float is deprecated, and may be removed in a "+"future version of Python.";$B.warn(_b_.DeprecationWarning,msg);return float.$factory(res.value)}throw _b_.TypeError.$factory("__float__ returned non-float"+` (type ${$B.class_name(res)})`)}return res};$B.set_func_names(float,"builtins");float.fromhex=_b_.classmethod.$factory(float.fromhex);_b_.float=float;$B.MAX_VALUE=fast_float(Number.MAX_VALUE);$B.MIN_VALUE=fast_float(22250738585072014e-324);const NINF=fast_float(Number.NEGATIVE_INFINITY),INF=fast_float(Number.POSITIVE_INFINITY),NAN=fast_float(Number.NaN),ZERO=fast_float(0)})(__BRYTHON__);(function($B){var _b_=$B.builtins;function $UnsupportedOpType(op,class1,class2){throw _b_.TypeError.$factory("unsupported operand type(s) for "+op+": '"+class1+"' and '"+class2+"'")}var complex={__class__:_b_.type,__dir__:_b_.object.__dir__,__qualname__:"complex",$is_class:true,$native:true,$descriptors:{real:true,imag:true}};complex.__abs__=function(self){var _rf=isFinite(self.$real.value),_if=isFinite(self.$imag.value);if(_rf&&isNaN(self.$imag.value)||_if&&isNaN(self.$real.value)||isNaN(self.$imag.value)&&isNaN(self.$real.value)){return $B.fast_float(NaN)}if(!_rf||!_if){return $B.fast_float(Infinity)}var mag=Math.sqrt(Math.pow(self.$real.value,2)+Math.pow(self.$imag.value,2));if(!isFinite(mag)&&_rf&&_if){throw _b_.OverflowError.$factory("absolute value too large")}return $B.fast_float(mag)};complex.__add__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value+other.$real.value,self.$imag.value+other.$imag.value)}if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other);return make_complex($B.rich_op("__add__",self.$real,other).value,self.$imag.value)}if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value+other.value,self.$imag.value)}return _b_.NotImplemented};complex.__bool__=function(self){return!$B.rich_comp("__eq__",self.$real,0)||!$B.rich_comp("__eq__",self.$imag,0)};complex.__complex__=function(self){if(self.__class__===complex){return self}return $B.make_complex(self.$real,self.$imag)};complex.__eq__=function(self,other){if($B.$isinstance(other,complex)){return self.$real.value==other.$real.value&&self.$imag.value==other.$imag.value}if($B.$isinstance(other,_b_.int)){if(self.$imag.value!=0){return false}return self.$real.value==other.valueOf()}if($B.$isinstance(other,_b_.float)){if(!$B.rich_comp("__eq__",0,self.$imag)){return false}return self.$real.value==other.value}return _b_.NotImplemented};const max_precision=2**31-4;complex.__format__=function(self,format_spec){if(format_spec.length==0){return _b_.str.$factory(self)}var fmt=new $B.parse_format_spec(format_spec,self),type=fmt.conversion_type;var skip_re,add_parens;if(type===undefined||"eEfFgGn".indexOf(type)>-1){if(fmt.precision>max_precision){throw _b_.ValueError.$factory("precision too big")}if(fmt.fill_char=="0"){throw _b_.ValueError.$factory("Zero padding is not allowed in complex format specifier")}if(fmt.align=="="){throw _b_.ValueError.$factory("'=' alignment flag is not allowed in complex format "+"specifier")}var re=self.$real.value,precision=parseInt(fmt.precision,10);if(type===undefined){type="r";if(re==0&&Object.is(re,0)){skip_re=1}else{add_parens=1}}else if(type=="n"){type="g"}if(precision<0){precision=6}else if(type=="r"){type="g"}var format=$B.clone(fmt);format.conversion_type=type;format.precision=precision;var res="";if(!skip_re){res+=_b_.float.$format(self.$real,format);if(self.$imag.value>=0){res+="+"}}var formatted_im=_b_.float.$format(self.$imag,format);var pos=-1,last_num;for(var char of formatted_im){pos++;if(char.match(/\d/)){last_num=pos}}formatted_im=formatted_im.substr(0,last_num+1)+"j"+formatted_im.substr(last_num+1);res+=formatted_im;if(add_parens){res="("+res+")"}return res}throw _b_.ValueError.$factory(`invalid type for complex: ${type}`)};complex.$getnewargs=function(self){return $B.fast_tuple([self.$real,self.$imag])};complex.__getnewargs__=function(){return complex.$getnewargs($B.single_arg("__getnewargs__","self",arguments))};complex.__hash__=function(self){return $B.$hash(self.$real)+$B.$hash(self.$imag)*1000003};complex.__init__=function(){return _b_.None};complex.__invert__=function(self){return~self};complex.__mro__=[_b_.object];complex.__mul__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value*other.$real.value-self.$imag.value*other.$imag.value,self.$imag.value*other.$real.value+self.$real.value*other.$imag.value)}else if($B.$isinstance(other,_b_.int)){return make_complex(self.$real.value*other.valueOf(),self.$imag.value*other.valueOf())}else if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value*other.value,self.$imag.value*other.value)}else if($B.$isinstance(other,_b_.bool)){if(other.valueOf()){return self}return make_complex(0,0)}$UnsupportedOpType("*",complex,other)};complex.__ne__=function(self,other){var res=complex.__eq__(self,other);return res===_b_.NotImplemented?res:!res};complex.__neg__=function(self){return make_complex(-self.$real.value,-self.$imag.value)};complex.__new__=function(cls){if(cls===undefined){throw _b_.TypeError.$factory("complex.__new__(): not enough arguments")}var res,missing={},$=$B.args("complex",3,{cls:null,real:null,imag:null},["cls","real","imag"],arguments,{real:0,imag:missing},null,null);cls=$.cls;var first=$.real,second=$.imag;if(typeof first=="string"){if(second!==missing){throw _b_.TypeError.$factory("complex() can't take second arg "+"if first is a string")}else{var arg=first;first=first.trim();if(first.startsWith("(")&&first.endsWith(")")){first=first.substr(1);first=first.substr(0,first.length-1)}var complex_re=/^\s*([+-]*[0-9_]*\.?[0-9_]*(e[+-]*[0-9_]*)?)([+-]?)([0-9_]*\.?[0-9_]*(e[+-]*[0-9_]*)?)(j?)\s*$/i;var parts=complex_re.exec(first);function to_num(s){var res=parseFloat(s.charAt(0)+s.substr(1).replace(/_/g,""));if(isNaN(res)){throw _b_.ValueError.$factory("could not convert string "+"to complex: '"+arg+"'")}return res}if(parts===null){throw _b_.ValueError.$factory("complex() arg is a malformed string")}if(parts[_real]&&parts[_imag].startsWith(".")&&parts[_sign]==""){throw _b_.ValueError.$factory("complex() arg is a malformed string")}else if(parts[_real]=="."||parts[_imag]=="."||parts[_real]==".e"||parts[_imag]==".e"||parts[_real]=="e"||parts[_imag]=="e"){throw _b_.ValueError.$factory("complex() arg is a malformed string")}else if(parts[_j]!=""){if(parts[_sign]==""){first=0;if(parts[_real]=="+"||parts[_real]==""){second=1}else if(parts[_real]=="-"){second=-1}else{second=to_num(parts[_real])}}else{first=to_num(parts[_real]);second=parts[_imag]==""?1:to_num(parts[_imag]);second=parts[_sign]=="-"?-second:second}}else{if(parts[_sign]&&parts[_imag]==""){throw _b_.ValueError.$factory("complex() arg is a malformed string")}first=to_num(parts[_real]);second=0}res=make_complex(first,second);res.__class__=cls;res.__dict__=$B.empty_dict();return res}}if(first.__class__===complex&&cls===complex&&second===missing){return first}var arg1=_convert(first),r,i;if(arg1===null){throw _b_.TypeError.$factory("complex() first argument must be a "+`string or a number, not '${$B.class_name(first)}'`)}if(typeof second=="string"){throw _b_.TypeError.$factory("complex() second arg can't be a string")}var arg2=_convert(second===missing?0:second);if(arg2===null){throw _b_.TypeError.$factory("complex() second argument must be a "+`number, not '${$B.class_name(second)}'`)}if(arg1.method=="__complex__"){if(arg2.method=="__complex__"){r=$B.rich_op("__sub__",arg1.result.$real,arg2.result.$imag);i=$B.rich_op("__add__",arg1.result.$imag,arg2.result.$real)}else{r=arg1.result.$real;i=$B.rich_op("__add__",arg1.result.$imag,arg2.result)}}else{if(arg2.method=="__complex__"){r=$B.rich_op("__sub__",arg1.result,arg2.result.$imag);i=arg2.result.$real}else{r=arg1.result;i=arg2.result}}res=make_complex(r,i);res.__class__=cls;res.__dict__=$B.empty_dict();return res};complex.__pos__=function(self){return self};function complex2expo(cx){var norm=Math.sqrt(cx.$real.value*cx.$real.value+cx.$imag.value*cx.$imag.value),sin=cx.$imag.value/norm,cos=cx.$real.value/norm,angle;if(cos==0){angle=sin==1?Math.PI/2:3*Math.PI/2}else if(sin==0){angle=cos==1?0:Math.PI}else{angle=Math.atan(sin/cos)}return{norm:norm,angle:angle}}function c_powi(x,n){if(n>0){return c_powu(x,n)}else{return c_quot(c_1,c_powu(x,-n))}}function c_powu(x,n){var mask=1,r=c_1,p=x;while(mask>0&&n>=mask){if(n&mask){r=c_prod(r,p)}mask<<=1;p=c_prod(p,p)}return r}function c_prod(a,b){return make_complex(a.$real.value*b.$real.value-a.$imag.value*b.$imag.value,a.$real.value*b.$imag.value+a.$imag.value*b.$real.value)}function c_quot(a,b){var abs_breal=Math.abs(b.$real.value),abs_bimag=Math.abs(b.$imag.value);if($B.rich_comp("__ge__",abs_breal,abs_bimag)){if(abs_breal==0){throw _b_.ZeroDivisionError.$factory()}else{let ratio=b.$imag.value/b.$real.value,denom=b.$real.value+b.$imag.value*ratio;return make_complex((a.$real.value+a.$imag.value*ratio)/denom,(a.$imag.value-a.$real.value*ratio)/denom)}}else if(abs_bimag>=abs_breal){let ratio=b.$real.value/b.$imag.value,denom=b.$real.value*ratio+b.$imag.value;if(b.$imag.value==0){throw _b_.ZeroDivisionError.$factory()}return make_complex((a.$real.value*ratio+a.$imag.value)/denom,(a.$imag.value*ratio-a.$real.value)/denom)}else{return $B.make_complex("nan","nan")}}complex.__pow__=function(self,other,mod){if(mod!==undefined&&mod!==_b_.None){throw _b_.ValueError.$factory("complex modulo")}if($B.rich_comp("__eq__",other,1)){var funcs=_b_.float.$funcs;if(funcs.isinf(self.$real)||funcs.isninf(self.$real)||funcs.isinf(self.$imag)||funcs.isninf(self.$imag)){throw _b_.OverflowError.$factory("complex exponentiation")}return self}var small_int=null;if($B.$isinstance(other,_b_.int)&&_b_.abs(other)<100){small_int=other}else if($B.$isinstance(other,_b_.float)&&Number.isInteger(other.value)&&Math.abs(other.value<100)){small_int=other.value}else if($B.$isinstance(other,complex)&&other.$imag.value==0&&Number.isInteger(other.$real.value)&&Math.abs(other.$real.value)<100){small_int=other.$real.value}if(small_int!==null){return c_powi(self,small_int)}if($B.$isinstance(other,_b_.float)){other=_b_.float.$to_js_number(other)}if(self.$real.value==0&&self.$imag.value==0){if($B.$isinstance(other,complex)&&(other.$imag.value!=0||other.$real.value<0)){throw _b_.ZeroDivisionError.$factory("0.0 to a negative or complex power")}return $B.make_complex(0,0)}var exp=complex2expo(self),angle=exp.angle,res=Math.pow(exp.norm,other);if($B.$isinstance(other,_b_.int)){return make_complex(res*Math.cos(angle*other),res*Math.sin(angle*other))}else if($B.$isinstance(other,_b_.float)){return make_complex(res*Math.cos(angle*other.value),res*Math.sin(angle*other.value))}else if($B.$isinstance(other,complex)){var x=other.$real.value,y=other.$imag.value;var pw=Math.pow(exp.norm,x)*Math.pow(Math.E,-y*angle),theta=y*Math.log(exp.norm)-x*angle;if(pw==Number.POSITIVE_INFINITY||pw===Number.NEGATIVE_INFINITY){throw _b_.OverflowError.$factory("complex exponentiation")}return make_complex(pw*Math.cos(theta),pw*Math.sin(theta))}else{throw _b_.TypeError.$factory("unsupported operand type(s) "+"for ** or pow(): 'complex' and '"+$B.class_name(other)+"'")}};complex.__radd__=function(self,other){if($B.$isinstance(other,_b_.bool)){other=other?1:0}if($B.$isinstance(other,_b_.int)){return make_complex(other+self.$real.value,self.$imag.value)}else if($B.$isinstance(other,_b_.float)){return make_complex(other.value+self.$real.value,self.$imag.value)}return _b_.NotImplemented};complex.__repr__=function(self){$B.builtins_repr_check(complex,arguments);var real=Number.isInteger(self.$real.value)?self.$real.value+"":_b_.str.$factory(self.$real),imag=Number.isInteger(self.$imag.value)?self.$imag.value+"":_b_.str.$factory(self.$imag);if(imag.endsWith(".0")){imag=imag.substr(0,imag.length-2)}if(Object.is(self.$imag.value,-0)){imag="-0"}var sign=imag.startsWith("-")?"":"+";if(self.$real.value==0){if(Object.is(self.$real.value,-0)){return"(-0"+sign+imag+"j)"}else{return imag+"j"}}if(self.$imag.value>0||isNaN(self.$imag.value)){return"("+real+"+"+imag+"j)"}if(self.$imag.value==0){if(1/self.$imag.value<0){return"("+real+"-0j)"}return"("+real+"+0j)"}return"("+real+sign+imag+"j)"};complex.__rmul__=function(self,other){if($B.$isinstance(other,_b_.bool)){other=other?1:0}if($B.$isinstance(other,_b_.int)){return make_complex(other*self.$real.value,other*self.$imag.value)}else if($B.$isinstance(other,_b_.float)){return make_complex(other.value*self.$real.value,other.value*self.$imag.value)}return _b_.NotImplemented};complex.__sub__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value-other.$real.value,self.$imag.value-other.$imag.value)}if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other);return make_complex(self.$real.value-other.valueOf(),self.$imag.value)}if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value-other.value,self.$imag.value)}return _b_.NotImplemented};complex.__truediv__=function(self,other){if($B.$isinstance(other,complex)){if(other.$real.value==0&&other.$imag.value==0){throw _b_.ZeroDivisionError.$factory("division by zero")}var _num=self.$real.value*other.$real.value+self.$imag.value*other.$imag.value,_div=other.$real.value*other.$real.value+other.$imag.value*other.$imag.value;var _num2=self.$imag.value*other.$real.value-self.$real.value*other.$imag.value;return make_complex(_num/_div,_num2/_div)}if($B.$isinstance(other,_b_.int)){if(!other.valueOf()){throw _b_.ZeroDivisionError.$factory("division by zero")}return complex.__truediv__(self,complex.$factory(other.valueOf()))}if($B.$isinstance(other,_b_.float)){if(!other.value){throw _b_.ZeroDivisionError.$factory("division by zero")}return complex.__truediv__(self,complex.$factory(other.value))}$UnsupportedOpType("//","complex",other.__class__)};complex.conjugate=function(self){return make_complex(self.$real.value,-self.$imag.value)};complex.__ior__=complex.__or__;var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or"];for(var r_opname of r_opnames){if(complex["__r"+r_opname+"__"]===undefined&&complex["__"+r_opname+"__"]){complex["__r"+r_opname+"__"]=function(name){return function(self,other){if($B.$isinstance(other,_b_.int)){other=make_complex(other,0);return complex["__"+name+"__"](other,self)}else if($B.$isinstance(other,_b_.float)){other=make_complex(other.value,0);return complex["__"+name+"__"](other,self)}else if($B.$isinstance(other,complex)){return complex["__"+name+"__"](other,self)}return _b_.NotImplemented}}(r_opname)}}var comp_func_body=`\n var _b_ = __BRYTHON__.builtins\n if(other === undefined || other == _b_.None){\n return _b_.NotImplemented\n }\n throw _b_.TypeError.$factory("no ordering relation " +\n "is defined for complex numbers")`;for(var $op in $B.$comps){complex["__"+$B.$comps[$op]+"__"]=Function("self","other",comp_func_body.replace(/>/gm,$op))}complex.real=function(self){return self.$real};complex.real.setter=function(){throw _b_.AttributeError.$factory("readonly attribute")};complex.imag=function(self){return self.$imag};complex.imag.setter=function(){throw _b_.AttributeError.$factory("readonly attribute")};var _real=1,_real_mantissa=2,_sign=3,_imag=4,_imag_mantissa=5,_j=6;var expected_class={__complex__:complex,__float__:_b_.float,__index__:_b_.int};function _convert(obj){var klass=obj.__class__||$B.get_class(obj);for(var method_name in expected_class){var missing={},method=$B.$getattr(klass,method_name,missing);if(method!==missing){var res=method(obj);if(!$B.$isinstance(res,expected_class[method_name])){throw _b_.TypeError.$factory(method_name+"returned non-"+expected_class[method_name].__name__+"(type "+$B.get_class(res)+")")}if(method_name=="__index__"&&$B.rich_comp("__gt__",res,__BRYTHON__.MAX_VALUE)){throw _b_.OverflowError.$factory("int too large to convert to float")}if(method_name=="__complex__"&&res.__class__!==complex){$B.warn(_b_.DeprecationWarning,"__complex__ returned "+`non-complex (type ${$B.class_name(res)}). `+"The ability to return an instance of a strict subclass "+"of complex is deprecated, and may be removed in a future "+"version of Python.")}return{result:res,method:method_name}}}return null}var make_complex=$B.make_complex=function(real,imag){return{__class__:complex,$real:_b_.float.$factory(real),$imag:_b_.float.$factory(imag)}};var c_1=make_complex(1,0);complex.$factory=function(){return complex.__new__(complex,...arguments)};$B.set_func_names(complex,"builtins");_b_.complex=complex})(__BRYTHON__);(function($B){var _b_=$B.builtins;var set_ops=["eq","le","lt","ge","gt","sub","rsub","and","rand","or","ror","xor","rxor"];function is_sublist(t1,t2){for(var i=0,ilen=t1.length;i-1){continue}else if(!_b_.hasattr(v.__class__,"__hash__")){return false}}return true};dict.$iter_items=function*(d){if(d.$all_str){for(let key in d.$strings){if(key!="$dict_strings"){yield{key:key,value:d.$strings[key]}}}}if(d.$jsobj){for(let key in d.$jsobj){if(!d.$exclude||!d.$exclude(key)){yield{key:key,value:d.$jsobj[key]}}}}else{var version=d.$version;for(var i=0,len=d._keys.length;i0};dict.__class_getitem__=$B.$class_getitem;dict.$lookup_by_key=function(d,key,hash){hash=hash===undefined?_b_.hash(key):hash;var indices=d.table[hash],index;if(indices!==undefined){for(var i=0,len=indices.length;ix!==undefined)))}return res};dict.$setitem_string=function(self,key,value){if(self.$all_str){self.$strings[key]=value;return _b_.None}else{var h=_b_.hash(key),indices=self.table[h];if(indices!==undefined){self._values[indices[0]]=value;return _b_.None}}var index=self._keys.length;self.$strings[key]=index;self._keys.push(key);self._values.push(value);self.$version++;return _b_.None};dict.$getitem=function(self,key,ignore_missing){if(self.$all_str){if(typeof key=="string"){if(self.$strings.hasOwnProperty(key)){return self.$strings[key]}}else{var hash_method=$B.$getattr($B.get_class(key),"__hash__");if(hash_method!==_b_.object.__hash__){convert_all_str(self);let lookup=dict.$lookup_by_key(self,key);if(lookup.found){return lookup.value}}}}else if(self.$jsobj){if(self.$exclude&&self.$exclude(key)){throw _b_.KeyError.$factory(key)}if(self.$jsobj.hasOwnProperty(key)){return self.$jsobj[key]}if(!self.table){throw _b_.KeyError.$factory(key)}}else{let lookup=dict.$lookup_by_key(self,key);if(lookup.found){return lookup.value}}if(!ignore_missing){if(self.__class__!==dict&&!ignore_missing){try{var missing_method=$B.$getattr(self.__class__,"__missing__",_b_.None)}catch(err){console.log(err)}if(missing_method!==_b_.None){return missing_method(self,key)}}}throw _b_.KeyError.$factory(key)};dict.__hash__=_b_.None;function init_from_list(self,args){var i=0;for(var item of args){if(item.length!=2){throw _b_.ValueError.$factory("dictionary "+`update sequence element #${i} has length ${item.length}; 2 is required`)}dict.$setitem(self,item[0],item[1]);i++}}dict.$set_string_no_duplicate=function(d,keys,string,value){if(typeof string!=="string"){throw _b_.TypeError.$factory("keywords must be strings")}if(keys.has(string)){throw _b_.TypeError.$factory("dict() got multiple values for keyword "+`argument '${string}'`)}d.$strings[string]=value;keys.add(string)};function add_mapping(d,obj){for(var entry of _b_.dict.$iter_items(obj)){dict.$setitem(d,entry.key,entry.value,entry.hash)}}function add_iterable(d,js_iterable){var i=0;for(var entry of js_iterable){var items=Array.from($B.make_js_iterator(entry));if(items.length!==2){throw _b_.ValueError.$factory("dictionary "+`update sequence element #${i} has length ${items.length}; 2 is required`)}dict.$setitem(d,items[0],items[1]);i++}}dict.__init__=function(self,first,second){if(first===undefined){return _b_.None}if(second===undefined){if(!first.$kw&&$B.$isinstance(first,$B.JSObj)){for(let key in first){dict.$setitem(self,key,first[key])}return _b_.None}else if(first.$kw){var keys=new Set;for(let item of first.$kw){if($B.$isinstance(item,dict)){for(let subitem of dict.$iter_items(item)){dict.$set_string_no_duplicate(self,keys,subitem.key,subitem.value)}}else{for(let key in item){dict.$set_string_no_duplicate(self,keys,key,item[key])}}}return _b_.None}else if(first[Symbol.iterator]){init_from_list(self,first);return _b_.None}else if(first.__class__===$B.generator){init_from_list(self,first.js_gen);return _b_.None}}var $=$B.args("dict",1,{self:null},["self"],arguments,{},"first","second");var args=$.first;if(args.length>1){if($B._experimental_dict){console.log("try dict(*args)");for(var arg of args){if(_b_.isinstance(arg,_b_.dict)){add_mapping(self,arg)}else{try{var js_iterable=$B.make_js_iterator(arg)}catch(err){console.log(arg);console.log(err);throw _b_.TypeError.$factory("expected mapping or "+`iterable, got ${$B.class_name(arg)}`)}add_iterable(self,js_iterable)}}}else{throw _b_.TypeError.$factory("dict expected at most 1 argument"+`, got ${args.length}`)}}else if(args.length==1){args=args[0];if(args.__class__===dict){for(let entry of dict.$iter_items(args)){dict.$setitem(self,entry.key,entry.value,entry.hash)}}else{var keys=$B.$getattr(args,"keys",null);if(keys!==null){var gi=$B.$getattr(args,"__getitem__",null);if(gi!==null){gi=$B.$call(gi);let kiter=_b_.iter($B.$call(keys)());while(true){try{let key=_b_.next(kiter),value=gi(key);dict.__setitem__(self,key,value)}catch(err){if(err.__class__===_b_.StopIteration){break}throw err}}}}else{if(!Array.isArray(args)){args=_b_.list.$factory(args)}init_from_list(self,args)}}}for(let item of _b_.dict.$iter_items($.second)){dict.$setitem(self,item.key,item.value)}return _b_.None};dict.__iter__=function(self){return _b_.iter(dict.keys(self))};dict.__ior__=function(self,other){dict.update(self,other);return self};dict.__len__=function(self){var _count=0;if(self.$all_str){return Object.keys(self.$strings).length}if(self.$jsobj){for(var attr in self.$jsobj){if(attr.charAt(0)!="$"&&(!self.$exclude||!self.$exclude(attr))){_count++}}return _count}for(var d of self._keys){if(d!==undefined){_count++}}return _count};dict.__ne__=function(self,other){var res=dict.__eq__(self,other);return res===_b_.NotImplemented?res:!res};dict.__new__=function(cls){if(cls===undefined){throw _b_.TypeError.$factory("int.__new__(): not enough arguments")}var instance=$B.empty_dict();instance.__class__=cls;if(cls!==dict){instance.__dict__=$B.empty_dict()}return instance};dict.__or__=function(self,other){if(!$B.$isinstance(other,dict)){return _b_.NotImplemented}var res=dict.copy(self);dict.update(res,other);return res};dict.__repr__=function(self){$B.builtins_repr_check(dict,arguments);if(self.$jsobj){return dict.__repr__(jsobj2dict(self.$jsobj,self.$exclude))}if($B.repr.enter(self)){return"{...}"}let res=[];for(let entry of dict.$iter_items(self)){res.push(_b_.repr(entry.key)+": "+_b_.repr(entry.value))}$B.repr.leave(self);return"{"+res.join(", ")+"}"};dict.$iter_items_reversed=function*(d){var version=d.$version;if(d.$all_str){for(var item of Object.entries(d.$strings).reverse()){yield $B.fast_tuple(item);if(d.$version!==version){throw _b_.RuntimeError.$factory("changed in iteration")}}}else{for(var i=d._keys.length-1;i>=0;i--){var key=d._keys[i];if(key!==undefined){yield $B.fast_tuple([key,d._values[i]]);if(d.$version!==version){throw _b_.RuntimeError.$factory("changed in iteration")}}}}if(d.$version!==version){throw _b_.RuntimeError.$factory("changed in iteration")}};dict.$iter_keys_reversed=function*(d){for(var entry of dict.$iter_items_reversed(d)){yield entry[0]}};dict.$iter_values_reversed=function*(d){for(var entry of dict.$iter_items_reversed(d)){yield entry[1]}};function make_reverse_iterator(name,iter_func){var klass=$B.make_class(name,(function(d){return{__class__:klass,d:d,iter:iter_func(d),make_iter:function(){return iter_func(d)}}}));klass.__iter__=function(self){self[Symbol.iterator]=self.make_iter;return self};klass.__next__=function(self){var res=self.iter.next();if(res.done){throw _b_.StopIteration.$factory("")}return res.value};klass.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])};$B.set_func_names(klass,"builtins");return klass}const dict_reversekeyiterator=make_reverse_iterator("dict_reversekeyiterator",dict.$iter_keys_reversed);dict.__reversed__=function(self){return dict_reversekeyiterator.$factory(self)};dict.__ror__=function(self,other){if(!$B.$isinstance(other,dict)){return _b_.NotImplemented}var res=dict.copy(other);dict.update(res,self);return res};dict.__setitem__=function(){var $=$B.args("__setitem__",3,{self:null,key:null,value:null},["self","key","value"],arguments,{},null,null);return dict.$setitem($.self,$.key,$.value)};function convert_all_str(d){d.$all_str=false;for(var key in d.$strings){dict.$setitem(d,key,d.$strings[key])}}dict.$setitem=function(self,key,value,$hash,from_setdefault){if(self[$B.JSOBJ]){value=$B.pyobj2jsobj(value);self[$B.JSOBJ][key]=value}if(self.$all_str){if(typeof key=="string"){var int=parseInt(key);if(isNaN(int)||int>=0){self.$strings[key]=value;return _b_.None}else{convert_all_str(self)}}else{convert_all_str(self)}}if(self.$jsobj){if(self.$from_js){value=$B.pyobj2jsobj(value)}if(self.$jsobj.__class__===_b_.type){self.$jsobj[key]=value;if(key=="__init__"||key=="__new__"){self.$jsobj.$factory=$B.$instance_creator(self.$jsobj)}}else{self.$jsobj[key]=value}return _b_.None}if(key instanceof String){key=key.valueOf()}var hash=$hash!==undefined?$hash:$B.$hash(key);var index;if(self.table[hash]===undefined){index=self._keys.length;self.table[hash]=[index]}else{if(!from_setdefault){var lookup=dict.$lookup_by_key(self,key,hash);if(lookup.found){self._values[lookup.index]=value;return _b_.None}}index=self._keys.length;if(self.table[hash]===undefined){self.table[hash]=[index]}else{self.table[hash].push(index)}}self._keys.push(key);self._values.push(value);self._hashes.push(hash);self.$version++;return _b_.None};$B.make_rmethods(dict);dict.clear=function(){var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null),self=$.self;self.table=Object.create(null);self._keys=[];self._values=[];self.$all_str=true;self.$strings=new $B.str_dict;if(self.$jsobj){for(var attr in self.$jsobj){if(attr.charAt(0)!=="$"&&attr!=="__class__"){delete self.$jsobj[attr]}}}self.$version++;return _b_.None};dict.copy=function(){var $=$B.args("copy",1,{self:null},["self"],arguments,{},null,null),self=$.self,res=$B.empty_dict();if(self.__class__===_b_.dict){$copy_dict(res,self);return res}var it=$B.make_js_iterator(self);for(var k of it){console.log("iteration yields key",k)}return res};dict.fromkeys=function(){var $=$B.args("fromkeys",3,{cls:null,keys:null,value:null},["cls","keys","value"],arguments,{value:_b_.None},null,null),keys=$.keys,value=$.value;var cls=$.cls,res=$B.$call(cls)(),klass=$B.get_class(res),keys_iter=$B.$iter(keys),setitem=klass===dict?dict.$setitem:$B.$getattr(klass,"__setitem__");while(1){try{var key=_b_.next(keys_iter);setitem(res,key,value)}catch(err){if($B.is_exc(err,[_b_.StopIteration])){return res}throw err}}};dict.get=function(){var $=$B.args("get",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:_b_.None},null,null);try{return dict.$getitem($.self,$.key,true)}catch(err){if($B.$isinstance(err,_b_.KeyError)){return $._default}else{throw err}}};var dict_items=$B.make_class("dict_items",(function(d){return{__class__:dict_items,dict:d,make_iter:function*(){for(var entry of dict.$iter_items(d)){yield $B.fast_tuple([entry.key,entry.value])}}}}));dict_items.__iter__=function(self){return dict_itemiterator.$factory(self.make_iter)};dict_items.__len__=function(self){return dict.__len__(self.dict)};dict_items.__reduce__=function(self){var items=$B.$list(Array.from(self.make_iter()));return $B.fast_tuple([_b_.iter,$B.fast_tuple([items])])};dict_items.__repr__=function(self){var items=Array.from(self.make_iter());items=items.map($B.fast_tuple);return"dict_items("+_b_.repr(items)+")"};const dict_reverseitemiterator=make_reverse_iterator("dict_reverseitemiterator",dict.$iter_items_reversed);dict_items.__reversed__=function(self){return dict_reverseitemiterator.$factory(self.dict)};make_view_comparison_methods(dict_items);$B.set_func_names(dict_items,"builtins");var dict_itemiterator=$B.make_class("dict_itemiterator",(function(make_iter){return{__class__:dict_itemiterator,iter:make_iter(),make_iter:make_iter}}));dict_itemiterator.__iter__=function(self){self[Symbol.iterator]=function(){return self.iter};return self};dict_itemiterator.__next__=function(self){var res=self.iter.next();if(res.done){throw _b_.StopIteration.$factory("")}return $B.fast_tuple(res.value)};dict_itemiterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])};$B.set_func_names(dict_itemiterator,"builtins");dict.items=function(self){$B.args("items",1,{self:null},["self"],arguments,{},null,null);return dict_items.$factory(self)};var dict_keys=$B.make_class("dict_keys",(function(d){return{__class__:dict_keys,dict:d,make_iter:function(){return dict.$iter_keys_check(d)}}}));dict_keys.__iter__=function(self){return dict_keyiterator.$factory(self.make_iter)};dict_keys.__len__=function(self){return dict.__len__(self.dict)};dict_keys.__reduce__=function(self){var items=$B.$list(Array.from(self.make_iter()));return $B.fast_tuple([_b_.iter,$B.fast_tuple([items])])};dict_keys.__repr__=function(self){var items=Array.from(self.make_iter());return"dict_keys("+_b_.repr(items)+")"};dict_keys.__reversed__=function(self){return dict_reversekeyiterator.$factory(self.dict)};make_view_comparison_methods(dict_keys);$B.set_func_names(dict_keys,"builtins");var dict_keyiterator=$B.make_class("dict_keyiterator",(function(make_iter){return{__class__:dict_keyiterator,iter:make_iter(),make_iter:make_iter}}));dict_keyiterator.__iter__=function(self){self[Symbol.iterator]=function(){return self.iter};return self};dict_keyiterator.__next__=function(self){var res=self.iter.next();if(res.done){throw _b_.StopIteration.$factory("")}return res.value};dict_keyiterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])};$B.set_func_names(dict_keyiterator,"builtins");dict.keys=function(self){$B.args("keys",1,{self:null},["self"],arguments,{},null,null);return dict_keys.$factory(self)};dict.pop=function(){var missing={},$=$B.args("pop",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:missing},null,null),self=$.self,key=$.key,_default=$._default;try{var res=dict.__getitem__(self,key);dict.__delitem__(self,key);return res}catch(err){if(err.__class__===_b_.KeyError){if(_default!==missing){return _default}throw err}throw err}};dict.popitem=function(self){$B.check_nb_args_no_kw("popitem",1,arguments);if(dict.__len__(self)==0){throw _b_.KeyError.$factory("'popitem(): dictionary is empty'")}if(self.$all_str){for(var key in self.$strings){}let res=$B.fast_tuple([key,self.$strings[key]]);delete self.$strings[key];self.$version++;return res}var index=self._keys.length-1;while(index>=0){if(self._keys[index]!==undefined){let res=$B.fast_tuple([self._keys[index],self._values[index]]);delete self._keys[index];delete self._values[index];self.$version++;return res}index--}};dict.setdefault=function(){var $=$B.args("setdefault",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:_b_.None},null,null),self=$.self,key=$.key,_default=$._default;_default=_default===undefined?_b_.None:_default;if(self.$all_str){if(!self.$strings.hasOwnProperty(key)){self.$strings[key]=_default}return self.$strings[key]}if(self.$jsobj){if(!self.$jsobj.hasOwnProperty(key)){self.$jsobj[key]=_default}return self.$jsobj[key]}var lookup=dict.$lookup_by_key(self,key);if(lookup.found){return lookup.value}var hash=lookup.hash;dict.$setitem(self,key,_default,hash,true);return _default};dict.update=function(){var $=$B.args("update",1,{self:null},["self"],arguments,{},"args","kw"),self=$.self,args=$.args,kw=$.kw;if(args.length>0){var o=args[0];if($B.$isinstance(o,dict)){if(o.$jsobj){o=jsobj2dict(o.$jsobj)}$copy_dict(self,o)}else if(_b_.hasattr(o,"keys")){var _keys=_b_.list.$factory($B.$call($B.$getattr(o,"keys"))());for(let i=0,len=_keys.length;i-1){continue}if(typeof dict[attr]=="function"){mappingproxy[attr]=function(key){return function(){return dict[key].apply(null,arguments)}}(attr)}else{mappingproxy[attr]=dict[attr]}}$B.set_func_names(mappingproxy,"builtins");function jsobj2dict(x,exclude){exclude=exclude||function(){return false};var d=$B.empty_dict();for(var attr in x){if(attr.charAt(0)!="$"&&!exclude(attr)){if(x[attr]===null){dict.$setitem(d,attr,_b_.None)}else if(x[attr]===undefined){continue}else if(x[attr].$jsobj===x){dict.$setitem(d,attr,d)}else{dict.$setitem(d,attr,$B.jsobj2pyobj(x[attr]))}}}return d}$B.obj_dict=function(obj,exclude){var klass=obj.__class__||$B.get_class(obj);if(!(obj instanceof $B.str_dict)&&klass!==undefined&&klass.$native){throw $B.attr_error("__dict__",obj)}var res={__class__:dict,$jsobj:obj,$exclude:exclude||function(){return false}};return res}})(__BRYTHON__);(function($B){var _b_=$B.builtins,isinstance=$B.$isinstance;function check_not_tuple(self,attr){if(self.__class__===tuple){throw $B.attr_error(attr,self)}}var list={__class__:_b_.type,__qualname__:"list",__mro__:[_b_.object],$is_class:true,$native:true,$match_sequence_pattern:true,__dir__:_b_.object.__dir__};list.__add__=function(self,other){if($B.get_class(self)!==$B.get_class(other)){var this_name=$B.class_name(self);var radd=$B.$getattr(other,"__radd__",null);if(radd===null){throw _b_.TypeError.$factory("can only concatenate "+this_name+' (not "'+$B.class_name(other)+'") to '+this_name)}return _b_.NotImplemented}var res=self.slice();for(const item of other){res.push(item)}if(isinstance(self,tuple)){return tuple.$factory(res)}else{return $B.$list(res)}};list.__bool__=function(self){return list.__len__(self)>0};list.__class_getitem__=$B.$class_getitem;list.__contains__=function(){var $=$B.args("__contains__",2,{self:null,item:null},["self","item"],arguments,{},null,null),self=$.self,item=$.item;for(var _item of self){if($B.is_or_equals(_item,item)){return true}}return false};list.__delitem__=function(self,arg){if(isinstance(arg,_b_.int)){let pos=arg;if(arg<0){pos=self.length+pos}if(pos>=0&&pos0?0:self.length}var stop=arg.stop;if(stop===_b_.None){stop=step>0?self.length:0}if(start<0){start=self.length+start}if(stop<0){stop=self.length+stop}let res=[],pos=0;if(step>0){if(stop>start){for(let i=start;istop;i+=step){if(self[i]!==undefined){res[pos++]=i}}res.reverse()}}let i=res.length;while(i--){self.splice(res[i],1)}return _b_.None}if(_b_.hasattr(arg,"__int__")||_b_.hasattr(arg,"__index__")){list.__delitem__(self,_b_.int.$factory(arg));return _b_.None}throw _b_.TypeError.$factory($B.class_name(self)+" indices must be integer, not "+$B.class_name(arg))};list.__eq__=function(self,other){if(other[$B.PYOBJ]){other=other[$B.PYOBJ]}var klass=isinstance(self,list)?list:tuple;if(isinstance(other,klass)){if(other.length==self.length){var i=self.length;while(i--){if(!$B.is_or_equals(self[i],other[i])){return false}}return true}return false}return _b_.NotImplemented};list.__getitem__=function(self,key){$B.check_nb_args_no_kw("__getitem__",2,arguments);return list.$getitem(self,key)};list.$getitem=function(self,key){var klass=self.__class__||$B.get_class(self);var factory=function(list_res){list_res.__class__=klass;return list_res};var int_key;try{int_key=$B.PyNumber_Index(key)}catch(err){}if(int_key!==undefined){let items=self.valueOf(),pos=int_key;if(int_key<0){pos=items.length+pos}if(pos>=0&&pos0){if(stop<=start){return factory(res)}for(let i=start;istart){return factory(res)}for(let i=start;i>stop;i+=step){res[pos++]=items[i]}return factory(res)}}throw _b_.TypeError.$factory($B.class_name(self)+" indices must be integer, not "+$B.class_name(key))};list.__ge__=function(self,other){if(!isinstance(other,list)){return _b_.NotImplemented}var res=list.__le__(other,self);if(res===_b_.NotImplemented){return res}return res};list.__gt__=function(self,other){if(!isinstance(other,list)){return _b_.NotImplemented}var res=list.__lt__(other,self);if(res===_b_.NotImplemented){return res}return res};list.__hash__=_b_.None;list.__iadd__=function(){var $=$B.args("__iadd__",2,{self:null,x:null},["self","x"],arguments,{},null,null);var x=list.$factory($.x);for(var i=0;i1){throw _b_.TypeError.$factory("expected at most 1 argument, got "+args.length)}if(_b_.dict.__len__(kw)>0){throw _b_.TypeError.$factory("list() takes no keyword arguments")}while(self.length>0){self.pop()}var arg=args[0];if(arg===undefined){return _b_.None}var pos=0;for(var item of $B.make_js_iterator(arg)){self[pos++]=item}return _b_.None};var list_iterator=$B.make_iterator_class("list_iterator");list_iterator.__reduce__=list_iterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([list.$factory(self)]),0])};list.__iter__=function(self){return list_iterator.$factory(self)};list.__le__=function(self,other){if(!isinstance(other,[list,_b_.tuple])){return _b_.NotImplemented}var i=0;while(i$B.max_array_size/other){throw _b_.OverflowError.$factory(`cannot fit `+`'${$B.class_name(other)}' into an index-sized integer`)}var res=[],$temp=self.slice(),len=$temp.length;for(var i=0;i=0&&pos0){if(args.length==1){for(var item of $B.make_js_iterator(args[0])){self.push(item)}}else{throw _b_.TypeError.$factory("tuple expected at most 1 "+`argument, got ${args.length}`)}}if(cls===tuple&&_b_.dict.__len__(kw)>0){throw _b_.TypeError.$factory("tuple() takes no keyword arguments")}return self};tuple.__repr__=function(self){$B.builtins_repr_check(tuple,arguments);return list_repr(self)};$B.set_func_names(tuple,"builtins");_b_.list=list;_b_.tuple=tuple;_b_.object.__bases__=tuple.$factory();_b_.type.__bases__=$B.fast_tuple([_b_.object])})(__BRYTHON__);(function($B){var _b_=$B.builtins;function to_simple(value){switch(typeof value){case"string":case"number":return value;case"boolean":return value?"true":"false";case"object":if(value===_b_.None){return"null"}else if(value instanceof Number){return value.valueOf()}else if(value instanceof String){return value.valueOf()}break;default:throw _b_.TypeError.$factory("keys must be str, int, "+"float, bool or None, not "+$B.class_name(value))}}$B.pyobj2structuredclone=function(obj,strict){strict=strict===undefined?true:strict;if(typeof obj=="boolean"||typeof obj=="number"||typeof obj=="string"||obj instanceof String){return obj}else if(obj.__class__===_b_.float){return obj.value}else if(obj===_b_.None){return null}else if(Array.isArray(obj)||obj.__class__===_b_.list||obj.__class__===_b_.tuple||obj.__class__===js_array){let res=new Array(obj.length);for(var i=0,len=obj.length;i`}var js_repr=Object.prototype.toString.call(_self);return``};$B.JSObj.bind=function(_self,evt,func){var js_func=function(ev){try{return func(jsobj2pyobj(ev))}catch(err){if(err.__class__!==undefined){$B.handle_error(err)}else{try{$B.$getattr($B.get_stderr(),"write")(err)}catch(err1){console.log(err)}}}};Object.defineProperty(_self,"$brython_events",{value:_self.$brython_events||{},writable:true});if(_self.$brython_events){_self.$brython_events[evt]=_self.$brython_events[evt]||[];_self.$brython_events[evt].push([func,js_func])}_self.addEventListener(evt,js_func);return _b_.None};$B.JSObj.bindings=function(_self){var res=$B.empty_dict();if(_self.$brython_events){for(var key in _self.$brython_events){_b_.dict.$setitem(res,key,$B.fast_tuple(_self.$brython_events[key].map((x=>x[0]))))}}return res};$B.JSObj.unbind=function(_self,evt,func){if(!_self.$brython_events){return _b_.None}if(!_self.$brython_events[evt]){return _b_.None}var events=_self.$brython_events[evt];if(func===undefined){for(var item of events){_self.removeEventListener(evt,item[1])}delete _self.$brython_events[evt]}else{for(var i=0,len=events.length;i-1){return function(){var args=new Array(arguments.length);args[0]=arguments[0];for(var i=1,len=arguments.length;i-1){return function(){var pylist=$B.$list(arguments[0].map(jsobj2pyobj));return jsobj2pyobj(_b_.list[attr].call(null,pylist,...Array.from(arguments).slice(1)))}}else if(js_array.hasOwnProperty(attr)){return js_array[attr]}else if(["__repr__","__str__"].includes(attr)){return function(js_array){var t=jsobj2pyobj(js_array);return _b_.list[attr]($B.$list(t))}}return function(js_array){var t=jsobj2pyobj(js_array);return _b_.list[attr](t)}};$B.set_func_names(js_list_meta,"builtins");$B.SizedJSObj=$B.make_class("SizedJavascriptObject");$B.SizedJSObj.__bases__=[$B.JSObj];$B.SizedJSObj.__mro__=[$B.JSObj,_b_.object];$B.SizedJSObj.__len__=function(_self){return _self.length};$B.set_func_names($B.SizedJSObj,"builtins");$B.IterableJSObj=$B.make_class("IterableJavascriptObject");$B.IterableJSObj.__bases__=[$B.JSObj];$B.IterableJSObj.__mro__=[$B.JSObj,_b_.object];$B.IterableJSObj.__contains__=function(self,key){if(self.contains!==undefined&&typeof self.contains=="function"){return self.contains(key)}else{for(var item of $B.IterableJSObj.__iter__(self).it){if($B.is_or_equals(item,key)){return true}}return false}};$B.IterableJSObj.__iter__=function(_self){return{__class__:$B.IterableJSObj,it:_self[Symbol.iterator]()}};$B.IterableJSObj.__len__=function(_self){return _self.length};$B.IterableJSObj.__next__=function(_self){var value=_self.it.next();if(!value.done){return jsobj2pyobj(value.value)}throw _b_.StopIteration.$factory("")};$B.set_func_names($B.IterableJSObj,"builtins");var js_array=$B.js_array=$B.make_class("Array");js_array.__class__=js_list_meta;js_array.__mro__=[$B.JSObj,_b_.object];js_array.__add__=function(_self,other){var res=_self.slice();if($B.$isinstance(other,js_array)){return _self.slice().concat(other)}for(var item of $B.make_js_iterator(other)){res.push(pyobj2jsobj(item))}return res};js_array.__getattribute__=function(_self,attr){if(_b_.list[attr]===undefined){var proto=Object.getPrototypeOf(_self),res=proto[attr];if(res!==undefined){return jsobj2pyobj(res,_self)}if(_self.hasOwnProperty(attr)){return jsobj2pyobj(_self[attr])}if(js_array.hasOwnProperty(attr)){return js_array[attr]}throw $B.attr_error(attr,_self)}if(js_array.hasOwnProperty(attr)){return function(){return js_array[attr](_self,...arguments)}}return function(){var args=pyobj2jsobj(Array.from(arguments));return _b_.list[attr].call(null,_self,...args)}};js_array.__getitem__=function(_self,i){i=$B.PyNumber_Index(i);return jsobj2pyobj(_self[i])};js_array.__iadd__=function(_self,other){if($B.$isinstance(other,js_array)){for(var item of other){_self.push(item)}}else{for(var item of $B.make_js_iterator(other)){_self.push($B.pyobj2jsobj(item))}}return _self};js_array.__iter__=function(_self){return js_array_iterator.$factory(_self)};js_array.__mul__=function(_self,nb){var res=_self.slice();for(var i=1;i-1){return $B.SizedJSObj}return $B.JSObj};$B.JSMeta=$B.make_class("JSMeta");$B.JSMeta.__call__=function(cls){var extra_args=new Array(arguments.length-1),klass=arguments[0];for(var i=1,len=arguments.length;i`};$B.generator.close=function(self){var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}try{$B.generator.throw(self,_b_.GeneratorExit.$factory())}catch(err){if(!$B.is_exc(err,[_b_.GeneratorExit,_b_.StopIteration])){$B.frame_obj=save_frame_obj;throw _b_.RuntimeError.$factory("generator ignored GeneratorExit")}}$B.frame_obj=save_frame_obj};$B.generator.send=function(self,value){var gen=self.js_gen;gen.$has_run=true;if(gen.$finished){throw _b_.StopIteration.$factory(value)}if(gen.gi_running===true){throw _b_.ValueError.$factory("generator already executing")}gen.gi_running=true;var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}try{var res=gen.next(value)}catch(err){gen.$finished=true;$B.frame_obj=save_frame_obj;throw err}if($B.frame_obj!==null&&$B.frame_obj.frame===self.$frame){$B.leave_frame()}$B.frame_obj=save_frame_obj;if(res.value&&res.value.__class__===$GeneratorReturn){gen.$finished=true;throw _b_.StopIteration.$factory(res.value.value)}gen.gi_running=false;if(res.done){throw _b_.StopIteration.$factory(res.value)}return res.value};$B.generator.throw=function(){var $=$B.args("throw",4,{self:null,type:null,value:null,traceback:null},["self","type","value","traceback"],arguments,{value:_b_.None,traceback:_b_.None},null,null),self=$.self,type=$.type,value=$.value,traceback=$.traceback;var gen=self.js_gen,exc=type;if(exc.$is_class){if(!_b_.issubclass(type,_b_.BaseException)){throw _b_.TypeError.$factory("exception value must be an "+"instance of BaseException")}else if(value===undefined||value===_b_.None){exc=$B.$call(exc)()}else if($B.$isinstance(value,type)){exc=value}}else{if(value===_b_.None){value=exc}else{exc=$B.$call(exc)(value)}}if(traceback!==_b_.None){exc.$traceback=traceback}var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}var res=gen.throw(exc);$B.frame_obj=save_frame_obj;if(res.done){throw _b_.StopIteration.$factory(res.value)}return res.value};$B.set_func_names($B.generator,"builtins");$B.async_generator=$B.make_class("async_generator",(function(func){var f=function(){var gen=func.apply(null,arguments);var res=Object.create(null);res.__class__=$B.async_generator;res.js_gen=gen;return res};return f}));$B.async_generator.__aiter__=function(self){return self};$B.async_generator.__anext__=function(self){return $B.async_generator.asend(self,_b_.None)};$B.async_generator.aclose=function(self){self.js_gen.$finished=true;return _b_.None};$B.async_generator.asend=async function(self,value){var gen=self.js_gen;if(gen.$finished){throw _b_.StopAsyncIteration.$factory(value)}if(gen.ag_running===true){throw _b_.ValueError.$factory("generator already executing")}gen.ag_running=true;var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}try{var res=await gen.next(value)}catch(err){gen.$finished=true;$B.frame_obj=save_frame_obj;throw err}if($B.frame_obj!==null&&$B.frame_obj.frame===self.$frame){$B.leave_frame()}$B.frame_obj=save_frame_obj;if(res.done){throw _b_.StopAsyncIteration.$factory(value)}if(res.value.__class__===$GeneratorReturn){gen.$finished=true;throw _b_.StopAsyncIteration.$factory(res.value.value)}gen.ag_running=false;return res.value};$B.async_generator.athrow=async function(self,type,value,traceback){var gen=self.js_gen,exc=type;if(exc.$is_class){if(!_b_.issubclass(type,_b_.BaseException)){throw _b_.TypeError.$factory("exception value must be an "+"instance of BaseException")}else if(value===undefined){value=$B.$call(exc)()}}else{if(value===undefined){value=exc}else{exc=$B.$call(exc)(value)}}if(traceback!==undefined){exc.$traceback=traceback}var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}await gen.throw(value);$B.frame_obj=save_frame_obj};$B.set_func_names($B.async_generator,"builtins")})(__BRYTHON__);(function($B){var _b_=$B.builtins,object=_b_.object,_window=globalThis;function convertDomValue(v){if(v===null||v===undefined){return _b_.None}return $B.jsobj2pyobj(v)}var py_immutable_to_js=$B.py_immutable_to_js=function(pyobj){if($B.$isinstance(pyobj,_b_.float)){return pyobj.value}else if($B.$isinstance(pyobj,$B.long_int)){return $B.long_int.$to_js_number(pyobj)}return pyobj};function js_immutable_to_py(jsobj){if(typeof jsobj=="number"){if(Number.isSafeInteger(jsobj)){return jsobj}else if(Number.isInteger(jsobj)){return $B.fast_long_int(BigInt(jsobj+""))}else{return $B.fast_float(jsobj)}}return jsobj}function $getPosition(e){var left=0,top=0,width=e.width||e.offsetWidth,height=e.height||e.offsetHeight;while(e.offsetParent){left+=e.offsetLeft;top+=e.offsetTop;e=e.offsetParent}left+=e.offsetLeft||0;top+=e.offsetTop||0;if(e.parentElement){var parent_pos=$getPosition(e.parentElement);left+=parent_pos.left;top+=parent_pos.top}return{left:left,top:top,width:width,height:height}}var $mouseCoords=$B.$mouseCoords=function(ev){if(ev.type.startsWith("touch")){let res={};res.x=_b_.int.$factory(ev.touches[0].screenX);res.y=_b_.int.$factory(ev.touches[0].screenY);res.__getattr__=function(attr){return this[attr]};res.__class__="MouseCoords";return res}var posx=0,posy=0;if(!ev){ev=_window.event}if(ev.pageX||ev.pageY){posx=ev.pageX;posy=ev.pageY}else if(ev.clientX||ev.clientY){posx=ev.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;posy=ev.clientY+document.body.scrollTop+document.documentElement.scrollTop}let res={};res.x=_b_.int.$factory(posx);res.y=_b_.int.$factory(posy);res.__getattr__=function(attr){return this[attr]};res.__class__="MouseCoords";return res};$B.$isNode=function(o){return typeof Node==="object"?o instanceof Node:o&&typeof o==="object"&&typeof o.nodeType==="number"&&typeof o.nodeName==="string"};$B.$isNodeList=function(nodes){try{var result=Object.prototype.toString.call(nodes);var re=new RegExp("^\\[object (HTMLCollection|NodeList)\\]$");return typeof nodes==="object"&&re.exec(result)!==null&&nodes.length!==undefined&&(nodes.length==0||typeof nodes[0]==="object"&&nodes[0].nodeType>0)}catch(err){return false}};var $DOMEventAttrs_W3C=["NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","type","target","currentTarget","eventPhase","bubbles","cancelable","timeStamp","stopPropagation","preventDefault","initEvent"];var $DOMEventAttrs_IE=["altKey","altLeft","button","cancelBubble","clientX","clientY","contentOverflow","ctrlKey","ctrlLeft","data","dataFld","dataTransfer","fromElement","keyCode","nextPage","offsetX","offsetY","origin","propertyName","reason","recordset","repeat","screenX","screenY","shiftKey","shiftLeft","source","srcElement","srcFilter","srcUrn","toElement","type","url","wheelDelta","x","y"];$B.$isEvent=function(obj){var flag=true;for(let attr of $DOMEventAttrs_W3C){if(obj[attr]===undefined){flag=false;break}}if(flag){return true}for(let attr of $DOMEventAttrs_IE){if(obj[attr]===undefined){return false}}return true};var $NodeTypes={1:"ELEMENT",2:"ATTRIBUTE",3:"TEXT",4:"CDATA_SECTION",5:"ENTITY_REFERENCE",6:"ENTITY",7:"PROCESSING_INSTRUCTION",8:"COMMENT",9:"DOCUMENT",10:"DOCUMENT_TYPE",11:"DOCUMENT_FRAGMENT",12:"NOTATION"};var Attributes=$B.make_class("Attributes",(function(elt){return{__class__:Attributes,elt:elt}}));Attributes.__contains__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null);if($.self.elt instanceof SVGElement){return $.self.elt.hasAttributeNS(null,$.key)}else if(typeof $.self.elt.hasAttribute=="function"){return $.self.elt.hasAttribute($.key)}return false};Attributes.__delitem__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null);if(!Attributes.__contains__($.self,$.key)){throw _b_.KeyError.$factory($.key)}if($.self.elt instanceof SVGElement){$.self.elt.removeAttributeNS(null,$.key);return _b_.None}else if(typeof $.self.elt.hasAttribute=="function"){$.self.elt.removeAttribute($.key);return _b_.None}};Attributes.__getitem__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null);if($.self.elt instanceof SVGElement&&$.self.elt.hasAttributeNS(null,$.key)){return $.self.elt.getAttributeNS(null,$.key)}else if(typeof $.self.elt.hasAttribute=="function"&&$.self.elt.hasAttribute($.key)){return $.self.elt.getAttribute($.key)}throw _b_.KeyError.$factory($.key)};Attributes.__iter__=function(self){self.$counter=0;var attrs=self.elt.attributes,items=[];for(var i=0;i");var DOMEvent=$B.DOMEvent=$B.make_class("DOMEvent",(function(evt_name){return DOMEvent.__new__(DOMEvent,evt_name)}));DOMEvent.__new__=function(cls,evt_name){var ev=new Event(evt_name);ev.__class__=DOMEvent;if(ev.preventDefault===undefined){ev.preventDefault=function(){ev.returnValue=false}}if(ev.stopPropagation===undefined){ev.stopPropagation=function(){ev.cancelBubble=true}}return ev};DOMEvent.__setattr__=function(self,attr,value){self[attr]=value};function dom2svg(svg_elt,coords){var pt=svg_elt.createSVGPoint();pt.x=coords.x;pt.y=coords.y;return pt.matrixTransform(svg_elt.getScreenCTM().inverse())}DOMEvent.__getattribute__=function(ev,attr){switch(attr){case"__repr__":case"__str__":return function(){return""};case"x":return $mouseCoords(ev).x;case"y":return $mouseCoords(ev).y;case"data":if(ev.dataTransfer!==null&&ev.dataTransfer!==undefined){return Clipboard.$factory(ev.dataTransfer)}else if(typeof Worker!=="undefined"&&ev.target instanceof Worker){return $B.structuredclone2pyobj(ev.data)}else if(typeof DedicatedWorkerGlobalScope!=="undefined"&&ev.target instanceof DedicatedWorkerGlobalScope){return $B.structuredclone2pyobj(ev.data)}return convertDomValue(ev.data);case"target":if(ev.target!==undefined){return DOMNode.$factory(ev.target)}break;case"char":return String.fromCharCode(ev.which);case"svgX":if(ev.target instanceof SVGSVGElement){return Math.floor(dom2svg(ev.target,$mouseCoords(ev)).x)}throw _b_.AttributeError.$factory("event target is not an SVG "+"element");case"svgY":if(ev.target instanceof SVGSVGElement){return Math.floor(dom2svg(ev.target,$mouseCoords(self)).y)}throw _b_.AttributeError.$factory("event target is not an SVG "+"element")}var res=ev[attr];if(res!==undefined){if(typeof res=="function"){var func=function(){var args=[];for(var i=0;i");var dom={File:function(){},FileReader:function(){}};dom.File.__class__=_b_.type;dom.File.__str__=function(){return""};dom.FileReader.__class__=_b_.type;dom.FileReader.__str__=function(){return""};var DOMNode=$B.make_class("DOMNode",(function(elt){return elt}));DOMNode.__add__=function(self,other){var res=TagSum.$factory();res.children=[self];var pos=1;if($B.$isinstance(other,TagSum)){res.children=res.children.concat(other.children)}else if($B.$isinstance(other,[_b_.str,_b_.int,_b_.float,_b_.list,_b_.dict,_b_.set,_b_.tuple])){res.children[pos++]=DOMNode.$factory(document.createTextNode(_b_.str.$factory(other)))}else if($B.$isinstance(other,DOMNode)){res.children[pos++]=other}else{try{res.children=res.children.concat(_b_.list.$factory(other))}catch(err){throw _b_.TypeError.$factory("can't add '"+$B.class_name(other)+"' object to DOMNode instance")}}return res};DOMNode.__bool__=function(){return true};DOMNode.__contains__=function(self,key){if(self.nodeType==9&&typeof key=="string"){return document.getElementById(key)!==null}if(self.length!==undefined&&typeof self.item=="function"){for(var i=0,len=self.length;i-1){return function(selector){if(selector===undefined){self.select();return _b_.None}return DOMNode.select(self,selector)}}if(attr=="query"&&self.nodeType==9){let res={__class__:Query,_keys:$B.$list([]),_values:{}};let qs=location.search.substr(1).split("&");if(location.search!=""){for(let i=0;i-1){res._values[key].push(value)}else{res._keys.push(key);res._values[key]=[value]}}}return res}var klass=$B.get_class(self);var property=self[attr];if(property!==undefined&&self.__class__&&klass.__module__!="browser.html"&&klass.__module__!="browser.svg"&&!klass.$webcomponent){var from_class=$B.$getattr(klass,attr,null);if(from_class!==null){property=from_class;if(typeof from_class==="function"){return property.bind(self,self)}}else{var bases=self.__class__.__bases__;var show_message=true;for(var base of bases){if(base.__module__=="browser.html"){show_message=false;break}}if(show_message){from_class=$B.$getattr(self.__class__,attr,_b_.None);if(from_class!==_b_.None){var frame=$B.frame_obj.frame,line=frame.$lineno;console.info("Warning: line "+line+", "+self.tagName+" element has instance attribute '"+attr+"' set."+" Attribute of class "+$B.class_name(self)+" is ignored.")}}}}if(property===undefined){if(self.tagName){var ce=customElements.get(self.tagName.toLowerCase());if(ce!==undefined&&ce.$cls!==undefined){var save_class=self.__class__;self.__class__=ce.$cls;try{let res=_b_.object.__getattribute__(self,attr);self.__class__=save_class;return res}catch(err){self.__class__=save_class;if(!$B.is_exc(err,[_b_.AttributeError])){throw err}}}}else{return object.__getattribute__(self,attr)}}var res=property;if(res!==undefined){if(res===null){return res}if(typeof res==="function"){if(self.__class__&&self.__class__.$webcomponent){var method=$B.$getattr(self.__class__,attr,null);if(method!==null){return res.bind(self)}}if(res.$is_func){return res}var func=function(f,elt){return function(){var args=[];for(var i=0;i0){var res=TagSum.$factory();var pos=res.children.length;for(var i=0;i"}var res=""};DOMNode.__setattr__=function(self,attr,value){switch(attr){case"left":case"top":case"width":case"height":if($B.$isinstance(value,[_b_.int,_b_.float])&&self.nodeType==1){self.style[attr]=value+"px";return _b_.None}else{throw _b_.ValueError.$factory(attr+" value should be"+" an integer or float, not "+$B.class_name(value))}}if(DOMNode["set_"+attr]!==undefined){return DOMNode["set_"+attr](self,value)}function warn(msg){console.log(msg);var frame=$B.frame_obj.frame;if(!frame){return}if($B.get_option("debug")>0){var file=frame.__file__,lineno=frame.$lineno;console.log("module",frame[2],"line",lineno);if($B.file_cache.hasOwnProperty(file)){var src=$B.file_cache[file];console.log(src.split("\n")[lineno-1])}}else{console.log("module",frame[2])}}var proto=Object.getPrototypeOf(self),nb=0;while(!!proto&&proto!==Object.prototype&&nb++<10){var descriptors=Object.getOwnPropertyDescriptors(proto);if(!!descriptors&&typeof descriptors.hasOwnProperty=="function"){if(descriptors.hasOwnProperty(attr)){if(!descriptors[attr].writable&&descriptors[attr].set===undefined){warn("Warning: property '"+attr+"' is not writable. Use element.attrs['"+attr+"'] instead.")}break}}else{break}proto=Object.getPrototypeOf(proto)}if(self.style&&self.style[attr]!==undefined&&attr!="src"){warn("Warning: '"+attr+"' is a property of element.style")}self[attr]=py_immutable_to_js(value);return _b_.None};DOMNode.__setitem__=function(self,key,value){if(typeof key=="number"){self.childNodes[key]=value}else if(typeof key=="string"){if(self.attributes){if(self instanceof SVGElement){self.setAttributeNS(null,key,value)}else if(typeof self.setAttribute=="function"){self.setAttribute(key,value)}}}};DOMNode.abs_left={__get__:function(self){return $getPosition(self).left},__set__:function(){throw _b_.AttributeError.$factory("'DOMNode' objectattribute "+"'abs_left' is read-only")}};DOMNode.abs_top={__get__:function(self){return $getPosition(self).top},__set__:function(){throw _b_.AttributeError.$factory("'DOMNode' objectattribute "+"'abs_top' is read-only")}};DOMNode.attach=DOMNode.__le__;DOMNode.bind=function(){var $=$B.args("bind",4,{self:null,event:null,func:null,options:null},["self","event","func","options"],arguments,{func:_b_.None,options:_b_.None},null,null),self=$.self,event=$.event,func=$.func,options=$.options;if(func===_b_.None){return function(f){return DOMNode.bind(self,event,f)}}var callback=function(f){return function(ev){try{return $B.$call(f)($DOMEvent(ev))}catch(err){if(err.__class__!==undefined){$B.handle_error(err)}else{try{$B.$getattr($B.get_stderr(),"write")(err)}catch(err1){console.log(err)}}}}}(func);callback.$infos=func.$infos;callback.$attrs=func.$attrs||{};callback.$func=func;if(typeof options=="boolean"){self.addEventListener(event,callback,options)}else if(options.__class__===_b_.dict){self.addEventListener(event,callback,_b_.dict.$to_obj(options))}else if(options===_b_.None){self.addEventListener(event,callback,false)}self.$events=self.$events||{};self.$events[event]=self.$events[event]||[];self.$events[event].push([func,callback]);return self};DOMNode.children=function(self){var res=[];if(self.nodeType==9){self=self.body}for(var child of self.children){res.push(DOMNode.$factory(child))}return $B.$list(res)};DOMNode.child_nodes=function(self){var res=[];if(self.nodeType==9){self=self.body}for(var child of self.childNodes){res.push(DOMNode.$factory(child))}return $B.$list(res)};DOMNode.clear=function(){var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null),self=$.self;if(self.nodeType==9){self=self.body}while(self.firstChild){self.removeChild(self.firstChild)}};DOMNode.Class=function(self){if(self.className!==undefined){return self.className}return _b_.None};DOMNode.class_name=function(self){return DOMNode.Class(self)};DOMNode.clone=function(self){var res=DOMNode.$factory(self.cloneNode(true));var events=self.$events||{};for(var event in events){var evt_list=events[event];evt_list.forEach((function(evt){var func=evt[0];DOMNode.bind(res,event,func)}))}return res};DOMNode.closest=function(){var $=$B.args("closest",2,{self:null,selector:null},["self","selector"],arguments,{},null,null),self=$.self,selector=$.selector;if(self.closest===undefined){throw _b_.AttributeError.$factory(_b_.str.$factory(self)+" has no attribute 'closest'")}var res=self.closest(selector);if(res===null){throw _b_.KeyError.$factory("no parent with selector "+selector)}return DOMNode.$factory(res)};DOMNode.bindings=function(self){var res=$B.empty_dict();for(var key in self.$events){_b_.dict.$setitem(res,key,self.$events[key].map((x=>x[1])))}return res};DOMNode.events=function(self,event){self.$events=self.$events||{};var evt_list=self.$events[event]=self.$events[event]||[],callbacks=[];evt_list.forEach((function(evt){callbacks.push(evt[1])}));return $B.$list(callbacks)};function make_list(node_list){var res=[];for(var i=0;i-1};Query.__getitem__=function(self,key){var result=self._values[key];if(result===undefined){throw _b_.KeyError.$factory(key)}else if(result.length==1){return result[0]}return result};var Query_iterator=$B.make_iterator_class("query string iterator");Query.__iter__=function(self){return Query_iterator.$factory(self._keys)};Query.__setitem__=function(self,key,value){self._values[key]=[value];return _b_.None};Query.__str__=Query.__repr__=function(self){var elts=[];for(var key in self._values){for(const val of self._values[key]){elts.push(encodeURIComponent(key)+"="+encodeURIComponent(val))}}if(elts.length==0){return""}else{return"?"+elts.join("&")}};Query.getfirst=function(self,key,_default){var result=self._values[key];if(result===undefined){if(_default===undefined){return _b_.None}return _default}return result[0]};Query.getlist=function(self,key){return $B.$list(self._values[key]??[])};Query.getvalue=function(self,key,_default){try{return Query.__getitem__(self,key)}catch(err){if(_default===undefined){return _b_.None}return _default}};Query.keys=function(self){return self._keys};$B.set_func_names(Query,"");var TagSum=$B.make_class("TagSum",(function(){return{__class__:TagSum,children:[],toString:function(){return"(TagSum)"}}}));TagSum.appendChild=function(self,child){self.children.push(child)};TagSum.__add__=function(self,other){if($B.get_class(other)===TagSum){self.children=self.children.concat(other.children)}else if($B.$isinstance(other,[_b_.str,_b_.int,_b_.float,_b_.dict,_b_.set,_b_.list])){self.children=self.children.concat(DOMNode.$factory(document.createTextNode(other)))}else{self.children.push(other)}return self};TagSum.__radd__=function(self,other){var res=TagSum.$factory();res.children=self.children.slice();res.children.splice(0,0,DOMNode.$factory(document.createTextNode(other)));return res};TagSum.__repr__=function(self){var res=" ";for(var i=0;i");$B.TagSum=TagSum;$B.DOMNode=DOMNode})(__BRYTHON__);(function($B){$B.pattern_match=function(subject,pattern){var _b_=$B.builtins,frame=$B.frame_obj.frame,locals=frame[1];function bind(pattern,subject){if(pattern.alias){locals[pattern.alias]=subject}}if(pattern.sequence){if($B.$isinstance(subject,[_b_.str,_b_.bytes,_b_.bytearray])){return false}let Sequence;if($B.imported["collections.abc"]){Sequence=$B.imported["collections.abc"].Sequence}let deque;if($B.imported["collections"]){deque=$B.imported["collections"].deque}let supported=false;let klass=subject.__class__||$B.get_class(subject);for(let base of[klass].concat(klass.__bases__||[])){if(base.$match_sequence_pattern){supported=true;break}else if(base===Sequence||base==deque){supported=true;break}}if(!supported&&Sequence){supported=_b_.issubclass(klass,Sequence)}if(!supported){return false}if(pattern.sequence.length==1&&pattern.sequence[0].capture_starred=="_"){return true}let subject_length=_b_.len(subject),nb_fixed_length=0;for(let item of pattern.sequence){if(!item.capture_starred){nb_fixed_length++}}if(subject_length0){if([_b_.bool,_b_.bytearray,_b_.bytes,_b_.dict,_b_.float,_b_.frozenset,_b_.int,_b_.list,_b_.set,_b_.str,_b_.tuple].indexOf(klass)>-1){if(pattern.args.length>1){throw _b_.TypeError.$factory("for builtin type "+$B.class_name(subject)+", a single positional "+"subpattern is accepted")}return $B.pattern_match(subject,pattern.args[0])}else{let match_args=$B.$getattr(klass,"__match_args__",$B.fast_tuple([]));if(!$B.$isinstance(match_args,_b_.tuple)){throw _b_.TypeError.$factory("__match_args__() did not return a tuple")}if(pattern.args.length>match_args.length){throw _b_.TypeError.$factory("__match_args__() returns "+match_args.length+" names but "+pattern.args.length+" positional "+"arguments were passed")}for(let i=0,len=pattern.args.length;i"}else{return""}};$B.set_func_names(coroutine,"builtins");$B.make_async=func=>{if(func.$is_genfunc){return func}var f=function(){var args=arguments;var res={__class__:coroutine,$args:args,$func:func};if($B.frame_obj!==null){var frame=$B.frame_obj.frame;frame.$coroutine=res;res.$lineno=frame.$lineno}return res};f.$infos=func.$infos;f.$is_func=true;f.$is_async=true;f.$args_parser=func.$args_parser;return f};$B.promise=function(obj){if(obj.__class__===coroutine){obj.$frame_obj=$B.frame_obj;return coroutine.send(obj)}if(typeof obj=="function"){return obj()}if(obj instanceof Promise||typeof obj.then=="function"){obj.frame_obj=$B.frame_obj;return obj.then((function(x){$B.frame_obj=obj.frame_obj;return $B.jsobj2pyobj(x)})).catch((function(err){$B.frame_obj=obj.frame_obj;throw $B.exception(err)}))}var awaitable=$B.$getattr(obj,"__await__",null);if(awaitable!==null){awaitable=$B.$call(awaitable)();if($B.$getattr(awaitable,"__next__",null)===null){throw _b_.TypeError.$factory("__await__() returned non-iterator"+` of type '${$B.class_name(awaitable)}'`)}return awaitable}throw _b_.TypeError.$factory(`object ${$B.class_name(obj)} `+`can't be used in 'await' expression`)}})(__BRYTHON__);(function($B){$B.builtin_class_flags={builtins:{1073763586:["NameError","RecursionError","BufferError","ImportError","RuntimeError","FileExistsError","MemoryError","BaseExceptionGroup","TimeoutError","SystemError","ZeroDivisionError","FloatingPointError","BlockingIOError","EnvironmentError","InterruptedError","BrokenPipeError","ConnectionResetError","ArithmeticError","AssertionError","IndentationError","LookupError","RuntimeWarning","AttributeError","SyntaxError","UnicodeTranslateError","ProcessLookupError","StopAsyncIteration","FileNotFoundError","FutureWarning","ReferenceError","TabError","ChildProcessError","OSError","IOError","PermissionError","ImportWarning","ModuleNotFoundError","EOFError","UnicodeError","SystemExit","UnicodeWarning","SyntaxWarning","ConnectionAbortedError","BytesWarning","ConnectionRefusedError","EncodingWarning","GeneratorExit","IndexError","NotADirectoryError","PythonFinalizationError","DeprecationWarning","ResourceWarning","StopIteration","OverflowError","ValueError","UnicodeEncodeError","IsADirectoryError","_IncompleteInputError","TypeError","KeyboardInterrupt","UnboundLocalError","WindowsError","UserWarning","NotImplementedError","Warning","KeyError","Exception","BaseException","PendingDeprecationWarning","ConnectionError","UnicodeDecodeError"],1073763848:["ExceptionGroup"],20975874:["bool"],4199682:["bytearray","float"],138417410:["bytes"],21762:["staticmethod","classmethod","property","enumerate","map","super","filter","reversed","zip"],5378:["object","complex"],541087042:["dict"],4216066:["set","frozenset"],20976898:["int"],37770530:["list"],20770:["memoryview"],4386:["range"],20738:["slice"],272635138:["str"],71324962:["tuple"],2155896066:["type"]},types:{20866:["frame","getset_descriptor","member_descriptor","async_generator","method-wrapper","classmethod_descriptor","generator","coroutine"],22914:["builtin_function_or_method"],20738:["cell","traceback"],4354:["ellipsis","code","NotImplementedType","NoneType"],153858:["function"],20802:["mappingproxy"],153986:["method_descriptor"],22786:["method"],21762:["module"],151938:["wrapper_descriptor"]}}})(__BRYTHON__);(function($B){var _b_=$B.builtins;var update=$B.update_obj=function(mod,data){for(let attr in data){mod[attr]=data[attr]}};var modules={};var win=$B.jsobj2pyobj(globalThis);var browser={$package:true,$is_package:true,__initialized__:true,__package__:"browser",__file__:$B.brython_path.replace(new RegExp("/*$","g"),"")+"/Lib/browser/__init__.py",bind:function(){var $=$B.args("bind",3,{elt:null,evt:null,options:null},["elt","evt","options"],arguments,{options:_b_.None},null,null);var options=$.options;if(typeof options=="boolean"){}else if(options.__class__===_b_.dict){var _options={};for(var key of _b_.dict.$keys_string(options)){_options[key]=_b_.dict.$getitem_string(options,key)}options=_options}else{options==false}return function(callback){if($B.get_class($.elt)===$B.JSObj){function f(ev){try{return callback($B.jsobj2pyobj(ev))}catch(err){$B.handle_error(err)}}$.elt.addEventListener($.evt,f,options);return callback}else if($B.$isinstance($.elt,$B.DOMNode)){$B.DOMNode.bind($.elt,$.evt,callback,options);return callback}else if($B.$isinstance($.elt,_b_.str)){var items=document.querySelectorAll($.elt);for(var i=0;i1){console.log(err,err.__class__,err.args);console.log("first",first);console.log(arguments)}throw err}}}}for(var item of _b_.dict.$iter_items($ns.kw)){var arg=item.key,value=item.value;if(arg.toLowerCase().substr(0,2)=="on"){$B.DOMNode.__setattr__(self,arg,value)}else if(arg.toLowerCase()=="style"){$B.DOMNode.set_style(self,value)}else{if(value!==false){try{arg=$B.imported["browser.html"].attribute_mapper(arg);self.setAttribute(arg,$B.pyobj2jsobj(value))}catch(err){throw _b_.ValueError.$factory("can't set attribute "+arg)}}}}};dict.__mro__=[$B.DOMNode,$B.builtins.object];dict.__new__=function(cls){var res=document.createElement(tagName);if(cls!==html[tagName]){res.__class__=cls}return res};dict.__rmul__=function(self,num){return $B.DOMNode.__mul__(self,num)};$B.set_func_names(dict,"browser.html");return dict}function makeFactory(klass){return function(k){return function(){var res;if(k.__name__=="SVG"){res=$B.DOMNode.$factory(document.createElementNS("http://www.w3.org/2000/svg","svg"),true)}else{try{res=document.createElement(k.__name__)}catch(err){console.log("error "+err);console.log("creating element",k.__name__);throw err}}var init=$B.$getattr(k,"__init__",null);if(init!==null){init(res,...arguments)}return res}}(klass)}var tags=["A","ABBR","ACRONYM","ADDRESS","APPLET","AREA","B","BASE","BASEFONT","BDO","BIG","BLOCKQUOTE","BODY","BR","BUTTON","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","DD","DEL","DFN","DIR","DIV","DL","DT","EM","FIELDSET","FONT","FORM","FRAME","FRAMESET","H1","H2","H3","H4","H5","H6","HEAD","HR","HTML","I","IFRAME","IMG","INPUT","INS","ISINDEX","KBD","LABEL","LEGEND","LI","LINK","MAP","MENU","META","NOFRAMES","NOSCRIPT","OBJECT","OL","OPTGROUP","OPTION","P","PARAM","PRE","Q","S","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRIKE","STRONG","STYLE","SUB","SUP","SVG","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TITLE","TR","TT","U","UL","VAR","ARTICLE","ASIDE","AUDIO","BDI","CANVAS","COMMAND","DATA","DATALIST","EMBED","FIGCAPTION","FIGURE","FOOTER","HEADER","KEYGEN","MAIN","MARK","MATH","METER","NAV","OUTPUT","PROGRESS","RB","RP","RT","RTC","RUBY","SECTION","SOURCE","TEMPLATE","TIME","TRACK","VIDEO","WBR","DETAILS","DIALOG","MENUITEM","PICTURE","SUMMARY"];var html={};html.tags=$B.empty_dict();function maketag(tagName,ComponentClass){if(!(typeof tagName=="string")){throw _b_.TypeError.$factory("html.maketag expects a string as argument")}if(html[tagName]!==undefined){throw _b_.ValueError.$factory("cannot reset class for "+tagName)}var klass=makeTagDict(tagName);klass.$factory=makeFactory(klass,ComponentClass);html[tagName]=klass;_b_.dict.$setitem(html.tags,tagName,html[tagName]);return klass}for(var tagName of tags){maketag(tagName)}html.maketag=maketag;html.attribute_mapper=function(attr){return attr.replace(/_/g,"-")};return html}(__BRYTHON__)}modules["browser"]=browser;$B.UndefinedType=$B.make_class("UndefinedType",(function(){return $B.Undefined}));$B.UndefinedType.__mro__=[_b_.object];$B.UndefinedType.__bool__=function(){return false};$B.UndefinedType.__repr__=function(){return""};$B.UndefinedType.__str__=$B.UndefinedType.__repr__;$B.Undefined={__class__:$B.UndefinedType};$B.set_func_names($B.UndefinedType,"javascript");var super_class=$B.make_class("JavascriptSuper",(function(){var res=_b_.super.$factory();var js_constr=res.__thisclass__.__bases__[0];return function(){var obj=new js_constr.$js_func(...arguments);for(var attr in obj){res.__self_class__.__dict__[attr]=$B.jsobj2pyobj(obj[attr])}return obj}}));super_class.__getattribute__=function(self,attr){if(attr=="__init__"||attr=="__call__"){return self.__init__}return $B.$getattr(self.__self_class__,attr)};$B.set_func_names(super_class,"javascript");modules["javascript"]={this:function(){if($B.js_this===undefined){return $B.builtins.None}return $B.jsobj2pyobj($B.js_this)},Array:$B.js_array,Date:self.Date&&$B.jsobj2pyobj(self.Date),extends:function(js_constr){if(!js_constr.$js_func||!js_constr.$js_func.toString().startsWith("class ")){console.log(js_constr);throw _b_.TypeError.$factory("argument of extend must be a Javascript class")}js_constr.__class__=_b_.type;return function(obj){obj.__bases__.splice(0,0,js_constr);obj.__mro__.splice(0,0,js_constr);return obj}},import_js:function(){var $=$B.args("import_js",2,{url:null,alias:null},["url","alias"],arguments,{alias:_b_.None},null,null),url=$.url,alias=$.alias;var xhr=new XMLHttpRequest,result;xhr.open("GET",url,false);xhr.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){var js=this.responseText+"\nreturn $module",f=new Function(js);var $module=f();if(typeof $module!=="undefined"){result=$B.module.$factory(alias);for(var key in $module){result[key]=$B.jsobj2pyobj($module[key])}result.__file__=url}else{console.log(this.responseText);result=_b_.ImportError.$factory("Javascript "+`module at ${url} doesn't define $module`)}}else{result=_b_.ModuleNotFoundError.$factory(url)}}};xhr.send();if($B.$isinstance(result,_b_.BaseException)){$B.handle_error(result)}else{if(alias===_b_.None){var name=url.split(".");if(name.length>1){name.pop()}alias=name.join(".");result.__name__=alias}$B.imported[alias]=result;var frame=$B.frame_obj.frame;frame[1][alias]=result}},import_modules:function(refs,callback,loaded){if(loaded===undefined){loaded=[]}if(!Array.isArray(refs)){throw _b_.TypeError.$factory(`first argument must be a list, got ${$B.class_name(refs)}`)}if(refs.length>1){var ref=refs.shift();import(ref).then((function(module){loaded.push(module);$B.imported.javascript.import_modules(refs,callback,loaded)})).catch($B.show_error)}else{import(refs[0]).then((function(module){loaded.push(module);return $B.$call(callback).apply(null,loaded)})).catch($B.show_error)}},import_scripts:function(refs,callback,loaded){console.log("import scripts",refs);if(loaded===undefined){loaded=[]}if(!Array.isArray(refs)){throw _b_.TypeError.$factory(`first argument must be a list, got ${$B.class_name(refs)}`)}if(refs.length>0){var ref=refs.shift();var script=document.createElement("script");script.src=ref;script.addEventListener("load",(function(){loaded.push(script);$B.imported.javascript.import_scripts(refs,callback,loaded)}));document.body.appendChild(script)}else{return $B.$call(callback).apply(null,loaded)}},JSObject:$B.JSObj,JSON:{__class__:$B.make_class("JSON"),parse:function(){return $B.structuredclone2pyobj(JSON.parse.apply(this,arguments))},stringify:function(obj,replacer,space){return JSON.stringify($B.pyobj2structuredclone(obj,false),$B.jsobj2pyobj(replacer),space)}},jsobj2pyobj:function(obj){return $B.jsobj2pyobj(obj)},load:function(script_url){console.log('"javascript.load" is deprecrated. '+"Use browser.load instead.");var file_obj=$B.builtins.open(script_url);var content=$B.$getattr(file_obj,"read")();eval(content)},Math:self.Math&&$B.jsobj2pyobj(self.Math),NULL:null,NullType:$B.make_class("NullType"),Number:self.Number&&$B.jsobj2pyobj(self.Number),py2js:function(src,module_name){if(module_name===undefined){module_name="__main__"+$B.UUID()}var js=$B.py2js({src:src,filename:""},module_name,module_name,$B.builtins_scope).to_js();return $B.format_indent(js,0)},pyobj2jsobj:function(obj){return $B.pyobj2jsobj(obj)},RegExp:self.RegExp&&$B.jsobj2pyobj(self.RegExp),String:self.String&&$B.jsobj2pyobj(self.String),super:super_class,UNDEFINED:$B.Undefined,UndefinedType:$B.UndefinedType};modules.javascript.NullType.__module__="javascript";modules.javascript.NullType.__eq__=function(_self,other){return other===null||other===$B.Undefined};modules.javascript.NullType.__repr__=function(_self){return""};$B.set_func_names(modules.javascript.NullType,"javascript");modules.javascript.UndefinedType.__module__="javascript";var $io=$B.$io=$B.make_class("io",(function(out){return{__class__:$io,__dict__:$B.empty_dict(),out:out,encoding:"utf-8"}}));$io.flush=function(self){if(self.buf){var s=self.buf.join(""),chr0=String.fromCodePoint(0);s=s.replace(new RegExp(chr0,"g")," ");console[self.out](s);self.buf=[]}};$io.write=function(self,msg){if(self.buf===undefined){self.buf=[]}if(typeof msg!="string"){throw _b_.TypeError.$factory("write() argument must be str, not "+$B.class_name(msg))}self.buf.push(msg);return _b_.None};modules["_sys"]={_getframe:function(){var $=$B.args("_getframe",1,{depth:null},["depth"],arguments,{depth:0},null,null),depth=$.depth,frame_obj=$B.frame_obj;for(var i=0;i0){var lines=headers.trim().split(/[\r\n]+/);lines.forEach((function(line){var parts=line.split(": ");var header=parts.shift();var value=parts.join(": ");_b_.dict.$setitem(res,header,value)}))}return res}));var Future=$B.make_class("Future",(function(){var methods={};var promise=new Promise((function(resolve,reject){methods.resolve=resolve;methods.reject=reject}));promise._methods=methods;promise._done=false;promise.__class__=Future;return promise}));Future.done=function(){var $=$B.args("done",1,{self:null},["self"],arguments,{},null,null);return!!$.self._done};Future.set_result=function(){var $=$B.args("set_result",2,{self:null,value:null},["self","value"],arguments,{},null,null);$.self._done=true;$.self._methods.resolve($.value);return _b_.None};Future.set_exception=function(){var $=$B.args("set_exception",2,{self:null,exception:null},["self","exception"],arguments,{},null,null);$.self._done=true;$.self._methods.reject($.exception);return _b_.None};$B.set_func_names(Future,"browser.aio");modules["browser.aio"]={ajax:function(){var $=$B.args("ajax",2,{method:null,url:null},["method","url"],arguments,{},null,"kw"),method=$.method.toUpperCase(),url=$.url,kw=$.kw;var args=handle_kwargs(kw,"get");if(method=="GET"&&!args.cache){url=url+"?ts"+(new Date).getTime()+"=0"}if(args.body&&method=="GET"){url=url+(args.cache?"?":"&")+args.body}var func=function(){return new Promise((function(resolve){var xhr=new XMLHttpRequest;xhr.open(method,url,true);for(var key in args.headers){xhr.setRequestHeader(key,args.headers[key])}xhr.format=args.format;xhr.responseType=responseType[args.format];xhr.onreadystatechange=function(){if(this.readyState==4){this.__class__=HTTPRequest;resolve(this)}};if(args.body&&["POST","PUT","DELETE","PATCH"].indexOf(method)>-1){xhr.send(args.body)}else{xhr.send()}}))};func.$infos={__name__:"ajax_"+method};return{__class__:$B.coroutine,$args:[url,args],$func:func}},event:function(){var $=$B.args("event",1,{element:null},["element"],arguments,{},"names",null),element=$.element,names=$.names;return new Promise((function(resolve){var callbacks=[];names.forEach((function(name){var callback=function(evt){callbacks.forEach((function(items){$B.DOMNode.unbind(element,items[0],items[1])}));resolve($B.$DOMEvent(evt))};callbacks.push([name,callback]);$B.DOMNode.bind(element,name,callback)}))}))},get:function(){return $B.imported["browser.aio"].ajax.bind(null,"GET").apply(null,arguments)},iscoroutine:function(f){return f.__class__===$B.coroutine},iscoroutinefunction:function(f){return(f.$infos.__code__.co_flags&128)!=0},post:function(){return $B.imported["browser.aio"].ajax.bind(null,"POST").apply(null,arguments)},run:function(){var handle_success=function(){$B.leave_frame()},handle_error=$B.show_error;var $=$B.args("run",3,{coro:null,onsuccess:null,onerror:null},["coro","onsuccess","onerror"],arguments,{onsuccess:handle_success,onerror:handle_error},null,null),coro=$.coro,onsuccess=$.onsuccess,onerror=$.onerror;var save_frame_obj=$B.frame_obj;$B.coroutine.send(coro).then(onsuccess).catch(onerror);$B.frame_obj=save_frame_obj;return _b_.None},sleep:function(seconds){if(seconds.__class__===_b_.float){seconds=seconds.value}else if(typeof seconds!="number"){throw _b_.TypeError.$factory("'sleep' argument must be "+"int or float, not "+$B.class_name(seconds))}var func=function(){return new Promise((resolve=>setTimeout((function(){resolve(_b_.None)}),1e3*seconds)))};func.$infos={__name__:"sleep"};return{__class__:$B.coroutine,$args:[seconds],$func:func}},Future:Future,__getattr__:function(attr){$B.$import("_aio");return $B.$getattr($B.imported._aio,attr)}};function load(name,module_obj){module_obj.__class__=$B.module;module_obj.__name__=name;$B.imported[name]=module_obj;for(var attr in module_obj){if(typeof module_obj[attr]=="function"){module_obj[attr].$infos={__module__:name,__name__:attr,__qualname__:name+"."+attr}}}}for(let attr in modules){load(attr,modules[attr])}if(!($B.isWebWorker||$B.isNode)){modules["browser"].html=modules["browser.html"];modules["browser"].aio=modules["browser.aio"]}_b_.__builtins__=$B.module.$factory("__builtins__","Python builtins");for(let attr in _b_){_b_.__builtins__[attr]=_b_[attr];$B.builtins_scope.binding[attr]=true;if(_b_[attr].$is_class){if(_b_[attr].__bases__){_b_[attr].__bases__.__class__=_b_.tuple}else{_b_[attr].__bases__=$B.fast_tuple([_b_.object])}}}_b_.__builtins__.__setattr__=function(attr,value){_b_[attr]=value};$B.method_descriptor.__getattribute__=$B.function.__getattribute__;$B.wrapper_descriptor.__getattribute__=$B.function.__getattribute__;var tp_dict=_b_.type.__dict__=$B.empty_dict(),setitem=_b_.dict.$setitem;for(let method in _b_.type){if(method.startsWith("__")&&method.endsWith("__")){setitem(tp_dict,method,_b_.type[method])}}setitem(tp_dict,"__mro__",{__get__:function(cls){return $B.fast_tuple([cls].concat(cls.__mro__))}});for(var name in _b_){var builtin=_b_[name];if(_b_[name].__class__===_b_.type){_b_[name].__qualname__=name;_b_[name].__module__="builtins";_b_[name].__name__=name;_b_[name].$is_builtin_class=true;$B.builtin_classes.push(_b_[name]);for(var key in _b_[name]){var value=_b_[name][key];if(value===undefined||value.__class__||typeof value!="function"){continue}else if(key=="__new__"){value.__class__=$B.builtin_function_or_method}else if(key.startsWith("__")){value.__class__=$B.wrapper_descriptor}else{value.__class__=$B.method_descriptor}value.__objclass__=_b_[name]}}else if(typeof builtin=="function"){builtin.$infos={__name__:name,__qualname__:name}}}for(let attr in $B){if(Array.isArray($B[attr])){$B[attr].__class__=_b_.list}}$B.cell=$B.make_class("cell",(function(value){return{__class__:$B.cell,$cell_contents:value}}));$B.cell.cell_contents=$B.$call(_b_.property)((function(self){if(self.$cell_contents===null){throw _b_.ValueError.$factory("empty cell")}return self.$cell_contents}),(function(self,value){self.$cell_contents=value}));var $comps=Object.values($B.$comps).concat(["eq","ne"]);$comps.forEach((function(comp){var op="__"+comp+"__";$B.cell[op]=function(op){return function(self,other){if(!$B.$isinstance(other,$B.cell)){return _b_.NotImplemented}if(self.$cell_contents===null){if(other.$cell_contents===null){return op=="__eq__"}else{return["__ne__","__lt__","__le__"].indexOf(op)>-1}}else if(other.$cell_contents===null){return["__ne__","__gt__","__ge__"].indexOf(op)>-1}return $B.rich_comp(op,self.$cell_contents,other.$cell_contents)}}(op)}));$B.set_func_names($B.cell,"builtins");for(let flag in $B.builtin_class_flags.builtins){for(let key of $B.builtin_class_flags.builtins[flag]){if(_b_[key]){_b_[key].__flags__=parseInt(flag)}else{console.log("not in _b_",key)}}}for(let flag in $B.builtin_class_flags.types){for(let key of $B.builtin_class_flags.types[flag]){if($B[key]){$B[key].__flags__=parseInt(flag)}}}$B.AST={__class__:_b_.type,__mro__:[_b_.object],__name__:"AST",__qualname__:"AST",$is_class:true,$convert:function(js_node){if(js_node===undefined){return _b_.None}var constr=js_node.constructor;if(constr&&constr.$name){$B.create_python_ast_classes();return $B.python_ast_classes[constr.$name].$factory(js_node)}else if(Array.isArray(js_node)){return js_node.map($B.AST.$convert)}else if(js_node.type){switch(js_node.type){case"int":var value=js_node.value[1],base=js_node.value[0];var res=parseInt(value,base);if(!Number.isSafeInteger(res)){res=$B.long_int.$factory(value,base)}return res;case"float":return $B.fast_float(parseFloat(js_node.value));case"imaginary":return $B.make_complex(0,$B.AST.$convert(js_node.value));case"ellipsis":return _b_.Ellipsis;case"str":if(js_node.is_bytes){return _b_.bytes.$factory(js_node.value,"latin-1")}return js_node.value;case"id":if(["False","None","True"].indexOf(js_node.value)>-1){return _b_[js_node.value]}break}}else if(["string","number"].indexOf(typeof js_node)>-1){return js_node}else if(js_node.$name){return js_node.$name+"()"}else if([_b_.None,_b_.True,_b_.False].indexOf(js_node)>-1){return js_node}else if(js_node.__class__){return js_node}else{console.log("cannot handle",js_node);return js_node}}};$B.stdin={__class__:$io,__original__:true,closed:false,len:1,pos:0,read:function(){return""},readline:function(){return""}};$B.__ARGV=$B.$list([]);$B.tracefunc=_b_.None})(__BRYTHON__);(function($B){var _b_=$B.builtins;function ast_dump(tree,indent){var attr,value;indent=indent||0;if(tree===_b_.None){return"None"}else if(typeof tree=="string"){return`'${tree}'`}else if(typeof tree=="number"){return tree+""}else if(tree.imaginary){return tree.value+"j"}else if(Array.isArray(tree)){if(tree.length==0){return"[]"}res="[\n";var items=[];for(var x of tree){try{items.push(ast_dump(x,indent+1))}catch(err){console.log("error",tree);console.log("for item",x);throw err}}res+=items.join(",\n");return res+"]"}else if(tree.$name){return tree.$name+"()"}else if(tree instanceof ast.MatchSingleton){return`MatchSingleton(value=${$B.AST.$convert(tree.value)})`}else if(tree instanceof ast.Constant){value=tree.value;if(value.imaginary){return`Constant(value=${_b_.repr(value.value)}j)`}return`Constant(value=${$B.AST.$convert(value)})`}var proto=Object.getPrototypeOf(tree).constructor;var res=" ".repeat(indent)+proto.$name+"(";if($B.ast_classes[proto.$name]===undefined){console.log("no ast class",proto)}var attr_names=$B.ast_classes[proto.$name].split(","),attrs=[];attr_names=attr_names.map((x=>x.endsWith("*")||x.endsWith("?")?x.substr(0,x.length-1):x));if([ast.Name].indexOf(proto)>-1){for(attr of attr_names){if(tree[attr]!==undefined){attrs.push(`${attr}=${ast_dump(tree[attr])}`)}}return res+attrs.join(", ")+")"}for(attr of attr_names){if(tree[attr]!==undefined){value=tree[attr];attrs.push(attr+"="+ast_dump(tree[attr],indent+1).trimStart())}}if(attrs.length>0){res+="\n";res+=attrs.map((x=>" ".repeat(indent+1)+x)).join(",\n")}res+=")";return res}function string_from_ast_value(value){return value.replace(new RegExp("\\\\'","g"),"'")}function compiler_error(ast_obj,message,end){var exc=_b_.SyntaxError.$factory(message);exc.filename=state.filename;if(exc.filename!=""){var src=$B.file_cache[exc.filename],lines=src.split("\n"),line=lines[ast_obj.lineno-1];exc.text=line}else{exc.text=_b_.None}exc.lineno=ast_obj.lineno;exc.offset=ast_obj.col_offset+1;end=end||ast_obj;exc.end_lineno=end.end_lineno;exc.end_offset=end.end_col_offset+1;exc.args[1]=[exc.filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset];exc.$frame_obj=$B.frame_obj;if($B.frame_obj===null){}throw exc}var uuid=Math.floor(Math.random()*1e6);function make_id(){uuid+=1;return uuid}function fast_id(obj){if(obj.$id!==undefined){return obj.$id}return obj.$id=make_id()}function copy_position(target,origin){target.lineno=origin.lineno;target.col_offset=origin.col_offset;target.end_lineno=origin.end_lineno;target.end_col_offset=origin.end_col_offset}function encode_position(a,b,c,d){if(d===undefined){return`[${[a,b,c]}]`}else{return`[${[a,b,c,d]}]`}}$B.decode_position=function(pos){return pos};function get_source_from_position(src,ast_obj){var lines=src.split("\n"),start_line=lines[ast_obj.lineno-1];if(ast_obj.end_lineno==ast_obj.lineno){return start_line.substring(ast_obj.col_offset,ast_obj.end_col_offset)}else{var res=start_line.substr(ast_obj.col_offset),line_num=ast_obj.lineno+1;while(line_num-1){_scopes=scopes.slice(0,ix+1)}else{_scopes=scopes.concat(scope)}}var names=[];for(var _scope of _scopes){if(!_scope.parent){names.push(_scope.name)}}return names.join("_").replace(/\./g,"_")}function module_name(scopes){var _scopes=scopes.slice();var names=[];for(var _scope of _scopes){if(!_scope.parent){names.push(_scope.name)}}return names.join(".")}function make_scope_name(scopes,scope){if(scope===builtins_scope){return`_b_`}return"locals_"+qualified_scope_name(scopes,scope)}function make_search_namespaces(scopes){var namespaces=[];for(var scope of scopes.slice().reverse()){if(scope.parent||scope.type=="class"){continue}else if(scope.is_exec_scope){namespaces.push("$B.exec_scope")}namespaces.push(make_scope_name(scopes,scope))}namespaces.push("_b_");return namespaces}function mangle(scopes,scope,name){if(name.startsWith("__")&&!name.endsWith("__")){var ix=scopes.indexOf(scope);while(ix>=0){if(scopes[ix].ast instanceof $B.ast.ClassDef){var scope_name=scopes[ix].name;while(scope_name.length>0&&scope_name.startsWith("_")){scope_name=scope_name.substr(1)}if(scope_name.length==0){return name}return"_"+scope_name+name}ix--}}return name}function reference(scopes,scope,name){return make_scope_name(scopes,scope)+"."+mangle(scopes,scope,name)}function bind(name,scopes){var scope=$B.last(scopes),up_scope=last_scope(scopes);name=mangle(scopes,up_scope,name);if(up_scope.globals&&up_scope.globals.has(name)){scope=scopes[0]}else if(up_scope.nonlocals.has(name)){for(var i=scopes.indexOf(up_scope)-1;i>=0;i--){if(scopes[i].locals.has(name)){return scopes[i]}}}scope.locals.add(name);return scope}var SF=$B.SYMBOL_FLAGS;function name_reference(name,scopes,position){var scope=name_scope(name,scopes);return make_ref(name,scopes,scope,position)}function make_ref(name,scopes,scope,position){var test=false;if(test){console.log("make ref",name,scopes.slice(),scope)}if(scope.found){var res=reference(scopes,scope.found,name);if(test){console.log("res",res)}return res}else if(scope.resolve=="all"){var scope_names=make_search_namespaces(scopes);return`$B.resolve_in_scopes('${name}', [${scope_names}], [${position}])`}else if(scope.resolve=="local"){return`$B.resolve_local('${name}', [${position}])`}else if(scope.resolve=="global"){return`$B.resolve_global('${name}', _frame_obj)`}else if(Array.isArray(scope.resolve)){return`$B.resolve_in_scopes('${name}', [${scope.resolve}], [${position}])`}else if(scope.resolve=="own_class_name"){return`$B.own_class_name('${name}')`}}function local_scope(name,scope){var s=scope;while(true){if(s.locals.has(name)){return{found:true,scope:s}}if(!s.parent){return{found:false}}s=s.parent}}function name_scope(name,scopes){var test=false;if(test){console.log("name scope",name,scopes.slice());alert()}var flags,block;if(scopes.length==0){return{found:false,resolve:"all"}}var scope=$B.last(scopes),up_scope=last_scope(scopes);name=mangle(scopes,scope,name);if(up_scope.ast===undefined){console.log("no ast",scope)}block=scopes.symtable.table.blocks.get(fast_id(up_scope.ast));if(block===undefined){console.log("no block",scope,scope.ast,"id",fast_id(up_scope.ast));console.log("scopes",scopes.slice());console.log("symtable",scopes.symtable)}if(test){console.log("block symbols",block.symbols)}try{flags=_b_.dict.$getitem_string(block.symbols,name)}catch(err){console.log("name",name,"not in symbols of block",block);console.log("symtables",scopes.symtable);console.log("scopes",scopes.slice());return{found:false,resolve:"all"}}let __scope=flags>>SF.SCOPE_OFF&SF.SCOPE_MASK,is_local=[SF.LOCAL,SF.CELL].indexOf(__scope)>-1;if(test){console.log("block",block,"is local",is_local,"__scope",__scope);console.log("flags",flags,"scopeoff",SF.SCOPE_OFF,"scope mask",SF.SCOPE_MASK)}if(up_scope.ast instanceof $B.ast.ClassDef&&name==up_scope.name){return{found:false,resolve:"own_class_name"}}if(name=="__annotations__"){if(block.type==SF.TYPE_CLASS&&up_scope.has_annotation){is_local=true}else if(block.type==SF.TYPE_MODULE){is_local=true}}if(test){console.log("is local ???",is_local,"scope",scope)}if(is_local){var l_scope=local_scope(name,scope);if(!l_scope.found){if(block.type==SF.TYPE_CLASS){scope.needs_frames=true;return{found:false,resolve:"global"}}else if(block.type==SF.TYPE_MODULE){scope.needs_frames=true;return{found:false,resolve:"global"}}return{found:false,resolve:"local"}}else{return{found:l_scope.scope}}}else if(scope.globals.has(name)){var global_scope=scopes[0];if(global_scope.locals.has(name)){return{found:global_scope}}scope.needs_frames=true;return{found:false,resolve:"global"}}else if(scope.nonlocals.has(name)){for(let i=scopes.length-2;i>=0;i--){block=scopes.symtable.table.blocks.get(fast_id(scopes[i].ast));if(block&&_b_.dict.$contains_string(block.symbols,name)){var fl=_b_.dict.$getitem_string(block.symbols,name),local_to_block=[SF.LOCAL,SF.CELL].indexOf(fl>>SF.SCOPE_OFF&SF.SCOPE_MASK)>-1;if(!local_to_block){continue}return{found:scopes[i]}}}}if(scope.has_import_star){if(!is_local){scope.needs_frames=true}return{found:false,resolve:is_local?"all":"global"}}for(let i=scopes.length-2;i>=0;i--){block=undefined;if(scopes[i].ast){block=scopes.symtable.table.blocks.get(fast_id(scopes[i].ast))}if(scopes[i].globals.has(name)){scope.needs_frames=true;return{found:false,resolve:"global"}}if(scopes[i].locals.has(name)&&scopes[i].type!="class"){return{found:scopes[i]}}else if(block&&_b_.dict.$contains_string(block.symbols,name)){flags=_b_.dict.$getitem_string(block.symbols,name);let __scope=flags>>SF.SCOPE_OFF&SF.SCOPE_MASK;if([SF.LOCAL,SF.CELL].indexOf(__scope)>-1){return{found:false,resolve:"all"}}}if(scopes[i].has_import_star){return{found:false,resolve:"all"}}}if(builtins_scope.locals.has(name)){return{found:builtins_scope}}var scope_names=make_search_namespaces(scopes);return{found:false,resolve:scope_names}}function resolve_in_namespace(name,ns){if(ns.$proxy){return ns[name]===undefined?{found:false}:{found:true,value:ns[name]}}if(!ns.hasOwnProperty){if(ns[name]!==undefined){return{found:true,value:ns[name]}}}else if(ns.hasOwnProperty(name)){return{found:true,value:ns[name]}}else if(ns.$dict){try{return{found:true,value:ns.$getitem(ns.$dict,name)}}catch(err){if(ns.$missing){try{return{found:true,value:$B.$call(ns.$missing)(ns.$dict,name)}}catch(err){if(!$B.is_exc(err,[_b_.KeyError])){throw err}}}}}return{found:false}}$B.resolve=function(name){var checked=new Set,current_globals,frame_obj=$B.frame_obj,frame;while(frame_obj!==null){frame=frame_obj.frame;if(current_globals===undefined){current_globals=frame[3]}else if(frame[3]!==current_globals){let v=resolve_in_namespace(name,current_globals);if(v.found){return v.value}checked.add(current_globals);current_globals=frame[3]}let v=resolve_in_namespace(name,frame[1]);if(v.found){return v.value}frame_obj=frame_obj.prev}if(!checked.has(frame[3])){var v=resolve_in_namespace(name,frame[3]);if(v.found){return v.value}}if(builtins_scope.locals.has(name)){return _b_[name]}throw $B.name_error(name)};$B.resolve_local=function(name,position){if($B.frame_obj!==null){var frame=$B.frame_obj.frame;if(frame[1].hasOwnProperty){if(frame[1].hasOwnProperty(name)){return frame[1][name]}}else{var value=frame[1][name];if(value!==undefined){return value}}}var exc=_b_.UnboundLocalError.$factory(`cannot access local variable `+`'${name}' where it is not associated with a value`);if(position&&$B.frame_obj){$B.set_exception_offsets(exc,position)}throw exc};$B.resolve_in_scopes=function(name,namespaces,position){for(var ns of namespaces){if(ns===$B.exec_scope){var exec_top,frame_obj=$B.frame_obj,frame;while(frame_obj!==null){frame=frame_obj.frame;if(frame.is_exec_top){exec_top=frame;break}frame_obj=frame_obj.prev}if(exec_top){for(var ns1 of[exec_top[1],exec_top[3]]){let v=resolve_in_namespace(name,ns1);if(v.found){return v.value}}}}else{let v=resolve_in_namespace(name,ns);if(v.found){return v.value}}}var exc=$B.name_error(name);if(position){$B.set_exception_offsets(exc,position)}throw exc};$B.resolve_global=function(name,frame_obj){while(frame_obj!==null){var frame=frame_obj.frame,v=resolve_in_namespace(name,frame[3]);if(v.found){return v.value}if(frame.is_exec_top){break}frame_obj=frame_obj.prev}if(builtins_scope.locals.has(name)){return _b_[name]}throw $B.name_error(name)};$B.own_class_name=function(name){throw $B.name_error(name)};var $operators=$B.op2method.subset("all");var opname2opsign={};for(var key in $operators){opname2opsign[$operators[key]]=key}var opclass2dunder={};for(var op_type of $B.op_types){for(var operator in op_type){opclass2dunder[op_type[operator]]="__"+$operators[operator]+"__"}}opclass2dunder["UAdd"]="__pos__";opclass2dunder["USub"]="__neg__";opclass2dunder["Invert"]="__invert__";var builtins_scope=new Scope("__builtins__");for(var name in $B.builtins){builtins_scope.locals.add(name)}function mark_parents(node){if(node.body&&node.body instanceof Array){for(let child of node.body){child.$parent=node;mark_parents(child)}}else if(node.handlers){var p={$parent:node,type:"except_handler"};for(let child of node.handlers){child.$parent=p;mark_parents(child)}}}function add_body(body,scopes){var res="";let js;for(var item of body){js=$B.js_from_ast(item,scopes);if(js.length>0){res+=js+"\n"}}return res.trimRight()}function extract_docstring(ast_obj,scopes){var js="_b_.None";if(ast_obj.body.length&&ast_obj.body[0]instanceof $B.ast.Expr&&ast_obj.body[0].value instanceof $B.ast.Constant){var value=ast_obj.body[0].value.value;if(typeof value=="string"){js=ast_obj.body[0].value.to_js(scopes);ast_obj.body.shift()}}return js}function init_comprehension(comp,scopes){if(comp.type=="genexpr"){return init_genexpr(comp,scopes)}return`var next_func_${comp.id} = $B.make_js_iterator(expr, frame, ${comp.ast.lineno})\n`}function init_genexpr(comp,scopes){var varnames=Object.keys(comp.varnames||{}).map((x=>`'${x}'`)).join(", ");return`var ${comp.locals_name} = {},\n`+`locals = ${comp.locals_name}\n`+`locals['.0'] = expr\n`+`var frame = ["<${comp.type.toLowerCase()}>", ${comp.locals_name}, `+`"${comp.module_name}", ${comp.globals_name}]\n`+`frame.$has_generators = true\n`+`frame.__file__ = '${scopes.filename}'\n`+`frame.$lineno = ${comp.ast.lineno}\n`+`frame.f_code = {\n`+`co_argcount: 1,\n`+`co_firstlineno:${comp.ast.lineno},\n`+`co_name: "<${comp.type.toLowerCase()}>",\n`+`co_filename: "${scopes.filename}",\n`+`co_flags: ${comp.type=="genexpr"?115:83},\n`+`co_freevars: $B.fast_tuple([]),\n`+`co_kwonlyargcount: 0,\n`+`co_posonlyargount: 0,\n`+`co_qualname: "<${comp.type.toLowerCase()}>",\n`+`co_varnames: $B.fast_tuple(['.0', ${varnames}])\n`+`}\n`+`var next_func_${comp.id} = $B.make_js_iterator(expr, frame, ${comp.ast.lineno})\n`+`frame.$f_trace = _b_.None\n`+`var _frame_obj = $B.frame_obj\n`}function make_comp(scopes){var id=make_id(),type=this.constructor.$name,symtable_block=scopes.symtable.table.blocks.get(fast_id(this)),varnames=Object.keys(symtable_block.symbols.$strings).map((x=>`"${x}"`)),comp_iter,comp_scope=$B.last(scopes),upper_comp_scope=comp_scope;while(upper_comp_scope.parent){upper_comp_scope=upper_comp_scope.parent}var comp_scope_block=scopes.symtable.table.blocks.get(fast_id(upper_comp_scope.ast)),comp_scope_symbols=comp_scope_block.symbols;var initial_nb_await_in_scope=upper_comp_scope.nb_await===undefined?0:upper_comp_scope.nb_await;for(var symbol of _b_.dict.$iter_items(symtable_block.symbols)){if(symbol.value&SF.DEF_COMP_ITER){comp_iter=symbol.key}}var comp_iter_scope=name_scope(comp_iter,scopes);var first_for=this.generators[0],outmost_expr=$B.js_from_ast(first_for.iter,scopes),nb_paren=1;var comp={ast:this,id:id,type:type,varnames:varnames,module_name:scopes[0].name,locals_name:make_scope_name(scopes),globals_name:make_scope_name(scopes,scopes[0])};var js=init_comprehension(comp,scopes);if(comp_iter_scope.found){js+=`var save_comp_iter = ${name_reference(comp_iter,scopes)}\n`}if(this instanceof $B.ast.ListComp){js+=`var result_${id} = $B.$list([])\n`}else if(this instanceof $B.ast.SetComp){js+=`var result_${id} = _b_.set.$factory()\n`}else if(this instanceof $B.ast.DictComp){js+=`var result_${id} = $B.empty_dict()\n`}var first=this.generators[0];js+=`try{\n`+`for(var next_${id} of next_func_${id}){\n`;var save_target_flags;if(first.target instanceof $B.ast.Name){var target_name=first.target.id;if(comp_scope_symbols.$strings.hasOwnProperty(target_name)){save_target_flags=comp_scope_symbols.$strings[target_name];comp_scope_symbols.$strings[target_name]=SF.LOCAL<initial_nb_await_in_scope;js=`(${has_await?"async ":""}function(expr){\n`+js;js+=has_await?"var save_frame_obj = $B.frame_obj;\n":"";if(this instanceof $B.ast.ListComp){js+=`result_${id}.push(${elt})\n`}else if(this instanceof $B.ast.SetComp){js+=`_b_.set.add(result_${id}, ${elt})\n`}else if(this instanceof $B.ast.DictComp){js+=`_b_.dict.$setitem(result_${id}, ${key}, ${value})\n`}for(var i=0;i")){name="exec"}else{name=filename.replace(/\./g,"_")}var top_scope=new Scope(name,`${type}`,this),block=scopes.symtable.table.blocks.get(fast_id(this));if(block&&block.$has_import_star){top_scope.has_import_star=true}scopes.push(top_scope);var namespaces=scopes.namespaces;if(namespaces){top_scope.is_exec_scope=true;for(let key in namespaces.exec_globals){if(!key.startsWith("$")){top_scope.globals.add(key)}}if(namespaces.exec_locals!==namespaces.exec_globals){if(namespaces.exec_locals[$B.LOCALS_PROXY]){for(let item of $B.make_js_iterator(namespaces.exec_locals.$target)){top_scope.locals.add(item)}}else{for(let key in namespaces.exec_locals){if(!key.startsWith("$")){top_scope.locals.add(key)}}}}}return name}function compiler_check(obj){var check_func=Object.getPrototypeOf(obj)._check;if(check_func){obj._check()}}function check_assign_or_delete(obj,target,action){action=action??"assign to";if(target instanceof $B.ast.Attribute){if(target.attr=="__debug__"){compiler_error(obj,`cannot ${action} __debug__`,target)}}else if(target instanceof $B.ast.Name){if(target.id=="__debug__"){compiler_error(obj,`cannot ${action} __debug__`,target)}}else if(target instanceof $B.ast.Tuple){for(var elt of target.elts){check_assign_or_delete(elt,elt,action)}}else if(target instanceof $B.ast.Starred){check_assign_or_delete(obj,target.value,action)}}function check_is_arg(e){if(!(e instanceof $B.ast.Constant)){return true}var value=e.value;return value===_b_.None||value===false||value===true||value===_b_.Ellipsis}function check_compare(op_name,left,right,scopes){var test_left=check_is_arg(left),test_right=check_is_arg(right);if(!test_left||!test_right){var item=test_left?right:left,name=$B.class_name(item.value);$B.warn(_b_.SyntaxWarning,`"${op_name}" with '${name}' literal. `+`Did you mean "=="?`,scopes.filename,item)}}function check_type_params(ast_obj){var type_params=ast_obj.type_params;if(Array.isArray(type_params)){var has_defaults=false;for(var type_param of type_params){if(type_param.default_value===undefined&&has_defaults){throw compiler_error(type_param,`non-default type `+`parameter '${type_param.name}' follows default type parameter`)}else if(type_param.default_value){has_defaults=true}}}}function maybe_add_static(attr,scopes){var last=last_scope(scopes);if(last.type=="def"){var ix=scopes.indexOf(last)-1;while(scopes[ix]){last=last_scope(scopes.slice(0,ix+1));if(last.type=="class"){last.static_attributes=last.static_attributes??new Set;last.static_attributes.add(attr.attr);return}else if(last.type=="def"){ix=scopes.indexOf(last)-1}else{return}}}}$B.ast.Assert.prototype.to_js=function(scopes){var test=$B.js_from_ast(this.test,scopes),msg=this.msg?$B.js_from_ast(this.msg,scopes):"";return`if($B.set_lineno(frame, ${this.lineno}) && !$B.$bool(${test})){\n`+`throw _b_.AssertionError.$factory(${msg})}\n`};function annotation_to_str(obj,scopes){return get_source_from_position(scopes.src,obj)}$B.ast.AnnAssign.prototype.to_js=function(scopes){compiler_check(this);var postpone_annotation=scopes.symtable.table.future.features&$B.CO_FUTURE_ANNOTATIONS;var scope=last_scope(scopes);var js="";if(!scope.has_annotation){js+="locals.__annotations__ = locals.__annotations__ || $B.empty_dict()\n";scope.has_annotation=true;scope.locals.add("__annotations__")}if(this.target instanceof $B.ast.Name){var ann_value=postpone_annotation?`'${annotation_to_str(this.annotation,scopes)}'`:$B.js_from_ast(this.annotation,scopes)}if(this.value){js+=`var ann = ${$B.js_from_ast(this.value,scopes)}\n`;if(this.target instanceof $B.ast.Name&&this.simple){let scope=bind(this.target.id,scopes),mangled=mangle(scopes,scope,this.target.id);if(scope.type!="def"){js+=`$B.$setitem(locals.__annotations__, `+`'${mangled}', ${ann_value})\n`}let target_ref=name_reference(this.target.id,scopes);js+=`${target_ref} = ann`}else if(this.target instanceof $B.ast.Attribute){js+=`$B.$setattr(${$B.js_from_ast(this.target.value,scopes)}`+`, "${this.target.attr}", ann)`}else if(this.target instanceof $B.ast.Subscript){js+=`$B.$setitem(${$B.js_from_ast(this.target.value,scopes)}`+`, ${$B.js_from_ast(this.target.slice,scopes)}, ann)`}}else{if(this.target instanceof $B.ast.Name){if(this.simple&&scope.type!="def"){let mangled=mangle(scopes,scope,this.target.id);js+=`$B.$setitem(locals.__annotations__, `+`'${mangled}', ${ann_value})`}}}return`$B.set_lineno(frame, ${this.lineno})\n`+js};$B.ast.AnnAssign.prototype._check=function(){check_assign_or_delete(this,this.target)};$B.ast.Assign.prototype.to_js=function(scopes){compiler_check(this);var js=this.lineno?`$B.set_lineno(frame, ${this.lineno})\n`:"",value=$B.js_from_ast(this.value,scopes);function assign_one(target,value){if(target instanceof $B.ast.Name){return $B.js_from_ast(target,scopes)+" = "+value}else if(target instanceof $B.ast.Starred){return assign_one(target.value,value)}else if(target instanceof $B.ast.Subscript){return`$B.$setitem(${$B.js_from_ast(target.value,scopes)}`+`, ${$B.js_from_ast(target.slice,scopes)}, ${value})`}else if(target instanceof $B.ast.Attribute){if(target.value.id=="self"){maybe_add_static(target,scopes)}var attr=mangle(scopes,last_scope(scopes),target.attr);return`$B.$setattr(${$B.js_from_ast(target.value,scopes)}`+`, "${attr}", ${value})`}}function assign_many(target,value){var js="";var nb_targets=target.elts.length,has_starred=false,nb_after_starred;for(var i=0,len=nb_targets;ithis.lineno){end_col_offset=this.col_offset+1}var position=encode_position(this.col_offset,this.col_offset,end_col_offset);js+=`, ${position}`;js+=")";var args=make_args.bind(this)(scopes);return js+(args.has_starred?`.apply(null, ${args.js})`:`(${args.js})`)};$B.ast.Call.prototype._check=function(){for(var kw of this.keywords){if(kw.arg=="__debug__"){compiler_error(this,"cannot assign to __debug__",kw)}}};function make_args(scopes){var js="",named_args=[],named_kwargs=[],starred_kwargs=[],has_starred=false;for(let arg of this.args){if(arg instanceof $B.ast.Starred){arg.$handled=true;has_starred=true}else{named_args.push($B.js_from_ast(arg,scopes))}}var kwds=new Set;for(var keyword of this.keywords){if(keyword.arg){if(kwds.has(keyword.arg)){compiler_error(keyword,`keyword argument repeated: ${keyword.arg}`)}kwds.add(keyword.arg);named_kwargs.push(`${keyword.arg}: ${$B.js_from_ast(keyword.value,scopes)}`)}else{starred_kwargs.push($B.js_from_ast(keyword.value,scopes))}}var args="";named_args=named_args.join(", ");if(!has_starred){args+=`${named_args}`}else{var start=true,not_starred=[];for(let arg of this.args){if(arg instanceof $B.ast.Starred){if(not_starred.length>0){let arg_list=not_starred.map((x=>$B.js_from_ast(x,scopes)));if(start){args+=`[${arg_list.join(", ")}]`}else{args+=`.concat([${arg_list.join(", ")}])`}not_starred=[]}else if(args==""){args="[]"}var starred_arg=$B.js_from_ast(arg.value,scopes);args+=`.concat(_b_.list.$factory(${starred_arg}))`;start=false}else{not_starred.push(arg)}}if(not_starred.length>0){let arg_list=not_starred.map((x=>$B.js_from_ast(x,scopes)));if(start){args+=`[${arg_list.join(", ")}]`;start=false}else{args+=`.concat([${arg_list.join(", ")}])`}}if(args[0]=="."){console.log("bizarre",args)}}if(named_kwargs.length+starred_kwargs.length==0){return{has_starred:has_starred,js:js+`${args}`}}else{var kw=`{${named_kwargs.join(", ")}}`;for(var starred_kwarg of starred_kwargs){kw+=`, ${starred_kwarg}`}kw=`{$kw:[${kw}]}`;if(args.length>0){if(has_starred){kw=`.concat([${kw}])`}else{kw=", "+kw}}return{has_starred:has_starred,js:js+`${args}${kw}`}}}$B.ast.ClassDef.prototype.to_js=function(scopes){var enclosing_scope=bind(this.name,scopes);var class_scope=new Scope(this.name,"class",this);var js="",locals_name=make_scope_name(scopes,class_scope),ref=this.name+make_id(),glob=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]),decorators=[],decorated=false;for(let dec of this.decorator_list){decorated=true;var dec_id="decorator"+make_id();decorators.push(dec_id);js+=`$B.set_lineno(frame, ${dec.lineno})\n`+`var ${dec_id} = ${$B.js_from_ast(dec,scopes)}\n`}js+=`$B.set_lineno(frame, ${this.lineno})\n`;var qualname=this.name;var ix=scopes.length-1;while(ix>=0){if(scopes[ix].parent){ix--}else if(scopes[ix].ast instanceof $B.ast.ClassDef){qualname=scopes[ix].name+"."+qualname;ix--}else{break}}var bases=this.bases.map((x=>$B.js_from_ast(x,scopes)));var has_type_params=this.type_params.length>0;if(has_type_params){check_type_params(this);js+=`$B.$import('_typing')\n`+`var _typing = $B.imported._typing\n`;var params=[];for(let item of this.type_params){if(item instanceof $B.ast.TypeVar){params.push(`$B.$call(_typing.TypeVar)('${item.name}')`)}else if(item instanceof $B.ast.TypeVarTuple){params.push(`$B.$call($B.$getattr(_typing.Unpack, '__getitem__'))($B.$call(_typing.TypeVarTuple)('${item.name.id}'))`)}else if(item instanceof $B.ast.ParamSpec){params.push(`$B.$call(_typing.ParamSpec)('${item.name.id}')`)}}bases.push(`_typing.Generic.__class_getitem__(_typing.Generic,`+` $B.fast_tuple([${params}]))`);for(let item of this.type_params){var name,param_type=item.constructor.$name;if(param_type=="TypeVar"){name=item.name}else{name=item.name.id}js+=`locals.${name} = $B.$call(_typing.${param_type})('${name}')\n`}}var keywords=[],metaclass;for(var keyword of this.keywords){if(keyword.arg=="metaclass"){metaclass=keyword.value}keywords.push(`["${keyword.arg}", `+$B.js_from_ast(keyword.value,scopes)+"]")}var docstring=extract_docstring(this,scopes);js+=`var ${ref} = (function(name, module, bases){\n`+`var _frame_obj = $B.frame_obj,\n`+`resolved_bases = $B.resolve_mro_entries(bases),\n`+`metaclass = $B.get_metaclass(name, module, `+`resolved_bases`;if(metaclass){js+=`, ${metaclass.to_js(scopes)}`}js+=")\n";js+=`var ${locals_name} = $B.make_class_namespace(metaclass, `+`name, module ,"${qualname}", resolved_bases),\n`;js+=`locals = ${locals_name}\n`+`if(resolved_bases !== bases){\nlocals.__orig_bases__ = bases}\n`+`locals.__doc__ = ${docstring}\n`+`var frame = [name, locals, module, ${globals_name}]\n`+`$B.enter_frame(frame, __file__, ${this.lineno})\n`+`var _frame_obj = $B.frame_obj\n`+`if(frame.$f_trace !== _b_.None){\n$B.trace_line()}\n`;scopes.push(class_scope);js+=add_body(this.body,scopes);scopes.pop();var static_attrs=[];if(class_scope.static_attributes){static_attrs=Array.from(class_scope.static_attributes).map((x=>`"${x}"`))}js+="\n$B.trace_return_and_leave(frame, _b_.None)\n"+`return $B.$class_constructor('${this.name}', locals, metaclass, `+`resolved_bases, bases, [${keywords.join(", ")}], `+`[${static_attrs}], ${this.lineno})\n`+`})('${this.name}',${globals_name}.__name__ ?? '${glob}', $B.fast_tuple([${bases}]))\n`;var class_ref=reference(scopes,enclosing_scope,this.name);if(decorated){class_ref=`decorated${make_id()}`;js+="var "}js+=`${class_ref} = ${ref}\n`;if(decorated){js+=reference(scopes,enclosing_scope,this.name)+" = ";var decorate=class_ref;for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`}js+=decorate+"\n"}return js};$B.ast.Compare.prototype.to_js=function(scopes){var test_left=check_is_arg(this.left);var left=$B.js_from_ast(this.left,scopes),comps=[];var len=this.ops.length,prefix=len>1?"locals.$op = ":"";for(var i=0;i1){left="locals.$op"}}return comps.join(" && ")};$B.ast.comprehension.prototype.to_js=function(scopes){var id=make_id(),iter=$B.js_from_ast(this.iter,scopes);var js=`var next_func_${id} = $B.make_js_iterator(${iter}, frame, ${this.lineno})\n`+`for(var next_${id} of next_func_${id}){\n`;var name=new $B.ast.Name(`next_${id}`,new $B.ast.Load);copy_position(name,this.target);name.to_js=function(){return`next_${id}`};var assign=new $B.ast.Assign([this.target],name);copy_position(assign,this.target);js+=assign.to_js(scopes)+" // assign to target\n";for(var _if of this.ifs){js+=`if($B.$bool(${$B.js_from_ast(_if,scopes)})){\n`}return js};$B.ast.Constant.prototype.to_js=function(){if(this.value===true||this.value===false){return this.value+""}else if(this.value===_b_.None){return"_b_.None"}else if(typeof this.value=="string"){var s=this.value,srg=$B.surrogates(s);if(srg.length==0){return`'${s}'`}return`$B.make_String('${s}', [${srg}])`}else if(this.value.__class__===_b_.bytes){return`_b_.bytes.$factory([${this.value.source}])`}else if(typeof this.value=="number"){if(Number.isInteger(this.value)){return this.value}else{return`({__class__: _b_.float, value: ${this.value}})`}}else if(this.value.__class__===$B.long_int){return`$B.fast_long_int(${this.value.value}n)`}else if(this.value.__class__===_b_.float){return`({__class__: _b_.float, value: ${this.value.value}})`}else if(this.value.__class__===_b_.complex){return`$B.make_complex(${this.value.$real.value}, ${this.value.$imag.value})`}else if(this.value===_b_.Ellipsis){return`_b_.Ellipsis`}else{console.log("invalid value",this.value);throw SyntaxError("bad value",this.value)}};$B.ast.Continue.prototype.to_js=function(scopes){if(!in_loop(scopes)){compiler_error(this,"'continue' not properly in loop")}return"continue"};$B.ast.Delete.prototype.to_js=function(scopes){compiler_check(this);var js="";for(var target of this.targets){if(target instanceof $B.ast.Name){var scope=name_scope(target.id,scopes);if(scope.found){scope.found.locals.delete(target.id)}js+=`$B.$delete("${target.id}")\n`}else if(target instanceof $B.ast.Subscript){js+=`$B.$delitem(${$B.js_from_ast(target.value,scopes)}, `+`${$B.js_from_ast(target.slice,scopes)})\n`}else if(target instanceof $B.ast.Attribute){js+=`_b_.delattr(${$B.js_from_ast(target.value,scopes)}, `+`'${target.attr}')\n`}}return`$B.set_lineno(frame, ${this.lineno})\n`+js};$B.ast.Delete.prototype._check=function(){for(var target of this.targets){check_assign_or_delete(this,target,"delete")}};$B.ast.Dict.prototype.to_js=function(scopes){var items=[],keys=this.keys,has_packed=false;function no_key(i){return keys[i]===_b_.None||keys[i]===undefined}for(let i=0,len=this.keys.length;i0){js+=`\nif(no_break_${id}){\n`+add_body(this.orelse,scopes)+"}\n"}return js};$B.ast.FormattedValue.prototype.to_js=function(scopes){var value=$B.js_from_ast(this.value,scopes);if(this.conversion==114){value=`_b_.repr(${value})`}else if(this.conversion==115){value=`_b_.str.$factory(${value})`}else if(this.conversion==97){value=`_b_.ascii(${value})`}if(this.format_spec){value=`_b_.str.format('{0:' + `+$B.js_from_ast(this.format_spec,scopes)+` + '}', ${value})`}else if(this.conversion==-1){value=`_b_.str.$factory(${value})`}return value};function transform_args(scopes){var has_posonlyargs=this.args.posonlyargs.length>0,_defaults=[],nb_defaults=this.args.defaults.length,positional=this.args.posonlyargs.concat(this.args.args),ix=positional.length-nb_defaults,default_names=[],kw_defaults=[],annotations;for(let arg of positional.concat(this.args.kwonlyargs).concat([this.args.vararg,this.args.kwarg])){if(arg&&arg.annotation){annotations=annotations||{};annotations[arg.arg]=arg.annotation}}for(var i=ix;i ${PARAMS_POS_COUNT} ) {\n $B.args0_old(fct, args);\n throw new Error('Too much positional arguments given (args0 should have raised an error) !');\n }\n`;if(hasPosOnly||hasPos){fct+=`\n for( ; offset < ARGS_POS_COUNT ; ++offset)\n result[ PARAMS_NAMES[offset] ] = args[offset];\n`}}if(!hasPos&&!hasNamedOnly&&!hasKWargs){fct+=`\n if( HAS_KW === true ) {\n for(let argname in ARGS_NAMED[0] ) {\n $B.args0_old(fct, args);\n throw new Error('No named arguments expected !!!');\n }\n for(let id = 1; id < ARGS_NAMED.length; ++id ) {\n const kargs = ARGS_NAMED[id];\n for(let argname of $B.unpack_mapping( fct, kargs) ) { //TODO: not optimal\n $B.args0_old(fct, args);\n throw new Error('No named arguments expected !!!');\n }\n }\n }\n`}else{fct+=`\n if( HAS_KW === false ) {\n `}if(hasPos||hasPosOnly){if(posOnlyDefaults!==DEFAULTS.ALL&&posDefaults!==DEFAULTS.ALL){fct+=`\n if( offset < ${PARAMS_POS_DEFAULTS_OFFSET} ) {\n $B.args0_old(fct, args);\n throw new Error('Not enough positional arguments given (args0 should have raised an error) !');\n }\n`}if(posOnlyDefaults!==DEFAULTS.NONE||posDefaults!==DEFAULTS.NONE){fct+=`\n for(let i = offset - PARAMS_POS_DEFAULTS_OFFSET;\n i < PARAMS_POS_DEFAULTS_COUNT;\n ++i)\n result[ PARAMS_NAMES[offset++] ] = PARAMS_POS_DEFAULTS[i];`}}if(hasKWargs){fct+=`\n result[$INFOS.kwarg] = __BRYTHON__.empty_dict();`}if(hasNamedOnly&&namedOnlyDefaults!==DEFAULTS.ALL){fct+=`\n $B.args0_old(fct, args);\n throw new Error('Named argument expected (args0 should have raised an error) !');\n`}else if(namedOnlyDefaults!==DEFAULTS.NONE){fct+=`\n const kwargs_defaults_values = fct.$kwdefaults_values;\n for(let i = 0; i < kwargs_defaults_values.length; ++i )\n result[ PARAMS_NAMES[offset++] ] = kwargs_defaults_values[i];\n`}fct+=`\n return result;\n`;if(!hasPos&&!hasNamedOnly&&!hasKWargs){return fct}else{fct+=`\n }\n`}if(namedOnlyDefaults!==DEFAULTS.NONE){fct+=`\n const kwargs_defaults = fct.$kwdefaults;\n`}if(hasPosOnly){fct+=`\n const PARAMS_POSONLY_COUNT = $CODE.co_posonlyargcount;\n if( offset < PARAMS_POSONLY_COUNT ) {\n `;if(posOnlyDefaults!==DEFAULTS.SOME){fct+=`\n if( offset < ${PARAMS_POS_DEFAULTS_OFFSET} ) {\n $B.args0_old(fct, args);\n throw new Error('Not enough positional parameters given (args0 should have raised an error) !');\n }\n`}if(posOnlyDefaults===DEFAULTS.NONE){fct+=`\n $B.args0_old(fct, args);\n throw new Error('Not enough positional parameters given (args0 should have raised an error) !');\n`}fct+=`\n const max = ${PARAMS_POS_DEFAULTS_COUNT} - (${PARAMS_POS_COUNT} - PARAMS_POSONLY_COUNT);\n // default parameters\n for(let i = offset - ${PARAMS_POS_DEFAULTS_OFFSET};\n i < max;\n ++i)\n result[ PARAMS_NAMES[offset++] ] = PARAMS_POS_DEFAULTS[i];\n }\n`}if(hasKWargs){fct+=`\n const extra = {};\n let nb_extra_args = 0;\n`;if(hasPos||hasNamedOnly){fct+=`\n const HAS_PARAMS = fct.$hasParams;\n`}}fct+=`\n let nb_named_args = 0;\n const kargs = ARGS_NAMED[0];\n for(let argname in kargs) {\n `;if(!hasKWargs){fct+=`\n result[ argname ] = kargs[argname];\n ++nb_named_args;\n`}if(hasKWargs){if(!hasNamedOnly&&!hasPos){fct+=`\n extra[ argname ] = kargs[argname];\n ++nb_extra_args;\n`}else{fct+=`\n if( HAS_PARAMS.has(argname) ) {\n result[ argname ] = kargs[argname];\n ++nb_named_args;\n } else {\n extra[ argname ] = kargs[argname];\n ++nb_extra_args;\n }\n`}}fct+=`\n }\n for(let id = 1; id < ARGS_NAMED.length; ++id ) {\n const kargs = ARGS_NAMED[id];\n for(let item of $B.unpack_mapping(fct, kargs) ) {\n let argname = item.key\n if( typeof argname !== "string") {\n $B.args0_old(fct, args);\n throw new Error('Non string key passed in **kargs');\n }\n `;if(!hasKWargs){fct+=`\n result[ argname ] = item.value;\n ++nb_named_args;\n`}if(hasKWargs){if(!hasNamedOnly&&!hasPos){fct+=`\n extra[ argname ] = $B.$getitem(kargs, argname);\n ++nb_extra_args;\n`}else{fct+=`\n if( HAS_PARAMS.has(argname) ) {\n result[ argname ] = $B.$getitem(kargs, argname);\n ++nb_named_args;\n } else {\n extra[ argname ] = $B.$getitem(kargs, argname);\n ++nb_extra_args;\n }\n`}}fct+=`\n }\n }\n`;fct+=`\n let found = 0;\n let ioffset = offset;\n`;if((hasPosOnly||hasPos)&&(!hasPosOnly||posOnlyDefaults!==DEFAULTS.ALL)&&(!hasPos||posDefaults!==DEFAULTS.ALL)){fct+=`\n for( ; ioffset < ${PARAMS_POS_DEFAULTS_OFFSET}; ++ioffset) {\n const key = PARAMS_NAMES[ioffset];\n if( key in result ) // maybe could be speed up using "!(key in result)"\n continue;\n $B.args0_old(fct, args);\n throw new Error('Missing a named arguments (args0 should have raised an error) !');\n }\n`}if(hasPosOnly&&posOnlyDefaults!==DEFAULTS.NONE||hasPos&&posDefaults!==DEFAULTS.NONE){fct+=`\n for( ; ioffset < PARAMS_POS_COUNT; ++ioffset) {\n const key = PARAMS_NAMES[ioffset];\n if( key in result )\n continue;\n result[key] = PARAMS_POS_DEFAULTS[ioffset - ${PARAMS_POS_DEFAULTS_OFFSET}];\n ++found;\n }\n`}if(hasNamedOnly){fct+=`\n for( ; ioffset < PARAMS_NAMES.length; ++ioffset) {\n const key = PARAMS_NAMES[ioffset];\n if( key in result )\n continue;\n`;if(namedOnlyDefaults===DEFAULTS.SOME){fct+=`\n if( ! kwargs_defaults.has(key) ) {\n $B.args0_old(fct, args);\n throw new Error('Missing a named arguments (args0 should have raised an error) !');\n }\n`}if(namedOnlyDefaults===DEFAULTS.NONE){fct+=`\n $B.args0_old(fct, args);\n throw new Error('Missing a named arguments (args0 should have raised an error) !');\n`}if(namedOnlyDefaults!==DEFAULTS.NONE){fct+=`\n result[key] = kwargs_defaults.get(key);\n ++found;\n`}fct+=`\n }\n`}if(hasNamedOnly||hasPos)fct+=`\n if( found + nb_named_args !== PARAMS_NAMES.length - offset) {\n $B.args0_old(fct, args);\n throw new Error('Inexistant or duplicate named arguments (args0 should have raised an error) !');\n }\n`;if(hasKWargs){fct+=`\n if( Object.keys(extra).length !== nb_extra_args ) {\n $B.args0_old(fct, args);\n throw new Error('Duplicate name given to **kargs parameter (args0 should have raised an error) !');\n }\n result[$INFOS.kwarg] = __BRYTHON__.builtins.dict.$from_js(extra);\n`}fct+=`\n return result\n `;return fct}function type_param_in_def(tp,ref,scopes){var gname=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]);var js="";var name,param_type=tp.constructor.$name;if(param_type=="TypeVar"){name=tp.name}else{name=tp.name.id}bind(name,scopes);if(tp.bound){var typevarscope=new Scope(name,"typevarbound",tp);scopes.push(typevarscope);js+=`function BOUND_OF_${name}(){\n`+`var current_frame = $B.frame_obj.frame,\n`+`frame = ['BOUND_OF_${name}', {}, '${gname}', ${globals_name}]\n`+`$B.enter_frame(frame, __file__, ${tp.bound.lineno})\n`+`try{\n`+`var res = ${tp.bound.to_js(scopes)}\n`+`$B.leave_frame()\nreturn res\n`+`}catch(err){\n`+`$B.leave_frame()\n`+`throw err\n}\n}\n`;scopes.pop()}js+=`locals_${ref}.${name} = `+`$B.$call(_typing.${param_type})('${name}', {$kw: [{infer_variance: true}]})\n`+`type_params.push(locals_${ref}.${name})\n`;if(tp.bound){if(!tp.bound.elts){js+=`_typing.${param_type}._set_lazy_eval(locals_${ref}.${name}, `+`'__bound__', BOUND_OF_${name})\n`}else{js+=`_typing.${param_type}._set_lazy_eval(locals_${ref}.${name}, `+`'__constraints__', BOUND_OF_${name})\n`}}return js}$B.make_args_parser_and_parse=function make_args_parser_and_parse(fct,args){return $B.make_args_parser(fct)(fct,args)};$B.ast.FunctionDef.prototype.to_js=function(scopes){compiler_check(this);var symtable_block=scopes.symtable.table.blocks.get(fast_id(this));var in_class=last_scope(scopes).ast instanceof $B.ast.ClassDef,is_async=this instanceof $B.ast.AsyncFunctionDef,mangle_arg=x=>x;if(in_class){var class_scope=last_scope(scopes);mangle_arg=x=>mangle(scopes,class_scope,x)}var func_name_scope=bind(this.name,scopes);var gname=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]);var decorators=[],decorated=false,decs_declare=this.decorator_list.length>0?"// declare decorators\n":"";for(let dec of this.decorator_list){decorated=true;var dec_id="decorator"+make_id();decorators.push(dec_id);decs_declare+=`$B.set_lineno(frame, ${dec.lineno})\n`;decs_declare+=`var ${dec_id} = ${$B.js_from_ast(dec,scopes)}\n`}var docstring=extract_docstring(this,scopes);var parsed_args=transform_args.bind(this)(scopes),positional=parsed_args.positional,kw_defaults=parsed_args.kw_defaults,kw_default_names=parsed_args.kw_default_names;var defaults=`$B.fast_tuple([${this.args.defaults.map((x=>x.to_js(scopes)))}])`;kw_defaults=kw_default_names.length==0?"_b_.None":`_b_.dict.$from_js({${kw_defaults.join(", ")}})`;var id=make_id(),name2=this.name+id;var has_type_params=this.type_params.length>0,type_params="";if(has_type_params){check_type_params(this);var tp_name=`type_params_${name2}`;var type_params_scope=new Scope(tp_name,"type_params",this.type_params);scopes.push(type_params_scope);var type_params_ref=qualified_scope_name(scopes,type_params_scope);var type_params_func=`function TYPE_PARAMS_OF_${name2}(){\n`;type_params=`$B.$import('_typing')\n`+`var _typing = $B.imported._typing\n`+`var locals_${type_params_ref} = {\n},\n`+`locals = locals_${type_params_ref},\n`+`frame = ['${type_params_ref}', locals, '${gname}', ${globals_name}],\n`+`type_params = []\n`+`$B.enter_frame(frame, '${scopes.filename}', ${this.lineno})\n`;for(var item of this.type_params){type_params+=type_param_in_def(item,type_params_ref,scopes)}type_params_func+=type_params}var func_scope=new Scope(this.name,"def",this);scopes.push(func_scope);var args=positional.concat(this.args.kwonlyargs),slots=[],arg_names=[];for(let arg of args){slots.push(arg.arg+": null");bind(arg.arg,scopes)}for(let arg of this.args.posonlyargs){arg_names.push(`'${mangle_arg(arg.arg)}'`)}for(let arg of this.args.args.concat(this.args.kwonlyargs)){arg_names.push(`'${mangle_arg(arg.arg)}'`)}if(this.args.vararg){bind(mangle_arg(this.args.vararg.arg),scopes)}if(this.args.kwarg){bind(mangle_arg(this.args.kwarg.arg),scopes)}var function_body;if(this.$is_lambda){var _return=new $B.ast.Return(this.body);copy_position(_return,this.body);var body=[_return];function_body=add_body(body,scopes)}else{function_body=add_body(this.body,scopes)}var is_generator=symtable_block.generator;var parse_args=[name2];var js=`$B.set_lineno(frame, ${this.lineno})\n`;if(is_async&&!is_generator){js+="async "}js+=`function ${name2}(){\n`;var locals_name=make_scope_name(scopes,func_scope);js+=`var locals\n`;parse_args.push("arguments");var args_vararg=this.args.vararg===undefined?"null":"'"+mangle_arg(this.args.vararg.arg)+"'",args_kwarg=this.args.kwarg===undefined?"null":"'"+mangle_arg(this.args.kwarg.arg)+"'";if(positional.length==0&&slots.length==0&&this.args.vararg===undefined&&this.args.kwarg===undefined){js+=`var ${locals_name} = locals = {};\n`;js+=`if(arguments.length !== 0){\n`+`${name2}.$args_parser(${parse_args.join(", ")})\n`+`}\n`}else{js+=`var ${locals_name} = locals = ${name2}.$args_parser(${parse_args.join(", ")})\n`}js+=`var frame = ["${this.$is_lambda?"":this.name}", `+`locals, "${gname}", ${globals_name}, ${name2}]\n $B.enter_frame(frame, __file__, ${this.lineno})\n`;if(func_scope.needs_stack_length){js+=`var stack_length = $B.count_frames()\n`}if(func_scope.needs_frames||is_async){js+=`var _frame_obj = $B.frame_obj,\n`+`_linenums = $B.make_linenums()\n`}if(is_async){js+="frame.$async = true\n"}if(is_generator){js+=`locals.$is_generator = true\n`;if(is_async){js+=`var gen_${id} = $B.async_generator.$factory(async function*(){\n`}else{js+=`var gen_${id} = $B.generator.$factory(function*(){\n`}}js+=`try{\n$B.js_this = this\n`;if(in_class){var ix=scopes.indexOf(class_scope),parent=scopes[ix-1];var scope_ref=make_scope_name(scopes,parent),class_ref=class_scope.name,refs=class_ref.split(".").map((x=>`'${x}'`));bind("__class__",scopes);js+=`locals.__class__ = `+`$B.get_method_class(${name2}, ${scope_ref}, "${class_ref}", [${refs}])\n`}js+=function_body+"\n";if(!this.$is_lambda&&!($B.last(this.body)instanceof $B.ast.Return)){js+="var result = _b_.None\n"+"$B.trace_return_and_leave(frame, result)\n"+"return result\n"}js+=`}catch(err){\n`;if(func_scope.needs_frames){js+=`$B.set_exc_and_trace(frame, err)\n`+`err.$frame_obj = _frame_obj\n`+`_linenums[_linenums.length - 1] = frame.$lineno\n`+`err.$linenums = _linenums\n`+`$B.leave_frame()\n`}else{js+=`$B.set_exc_and_leave(frame, err)\n`}js+=`throw err\n }\n }\n`;if(is_generator){js+=`, '${this.name}')\n`+`var _gen_${id} = gen_${id}()\n`+`_gen_${id}.$frame = frame\n`+`$B.leave_frame()\n`+`return _gen_${id}}\n`}scopes.pop();var qualname=in_class?`${func_name_scope.name}.${this.name}`:this.name;var flags=$B.COMPILER_FLAGS.OPTIMIZED|$B.COMPILER_FLAGS.NEWLOCALS;if(this.args.vararg){flags|=$B.COMPILER_FLAGS.VARARGS}if(this.args.kwarg){flags|=$B.COMPILER_FLAGS.VARKEYWORDS}if(is_generator){flags|=$B.COMPILER_FLAGS.GENERATOR}if(is_async){flags|=$B.COMPILER_FLAGS.COROUTINE}var parameters=[],locals=[],identifiers=_b_.dict.$keys_string(symtable_block.symbols);var free_vars=[];for(var ident of identifiers){var flag=_b_.dict.$getitem_string(symtable_block.symbols,ident),_scope=flag>>SF.SCOPE_OFF&SF.SCOPE_MASK;if(_scope==SF.FREE){free_vars.push(`'${ident}'`)}if(flag&SF.DEF_PARAM){parameters.push(`'${ident}'`)}else if(flag&SF.DEF_LOCAL){locals.push(`'${ident}'`)}}var varnames=parameters.concat(locals);if(in_class){js+=`${name2}.$is_method = true\n`}js+=`$B.make_function_infos(${name2}, `+`'${gname}', `+`${defaults}, `+`${kw_defaults}, `+`${docstring}, `+`[${arg_names}], `+`${args_vararg}, `+`${args_kwarg},\n`+`${positional.length}, `+`__file__, `+`${this.lineno}, `+`${flags}, `+`[${free_vars}], `+`${this.args.kwonlyargs.length}, `+`'${this.$is_lambda?"":this.name}', `+`${this.args.posonlyargs.length}, `+`'${this.$is_lambda?"":qualname}', `+`[${varnames}])\n`;if(is_async&&!is_generator){js+=`${name2} = $B.make_async(${name2})\n`}var mangled=mangle(scopes,func_name_scope,this.name),func_ref=`${make_scope_name(scopes,func_name_scope)}.${mangled}`;if(decorated){func_ref=`decorated${make_id()}`;js+="var "}js+=`${func_ref} = ${name2}\n`;if(this.returns||parsed_args.annotations){var features=scopes.symtable.table.future.features,postponed=features&$B.CO_FUTURE_ANNOTATIONS;if(postponed){var src=scopes.src;if(src===undefined){console.log("no src, filename",scopes)}}var ann_items=[];if(parsed_args.annotations){for(var arg_ann in parsed_args.annotations){var ann_ast=parsed_args.annotations[arg_ann];if(in_class){arg_ann=mangle(scopes,class_scope,arg_ann)}if(postponed){var ann_str=annotation_to_str(ann_ast,scopes);ann_items.push(`['${arg_ann}', '${ann_str}']`)}else{var value=ann_ast.to_js(scopes);ann_items.push(`['${arg_ann}', ${value}]`)}}}if(this.returns){if(postponed){var ann_str=annotation_to_str(this.returns,scopes);ann_items.push(`['return', '${ann_str}']`)}else{ann_items.push(`['return', ${this.returns.to_js(scopes)}]`)}}js+=`${func_ref}.__annotations__ = _b_.dict.$from_array([${ann_items.join(", ")}])\n`}else{js+=`${func_ref}.__annotations__ = $B.empty_dict()\n`}if(has_type_params){scopes.pop()}if(decorated&&!has_type_params){js+=`${make_scope_name(scopes,func_name_scope)}.${mangled} = `;let decorate=func_ref;for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`}js+=decorate}if(has_type_params){type_params_func+="\n"+js+"\n"+`${name2}.__type_params__ = $B.fast_tuple(type_params)\n`+`$B.leave_frame()\n`+`return ${name2}\n}\n`;js=type_params_func;if(decorated){js+=`var ${func_ref} = TYPE_PARAMS_OF_${name2}()\n`+`${make_scope_name(scopes,func_name_scope)}.${mangled} = `;let decorate=func_ref;for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`}js+=decorate}else{js+=`var locals_${type_params_ref} = TYPE_PARAMS_OF_${name2}()\n`}}js=decs_declare+js;return js};$B.ast.FunctionDef.prototype._check=function(){for(var arg of this.args.args){if(arg instanceof $B.ast.arg){if(arg.arg=="__debug__"){compiler_error(arg,"cannot assign to __debug__")}}}for(var arg of this.args.kwonlyargs){if(arg instanceof $B.ast.arg){if(arg.arg=="__debug__"){compiler_error(arg,"cannot assign to __debug__")}}}if(this.args.kwarg&&this.args.kwarg.arg=="__debug__"){compiler_error(this.args.kwarg,"cannot assign to __debug__")}};$B.ast.GeneratorExp.prototype.to_js=function(scopes){var id=make_id(),symtable_block=scopes.symtable.table.blocks.get(fast_id(this)),varnames=symtable_block.varnames.map((x=>`"${x}"`));var first_for=this.generators[0],outmost_expr=$B.js_from_ast(first_for.iter,scopes),nb_paren=1;var comp_scope=new Scope(`genexpr_${id}`,"comprehension",this);scopes.push(comp_scope);var comp={ast:this,id:id,type:"genexpr",varnames:varnames,module_name:scopes[0].name,locals_name:make_scope_name(scopes),globals_name:make_scope_name(scopes,scopes[0])};var head=init_comprehension(comp,scopes);var first=this.generators[0];var js=`$B.enter_frame(frame, __file__, ${this.lineno})\n`+`var next_func_${id} = $B.make_js_iterator(expr, frame, ${this.lineno})\n`+`for(var next_${id} of next_func_${id}){\n`+`$B.enter_frame(frame, __file__, ${this.lineno})\n`;var name=new $B.ast.Name(`next_${id}`,new $B.ast.Load);copy_position(name,first_for.iter);name.to_js=function(){return`next_${id}`};var assign=new $B.ast.Assign([first.target],name);assign.lineno=this.lineno;js+=assign.to_js(scopes)+"\n";for(let _if of first.ifs){nb_paren++;js+=`if($B.$bool(${$B.js_from_ast(_if,scopes)})){\n`}for(var comprehension of this.generators.slice(1)){js+=comprehension.to_js(scopes);nb_paren++;for(let _if of comprehension.ifs){nb_paren++}}var elt=$B.js_from_ast(this.elt,scopes),has_await=comp_scope.has_await;js=`var gen${id} = $B.generator.$factory(${has_await?"async ":""}function*(expr){\n`+js;js+=has_await?"var save_frame_obj = $B.frame_obj;\n":"";js+=`try{\n`+` yield ${elt}\n`+`}catch(err){\n`+(has_await?"$B.restore_frame_obj(save_frame_obj, locals)\n":"")+`$B.leave_frame()\nthrow err\n}\n`+(has_await?"\n$B.restore_frame_obj(save_frame_obj, locals);":"");for(var i=0;i")(expr)\n';scopes.pop();var func=`${head}\n${js}\nreturn gen${id}`;return`(function(expr){\n${func}\n})(${outmost_expr})\n`};$B.ast.Global.prototype.to_js=function(scopes){var scope=last_scope(scopes);for(var name of this.names){scope.globals.add(name)}return""};$B.ast.If.prototype.to_js=function(scopes){var scope=$B.last(scopes),new_scope=copy_scope(scope,this);var js=`if($B.set_lineno(frame, ${this.lineno}) && `;if(this.test instanceof $B.ast.BoolOp){this.test.$dont_evaluate=true;js+=`${$B.js_from_ast(this.test,scopes)}){\n`}else{js+=`$B.$bool(${$B.js_from_ast(this.test,scopes)})){\n`}scopes.push(new_scope);js+=add_body(this.body,scopes)+"\n}";scopes.pop();if(this.orelse.length>0){if(this.orelse[0]instanceof $B.ast.If&&this.orelse.length==1){js+="else "+$B.js_from_ast(this.orelse[0],scopes)+add_body(this.orelse.slice(1),scopes)}else{js+="\nelse{\n"+add_body(this.orelse,scopes)+"\n}"}}return js};$B.ast.IfExp.prototype.to_js=function(scopes){return"($B.$bool("+$B.js_from_ast(this.test,scopes)+") ? "+$B.js_from_ast(this.body,scopes)+": "+$B.js_from_ast(this.orelse,scopes)+")"};$B.ast.Import.prototype.to_js=function(scopes){var js=`$B.set_lineno(frame, ${this.lineno})\n`;for(var alias of this.names){js+=`$B.$import("${alias.name}", [], `;if(alias.asname){js+=`{'${alias.name}' : '${alias.asname}'}, `;bind(alias.asname,scopes)}else{js+="{}, ";bind(alias.name,scopes)}var parts=alias.name.split(".");for(var i=0;i`"${x.name}"`)).join(", "),aliases=[];for(var name of this.names){if(name.asname){aliases.push(`${name.name}: '${name.asname}'`)}}js+=`[${names}], {${aliases.join(", ")}}, ${this.level}, locals);`;for(var alias of this.names){if(alias.asname){bind(alias.asname,scopes)}else if(alias.name=="*"){last_scope(scopes).blurred=true;js+=`\n$B.import_all(locals, module)`}else{bind(alias.name,scopes)}}return js};$B.ast.Interactive.prototype.to_js=function(scopes){mark_parents(this);var name=init_scopes.bind(this)("module",scopes);var module_id=name,global_name=make_scope_name(scopes),mod_name=module_name(scopes);var js=`// Javascript code generated from ast\n`+`var $B = __BRYTHON__,\n_b_ = $B.builtins,\n`;js+=`${global_name} = {}, // $B.imported["${mod_name}"],\n`+`locals = ${global_name},\n`+`frame = ["${module_id}", locals, "${module_id}", locals]`;js+=`\nvar __file__ = '${scopes.filename??""}'\n`+`locals.__name__ = '${name}'\n`+`locals.__doc__ = ${extract_docstring(this,scopes)}\n`;if(!scopes.imported){js+=`locals.__annotations__ = locals.__annotations__ || $B.empty_dict()\n`}js+=`$B.enter_frame(frame, __file__, 1)\n`;js+="\nvar _frame_obj = $B.frame_obj\n";js+="var stack_length = $B.count_frames()\n";js+=`try{\n`+add_body(this.body,scopes)+"\n"+`$B.leave_frame({locals, value: _b_.None})\n`+`}catch(err){\n`+`$B.set_exc_and_trace(frame, err)\n`+`$B.leave_frame({locals, value: _b_.None})\n`+"throw err\n"+`}`;scopes.pop();console.log("Interactive",js);return js};$B.ast.JoinedStr.prototype.to_js=function(scopes){var items=this.values.map((s=>$B.js_from_ast(s,scopes)));if(items.length==0){return"''"}return items.join(" + ")};$B.ast.Lambda.prototype.to_js=function(scopes){var id=make_id(),name="lambda_"+$B.lambda_magic+"_"+id;var f=new $B.ast.FunctionDef(name,this.args,this.body,[]);f.lineno=this.lineno;f.$id=fast_id(this);f.$is_lambda=true;var js=f.to_js(scopes),lambda_ref=reference(scopes,last_scope(scopes),name);return`(function(){ ${js}\n`+`return ${lambda_ref}\n})()`};function list_or_tuple_to_js(func,scopes){if(this.elts.filter((x=>x instanceof $B.ast.Starred)).length>0){var parts=[],simple=[];for(var elt of this.elts){if(elt instanceof $B.ast.Starred){elt.$handled=true;parts.push(`[${simple.join(", ")}]`);simple=[];parts.push(`_b_.list.$factory(${$B.js_from_ast(elt,scopes)})`)}else{simple.push($B.js_from_ast(elt,scopes))}}if(simple.length>0){parts.push(`[${simple.join(", ")}]`)}var js=parts[0];for(var part of parts.slice(1)){js+=`.concat(${part})`}return`${func}(${js})`}var elts=this.elts.map((x=>$B.js_from_ast(x,scopes)));return`${func}([${elts.join(", ")}])`}$B.ast.List.prototype.to_js=function(scopes){return list_or_tuple_to_js.bind(this)("$B.$list",scopes)};$B.ast.ListComp.prototype.to_js=function(scopes){compiler_check(this);return make_comp.bind(this)(scopes)};$B.ast.match_case.prototype.to_js=function(scopes){var js=`($B.set_lineno(frame, ${this.lineno}) && `+`$B.pattern_match(subject, {`+`${$B.js_from_ast(this.pattern,scopes)}})`;if(this.guard){js+=` && $B.$bool(${$B.js_from_ast(this.guard,scopes)})`}js+=`){\n`;js+=add_body(this.body,scopes)+"\n}";return js};function is_irrefutable(pattern){switch(pattern.constructor){case $B.ast.MatchAs:if(pattern.pattern===undefined){return pattern}else{return is_irrefutable(pattern.pattern)}case $B.ast.MatchOr:for(var i=0;i-1){compiler_error(this,`multiple assignment to name '${name}' in pattern`)}scope.bindings.push(name)}return params};$B.ast.MatchClass.prototype.to_js=function(scopes){var names=[];for(let pattern of this.patterns.concat(this.kwd_patterns)){let name=pattern.name;if(name){if(names.indexOf(name)>-1){compiler_error(pattern,`multiple assignment to name '${name}' in pattern`)}names.push(name)}}names=[];for(let i=0;i-1){compiler_error(this.kwd_patterns[i],`attribute name repeated in class pattern: ${kwd_attr}`)}names.push(kwd_attr)}var cls=$B.js_from_ast(this.cls,scopes),patterns=this.patterns.map((x=>`{${$B.js_from_ast(x,scopes)}}`));var kw=[];for(let i=0,len=this.kwd_patterns.length;i-1){compiler_error(pattern,`multiple assignments to name '${pattern.name}' in pattern`)}names.push(pattern.name)}}var items=[];for(let i=0,len=this.keys.length;i-1){compiler_error(pattern,`multiple assignments to name '${pattern.name}' in pattern`)}names.push(pattern.name)}items.push("{"+$B.js_from_ast(pattern,scopes)+"}")}return`sequence: [${items.join(", ")}]`};$B.ast.MatchSingleton.prototype.to_js=function(){var value=this.value===true?"_b_.True":this.value===false?"_b_.False":"_b_.None";return`literal: ${value}`};$B.ast.MatchStar.prototype.to_js=function(){var name=this.name===undefined?"_":this.name;return`capture_starred: '${name}'`};$B.ast.MatchValue.prototype.to_js=function(scopes){if(this.value instanceof $B.ast.Constant){return`literal: ${$B.js_from_ast(this.value,scopes)}`}else if(this.value instanceof $B.ast.Constant||this.value instanceof $B.ast.UnaryOp||this.value instanceof $B.ast.BinOp||this.value instanceof $B.ast.Attribute){return`value: ${$B.js_from_ast(this.value,scopes)}`}else{compiler_error(this,"patterns may only match literals and attribute lookups")}};$B.ast.Module.prototype.to_js=function(scopes){mark_parents(this);var name=init_scopes.bind(this)("module",scopes),namespaces=scopes.namespaces;var module_id=name,global_name=make_scope_name(scopes),mod_name=module_name(scopes);var js=`var $B = __BRYTHON__,\n_b_ = $B.builtins,\n`;if(!namespaces){js+=`${global_name} = $B.imported["${mod_name}"],\n`+`locals = ${global_name},\n`+`frame = ["${module_id}", locals, "${module_id}", locals]`}else{js+=`locals = ${namespaces.local_name},\n`+`globals = ${namespaces.global_name}`;if(name){let local_name=("locals_"+name).replace(/\./g,"_");js+=`,\n${local_name} = locals`}}js+=`\nvar __file__ = '${scopes.filename??""}'\n`+`locals.__name__ = '${name}'\n`+`locals.__doc__ = ${extract_docstring(this,scopes)}\n`;if(!scopes.imported){js+=`locals.__annotations__ = locals.__annotations__ || $B.empty_dict()\n`}if(!namespaces){js+=`$B.enter_frame(frame, __file__, 1)\n`;js+="\nvar _frame_obj = $B.frame_obj\n"}js+="var stack_length = $B.count_frames()\n";js+=`try{\n`+add_body(this.body,scopes)+"\n"+`$B.leave_frame({locals, value: _b_.None})\n`+`}catch(err){\n`+`$B.set_exc_and_trace(frame, err)\n`+`$B.leave_frame({locals, value: _b_.None})\n`+"throw err\n"+`}`;scopes.pop();return js};$B.ast.Name.prototype.to_js=function(scopes){if(this.ctx instanceof $B.ast.Store){var scope=bind(this.id,scopes);if(scope===$B.last(scopes)&&scope.freevars.has(this.id)){scope.freevars.delete(this.id)}return reference(scopes,scope,this.id)}else if(this.ctx instanceof $B.ast.Load){var res=name_reference(this.id,scopes,[this.col_offset,this.col_offset,this.end_col_offset]);if(this.id=="__debugger__"&&res.startsWith("$B.resolve_in_scopes")){return"debugger"}return res}};$B.ast.NamedExpr.prototype.to_js=function(scopes){compiler_check(this);var i=scopes.length-1;while(scopes[i].type=="comprehension"){i--}var enclosing_scopes=scopes.slice(0,i+1);enclosing_scopes.symtable=scopes.symtable;bind(this.target.id,enclosing_scopes);return"("+$B.js_from_ast(this.target,enclosing_scopes)+" = "+$B.js_from_ast(this.value,scopes)+")"};$B.ast.NamedExpr.prototype._check=function(){check_assign_or_delete(this,this.target)};$B.ast.Nonlocal.prototype.to_js=function(scopes){var scope=$B.last(scopes);for(var name of this.names){scope.nonlocals.add(name)}return""};$B.ast.Pass.prototype.to_js=function(){return`$B.set_lineno(frame, ${this.lineno})\n`+"void(0)"};$B.ast.Raise.prototype.to_js=function(scopes){var js=`$B.set_lineno(frame, ${this.lineno})\n`+"$B.$raise(";if(this.exc){js+=$B.js_from_ast(this.exc,scopes)}if(this.cause){js+=", "+$B.js_from_ast(this.cause,scopes)}return js+")"};$B.ast.Return.prototype.to_js=function(scopes){if(last_scope(scopes).type!="def"){compiler_error(this,"'return' outside function")}compiler_check(this);var js=`$B.set_lineno(frame, ${this.lineno})\n`+"var result = "+(this.value?$B.js_from_ast(this.value,scopes):" _b_.None")+"\n"+`$B.trace_return_and_leave(frame, result)\nreturn result\n`;return js};function remove_escapes(value){for(var key in $B.escape2cp){value=value.replace(new RegExp("\\\\"+key,"g"),$B.escape2cp[key])}return value}$B.ast.Set.prototype.to_js=function(scopes){var elts=[];for(var elt of this.elts){var js;if(elt instanceof $B.ast.Constant){var v=elt.value;if(typeof v=="string"){v=remove_escapes(v)}js=`{constant: [${$B.js_from_ast(elt,scopes)}, `+`${$B.$hash(v)}]}`}else if(elt instanceof $B.ast.Starred){js=`{starred: ${$B.js_from_ast(elt.value,scopes)}}`}else{js=`{item: ${$B.js_from_ast(elt,scopes)}}`}elts.push(js)}return`_b_.set.$literal([${elts.join(", ")}])`};$B.ast.SetComp.prototype.to_js=function(scopes){return make_comp.bind(this)(scopes)};$B.ast.Slice.prototype.to_js=function(scopes){var lower=this.lower?$B.js_from_ast(this.lower,scopes):"_b_.None",upper=this.upper?$B.js_from_ast(this.upper,scopes):"_b_.None",step=this.step?$B.js_from_ast(this.step,scopes):"_b_.None";return`_b_.slice.$fast_slice(${lower}, ${upper}, ${step})`};$B.ast.Starred.prototype.to_js=function(scopes){if(this.$handled){return`_b_.list.$unpack(${$B.js_from_ast(this.value,scopes)})`}if(this.ctx instanceof $B.ast.Store){compiler_error(this,"starred assignment target must be in a list or tuple")}else{compiler_error(this,"can't use starred expression here")}};$B.ast.Subscript.prototype.to_js=function(scopes){var value=$B.js_from_ast(this.value,scopes),slice=$B.js_from_ast(this.slice,scopes);if(this.slice instanceof $B.ast.Slice){return`$B.getitem_slice(${value}, ${slice})`}else{var position=encode_position(this.value.col_offset,this.slice.col_offset,this.slice.end_col_offset);return`$B.$getitem(${value}, ${slice},${position})`}};$B.ast.Try.prototype.to_js=function(scopes){compiler_check(this);var id=make_id(),has_except_handlers=this.handlers.length>0,has_else=this.orelse.length>0,has_finally=this.finalbody.length>0;var js=`$B.set_lineno(frame, ${this.lineno})\ntry{\n`;js+=`var stack_length_${id} = $B.count_frames()\n`;if(has_finally){js+=`var save_frame_obj_${id} = $B.frames_obj\n`}if(has_else){js+=`var failed${id} = false\n`}var try_scope=copy_scope($B.last(scopes));scopes.push(try_scope);js+=add_body(this.body,scopes)+"\n";if(has_except_handlers){var err="err"+id;js+="}\n";js+=`catch(${err}){\n`+`$B.set_exc_and_trace(frame, ${err})\n`;if(has_else){js+=`failed${id} = true\n`}var first=true,has_untyped_except=false;for(var handler of this.handlers){if(first){js+="if";first=false}else{js+="}else if"}js+=`($B.set_lineno(frame, ${handler.lineno})`;if(handler.type){js+=` && $B.is_exc(${err}, `;if(handler.type instanceof $B.ast.Tuple){js+=`${$B.js_from_ast(handler.type,scopes)}`}else{js+=`[${$B.js_from_ast(handler.type,scopes)}]`}js+=`)){\n`}else{has_untyped_except=true;js+="){\n"}if(handler.name){bind(handler.name,scopes);var mangled=mangle(scopes,try_scope,handler.name);js+=`locals.${mangled} = ${err}\n`}js+=add_body(handler.body,scopes)+"\n";if(!($B.last(handler.body)instanceof $B.ast.Return)){js+="$B.del_exc(frame)\n"}}if(!has_untyped_except){js+=`}else{\nthrow ${err}\n`}js+="}\n"}if(has_else||has_finally){js+="}\n";js+="finally{\n";var finalbody=`var exit = false\n`+`if($B.count_frames() < stack_length_${id}){\n`+`exit = true\n`+`$B.frame_obj = $B.push_frame(frame)\n`+`}\n`+add_body(this.finalbody,scopes);if(this.finalbody.length>0&&!($B.last(this.finalbody)instanceof $B.ast.Return)){finalbody+=`\nif(exit){\n`+`$B.leave_frame()\n`+`}`}var elsebody=`if($B.count_frames() == stack_length_${id} `+`&& ! failed${id}){\n`+add_body(this.orelse,scopes)+"\n}";if(has_else&&has_finally){js+=`try{\n`+elsebody+"\n}\n"+`finally{\n`+finalbody+"}\n"}else if(has_else&&!has_finally){js+=elsebody}else{js+=finalbody}js+="\n}\n"}else{js+="}\n"}scopes.pop();return js};$B.ast.TryStar.prototype.to_js=function(scopes){var id=make_id(),has_except_handlers=this.handlers.length>0,has_else=this.orelse.length>0,has_finally=this.finalbody.length>0;var js=`$B.set_lineno(frame, ${this.lineno})\ntry{\n`;js+=`var stack_length_${id} = $B.count_frames()\n`;if(has_finally){js+=`var save_frame_obj_${id} = $B.frame_obj\n`}if(has_else){js+=`var failed${id} = false\n`}var try_scope=copy_scope($B.last(scopes));scopes.push(try_scope);js+=add_body(this.body,scopes)+"\n";if(has_except_handlers){var err="err"+id;js+="}\n";js+=`catch(${err}){\n`+`$B.set_exc_and_trace(frame, ${err})\n`+`if(! $B.$isinstance(${err}, _b_.BaseExceptionGroup)){\n`+`${err} = _b_.BaseExceptionGroup.$factory(_b_.None, [${err}])\n`+"}\n"+`function fake_split(exc, condition){\n`+`return condition(exc) ? `+`$B.fast_tuple([exc, _b_.None]) : $B.fast_tuple([_b_.None, exc])\n`+"}\n";if(has_else){js+=`failed${id} = true\n`}for(var handler of this.handlers){js+=`$B.set_lineno(frame, ${handler.lineno})\n`;if(handler.type){js+="var condition = function(exc){\n"+" return $B.$isinstance(exc, "+`${$B.js_from_ast(handler.type,scopes)})\n`+"}\n"+`var klass = $B.get_class(${err}),\n`+`split_method = $B.$getattr(klass, 'split'),\n`+`split = $B.$call(split_method)(${err}, condition),\n`+" matching = split[0],\n"+" rest = split[1]\n"+"if(matching.exceptions !== _b_.None){\n"+" for(var err of matching.exceptions){\n";if(handler.name){bind(handler.name,scopes);var mangled=mangle(scopes,try_scope,handler.name);js+=`locals.${mangled} = ${err}\n`}js+=add_body(handler.body,scopes)+"\n";if(!($B.last(handler.body)instanceof $B.ast.Return)){js+="$B.del_exc(frame)\n"}js+="}\n";js+="}\n";js+=`${err} = rest\n`}}js+=`if(${err}.exceptions !== _b_.None){\n`+`throw ${err}\n`+"}\n"}if(has_else||has_finally){js+="}\n";js+="finally{\n";var finalbody=`var exit = false\n`+`if($B.count_frames() < stack_length_${id}){\n`+`exit = true\n`+`$B.frame_obj = $B.push_frame(frame)\n`+`}\n`+add_body(this.finalbody,scopes);if(this.finalbody.length>0&&!($B.last(this.finalbody)instanceof $B.ast.Return)){finalbody+=`\nif(exit){\n`+`$B.leave_frame(locals)\n`+`}`}var elsebody=`if($B.count_frames() == stack_length_${id} `+`&& ! failed${id}){\n`+add_body(this.orelse,scopes)+"\n}";if(has_else&&has_finally){js+=`try{\n`+elsebody+"\n}\n"+`finally{\n`+finalbody+"}\n"}else if(has_else&&!has_finally){js+=elsebody}else{js+=finalbody}js+="\n}\n"}else{js+="}\n"}scopes.pop();return js};$B.ast.Tuple.prototype.to_js=function(scopes){return list_or_tuple_to_js.bind(this)("$B.fast_tuple",scopes)};$B.ast.TypeAlias.prototype.to_js=function(scopes){var type_param_scope=new Scope("type_params","type_params",this.type_params);scopes.push(type_param_scope);var type_alias_scope=new Scope("type_alias","type_alias",this);scopes.push(type_alias_scope);var type_params_names=[];check_type_params(this);for(var type_param of this.type_params){if(type_param instanceof $B.ast.TypeVar){type_params_names.push(type_param.name)}else if(type_param instanceof $B.ast.TypeVarTuple||type_param instanceof $B.ast.ParamSpec){type_params_names.push(type_param.name.id)}}for(var name of type_params_names){bind(name,scopes)}var qualified_name=qualified_scope_name(scopes,type_alias_scope);var value=this.value.to_js(scopes);scopes.pop();scopes.pop();var js=`$B.$import('_typing')\n`;js+=`var locals_${qualified_scope_name(scopes,type_param_scope)} = {}\n`;js+=`function TYPE_PARAMS_OF_${this.name.id}(){\n`+`var locals_${qualified_name} = {},\n`+` locals = locals_${qualified_name}, \n`+` type_params = $B.fast_tuple([])\n`;for(var i=0,len=this.type_params.length;i0){js+=`\nif(no_break_${id}){\n`+add_body(this.orelse,scopes)+"}\n"}return js};$B.ast.With.prototype.to_js=function(scopes){function add_item(item,js){var id=make_id();var s=`var mgr_${id} = `+$B.js_from_ast(item.context_expr,scopes)+",\n"+`klass = $B.get_class(mgr_${id})\n`+`try{\n`+`var exit_${id} = $B.$getattr(klass, '__exit__'),\n`+`enter_${id} = $B.$getattr(klass, '__enter__')\n`+`}catch(err){\n`+`var klass_name = $B.class_name(mgr_${id})\n`+`throw _b_.TypeError.$factory("'" + klass_name + `+`"' object does not support the con`+`text manager protocol")\n`+`}\n`+`var value_${id} = $B.$call(enter_${id})(mgr_${id}),\n`+`exc_${id} = true\n`;if(in_generator){s+=`locals.$context_managers = locals.$context_managers || []\n`+`locals.$context_managers.push(mgr_${id})\n`}s+="try{\ntry{\n";if(item.optional_vars){var value={to_js:function(){return`value_${id}`}};copy_position(value,_with);var assign=new $B.ast.Assign([item.optional_vars],value);copy_position(assign,_with);s+=assign.to_js(scopes)+"\n"}s+=js;s+=`}catch(err_${id}){\n`+`frame.$lineno = ${lineno}\n`+`exc_${id} = false\n`+`err_${id} = $B.exception(err_${id}, frame)\n`+`var $b = exit_${id}(mgr_${id}, err_${id}.__class__, `+`err_${id}, $B.$getattr(err_${id}, '__traceback__'))\n`+`if(! $B.$bool($b)){\n`+`throw err_${id}\n`+`}\n`+`}\n`;s+=`}\nfinally{\n`+`frame.$lineno = ${lineno}\n`+(in_generator?`locals.$context_managers.pop()\n`:"")+`if(exc_${id}){\n`+`try{\n`+`exit_${id}(mgr_${id}, _b_.None, _b_.None, _b_.None)\n`+`}catch(err){\n`+`if($B.count_frames() < stack_length){\n`+`$B.frame_obj = $B.push_frame(frame)\n`+`}\n`+`throw err\n`+`}\n`+`}\n`+`}\n`;return s}var _with=this,scope=last_scope(scopes),lineno=this.lineno;scope.needs_stack_length=true;var js=add_body(this.body,scopes)+"\n";var in_generator=scopes.symtable.table.blocks.get(fast_id(scope.ast)).generator;for(var item of this.items.slice().reverse()){js=add_item(item,js)}return`$B.set_lineno(frame, ${this.lineno})\n`+js};$B.ast.Yield.prototype.to_js=function(scopes){var scope=last_scope(scopes);if(scope.type!="def"){compiler_error(this,"'yield' outside function")}last_scope(scopes).is_generator=true;var value=this.value?$B.js_from_ast(this.value,scopes):"_b_.None";return`yield ${value}`};$B.ast.YieldFrom.prototype.to_js=function(scopes){var scope=last_scope(scopes);if(scope.type!="def"){compiler_error(this,"'yield' outside function")}scope.is_generator=true;var value=$B.js_from_ast(this.value,scopes);var n=make_id();return`yield* (function* f(){\n var _i${n} = _b_.iter(${value}),\n _r${n}\n var failed${n} = false\n try{\n var _y${n} = _b_.next(_i${n})\n }catch(_e){\n $B.set_exc(_e, frame)\n failed${n} = true\n $B.pmframe = $B.frame_obj.frame\n _e = $B.exception(_e)\n if(_e.__class__ === _b_.StopIteration){\n var _r${n} = $B.$getattr(_e, "value")\n }else{\n throw _e\n }\n }\n if(! failed${n}){\n while(true){\n var failed1${n} = false\n try{\n $B.leave_frame()\n var _s${n} = yield _y${n}\n $B.frame_obj = $B.push_frame(frame)\n }catch(_e){\n $B.set_exc(_e, frame)\n if(_e.__class__ === _b_.GeneratorExit){\n var failed2${n} = false\n try{\n var _m${n} = $B.$getattr(_i${n}, "close")\n }catch(_e1){\n failed2${n} = true\n if(_e1.__class__ !== _b_.AttributeError){\n throw _e1\n }\n }\n if(! failed2${n}){\n $B.$call(_m${n})()\n }\n throw _e\n }else if($B.is_exc(_e, [_b_.BaseException])){\n var sys_module = $B.imported._sys,\n _x${n} = sys_module.exc_info()\n var failed3${n} = false\n try{\n var _m${n} = $B.$getattr(_i${n}, "throw")\n }catch(err){\n failed3${n} = true\n if($B.is_exc(err, [_b_.AttributeError])){\n throw err\n }\n }\n if(! failed3${n}){\n try{\n _y${n} = $B.$call(_m${n}).apply(null,\n _b_.list.$factory(_x${n}))\n }catch(err){\n if($B.is_exc(err, [_b_.StopIteration])){\n _r${n} = $B.$getattr(err, "value")\n break\n }\n throw err\n }\n }\n }\n }\n if(! failed1${n}){\n try{\n if(_s${n} === _b_.None){\n _y${n} = _b_.next(_i${n})\n }else{\n _y${n} = $B.$call($B.$getattr(_i${n}, "send"))(_s${n})\n }\n }catch(err){\n if($B.is_exc(err, [_b_.StopIteration])){\n _r${n} = $B.$getattr(err, "value")\n break\n }\n throw err\n }\n }\n }\n }\n return _r${n}\n })()`};var state={};$B.js_from_root=function(arg){var ast_root=arg.ast,symtable=arg.symtable,filename=arg.filename,src=arg.src,namespaces=arg.namespaces,imported=arg.imported;if($B.show_ast_dump){console.log($B.ast_dump(ast_root))}if($B.compiler_check){$B.compiler_check(ast_root,symtable)}var scopes=[];state.filename=filename;scopes.symtable=symtable;scopes.filename=filename;scopes.src=src;scopes.namespaces=namespaces;scopes.imported=imported;scopes.imports={};var js=ast_root.to_js(scopes);return{js:js,imports:scopes.imports}};$B.js_from_ast=function(ast,scopes){if(!scopes.symtable){throw Error("perdu symtable")}scopes=scopes||[];if(ast.to_js!==undefined){if(ast.col_offset===undefined){var klass=ast.constructor.$name;if(["match_case"].indexOf(klass)==-1){console.log("no col_offset for",klass);console.log(ast);throw Error("no col offset")}}return ast.to_js(scopes)}console.log("unhandled",ast.constructor.$name,ast,typeof ast);return"// unhandled class ast."+ast.constructor.$name}})(__BRYTHON__);(function($B){var _b_=$B.builtins;var GLOBAL_PARAM="name '%s' is parameter and global",NONLOCAL_PARAM="name '%s' is parameter and nonlocal",GLOBAL_AFTER_ASSIGN="name '%s' is assigned to before global declaration",NONLOCAL_AFTER_ASSIGN="name '%s' is assigned to before nonlocal declaration",GLOBAL_AFTER_USE="name '%s' is used prior to global declaration",NONLOCAL_AFTER_USE="name '%s' is used prior to nonlocal declaration",GLOBAL_ANNOT="annotated name '%s' can't be global",NONLOCAL_ANNOT="annotated name '%s' can't be nonlocal",IMPORT_STAR_WARNING="import * only allowed at module level",NAMED_EXPR_COMP_IN_CLASS="assignment expression within a comprehension cannot be used in a class body",NAMED_EXPR_COMP_CONFLICT="assignment expression cannot rebind comprehension iteration variable '%s'",NAMED_EXPR_COMP_INNER_LOOP_CONFLICT="comprehension inner loop cannot rebind assignment expression target '%s'",NAMED_EXPR_COMP_ITER_EXPR="assignment expression cannot be used in a comprehension iterable expression",ANNOTATION_NOT_ALLOWED="'%s' can not be used within an annotation",DUPLICATE_ARGUMENT="duplicate argument '%s' in function definition",TYPEVAR_BOUND_NOT_ALLOWED="%s cannot be used within a TypeVar bound",TYPEALIAS_NOT_ALLOWED="%s cannot be used within a type alias",TYPEPARAM_NOT_ALLOWED="%s cannot be used within the definition of a generic",DUPLICATE_TYPE_PARAM="duplicate type parameter '%s'";var SF=$B.SYMBOL_FLAGS;var NULL=undefined;var ModuleBlock=2,ClassBlock=1,FunctionBlock=0,AnnotationBlock=4,TypeVarBoundBlock=5,TypeAliasBlock=6,TypeParamBlock=7;var PyExc_SyntaxError=_b_.SyntaxError;function assert(test){if(!$B.$bool(test)){console.log("test fails",test);throw Error("test fails")}}function LOCATION(x){return[x.lineno,x.col_offset,x.end_lineno,x.end_col_offset]}function ST_LOCATION(x){return[x.lineno,x.col_offset,x.end_lineno,x.end_col_offset]}function _Py_Mangle(privateobj,ident){var plen,ipriv;if(privateobj==NULL||!ident.startsWith("__")){return ident}plen=privateobj.length;if(ident.endsWith("__")||ident.search(/\./)!=-1){return ident}ipriv=0;while(privateobj[ipriv]=="_"){ipriv++}if(ipriv==plen){return ident}var prefix=privateobj.substr(ipriv);return"_"+prefix+ident}var lambda=NULL;var NoComprehension=0,ListComprehension=1,DictComprehension=2,SetComprehension=3,GeneratorExpression=4;function GET_IDENTIFIER(VAR){return VAR}function Symtable(){this.filename=NULL;this.stack=[];this.blocks=new Map;this.cur=NULL;this.private=NULL}function id(obj){if(obj.$id!==undefined){return obj.$id}return obj.$id=$B.UUID()}function ste_new(st,name,block,key,lineno,col_offset,end_lineno,end_col_offset){var ste;ste={table:st,id:id(key),name:name,directives:NULL,type:block,nested:0,free:0,varargs:0,varkeywords:0,opt_lineno:0,opt_col_offset:0,lineno:lineno,col_offset:col_offset,end_lineno:end_lineno,end_col_offset:end_col_offset};if(st.cur!=NULL&&(st.cur.nested||st.cur.type==FunctionBlock)){ste.nested=1}ste.child_free=0;ste.generator=0;ste.coroutine=0;ste.comprehension=NoComprehension;ste.returns_value=0;ste.needs_class_closure=0;ste.comp_inlined=0;ste.comp_iter_target=0;ste.comp_iter_expr=0;ste.symbols=$B.empty_dict();ste.varnames=[];ste.children=[];st.blocks.set(ste.id,ste);return ste}$B._PySymtable_Build=function(mod,filename,future){var st=new Symtable,seq;st.filename=filename;st.future=future||{};st.type=SF.TYPE_MODULE;if(!symtable_enter_block(st,"top",ModuleBlock,mod,0,0,0,0)){return NULL}st.top=st.cur;switch(mod.constructor){case $B.ast.Module:seq=mod.body;for(let item of seq){visitor.stmt(st,item)}break;case $B.ast.Expression:visitor.expr(st,mod.body);break;case $B.ast.Interactive:seq=mod.body;for(let item of seq){visitor.stmt(st,item)}break}symtable_analyze(st);return st.top};function _PyST_GetSymbol(ste,name){if(!_b_.dict.$contains_string(ste.symbols,name)){return 0}return _b_.dict.$getitem_string(ste.symbols,name)}function _PyST_GetScope(ste,name){var symbol=_PyST_GetSymbol(ste,name);return symbol>>SF.SCOPE_OFFSET&SF.SCOPE_MASK}function _PyST_IsFunctionLike(ste){return ste.type==FunctionBlock||ste.type==TypeVarBoundBlock||ste.type==TypeAliasBlock||ste.type==TypeParamBlock}function PyErr_Format(exc_type,message,arg){if(arg){message=_b_.str.__mod__(message,arg)}return exc_type.$factory(message)}function PyErr_SetString(exc_type,message){return exc_type.$factory(message)}function set_exc_info(exc,filename,lineno,offset,end_lineno,end_offset){exc.filename=filename;exc.lineno=lineno;exc.offset=offset+1;exc.end_lineno=end_lineno;exc.end_offset=end_offset+1;var src=$B.file_cache[filename];if(src!==undefined){var lines=src.split("\n");exc.text=lines[lineno-1]}else{exc.text=""}exc.args[1]=[filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]}function error_at_directive(exc,ste,name){assert(ste.directives);for(var data of ste.directives){if(data[0]==name){set_exc_info(exc,ste.table.filename,data[1],data[2],data[3],data[4]);return 0}}throw _b_.RuntimeError.$factory("BUG: internal directive bookkeeping broken")}function SET_SCOPE(DICT,NAME,I){DICT[NAME]=I}function is_free_in_any_child(entry,key){for(var child_ste of entry.ste_children){var scope=_PyST_GetScope(child_ste,key);if(scope==SF.FREE){return 1}}return 0}function inline_comprehension(ste,comp,scopes,comp_free,inlined_cells){for(var item of _b_.dict.$iter_items(comp.symbols)){var k=item.key,comp_flags=item.value;if(comp_flags&SF.DEF_PARAM){continue}var scope=comp_flags>>SF.SCOPE_OFFSET&SF.SCOPE_MASK;var only_flags=comp_flags&(1<=0;i--){let entry=ste.children[i];if(entry.comp_inlined){ste.children.splice(i,0,...entry.children)}}if(_PyST_IsFunctionLike(ste)&&!analyze_cells(scopes,newfree,inlined_cells)){return 0}else if(ste.type===ClassBlock&&!drop_class_free(ste,newfree)){return 0}if(!update_symbols(ste.symbols,scopes,bound,newfree,inlined_cells,ste.type===ClassBlock||ste.can_see_class_scope)){return 0}Set_Union(free,newfree);success=1;return success}function PySet_New(arg){if(arg===NULL){return new Set}return new Set(arg)}function Set_Union(setA,setB){for(let elem of setB){setA.add(elem)}}function analyze_child_block(entry,bound,free,global,typeparams,class_entry,child_free){var temp_bound=PySet_New(bound),temp_free=PySet_New(free),temp_global=PySet_New(global),temp_typeparams=PySet_New(typeparams);if(!analyze_block(entry,temp_bound,temp_free,temp_global,temp_typeparams,class_entry)){return 0}Set_Union(child_free,temp_free);return 1}function symtable_analyze(st){var free=new Set,global=new Set,typeparams=new Set;return analyze_block(st.top,NULL,free,global,typeparams,NULL)}function symtable_exit_block(st){var size=st.stack.length;st.cur=NULL;if(size){st.stack.pop();if(--size){st.cur=st.stack[size-1]}}return 1}function symtable_enter_block(st,name,block,ast,lineno,col_offset,end_lineno,end_col_offset){var prev;if(ast===undefined){console.log("call ste new, key undef",st,name)}var ste=ste_new(st,name,block,ast,lineno,col_offset,end_lineno,end_col_offset);st.stack.push(ste);prev=st.cur;if(prev){ste.comp_iter_expr=prev.comp_iter_expr}st.cur=ste;if(block===AnnotationBlock){return 1}if(block===ModuleBlock){st.global=st.cur.symbols}if(prev){prev.children.push(ste)}return 1}function symtable_lookup(st,name){var mangled=_Py_Mangle(st.private,name);if(!mangled){return 0}var ret=_PyST_GetSymbol(st.cur,mangled);return ret}function symtable_add_def_helper(st,name,flag,ste,_location){var o,dict,val,mangled=_Py_Mangle(st.private,name);if(!mangled){return 0}dict=ste.symbols;if(_b_.dict.$contains_string(dict,mangled)){o=_b_.dict.$getitem_string(dict,mangled);val=o;if(flag&SF.DEF_PARAM&&val&SF.DEF_PARAM){let exc=PyErr_Format(_b_.SyntaxError,DUPLICATE_ARGUMENT,name);set_exc_info(exc,st.filename,..._location);throw exc}if(flag&SF.DEF_TYPE_PARAM&&val&SF.DEF_TYPE_PARAM){let exc=PyErr_Format(_b_.SyntaxError,DUPLICATE_TYPE_PARAM,name);set_exc_info(exc,st.filename,...location);throw exc}val|=flag}else{val=flag}if(ste.comp_iter_target){if(val&(SF.DEF_GLOBAL|SF.DEF_NONLOCAL)){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_INNER_LOOP_CONFLICT,name);set_exc_info(exc,st.filename,..._location);throw exc}val|=SF.DEF_COMP_ITER}o=val;if(o==NULL){return 0}_b_.dict.$setitem(dict,mangled,o);if(flag&SF.DEF_PARAM){ste.varnames.push(mangled)}else if(flag&SF.DEF_GLOBAL){val=flag;if(st.global.hasOwnProperty(mangled)){val|=st.global[mangled]}o=val;if(o==NULL){return 0}st.global[mangled]=o}return 1}function symtable_add_def(st,name,flag,_location){return symtable_add_def_helper(st,name,flag,st.cur,_location)}function symtable_enter_type_param_block(st,name,ast,has_defaults,has_kwdefaults,kind,_location){var prev=st.cur,current_type=st.cur.type;if(!symtable_enter_block(st,name,TypeParamBlock,ast,..._location)){return 0}prev.$type_param=st.cur;if(current_type===ClassBlock){st.cur.can_see_class_scope=1;if(!symtable_add_def(st,"__classdict__",SF.USE,_location)){return 0}}if(kind==$B.ast.ClassDef){if(!symtable_add_def(st,"type_params",SF.DEF_LOCAL,_location)){return 0}if(!symtable_add_def(st,"type_params",SF.USE,_location)){return 0}st.st_private=name;var generic_base=".generic_base";if(!symtable_add_def(st,generic_base,SF.DEF_LOCAL,_location)){return 0}if(!symtable_add_def(st,generic_base,SF.USE,_location)){return 0}}if(has_defaults){var defaults=".defaults";if(!symtable_add_def(st,defaults,SF.DEF_PARAM,_location)){return 0}}if(has_kwdefaults){var kwdefaults=".kwdefaults";if(!symtable_add_def(st,kwdefaults,SF.DEF_PARAM,_location)){return 0}}return 1}function VISIT_QUIT(ST,X){return X}function VISIT(ST,TYPE,V){var f=visitor[TYPE];if(!f(ST,V)){VISIT_QUIT(ST,0)}}function VISIT_SEQ(ST,TYPE,SEQ){for(var elt of SEQ){if(!visitor[TYPE](ST,elt)){VISIT_QUIT(ST,0)}}}function VISIT_SEQ_TAIL(ST,TYPE,SEQ,START){for(var i=START,len=SEQ.length;i0){if(!symtable_enter_type_param_block(st,s.name,s.type_params,s.args.defaults!=NULL,has_kwonlydefaults(s.args.kwonlyargs,s.args.kw_defaults),s.constructor,LOCATION(s))){VISIT_QUIT(st,0)}VISIT_SEQ(st,type_param,s.type_params)}if(!visitor.annotations(st,s,s.args,s.returns))VISIT_QUIT(st,0);if(s.decorator_list){VISIT_SEQ(st,expr,s.decorator_list)}if(!symtable_enter_block(st,s.name,FunctionBlock,s,...LOCATION(s))){VISIT_QUIT(st,0)}VISIT(st,"arguments",s.args);VISIT_SEQ(st,stmt,s.body);if(!symtable_exit_block(st)){VISIT_QUIT(st,0)}if(s.type_params.length>0){if(!symtable_exit_block(st)){VISIT_QUIT(st,0)}}break;case $B.ast.ClassDef:var tmp;if(!symtable_add_def(st,s.name,SF.DEF_LOCAL,LOCATION(s)))VISIT_QUIT(st,0);VISIT_SEQ(st,expr,s.bases);VISIT_SEQ(st,keyword,s.keywords);if(s.decorator_list)VISIT_SEQ(st,expr,s.decorator_list);if(s.type_params.length>0){if(!symtable_enter_type_param_block(st,s.name,s.type_params,false,false,s.constructor,LOCATION(s))){VISIT_QUIT(st,0)}VISIT_SEQ(st,type_param,s.type_params)}VISIT_SEQ(st,expr,s.bases);VISIT_SEQ(st,keyword,s.keywords);if(!symtable_enter_block(st,s.name,ClassBlock,s,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset))VISIT_QUIT(st,0);tmp=st.private;st.private=s.name;if(s.type_params.length>0){if(!symtable_add_def(st,"__type_params__",SF.DEF_LOCAL,LOCATION(s))){VISIT_QUIT(st,0)}if(!symtable_add_def(st,"type_params",SF.USE,LOCATION(s))){VISIT_QUIT(st,0)}}VISIT_SEQ(st,stmt,s.body);st.private=tmp;if(!symtable_exit_block(st))VISIT_QUIT(st,0);if(s.type_params.length>0){if(!symtable_exit_block(st))VISIT_QUIT(st,0)}break;case $B.ast.TypeAlias:VISIT(st,expr,s.name);assert(s.name instanceof $B.ast.Name);var name=s.name.id,is_in_class=st.cur.type===ClassBlock,is_generic=s.type_params.length>0;if(is_generic){if(!symtable_enter_type_param_block(st,name,s.type_params,false,false,s.kind,LOCATION(s))){VISIT_QUIT(st,0)}VISIT_SEQ(st,type_param,s.type_params)}if(!symtable_enter_block(st,name,TypeAliasBlock,s,LOCATION(s))){VISIT_QUIT(st,0)}st.cur.can_see_class_scope=is_in_class;if(is_in_class&&!symtable_add_def(st,"__classdict__",SF.USE,LOCATION(s.value))){VISIT_QUIT(st,0)}VISIT(st,expr,s.value);if(!symtable_exit_block(st)){VISIT_QUIT(st,0)}if(is_generic){if(!symtable_exit_block(st))VISIT_QUIT(st,0)}break;case $B.ast.Return:if(s.value){VISIT(st,expr,s.value);st.cur.returns_value=1}break;case $B.ast.Delete:VISIT_SEQ(st,expr,s.targets);break;case $B.ast.Assign:VISIT_SEQ(st,expr,s.targets);VISIT(st,expr,s.value);break;case $B.ast.AnnAssign:if(s.target instanceof $B.ast.Name){var e_name=s.target;var cur=symtable_lookup(st,e_name.id);if(cur<0){VISIT_QUIT(st,0)}if(cur&(SF.DEF_GLOBAL|SF.DEF_NONLOCAL)&&st.cur.symbols!=st.global&&s.simple){var exc=PyErr_Format(_b_.SyntaxError,cur&SF.DEF_GLOBAL?GLOBAL_ANNOT:NONLOCAL_ANNOT,e_name.id);exc.args[1]=[st.filename,s.lineno,s.col_offset+1,s.end_lineno,s.end_col_offset+1];throw exc}if(s.simple&&!symtable_add_def(st,e_name.id,SF.DEF_ANNOT|SF.DEF_LOCAL,LOCATION(e_name))){VISIT_QUIT(st,0)}else{if(s.value&&!symtable_add_def(st,e_name.id,SF.DEF_LOCAL,LOCATION(e_name))){VISIT_QUIT(st,0)}}}else{VISIT(st,expr,s.target)}if(!visitor.annotation(st,s.annotation)){VISIT_QUIT(st,0)}if(s.value){VISIT(st,expr,s.value)}break;case $B.ast.AugAssign:VISIT(st,expr,s.target);VISIT(st,expr,s.value);break;case $B.ast.For:VISIT(st,expr,s.target);VISIT(st,expr,s.iter);VISIT_SEQ(st,stmt,s.body);if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)}break;case $B.ast.While:VISIT(st,expr,s.test);VISIT_SEQ(st,stmt,s.body);if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)}break;case $B.ast.If:VISIT(st,expr,s.test);VISIT_SEQ(st,stmt,s.body);if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)}break;case $B.ast.Match:VISIT(st,expr,s.subject);VISIT_SEQ(st,match_case,s.cases);break;case $B.ast.Raise:if(s.exc){VISIT(st,expr,s.exc);if(s.cause){VISIT(st,expr,s.cause)}}break;case $B.ast.Try:VISIT_SEQ(st,stmt,s.body);VISIT_SEQ(st,excepthandler,s.handlers);VISIT_SEQ(st,stmt,s.orelse);VISIT_SEQ(st,stmt,s.finalbody);break;case $B.ast.TryStar:VISIT_SEQ(st,stmt,s.body);VISIT_SEQ(st,stmt,s.orelse);VISIT_SEQ(st,excepthandler,s.handlers);VISIT_SEQ(st,stmt,s.finalbody);break;case $B.ast.Assert:VISIT(st,expr,s.test);if(s.msg){VISIT(st,expr,s.msg)}break;case $B.ast.Import:VISIT_SEQ(st,alias,s.names);break;case $B.ast.ImportFrom:VISIT_SEQ(st,alias,s.names);break;case $B.ast.Global:var seq=s.names;for(var name of seq){var cur=symtable_lookup(st,name);if(cur<0){VISIT_QUIT(st,0)}if(cur&(SF.DEF_PARAM|SF.DEF_LOCAL|SF.USE|SF.DEF_ANNOT)){var msg;if(cur&SF.DEF_PARAM){msg=GLOBAL_PARAM}else if(cur&SF.USE){msg=GLOBAL_AFTER_USE}else if(cur&SF.DEF_ANNOT){msg=GLOBAL_ANNOT}else{msg=GLOBAL_AFTER_ASSIGN}var exc=PyErr_Format(_b_.SyntaxError,msg,name);set_exc_info(exc,st.filename,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset);throw exc}if(!symtable_add_def(st,name,SF.DEF_GLOBAL,LOCATION(s)))VISIT_QUIT(st,0);if(!symtable_record_directive(st,name,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset))VISIT_QUIT(st,0)}break;case $B.ast.Nonlocal:var seq=s.names;for(var name of seq){var cur=symtable_lookup(st,name);if(cur<0){VISIT_QUIT(st,0)}if(cur&(SF.DEF_PARAM|SF.DEF_LOCAL|SF.USE|SF.DEF_ANNOT)){var msg;if(cur&SF.DEF_PARAM){msg=NONLOCAL_PARAM}else if(cur&SF.USE){msg=NONLOCAL_AFTER_USE}else if(cur&SF.DEF_ANNOT){msg=NONLOCAL_ANNOT}else{msg=NONLOCAL_AFTER_ASSIGN}var exc=PyErr_Format(_b_.SyntaxError,msg,name);set_exc_info(exc,st.filename,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset);throw exc}if(!symtable_add_def(st,name,SF.DEF_NONLOCAL,LOCATION(s)))VISIT_QUIT(st,0);if(!symtable_record_directive(st,name,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset))VISIT_QUIT(st,0)}break;case $B.ast.Expr:VISIT(st,expr,s.value);break;case $B.ast.Pass:case $B.ast.Break:case $B.ast.Continue:break;case $B.ast.With:VISIT_SEQ(st,"withitem",s.items);VISIT_SEQ(st,stmt,s.body);break;case $B.ast.AsyncFunctionDef:if(!symtable_add_def(st,s.name,SF.DEF_LOCAL,LOCATION(s)))VISIT_QUIT(st,0);if(s.args.defaults)VISIT_SEQ(st,expr,s.args.defaults);if(s.args.kw_defaults)VISIT_SEQ_WITH_NULL(st,expr,s.args.kw_defaults);if(!visitor.annotations(st,s,s.args,s.returns))VISIT_QUIT(st,0);if(s.decorator_list)VISIT_SEQ(st,expr,s.decorator_list);if(s.type_params.length>0){if(!symtable_enter_type_param_block(st,s.name,s.type_params,s.args.defaults!=NULL,has_kwonlydefaults(s.args.kwonlyargs,s.args.kw_defaults),s.constructor,LOCATION(s))){VISIT_QUIT(st,0)}VISIT_SEQ(st,type_param,s.type_params)}if(!visitor.annotations(st,s,s.args,s.returns))VISIT_QUIT(st,0);if(!symtable_enter_block(st,s.name,FunctionBlock,s,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset))VISIT_QUIT(st,0);st.cur.coroutine=1;VISIT(st,"arguments",s.args);VISIT_SEQ(st,stmt,s.body);if(!symtable_exit_block(st))VISIT_QUIT(st,0);if(s.type_params.length>0){if(!symtable_exit_block(st))VISIT_QUIT(st,0)}break;case $B.ast.AsyncWith:VISIT_SEQ(st,withitem,s.items);VISIT_SEQ(st,stmt,s.body);break;case $B.ast.AsyncFor:VISIT(st,expr,s.target);VISIT(st,expr,s.iter);VISIT_SEQ(st,stmt,s.body);if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)}break;default:console.log("unhandled",s);break}VISIT_QUIT(st,1)};function symtable_extend_namedexpr_scope(st,e){assert(st.stack);assert(e instanceof $B.ast.Name);var target_name=e.id;var i,size,ste;size=st.stack.length;assert(size);for(i=size-1;i>=0;i--){ste=st.stack[i];if(ste.comprehension){let target_in_scope=_PyST_GetSymbol(ste,target_name);if(target_in_scope&SF.DEF_COMP_ITER){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_CONFLICT,target_name);set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.ed_lineno,e.end_col_offset);throw exc}continue}if(_PyST_IsFunctionLike(ste)){let target_in_scope=_PyST_GetSymbol(ste,target_name);if(target_in_scope&SF.DEF_GLOBAL){if(!symtable_add_def(st,target_name,SF.DEF_GLOBAL,LOCATION(e)))VISIT_QUIT(st,0)}else{if(!symtable_add_def(st,target_name,SF.DEF_NONLOCAL,LOCATION(e)))VISIT_QUIT(st,0)}if(!symtable_record_directive(st,target_name,LOCATION(e)))VISIT_QUIT(st,0);return symtable_add_def_helper(st,target_name,SF.DEF_LOCAL,ste,LOCATION(e))}if(ste.type==ModuleBlock){if(!symtable_add_def(st,target_name,SF.DEF_GLOBAL,LOCATION(e)))VISIT_QUIT(st,0);if(!symtable_record_directive(st,target_name,LOCATION(e)))VISIT_QUIT(st,0);return symtable_add_def_helper(st,target_name,SF.DEF_GLOBAL,ste,LOCATION(e))}if(ste.type==ClassBlock){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_IN_CLASS);set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset);throw exc}}assert(0);return 0}function symtable_handle_namedexpr(st,e){if(st.cur.comp_iter_expr>0){var exc=PyErr_Format(PyExc_SyntaxError,NAMED_EXPR_COMP_ITER_EXPR);set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset);throw exc}if(st.cur.comprehension){if(!symtable_extend_namedexpr_scope(st,e.target))return 0}VISIT(st,expr,e.value);VISIT(st,expr,e.target);return 1}const alias="alias",comprehension="comprehension",excepthandler="excepthandler",expr="expr",keyword="keyword",match_case="match_case",pattern="pattern",stmt="stmt",type_param="type_param",withitem="withitem";visitor.expr=function(st,e){switch(e.constructor){case $B.ast.NamedExpr:if(!symtable_raise_if_annotation_block(st,"named expression",e)){VISIT_QUIT(st,0)}if(!symtable_handle_namedexpr(st,e))VISIT_QUIT(st,0);break;case $B.ast.BoolOp:VISIT_SEQ(st,"expr",e.values);break;case $B.ast.BinOp:VISIT(st,"expr",e.left);VISIT(st,"expr",e.right);break;case $B.ast.UnaryOp:VISIT(st,"expr",e.operand);break;case $B.ast.Lambda:{if(!GET_IDENTIFIER("lambda"))VISIT_QUIT(st,0);if(e.args.defaults)VISIT_SEQ(st,"expr",e.args.defaults);if(e.args.kw_defaults)VISIT_SEQ_WITH_NULL(st,"expr",e.args.kw_defaults);if(!symtable_enter_block(st,lambda,FunctionBlock,e,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset))VISIT_QUIT(st,0);VISIT(st,"arguments",e.args);VISIT(st,"expr",e.body);if(!symtable_exit_block(st))VISIT_QUIT(st,0);break}case $B.ast.IfExp:VISIT(st,"expr",e.test);VISIT(st,"expr",e.body);VISIT(st,"expr",e.orelse);break;case $B.ast.Dict:VISIT_SEQ_WITH_NULL(st,"expr",e.keys);VISIT_SEQ(st,"expr",e.values);break;case $B.ast.Set:VISIT_SEQ(st,"expr",e.elts);break;case $B.ast.GeneratorExp:if(!visitor.genexp(st,e))VISIT_QUIT(st,0);break;case $B.ast.ListComp:if(!visitor.listcomp(st,e))VISIT_QUIT(st,0);break;case $B.ast.SetComp:if(!visitor.setcomp(st,e))VISIT_QUIT(st,0);break;case $B.ast.DictComp:if(!visitor.dictcomp(st,e))VISIT_QUIT(st,0);break;case $B.ast.Yield:if(!symtable_raise_if_annotation_block(st,"yield expression",e)){VISIT_QUIT(st,0)}if(e.value)VISIT(st,"expr",e.value);st.cur.generator=1;if(st.cur.comprehension){return symtable_raise_if_comprehension_block(st,e)}break;case $B.ast.YieldFrom:if(!symtable_raise_if_annotation_block(st,"yield expression",e)){VISIT_QUIT(st,0)}VISIT(st,"expr",e.value);st.cur.generator=1;if(st.cur.comprehension){return symtable_raise_if_comprehension_block(st,e)}break;case $B.ast.Await:if(!symtable_raise_if_annotation_block(st,"await expression",e)){VISIT_QUIT(st,0)}VISIT(st,"expr",e.value);st.cur.coroutine=1;break;case $B.ast.Compare:VISIT(st,"expr",e.left);VISIT_SEQ(st,"expr",e.comparators);break;case $B.ast.Call:VISIT(st,"expr",e.func);VISIT_SEQ(st,"expr",e.args);VISIT_SEQ_WITH_NULL(st,"keyword",e.keywords);break;case $B.ast.FormattedValue:VISIT(st,"expr",e.value);if(e.format_spec)VISIT(st,"expr",e.format_spec);break;case $B.ast.JoinedStr:VISIT_SEQ(st,"expr",e.values);break;case $B.ast.Constant:break;case $B.ast.Attribute:VISIT(st,"expr",e.value);break;case $B.ast.Subscript:VISIT(st,"expr",e.value);VISIT(st,"expr",e.slice);break;case $B.ast.Starred:VISIT(st,"expr",e.value);break;case $B.ast.Slice:if(e.lower)VISIT(st,expr,e.lower);if(e.upper)VISIT(st,expr,e.upper);if(e.step)VISIT(st,expr,e.step);break;case $B.ast.Name:var flag=e.ctx instanceof $B.ast.Load?SF.USE:SF.DEF_LOCAL;if(!symtable_add_def(st,e.id,flag,LOCATION(e)))VISIT_QUIT(st,0);if(e.ctx instanceof $B.ast.Load&&_PyST_IsFunctionLike(st.cur)&&e.id=="super"){if(!GET_IDENTIFIER("__class__")||!symtable_add_def(st,"__class__",SF.USE,LOCATION(e)))VISIT_QUIT(st,0)}break;case $B.ast.List:VISIT_SEQ(st,expr,e.elts);break;case $B.ast.Tuple:VISIT_SEQ(st,expr,e.elts);break}VISIT_QUIT(st,1)};visitor.type_param_bound_or_default=function(st,e,name,key){if(e){var is_in_class=st.cur.can_see_class_scope;if(!symtable_enter_block(st,name,TypeVarBoundBlock,key,LOCATION(e))){return 0}st.cur.can_see_class_scope=is_in_class;if(is_in_class&&!symtable_add_def(st,"__classdict__",SF.USE,LOCATION(e))){VISIT_QUIT(st,0)}VISIT(st,expr,e);if(!symtable_exit_block(st)){return 0}}return 1};visitor.type_param=function(st,tp){switch(tp.constructor){case $B.ast.TypeVar:if(!symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM|SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0)}if(!visitor.type_param_bound_or_default(st,tp.bound,tp.name,tp)){VISIT_QUIT(st,0)}if(!visitor.type_param_bound_or_default(st,tp.default_value,tp.name,{$id:$B.UUID()})){VISIT_QUIT(st,0)}break;case $B.ast.TypeVarTuple:if(!symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM|SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0)}if(!visitor.type_param_bound_or_default(st,tp.default_value,tp.name,tp)){VISIT_QUIT(st,0)}break;case $B.ast.ParamSpec:if(!symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM|SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0)}if(!visitor.type_param_bound_or_default(st,tp.default_value,tp.name,tp)){VISIT_QUIT(st,0)}break}VISIT_QUIT(st,1)};visitor.pattern=function(st,p){switch(p.constructor){case $B.ast.MatchValue:VISIT(st,expr,p.value);break;case $B.ast.MatchSingleton:break;case $B.ast.MatchSequence:VISIT_SEQ(st,pattern,p.patterns);break;case $B.ast.MatchStar:if(p.name){symtable_add_def(st,p.name,SF.DEF_LOCAL,LOCATION(p))}break;case $B.ast.MatchMapping:VISIT_SEQ(st,expr,p.keys);VISIT_SEQ(st,pattern,p.patterns);if(p.rest){symtable_add_def(st,p.rest,SF.DEF_LOCAL,LOCATION(p))}break;case $B.ast.MatchClass:VISIT(st,expr,p.cls);VISIT_SEQ(st,pattern,p.patterns);VISIT_SEQ(st,pattern,p.kwd_patterns);break;case $B.ast.MatchAs:if(p.pattern){VISIT(st,pattern,p.pattern)}if(p.name){symtable_add_def(st,p.name,SF.DEF_LOCAL,LOCATION(p))}break;case $B.ast.MatchOr:VISIT_SEQ(st,pattern,p.patterns);break}VISIT_QUIT(st,1)};function symtable_implicit_arg(st,pos){var id="."+pos;if(!symtable_add_def(st,id,SF.DEF_PARAM,ST_LOCATION(st.cur))){return 0}return 1}visitor.params=function(st,args){if(!args){return-1}for(var arg of args){if(!symtable_add_def(st,arg.arg,SF.DEF_PARAM,LOCATION(arg)))return 0}return 1};visitor.annotation=function(st,annotation){var future_annotations=st.future.features&$B.CO_FUTURE_ANNOTATIONS;if(future_annotations&&!symtable_enter_block(st,"_annotation",AnnotationBlock,annotation,annotation.lineno,annotation.col_offset,annotation.end_lineno,annotation.end_col_offset)){VISIT_QUIT(st,0)}VISIT(st,expr,annotation);if(future_annotations&&!symtable_exit_block(st)){VISIT_QUIT(st,0)}return 1};visitor.argannotations=function(st,args){if(!args){return-1}for(var arg of args){if(arg.annotation){VISIT(st,expr,arg.annotation)}}return 1};visitor.annotations=function(st,o,a,returns){var future_annotations=st.future.ff_features&$B.CO_FUTURE_ANNOTATIONS;if(future_annotations&&!symtable_enter_block(st,"_annotation",AnnotationBlock,o,o.lineno,o.col_offset,o.end_lineno,o.end_col_offset)){VISIT_QUIT(st,0)}if(a.posonlyargs&&!visitor.argannotations(st,a.posonlyargs))return 0;if(a.args&&!visitor.argannotations(st,a.args))return 0;if(a.vararg&&a.vararg.annotation)VISIT(st,expr,a.vararg.annotation);if(a.kwarg&&a.kwarg.annotation)VISIT(st,expr,a.kwarg.annotation);if(a.kwonlyargs&&!visitor.argannotations(st,a.kwonlyargs))return 0;if(future_annotations&&!symtable_exit_block(st)){VISIT_QUIT(st,0)}if(returns&&!visitor.annotation(st,returns)){VISIT_QUIT(st,0)}return 1};visitor.arguments=function(st,a){if(a.posonlyargs&&!visitor.params(st,a.posonlyargs))return 0;if(a.args&&!visitor.params(st,a.args))return 0;if(a.kwonlyargs&&!visitor.params(st,a.kwonlyargs))return 0;if(a.vararg){if(!symtable_add_def(st,a.vararg.arg,SF.DEF_PARAM,LOCATION(a.vararg)))return 0;st.cur.varargs=1}if(a.kwarg){if(!symtable_add_def(st,a.kwarg.arg,SF.DEF_PARAM,LOCATION(a.kwarg)))return 0;st.cur.varkeywords=1}return 1};visitor.excepthandler=function(st,eh){if(eh.type)VISIT(st,expr,eh.type);if(eh.name)if(!symtable_add_def(st,eh.name,SF.DEF_LOCAL,LOCATION(eh)))return 0;VISIT_SEQ(st,stmt,eh.body);return 1};visitor.withitem=function(st,item){VISIT(st,"expr",item.context_expr);if(item.optional_vars){VISIT(st,"expr",item.optional_vars)}return 1};visitor.match_case=function(st,m){VISIT(st,pattern,m.pattern);if(m.guard){VISIT(st,expr,m.guard)}VISIT_SEQ(st,stmt,m.body);return 1};visitor.alias=function(st,a){var store_name,name=a.asname==NULL?a.name:a.asname;var dot=name.search("\\.");if(dot!=-1){store_name=name.substring(0,dot);if(!store_name)return 0}else{store_name=name}if(name!="*"){var r=symtable_add_def(st,store_name,SF.DEF_IMPORT,LOCATION(a));return r}else{if(st.cur.type!=ModuleBlock){var lineno=a.lineno,col_offset=a.col_offset,end_lineno=a.end_lineno,end_col_offset=a.end_col_offset;var exc=PyErr_SetString(PyExc_SyntaxError,IMPORT_STAR_WARNING);set_exc_info(exc,st.filename,lineno,col_offset,end_lineno,end_col_offset);throw exc}st.cur.$has_import_star=true;return 1}};visitor.comprehension=function(st,lc){st.cur.comp_iter_target=1;VISIT(st,expr,lc.target);st.cur.comp_iter_target=0;st.cur.comp_iter_expr++;VISIT(st,expr,lc.iter);st.cur.comp_iter_expr--;VISIT_SEQ(st,expr,lc.ifs);if(lc.is_async){st.cur.coroutine=1}return 1};visitor.keyword=function(st,k){VISIT(st,expr,k.value);return 1};function symtable_handle_comprehension(st,e,scope_name,generators,elt,value){var is_generator=e.constructor===$B.ast.GeneratorExp;var outermost=generators[0];st.cur.comp_iter_expr++;VISIT(st,expr,outermost.iter);st.cur.comp_iter_expr--;if(!scope_name||!symtable_enter_block(st,scope_name,FunctionBlock,e,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset)){return 0}switch(e.constructor){case $B.ast.ListComp:st.cur.comprehension=ListComprehension;break;case $B.ast.SetComp:st.cur.comprehension=SetComprehension;break;case $B.ast.DictComp:st.cur.comprehension=DictComprehension;break;default:st.cur.comprehension=GeneratorExpression;break}if(outermost.is_async){st.cur.coroutine=1}if(!symtable_implicit_arg(st,0)){symtable_exit_block(st);return 0}st.cur.comp_iter_target=1;VISIT(st,expr,outermost.target);st.cur.comp_iter_target=0;VISIT_SEQ(st,expr,outermost.ifs);VISIT_SEQ_TAIL(st,comprehension,generators,1);if(value)VISIT(st,expr,value);VISIT(st,expr,elt);st.cur.generator=is_generator;var is_async=st.cur.coroutine&&!is_generator;if(!symtable_exit_block(st)){return 0}if(is_async){st.cur.coroutine=1}return 1}visitor.genexp=function(st,e){return symtable_handle_comprehension(st,e,"genexpr",e.generators,e.elt,NULL)};visitor.listcomp=function(st,e){return symtable_handle_comprehension(st,e,"listcomp",e.generators,e.elt,NULL)};visitor.setcomp=function(st,e){return symtable_handle_comprehension(st,e,"setcomp",e.generators,e.elt,NULL)};visitor.dictcomp=function(st,e){return symtable_handle_comprehension(st,e,"dictcomp",e.generators,e.key,e.value)};function symtable_raise_if_annotation_block(st,name,e){var type=st.cur.type,exc;if(type==AnnotationBlock)exc=PyErr_Format(PyExc_SyntaxError,ANNOTATION_NOT_ALLOWED,name);else if(type==TypeVarBoundBlock)exc=PyErr_Format(PyExc_SyntaxError,TYPEVAR_BOUND_NOT_ALLOWED,name);else if(type==TypeAliasBlock)exc=PyErr_Format(PyExc_SyntaxError,TYPEALIAS_NOT_ALLOWED,name);else if(type==TypeParamBlock)exc=PyErr_Format(PyExc_SyntaxError,TYPEPARAM_NOT_ALLOWED,name);else return 1;set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset);throw exc}function symtable_raise_if_comprehension_block(st,e){var type=st.cur.comprehension;var exc=PyErr_SetString(PyExc_SyntaxError,type==ListComprehension?"'yield' inside list comprehension":type==SetComprehension?"'yield' inside set comprehension":type==DictComprehension?"'yield' inside dict comprehension":"'yield' inside generator expression");exc.$frame_obj=$B.frame_obj;set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset);throw exc}})(__BRYTHON__);(function($B){var _b_=$B.builtins,NULL=undefined,DOT=".",ELLIPSIS="...";const STAR_TARGETS=1,DEL_TARGETS=2,FOR_TARGETS=3;function make_string_for_ast_value(value){value=value.replace(/\n/g,"\\n\\\n");value=value.replace(/\r/g,"\\r\\\r");if(value[0]=="'"){var unquoted=value.substr(1,value.length-2);return unquoted}if(value.indexOf("'")>-1){var s="",escaped=false;for(var char of value){if(char=="\\"){if(escaped){s+="\\\\"}escaped=!escaped}else{if(char=="'"&&!escaped){s+="\\"}else if(escaped){s+="\\"}s+=char;escaped=false}}value=s}return value.substr(1,value.length-2)}function encode_bytestring(s){s=s.replace(/\\t/g,"\t").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\f/g,"\f").replace(/\\v/g,"\v").replace(/\\\\/g,"\\");var t=[];for(var i=0,len=s.length;i255){throw Error()}t.push(cp)}return t}function EXTRA_EXPR(head,tail){return{lineno:head.lineno,col_offset:head.col_offset,end_lineno:tail.end_lineno,end_col_offset:tail.end_col_offset}}function set_list(list,other){for(var item of other){list.push(item)}}var positions=["lineno","col_offset","end_lineno","end_col_offset"];function set_position_from_list(ast_obj,EXTRA){for(var i=0;i<4;i++){ast_obj[positions[i]]=EXTRA[i]}}function set_position_from_token(ast_obj,token){ast_obj.lineno=token.lineno;ast_obj.col_offset=token.col_offset;ast_obj.end_lineno=token.end_lineno;ast_obj.end_col_offset=token.end_col_offset}function set_position_from_obj(ast_obj,obj){for(var position of positions){ast_obj[position]=obj[position]}}function _get_names(p,names_with_defaults){var seq=[];for(var pair of names_with_defaults){seq.push(pair.arg)}return seq}function _get_defaults(p,names_with_defaults){var seq=[];for(var pair of names_with_defaults){seq.push(pair.value)}return seq}function _make_posonlyargs(p,slash_without_default,slash_with_default,posonlyargs){if(slash_without_default!=NULL){set_list(posonlyargs,slash_without_default)}else if(slash_with_default!=NULL){var slash_with_default_names=_get_names(p,slash_with_default.names_with_defaults);if(!slash_with_default_names){return-1}set_list(posonlyargs,$B._PyPegen.join_sequences(p,slash_with_default.plain_names,slash_with_default_names))}return posonlyargs==NULL?-1:0}function _make_posargs(p,plain_names,names_with_default,posargs){if(plain_names!=NULL&&names_with_default!=NULL){var names_with_default_names=_get_names(p,names_with_default);if(!names_with_default_names){return-1}var seqs=$B._PyPegen.join_sequences(p,plain_names,names_with_default_names);set_list(posargs,seqs)}else if(plain_names==NULL&&names_with_default!=NULL){set_list(posargs,_get_names(p,names_with_default))}else if(plain_names!=NULL&&names_with_default==NULL){set_list(posargs,plain_names)}return posargs==NULL?-1:0}function _make_posdefaults(p,slash_with_default,names_with_default,posdefaults){if(slash_with_default!=NULL&&names_with_default!=NULL){var slash_with_default_values=_get_defaults(p,slash_with_default.names_with_defaults);if(!slash_with_default_values){return-1}var names_with_default_values=_get_defaults(p,names_with_default);if(!names_with_default_values){return-1}set_list(posdefaults,$B._PyPegen.join_sequences(p,slash_with_default_values,names_with_default_values))}else if(slash_with_default==NULL&&names_with_default!=NULL){set_list(posdefaults,_get_defaults(p,names_with_default))}else if(slash_with_default!=NULL&&names_with_default==NULL){set_list(posdefaults,_get_defaults(p,slash_with_default.names_with_defaults))}return posdefaults==NULL?-1:0}function _make_kwargs(p,star_etc,kwonlyargs,kwdefaults){if(star_etc!=NULL&&star_etc.kwonlyargs!=NULL){set_list(kwonlyargs,_get_names(p,star_etc.kwonlyargs))}else{set_list(kwonlyargs,[])}if(kwonlyargs==NULL){return-1}if(star_etc!=NULL&&star_etc.kwonlyargs!=NULL){set_list(kwdefaults,_get_defaults(p,star_etc.kwonlyargs))}else{set_list(kwdefaults,[])}if(kwdefaults==NULL){return-1}return 0}function _seq_number_of_starred_exprs(seq){var n=0;for(var k of seq){if(!k.is_keyword){n++}}return n}$B._PyPegen={};$B._PyPegen.constant_from_string=function(p,token){var prepared=$B.prepare_string(p,token);var is_bytes=prepared.value.startsWith("b");if(!is_bytes){var value=make_string_for_ast_value(prepared.value)}else{value=prepared.value.substr(2,prepared.value.length-3);try{value=_b_.bytes.$factory(encode_bytestring(value))}catch(err){$B._PyPegen.raise_error_known_location(p,_b_.SyntaxError,token.lineno,token.col_offset,token.end_lineno,token.end_col_offset,"bytes can only contain ASCII literal characters")}}var ast_obj=new $B.ast.Constant(value);set_position_from_token(ast_obj,token);return ast_obj};$B._PyPegen.constant_from_token=function(p,t){var ast_obj=new $B.ast.Constant(t.string);set_position_from_token(ast_obj,t);return ast_obj};$B._PyPegen.decoded_constant_from_token=function(p,t){var ast_obj=new $B.ast.Constant(t.string);set_position_from_token(ast_obj,t);return ast_obj};$B._PyPegen.formatted_value=function(p,expression,debug,conversion,format,closing_brace,arena){var conversion_val=-1;if(conversion){var conversion_expr=conversion.result,first=conversion_expr.id;if(first.length>1||!"sra".includes(first)){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conversion_expr,`f-string: invalid conversion character {first}: `+"expected 's', 'r', or 'a'")}var conversion_val=first.charCodeAt(0)}var formatted_value=new $B.ast.FormattedValue(expression,conversion_val,format===undefined?format:format.result);set_position_from_obj(formatted_value,arena);if(debug){var debug_end_line,debug_end_offset,debug_metadata;if(conversion){debug_end_line=conversion.result.lineno;debug_end_offset=conversion.result.col_offset;debug_metadata=conversion.metadata}else if(format){debug_end_line=format.result.lineno;debug_end_offset=format.result.col_offset+1;debug_metadata=format.metadata}else{debug_end_line=p.end_lineno;debug_end_offset=p.end_col_offset;debug_metadata=closing_brace.metadata}var debug=new $B.ast.Constant(debug_metadata);debug.lineno=p.lineno;debug.col_offset=p.col_offset+1;debug.end_lineno=debug_end_line;debug.end_col_offset=debug_end_offset;var joined_str=new $B.ast.JoinedStr([debug,formatted_value]);set_position_from_obj(joined_str,arena);return joined_str}return formatted_value};$B._PyPegen.joined_str=function(p,a,items,c){var ast_obj=new $B.ast.JoinedStr(items);ast_obj.lineno=a.lineno;ast_obj.col_offset=a.col_offset;ast_obj.end_lineno=c.end_lineno;ast_obj.end_col_offset=c.end_col_offset;return ast_obj};$B._PyPegen.setup_full_format_spec=function(p,colon,spec,arena){var ast_obj=new $B.ast.JoinedStr(spec);set_position_from_obj(ast_obj,arena);return result_token_with_metadata(p,ast_obj,colon.metadata)};function result_token_with_metadata(p,result,metadata){return{result:result,metadata:metadata}}$B._PyPegen.check_fstring_conversion=function(p,conv_token,conv){if(conv_token.lineno!=conv.lineno||conv_token.end_col_offset!=conv.col_offset){$B._PyPegen.raise_error_known_location(p,_b_.SyntaxError,conv.lineno,conv.col_offset,conv.end_lineno,conv.end_col_offset,"f-string: conversion type must come right after the exclamanation mark")}return result_token_with_metadata(p,conv,conv_token.metadata)};$B._PyPegen.seq_count_dots=function(seq){if(seq===undefined){return 0}var number_of_dots=0;for(var token of seq){if(token.num_type==$B.py_tokens.DOT){number_of_dots+=token.string.length}else if(token.num_type==$B.py_tokens.ELLIPSIS){number_of_dots+=3}}return number_of_dots};$B._PyPegen.map_names_to_ids=function(p,seq){return seq.map((e=>e.id))};$B._PyPegen.alias_for_star=function(p,lineno,col_offset,end_lineno,end_col_offset,arena){var str="*";return $B._PyAST.alias(str,NULL,lineno,col_offset,end_lineno,end_col_offset,arena)};$B._PyPegen.cmpop_expr_pair=function(p,cmpop,expr){return{cmpop:cmpop,expr:expr}};$B._PyPegen.get_cmpops=function(p,seq){var new_seq=[];for(var pair of seq){new_seq.push(pair.cmpop)}return new_seq};$B._PyPegen.get_exprs=function(p,seq){var new_seq=[];for(var pair of seq){new_seq.push(pair.expr)}return new_seq};function _set_seq_context(p,seq,ctx){var new_seq=[];for(var e of seq){new_seq.push($B._PyPegen.set_expr_context(p,e,ctx))}return new_seq}function _set_name_context(p,e,ctx){return $B._PyAST.Name(e.id,ctx,EXTRA_EXPR(e,e))}function _set_tuple_context(p,e,ctx){return $B._PyAST.Tuple(_set_seq_context(p,e.elts,ctx),ctx,EXTRA_EXPR(e,e))}function _set_list_context(p,e,ctx){return $B._PyAST.List(_set_seq_context(p,e.elts,ctx),ctx,EXTRA_EXPR(e,e))}function _set_subscript_context(p,e,ctx){console.log("set subscritp cntext",p,e);return $B._PyAST.Subscript(e.value,e.slice,ctx,EXTRA_EXPR(e,e))}function _set_attribute_context(p,e,ctx){return $B._PyAST.Attribute(e.value,e.attr,ctx,EXTRA_EXPR(e,e))}function _set_starred_context(p,e,ctx){return $B._PyAST.Starred($B._PyPegen.set_expr_context(p,e.value,ctx),ctx,EXTRA_EXPR(e,e))}$B._PyPegen.set_expr_context=function(p,expr,ctx){var _new=NULL;switch(expr.constructor){case $B.ast.Name:_new=_set_name_context(p,expr,ctx);break;case $B.ast.Tuple:_new=_set_tuple_context(p,expr,ctx);break;case $B.ast.List:_new=_set_list_context(p,expr,ctx);break;case $B.ast.Subscript:_new=_set_subscript_context(p,expr,ctx);break;case $B.ast.Attribute:_new=_set_attribute_context(p,expr,ctx);break;case $B.ast.Starred:_new=_set_starred_context(p,expr,ctx);break;default:_new=expr}return _new};$B._PyPegen.key_value_pair=function(p,key,value){return{key:key,value:value}};$B._PyPegen.get_expr_name=function(e){switch(e.constructor.$name){case"Attribute":case"Subscript":case"Starred":case"Name":case"List":case"Tuple":case"Lambda":return e.constructor.$name.toLowerCase();case"Call":return"function call";case"BoolOp":case"BinOp":case"UnaryOp":return"expression";case"GeneratorExp":return"generator expression";case"Yield":case"YieldFrom":return"yield expression";case"Await":return"await expression";case"ListComp":return"list comprehension";case"SetComp":return"set comprehension";case"DictComp":return"dict comprehension";case"Dict":return"dict literal";case"Set":return"set display";case"JoinedStr":case"FormattedValue":return"f-string expression";case"Constant":var value=e.value;if(value===_b_.None){return"None"}if(value===false){return"False"}if(value===true){return"True"}if(value===_b_.Ellipsis){return"ellipsis"}return"literal";case"Compare":return"comparison";case"IfExp":return"conditional expression";case"NamedExpr":return"named expression";default:return NULL}};$B._PyPegen.get_keys=function(p,seq){return seq===undefined?[]:seq.map((pair=>pair.key))};$B._PyPegen.get_values=function(p,seq){return seq===undefined?[]:seq.map((pair=>pair.value))};$B._PyPegen.key_pattern_pair=function(p,key,pattern){return{key:key,pattern:pattern}};$B._PyPegen.get_pattern_keys=function(p,seq){return seq===undefined?[]:seq.map((x=>x.key))};$B._PyPegen.get_patterns=function(p,seq){return seq===undefined?[]:seq.map((x=>x.pattern))};$B._PyPegen.check_legacy_stmt=function(p,name){return["print","exec"].includes(name)};$B._PyPegen.dummy_name=function(p){var cache=NULL;if(cache!=NULL){return cache}var id="dummy"+Math.random().toString(36).substr(2),ast_obj=new $B.ast.Name(id,new $B.ast.Load);set_position_from_list(ast_obj,[1,0,1,0]);return ast_obj};$B._PyPegen.add_type_comment_to_arg=function(p,a,tc){if(tc==NULL){return a}var bytes=_b_.bytes.$factory(tc),tco=$B._PyPegen.new_type_comment(p,bytes);var ast_obj=$B._PyAST.arg(a.arg,a.annotation,tco,a.lineno,a.col_offset,a.end_lineno,a.end_col_offset,p.arena);console.log("arg with type comment",ast_obj);return ast_obj};$B._PyPegen.check_barry_as_flufl=function(p,t){return false};$B._PyPegen.empty_arguments=function(p){return $B._PyAST.arguments([],[],NULL,[],[],NULL,[],p.arena)};$B._PyPegen.augoperator=function(p,kind){return{kind:kind}};$B._PyPegen.function_def_decorators=function(p,decorators,function_def){var constr=function_def instanceof $B.ast.AsyncFunctionDef?$B.ast.AsyncFunctionDef:$B.ast.FunctionDef;var ast_obj=new constr(function_def.name,function_def.args,function_def.body,decorators,function_def.returns,function_def.type_comment,function_def.type_params);for(var position of positions){ast_obj[position]=function_def[position]}return ast_obj};$B._PyPegen.class_def_decorators=function(p,decorators,class_def){var ast_obj=$B._PyAST.ClassDef(class_def.name,class_def.bases,class_def.keywords,class_def.body,decorators,class_def.type_params);set_position_from_obj(ast_obj,class_def);return ast_obj};$B._PyPegen.keyword_or_starred=function(p,element,is_keyword){return{element:element,is_keyword:is_keyword}};$B._PyPegen.make_arguments=function(p,slash_without_default,slash_with_default,plain_names,names_with_default,star_etc){var posonlyargs=[];if(_make_posonlyargs(p,slash_without_default,slash_with_default,posonlyargs)==-1){return NULL}var posargs=[];if(_make_posargs(p,plain_names,names_with_default,posargs)==-1){return NULL}var posdefaults=[];if(_make_posdefaults(p,slash_with_default,names_with_default,posdefaults)==-1){return NULL}var vararg=NULL;if(star_etc!=NULL&&star_etc.vararg!=NULL){vararg=star_etc.vararg}var kwonlyargs=[],kwdefaults=[];if(_make_kwargs(p,star_etc,kwonlyargs,kwdefaults)==-1){return NULL}var kwarg=NULL;if(star_etc!=NULL&&star_etc.kwarg!=NULL){kwarg=star_etc.kwarg}var ast_obj=$B._PyAST.arguments(posonlyargs,posargs,vararg,kwonlyargs,kwdefaults,kwarg,posdefaults,p.arena);if(ast_obj.posonlyargs===undefined){console.log("pas de posonlyargs",ast_bj);alert()}return ast_obj};$B._PyPegen.name_default_pair=function(p,arg,value,tc){return{arg:$B._PyPegen.add_type_comment_to_arg(p,arg,tc),value:value}};$B._PyPegen.raise_error=function(p,errtype,errmsg){if(p.fill==0){var va=[errmsg];$B._PyPegen.raise_error_known_location(p,errtype,0,0,0,-1,errmsg,va);return NULL}var t=p.known_err_token!=NULL?p.known_err_token:p.tokens[p.fill-1];var va=errmsg;$B._PyPegen.raise_error_known_location(p,errtype,t.lineno,t.col_offset,t.end_lineno,t.end_col_offset,errmsg,va)};$B._PyPegen.raise_error_known_location=function(p,errtype,lineno,col_offset,end_lineno,end_col_offset,errmsg,va){var exc=errtype.$factory(errmsg);exc.filename=p.filename;if(p.known_err_token){var token=p.known_err_token;exc.lineno=token.lineno;exc.offset=token.col_offset+1;exc.end_lineno=token.end_lineno;exc.end_offset=token.end_col_offset;exc.text=token.line}else{exc.lineno=lineno;exc.offset=col_offset+1;exc.end_lineno=end_lineno;exc.end_offset=end_col_offset+1;var src=$B.file_cache[p.filename];if(src!==undefined){var lines=src.split("\n"),line=lines[exc.lineno-1];exc.text=line+"\n"}else{exc.text=_b_.None}}exc.args[1]=$B.fast_tuple([p.filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]);throw exc};$B._PyPegen.seq_delete_starred_exprs=function(p,kwargs){var len=kwargs.length,new_len=len-_seq_number_of_starred_exprs(kwargs);if(new_len==0){return NULL}var new_seq=[];for(var k of kwargs){if(k.is_keyword){new_seq.push(k.element)}}return new_seq};$B._PyPegen.seq_extract_starred_exprs=function(p,kwargs){var new_len=_seq_number_of_starred_exprs(kwargs);if(new_len==0){return NULL}var new_seq=[];var idx=0;for(var k of kwargs){if(!k.is_keyword){new_seq[idx++]=k.element}}return new_seq};$B._PyPegen.slash_with_default=function(p,plain_names,names_with_defaults){return{plain_names:plain_names,names_with_defaults:names_with_defaults}};$B._PyPegen.star_etc=function(p,vararg,kwonlyargs,kwarg){return{vararg:vararg,kwonlyargs:kwonlyargs,kwarg:kwarg}};$B._PyPegen.collect_call_seqs=function(p,a,b,lineno,col_offset,end_lineno,end_col_offset,arena){var args_len=a.length,total_len=args_len;if(b==NULL){return $B._PyAST.Call($B._PyPegen.dummy_name(p),a,[],lineno,col_offset,end_lineno,end_col_offset,arena)}var starreds=$B._PyPegen.seq_extract_starred_exprs(p,b),keywords=$B._PyPegen.seq_delete_starred_exprs(p,b);if(starreds){total_len+=starreds.length}var args=[];for(var i=0;ix.replace(new RegExp("'","g"),"\\'")));fs_item.value=parts.join("\\'");fs_item.value=fs_item.value.replace(/\n/g,"\\n").replace(/\r/g,"\\r")}items.push(fs_item)}state="string"}else{items.push(token);var is_bytes=token.value.__class__===_b_.bytes;if(is_bytes&&state=="string"||state=="bytestring"&&!is_bytes){error("cannot mix bytes and nonbytes literals")}state=is_bytes?"bytestring":"string"}}if(state=="bytestring"){var bytes=[];for(var item of items){bytes=bytes.concat(item.value.source)}value=_b_.bytes.$factory(bytes);var ast_obj=new $B.ast.Constant(value);set_position_from_list(ast_obj,items);return ast_obj}function group_consec_strings(items){if(items.length==1){return items[0]}var values=items.map((x=>x.value));let ast_obj=new $B.ast.Constant(values.join(""));set_position_from_list(ast_obj,items);return ast_obj}var items1=[],consec_strs=[],item_type=null;for(var i=0,len=items.length;i0){items1.push(group_consec_strings(consec_strs))}consec_strs=[];items1.push(item)}}if(consec_strs.length>0){items1.push(group_consec_strings(consec_strs))}if(!has_fstring){return items1[0]}var jstr_values=items1;var ast_obj=new $B.ast.JoinedStr(jstr_values);set_position_from_list(ast_obj,strings);return ast_obj};$B._PyPegen.ensure_imaginary=function(p,exp){if(!(exp instanceof $B.ast.Constant)||exp.value.__class__!=_b_.complex){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp,"imaginary number required in complex literal");return NULL}return exp};$B._PyPegen.ensure_real=function(p,exp){if(!(exp instanceof $B.ast.Constant)||exp.value.type=="imaginary"){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp,"real number required in complex literal");return NULL}return exp};$B._PyPegen.set_expr_context=function(p,a,ctx){a.ctx=ctx;return a};$B._PyPegen.singleton_seq=function(p,a){return[a]};$B._PyPegen.seq_insert_in_front=function(p,a,seq){return seq?[a].concat(seq):[a]};$B._PyPegen.seq_flatten=function(p,seqs){var res=[];for(var seq of seqs){for(var item of seq){res.push(item)}}return res};$B._PyPegen.join_names_with_dot=function(p,first_name,second_name){var str=first_name.id+"."+second_name.id;return $B._PyAST.Name(str,new $B.ast.Load,EXTRA_EXPR(first_name,second_name))};$B._PyPegen.make_module=function(p,a){return new $B.ast.Module(a)};$B._PyPegen.new_type_comment=function(p,s){if(s.length===0){return NULL}return s};$B._PyPegen.get_last_comprehension_item=function(comprehension){if(comprehension.ifs==NULL||comprehension.ifs.length==0){return comprehension.iter}return $B.last(comprehension.ifs)};$B._PyPegen.arguments_parsing_error=function(p,e){var kwarg_unpacking=0;for(let keyword of e.keywords){if(!keyword.arg){kwarg_unpacking=1}}var msg=NULL;if(kwarg_unpacking){msg="positional argument follows keyword argument unpacking"}else{msg="positional argument follows keyword argument"}return $B.helper_functions.RAISE_SYNTAX_ERROR(p,msg)};$B._PyPegen.nonparen_genexp_in_call=function(p,args,comprehensions){var len=args.args.length;if(len<=1){return NULL}var last_comprehension=$B.last(comprehensions);return $B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,args.args[len-1],$B._PyPegen.get_last_comprehension_item(last_comprehension),"Generator expression must be parenthesized")};$B._PyPegen.get_invalid_target=function(e,targets_type){if(e==NULL){return NULL}function VISIT_CONTAINER(CONTAINER,TYPE){for(var elt of CONTAINER.elts){var child=$B._PyPegen.get_invalid_target(elt,targets_type);if(child!=NULL){return child}}}switch(e.constructor){case $B.ast.List:case $B.ast.Tuple:return VISIT_CONTAINER(e,e.constructor);case $B.ast.Starred:if(targets_type==DEL_TARGETS){return e}return $B._PyPegen.get_invalid_target(e.value,targets_type);case $B.ast.Compare:if(targets_type==FOR_TARGETS){var cmpop=e.ops[0];if(cmpop instanceof $B.ast.In){return $B._PyPegen.get_invalid_target(e.left,targets_type)}return NULL}return e;case $B.ast.Name:case $B.ast.Subscript:case $B.ast.Attribute:return NULL;default:return e}}})(__BRYTHON__);(function($B){var _b_=$B.builtins;var s_escaped='abfnrtvxuU"0123456789'+"'"+"\\",is_escaped={};for(var i=0;i="4"){$B.warn(_b_.SyntaxWarning,`invalid octal escape sequence '\\${mo[0]}'`,p.filename,token)}return[String.fromCharCode(parseInt(mo[0],8)),1+mo[0].length]}switch(text[antislash_pos+1]){case"x":var mo=/^[0-9A-F]{0,2}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=2){seq_end=antislash_pos+mo[0].length+1;string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\xXX escape"])}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]}case"u":var mo=/^[0-9A-F]{0,4}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=4){seq_end=antislash_pos+mo[0].length+1;string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\uXXXX escape"])}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]}case"U":var mo=/^[0-9A-F]{0,8}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=8){seq_end=antislash_pos+mo[0].length+1;string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\UXXXXXXXX escape"])}else{var value=parseInt(mo[0],16);if(value>1114111){string_error(p,token,"invalid unicode escape "+mo[0])}else if(value>=65536){return[new SurrogatePair(value),2+mo[0].length]}else{return[String.fromCharCode(value),2+mo[0].length]}}}}$B.prepare_string=function(p,token){var s=token.string,len=s.length,pos=0,string_modifier,_type="string",quote,C={type:"str"};while(pos-1){elt.value+=char;pos++}else{return check(elt)}}else if(char.match(/j/i)){if(elt&&(!elt.subtype||elt.subtype=="float")){elt.imaginary=true;check(elt);elt.length++;return elt}else{error("invalid syntax")}}else{break}}return check(elt)}$B.prepare_number=function(n){n=n.replace(/_/g,"");if(n.startsWith(".")){if(n.endsWith("j")){return{type:"imaginary",value:$B.prepare_number(n.substr(0,n.length-1))}}else{return{type:"float",value:n+""}}pos=j}else if(n.startsWith("0")&&n!="0"){var num=test_num(n),base;if(num.imaginary){return{type:"imaginary",value:$B.prepare_number(num.value)}}if(num.subtype=="float"){return{type:num.subtype,value:num.value+""}}if(num.subtype===undefined){base=10}else{base={b:2,o:8,x:16}[num.subtype]}if(base!==undefined){return{type:"int",value:[base,num.value]}}}else{var num=test_num(n);if(num.subtype=="float"){if(num.imaginary){return{type:"imaginary",value:$B.prepare_number(num.value)}}else{return{type:"float",value:num.value+""}}}else{if(num.imaginary){return{type:"imaginary",value:$B.prepare_number(num.value)}}else{return{type:"int",value:[10,num.value]}}}}}})(__BRYTHON__);(function($B){var _b_=$B.builtins,debug=0;var p={feature_version:$B.version_info[1]};$B.parser_constants={Store:new $B.ast.Store,Load:new $B.ast.Load,Del:new $B.ast.Del,NULL:undefined,alias_ty:$B.ast.alias,keyword_ty:$B.ast.keyword,arguments_ty:$B.ast.arguments,expr_ty:$B.ast.expr,asdl_stmt_seq:Array,asdl_int_seq:Array,asdl_expr_seq:Array,asdl_keyword_seq:Array,asdl_identifier_seq:Array,asdl_pattern_seq:Array,asdl_type_param_seq:Array,AugOperator:$B.ast.AugAssign,IsNot:$B.ast.IsNot,Py_Ellipsis:_b_.Ellipsis,Py_False:false,Py_True:true,Py_None:_b_.None,PyExc_SyntaxError:_b_.SyntaxError,STAR_TARGETS:1,DEL_TARGETS:2,FOR_TARGETS:3,PyBytes_AS_STRING:b=>b};for(var op_type of $B.op_types){for(var key in op_type){var klass_name=op_type[key];$B.parser_constants[klass_name]=new $B.ast[klass_name]}}var NULL=$B.parser_constants.NULL;$B._PyAST={};for(var ast_class in $B.ast_classes){var args=$B.ast_classes[ast_class];if(Array.isArray(args)){continue}args=args.replace(/\*/g,"").replace(/\?/g,"");var arg_names=args.split(",");$B._PyAST[ast_class]=function(ast_name,ast_args){return function(){var _args=Array.from(arguments).slice(0,ast_args.length+1);var EXTRA=_args.pop();var ast_obj=new $B.ast[ast_name](..._args);set_position_from_EXTRA(ast_obj,EXTRA);return ast_obj}}(ast_class,arg_names)}function get_last_token(p){var last_token=$B.last(p.tokens);if(last_token.type=="ENDMARKER"){var src=$B.file_cache[p.filename];if(src){for(var token of $B.tokenizer(src)){if(token.type=="ENDMARKER"){break}if(token.type!="DEDENT"){last_token=token}}}else{last_token=undefined}}p.known_err_token=last_token}var helper_functions={CHECK:function(type,obj){if(Array.isArray(type)){var check;for(var t of type){check=helper_functions.CHECK(t,obj);if(check){return check}}return undefined}if(obj instanceof type){return obj}return undefined},CHECK_VERSION:function(type,version,msg,node){return helper_functions.INVALID_VERSION_CHECK(p,version,msg,node)},CHECK_NULL_ALLOWED:function(type,obj){if(obj!==NULL){if(type instanceof Array){for(var t of type){if(obj instanceof t){return obj}}return}else{return obj instanceof type?obj:undefined}}return obj},INVALID_VERSION_CHECK:function(p,version,msg,node){if(node==NULL){p.error_indicator=1;return NULL}if(p.feature_versiont.length,asdl_seq_GET:(t,i)=>t[i]};$B.helper_functions=helper_functions;function raise_error_known_location(type,filename,lineno,col_offset,end_lineno,end_col_offset,line,message){var exc=type.$factory(message);exc.filename=filename;exc.lineno=lineno;exc.offset=col_offset+1;exc.end_lineno=end_lineno;exc.end_offset=end_col_offset+1;exc.text=line;exc.args[1]=$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]);exc.$frame_obj=$B.frame_obj;throw exc}$B.raise_error_known_location=raise_error_known_location;function raise_error_known_token(type,filename,token,message){var exc=type.$factory(message);exc.filename=filename;exc.lineno=token.lineno;exc.offset=token.col_offset+1;exc.end_lineno=token.end_lineno;exc.end_offset=token.end_col_offset+1;exc.text=token.line;exc.args[1]=$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]);exc.$frame_obj=$B.frame_obj;throw exc}$B.raise_error_known_token=raise_error_known_token;function set_position_from_EXTRA(ast_obj,EXTRA){for(var key in EXTRA){ast_obj[key]=EXTRA[key]}}var Parser=$B.Parser=function(src,filename,mode){src=src.replace(/\r\n/gm,"\n");var tokenizer=$B.tokenizer(src,filename,mode,this);this.tokenizer=tokenizer;this.tok=tokenizer;this.mark=0;this.fill=0;this.level=0;this.size=1;this.starting_lineno=0;this.starting_col_offset=0;this.tokens=[];this.src=src;this.filename=filename;this.mode=mode;this.memo={};this.arena={a_objects:[]};if(filename){p.filename=filename}};var ignored=[$B.py_tokens.ENCODING,$B.py_tokens.NL,$B.py_tokens.COMMENT];Parser.prototype.read_token=function(){while(true){var next=this.tokenizer.next();if(!next.done){var value=next.value;if(!ignored.includes(value.num_type)){this.tokens.push(value);return value}}else{throw Error("tokenizer exhausted")}}}})(__BRYTHON__);(function($B){var _b_=__BRYTHON__.builtins;const Load=new $B.ast.Load;const NULL=undefined;const ENDMARKER=0,NAME=1,NUMBER=2,STRING=3;function strchr(s,char){return s.includes(char)}function strlen(s){return s.length}function strncmp(a,b){return ab?1:0}function PyOS_strtol(s,end,base){return parseFloat(s)}function PyOS_strtoul(s,end,base){return parseFloat(s)}function PyOS_string_to_double(s,x,y){return parseFloat(s)}function PyFloat_FromDouble(x){return x}const NSTATISTICS=2e3,memo_statistics={},TYPE_IGNORE="TYPE_IGNORE",ERRORTOKEN="ERRORTOKEN",NEWLINE=$B.py_tokens.NEWLINE,DEDENT=$B.py_tokens.DEDENT,Py_single_input="py_single_input",PyPARSE_ALLOW_INCOMPLETE_INPUT=256;function PyUnicode_IS_ASCII(char){return char.codePointAt(0)<128}function set_position_from_token(ast_obj,token){for(var attr of["lineno","col_offset","end_lineno","end_col_offset"]){ast_obj[attr]=token[attr]}}$B._PyPegen.interactive_exit=function(p){if(p.errcode){p.errcode=E_EOF}return NULL};$B._PyPegen.byte_offset_to_character_offset_raw=function(str,col_offset){var len=str.length;if(col_offset>len+1){col_offset=len+1}var text=PyUnicode_DecodeUTF8(str,col_offset,"replace");if(!text){return-1}return text.length};$B._PyPegen.calculate_display_width=function(line,character_offset){var segment=line.substring(0,character_offset);if(!segment){return-1}if(PyUnicode_IS_ASCII(segment)){return character_offset}var width_fn=_PyImport_GetModuleAttrString("unicodedata","east_asian_width");if(!width_fn){return-1}var width=0;var len=segment.length;for(let i=0;i=0;m--){token=p.tokens[m];if(token.num_type!=ENDMARKER&&(token.num_typeDEDENT)){break}}return token};$B._PyPegen.new_identifier=function(p,n){var id=n;if(!PyUnicode_IS_ASCII(id)){var id2;if(!init_normalization(p)){return error()}var form=PyUnicode_InternFromString("NFKC");if(form==NULL){return error()}var args={form:form,id:id};id2=_PyObject_FastCall(p.normalize,args,2);if(!id2){return error()}if(!PyUnicode_Check(id2)){PyErr_Format(PyExc_TypeError,"unicodedata.normalize() must return a string, not "+"%.200s",_PyType_Name(Py_TYPE(id2)));return error()}id=id2}PyUnicode_InternInPlace(id);return id;function error(){p.error_indicator=1;return NULL}};$B._PyPegen.name_from_token=function(p,t){if(t==NULL){return NULL}var s=t.string;if(!s){p.error_indicator=1;return NULL}var res=new $B.ast.Name(s,Load);set_position_from_token(res,t);return res};$B._PyPegen.name_token=function(p){var t=$B._PyPegen.expect_token(p,NAME);return $B._PyPegen.name_from_token(p,t)};$B._PyPegen.string_token=function(p){return $B._PyPegen.expect_token(p,STRING)};$B._PyPegen.soft_keyword_token=function(p){var t=$B._PyPegen.expect_token(p,NAME);if(t==NULL){return NULL}var the_token;var size;the_token=t.string;for(let keyword=p.soft_keywords;keyword!=NULL;keyword++){if(strncmp(keyword,the_token,size)==0){return $B._PyPegen.name_from_token(p,t)}}return NULL};function prepared_number_value(prepared){switch(prepared.type){case"float":return $B.fast_float(prepared.value);case"imaginary":return $B.make_complex(0,prepared_number_value(prepared.value));case"int":var res=parseInt(prepared.value[1],prepared.value[0]);if(!Number.isSafeInteger(res)){var base=prepared.value[0],num_str=prepared.value[1];switch(base){case 8:return $B.fast_long_int(BigInt("0x"+num_str));case 10:return $B.fast_long_int(BigInt(num_str));case 16:return $B.fast_long_int(BigInt("0x"+num_str))}}return res}}function parsenumber_raw(s){var prepared=$B.prepare_number(s);return prepared_number_value(prepared)}function parsenumber(s){var dup;var end;var res=NULL;if(strchr(s,"_")==NULL){return parsenumber_raw(s)}dup=s.replace(/_/g,"");res=parsenumber_raw(dup);return res}$B._PyPegen.number_token=function(p){var t=$B._PyPegen.expect_token(p,NUMBER);if(t==NULL){return NULL}var num_raw=t.string;if(num_raw==NULL){p.error_indicator=1;return NULL}if(p.feature_version<6&&strchr(num_raw,"_")!=NULL){p.error_indicator=1;return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "+"in Python 3.6 and greater")}var c=parsenumber(num_raw);if(c==NULL){p.error_indicator=1;var tstate=_PyThreadState_GET();if(tstate.current_exception!=NULL&&Py_TYPE(tstate.current_exception)==PyExc_ValueError){var exc=PyErr_GetRaisedException();RAISE_ERROR_KNOWN_LOCATION(p,PyExc_SyntaxError,t.lineno,-1,t.end_lineno,-1,"%S - Consider hexadecimal for huge integer literals "+"to avoid decimal conversion limits.",exc)}return NULL}var res=new $B.ast.Constant(c,NULL);set_position_from_token(res,t);return res};function bad_single_statement(p){var cur=p.tok.cur;var c=cur;var pos=0;for(;;){while(c==" "||c=="\t"||c=="\n"||c=="\f"){c=cur[pos++]}if(!c){return 0}if(c!="#"){return 1}while(c&&c!="\n"){c=cur[pos++]}}}function compute_parser_flags(flags){var parser_flags=0;if(!flags){return 0}if(flags.cf_flags&PyCF_DONT_IMPLY_DEDENT){parser_flags|=PyPARSE_DONT_IMPLY_DEDENT}if(flags.cf_flags&PyCF_IGNORE_COOKIE){parser_flags|=PyPARSE_IGNORE_COOKIE}if(flags.cf_flags&CO_FUTURE_BARRY_AS_BDFL){parser_flags|=PyPARSE_BARRY_AS_BDFL}if(flags.cf_flags&PyCF_TYPE_COMMENTS){parser_flags|=PyPARSE_TYPE_COMMENTS}if(flags.cf_flags&PyCF_ONLY_AST&&flags.cf_feature_version<7){parser_flags|=PyPARSE_ASYNC_HACKS}if(flags.cf_flags&PyCF_ALLOW_INCOMPLETE_INPUT){parser_flags|=PyPARSE_ALLOW_INCOMPLETE_INPUT}return parser_flags}$B._PyPegen.Parser_New=function(tok,start_rule,flags,feature_version,errcode,arena){var p={};if(p==NULL){return PyErr_NoMemory()}tok.type_comments=(flags&PyPARSE_TYPE_COMMENTS)>0;tok.async_hacks=(flags&PyPARSE_ASYNC_HACKS)>0;p.tok=tok;p.keywords=NULL;p.n_keyword_lists=-1;p.soft_keywords=NULL;p.tokens=[];if(!p.tokens){PyMem_Free(p);return PyErr_NoMemory()}p.tokens[0]=PyMem_Calloc(1,sizeof(Token));p.mark=0;p.fill=0;p.size=1;p.errcode=errcode;p.arena=arena;p.start_rule=start_rule;p.parsing_started=0;p.normalize=NULL;p.error_indicator=0;p.starting_lineno=0;p.starting_col_offset=0;p.flags=flags;p.feature_version=feature_version;p.known_err_token=NULL;p.level=0;p.call_invalid_rules=0;p.debug=_Py_GetConfig().parser_debug;return p};$B._PyPegen.Parser_Free=function(p){};function reset_parser_state_for_error_pass(p){for(let i=0;i0){var brace=$B.last(p.braces),err_lineno,msg;if("([{".includes(brace.char)){err_lineno=brace.line_num}else{if(p.braces.length>1){err_lineno=p.braces[p.braces.length-2].line_num}else{err_lineno=brace.line_num}}if(p.tokens.length==0||$B.last(p.tokens).lineno>=err_lineno){if("([{".includes(brace.char)){msg=`'${brace.char}' was never closed`}else if(p.braces.length>1){var closing=brace.char,opening=p.braces[p.braces.length-2].char;msg=`closing parenthesis '${closing}' does not match `+`opening parenthesis '${opening}'`}else{msg=`unmatched '${brace.char}'`}$B.raise_error_known_location(_b_.SyntaxError,p.filename,brace.line_num,brace.pos-brace.line_start,brace.line_num,brace.pos-brace.line_start+1,brace.line,msg)}}};$B._PyPegen.set_syntax_error=function(p,last_token){if(p.fill==0){$B.helper_functions.RAISE_SYNTAX_ERROR(p,"error at start before reading any input")}$B._PyPegen.tokenize_full_source_to_check_for_errors(p);if(last_token.num_type==ERRORTOKEN&&p.tok.done==E_EOF){if(p.tok.level){raise_unclosed_parentheses_error(p)}else{$B.helper_functions.RAISE_SYNTAX_ERROR(p,"unexpected EOF while parsing")}return}if(last_token.num_type==INDENT||last_token.num_type==DEDENT){$B.helper_functions.RAISE_INDENTATION_ERROR(p,last_token.num_type==INDENT?"unexpected indent":"unexpected unindent");return}$B._PyPegen.tokenize_full_source_to_check_for_errors(p);$B.raise_error_known_token(_b_.SyntaxError,p.filename,last_token,"invalid syntax")};$B._PyPegen.run_parser=function(p){var res=$B._PyPegen.parse(p);if(res==NULL){if(p.flags&$B.PyCF_ALLOW_INCOMPLETE_INPUT&&_is_end_of_source(p)){return $B.helper_functions.RAISE_ERROR(p,_b_._IncompleteInputError,"incomplete input")}var last_token=p.tokens[p.fill-1];reset_parser_state_for_error_pass(p);try{$B._PyPegen.parse(p)}catch(err){last_token=p.tokens[p.fill-1];$B._PyPegen.tokenize_full_source_to_check_for_errors(p);throw err}$B._PyPegen.set_syntax_error(p,last_token)}if(p.start_rule==Py_single_input&&bad_single_statement(p)){p.tok.done=E_BADSINGLE;return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement")}return res};$B._PyPegen.run_parser_from_file_pointer=function(fp,start_rule,filename_ob,enc,ps1,ps2,flags,errcode,arena){var tok=_PyTokenizer_FromFile(fp,enc,ps1,ps2);if(tok==NULL){if(PyErr_Occurred()){_PyPegen_raise_tokenizer_init_error(filename_ob);return NULL}return NULL}if(!tok.fp||ps1!=NULL||ps2!=NULL||PyUnicode_CompareWithASCIIString(filename_ob,"")==0){tok.fp_interactive=1}tok.filename=Py_NewRef(filename_ob);var result=NULL;var parser_flags=compute_parser_flags(flags);var p=$B._PyPegen.Parser_New(tok,start_rule,parser_flags,PY_MINOR_VERSION,errcode,arena);if(p==NULL){return error()}result=_PyPegen_run_parser(p);_PyPegen_Parser_Free(p);function error(){_PyTokenizer_Free(tok);return result}};$B._PyPegen.run_parser_from_string=function(str,start_rule,filename_ob,flags,arena){var exec_input=start_rule==Py_file_input;var tok;if(flags!=NULL&&flags.cf_flags&PyCF_IGNORE_COOKIE){tok=_PyTokenizer_FromUTF8(str,exec_input,0)}else{tok=_PyTokenizer_FromString(str,exec_input,0)}if(tok==NULL){if(PyErr_Occurred()){_PyPegen_raise_tokenizer_init_error(filename_ob)}return NULL}tok.filename=Py_NewRef(filename_ob);var result=NULL;var parser_flags=compute_parser_flags(flags);var feature_version=flags&&flags.cf_flags&PyCF_ONLY_AST?flags.cf_feature_version:PY_MINOR_VERSION;var p=$B._PyPegen.Parser_New(tok,start_rule,parser_flags,feature_version,NULL,arena);if(p==NULL){return error()}result=_PyPegen_run_parser(p);_PyPegen_Parser_Free(p);function error(){return result}};$B.PyPegen={first_item:function(a,type){return a[0]},last_item:function(a,ptype){return a[a.length-1]}}})(__BRYTHON__);function fprintf(dest,format){var args=Array.from(arguments).slice(2);for(var arg of args){format=format.replace(/%\*?[a-z]/,arg)}return format}const stderr=null;function D(x){console.log(x)}function UNUSED(){}function strcmp(x,y){return x==y?0:x[{src:"http://localhost/"}],currentScript:{src:"http://localhost/"},querySelectorAll:()=>[]};_window.HTMLElement||=class HTMLElement{};_window.MutationObserver||=function(){this.observe=()=>{}};_window.customElements||={define:()=>{}};var href=_window.location.href;$B.protocol=href.split(":")[0];$B.BigInt=_window.BigInt;$B.indexedDB=_window.indexedDB;if($B.brython_path===undefined){var this_url;if($B.isWebWorker){this_url=_window.location.href;if(this_url.startsWith("blob:")){this_url=this_url.substr(5)}}else{this_url=document.currentScript.src}var elts=this_url.split("/");elts.pop();$B.brython_path=elts.join("/")+"/"}else{if(!$B.brython_path.endsWith("/")){$B.brython_path+="/"}}var parts_re=new RegExp("(.*?)://(.*?)/(.*)"),mo=parts_re.exec($B.brython_path);if(mo){$B.full_url={protocol:mo[1],host:mo[2],address:mo[3]};if(["http","https"].includes(mo[1])){$B.domain=mo[1]+"://"+mo[2]}}var path=_window.location.origin+_window.location.pathname,path_elts=path.split("/");path_elts.pop();$B.script_dir=path_elts.join("/");mo=parts_re.exec($B.script_dir);if(mo){if(["http","https"].includes(mo[1])){$B.script_domain=mo[1]+"://"+mo[2]}}else{var parts_re_root=new RegExp("(.*?)://(.*?)"),mo=parts_re_root.exec($B.script_dir);if(mo&&["http","https"].includes(mo[1])){$B.script_domain=$B.script_dir}}$B.strip_host=function(url){var parts_re=new RegExp("(.*?)://([^/]*)?[/#]?(.*)"),mo=parts_re.exec(url);if(mo){return mo[3]}console.log(Error().stack);throw Error("not a url: "+url)};$B.webworkers={};$B.file_cache={};$B.url2name={};$B.scripts={};$B.import_info={};$B.imported={};$B.precompiled={};$B.frame_obj=null;$B.builtins=Object.create(null);$B.builtins_scope={id:"__builtins__",module:"__builtins__",binding:{}};$B.builtin_funcs={};$B.builtin_classes=[];$B.__getattr__=function(attr){return this[attr]};$B.__setattr__=function(attr,value){if(["debug","stdout","stderr"].indexOf(attr)>-1){$B[attr]=value}else{throw $B.builtins.AttributeError.$factory("__BRYTHON__ object has no attribute "+attr)}};$B.language=_window.navigator.userLanguage||_window.navigator.language;$B.locale="C";var date=new Date;var formatter=new Intl.DateTimeFormat($B.language,{timeZoneName:"short"}),short=formatter.format(date);formatter=new Intl.DateTimeFormat($B.language,{timeZoneName:"long"});var long=formatter.format(date);var ix=0,minlen=Math.min(short.length,long.length);while(ix>":"rshift","+":"add","-":"sub","*":"mul","/":"truediv","%":"mod","@":"matmul"},augmented_assigns:{"//=":"ifloordiv",">>=":"irshift","<<=":"ilshift","**=":"ipow","+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv","%=":"imod","&=":"iand","|=":"ior","^=":"ixor","@=":"imatmul"},binary:{"&":"and","|":"or","~":"invert","^":"xor"},comparisons:{"<":"lt",">":"gt","<=":"le",">=":"ge","==":"eq","!=":"ne"},boolean:{or:"or",and:"and",in:"in",not:"not",is:"is"},subset:function(){var res={},keys=[];if(arguments[0]=="all"){keys=Object.keys($B.op2method);keys.splice(keys.indexOf("subset"),1)}else{for(var arg of arguments){keys.push(arg)}}for(var key of keys){var ops=$B.op2method[key];if(ops===undefined){throw Error(key)}for(var attr in ops){res[attr]=ops[attr]}}return res}};$B.method_to_op={};for(var category in $B.op2method){for(var op in $B.op2method[category]){var method=`__${$B.op2method[category][op]}__`;$B.method_to_op[method]=op}}$B.special_string_repr={8:"\\x08",9:"\\t",10:"\\n",11:"\\x0b",12:"\\x0c",13:"\\r",92:"\\\\",160:"\\xa0"};$B.$py_next_hash=Math.pow(2,53)-1;$B.$py_UUID=Math.floor(Math.random()*2**50);$B.lambda_magic=Math.random().toString(36).substr(2,8);$B.set_func_names=function(klass,module){for(var attr in klass){if(typeof klass[attr]=="function"){klass[attr].$infos={__doc__:klass[attr].__doc__||"",__module__:module,__qualname__:klass.__qualname__+"."+attr,__name__:attr};if(klass[attr].$type=="classmethod"){klass[attr].__class__=$B.method}}}klass.__module__=module};var has_storage=typeof Storage!=="undefined";if(has_storage){$B.has_local_storage=false;try{if(localStorage){$B.local_storage=localStorage;$B.has_local_storage=true}}catch(err){}$B.has_session_storage=false;try{if(sessionStorage){$B.session_storage=sessionStorage;$B.has_session_storage=true}}catch(err){}}else{$B.has_local_storage=false;$B.has_session_storage=false}$B.globals=function(){return $B.frame_obj.frame[3]};$B.scripts={};$B.$options={};$B.builtins_repr_check=function(builtin,args){var $=$B.args("__repr__",1,{self:null},["self"],args,{},null,null),self=$.self;if(!$B.$isinstance(self,builtin)){var _b_=$B.builtins;throw _b_.TypeError.$factory("descriptor '__repr__' requires a "+`'${builtin.__name__}' object but received a `+`'${$B.class_name(self)}'`)}};$B.update_VFS=function(scripts){$B.VFS=$B.VFS||{};var vfs_timestamp=scripts.$timestamp;if(vfs_timestamp!==undefined){delete scripts.$timestamp}for(var script in scripts){if($B.VFS.hasOwnProperty(script)){console.warn("Virtual File System: duplicate entry "+script)}$B.VFS[script]=scripts[script];$B.VFS[script].timestamp=vfs_timestamp}$B.stdlib_module_names=Object.keys($B.VFS)};$B.add_files=function(files){$B.files=$B.files||{};for(var file in files){$B.files[file]=files[file]}};$B.has_file=function(file){return $B.files&&$B.files.hasOwnProperty(file)};$B.show_tokens=function(src,mode){for(var token of $B.tokenizer(src,"",mode||"file")){console.log(token.type,$B.builtins.repr(token.string),token.start,token.end,token.line)}};function from_py(src,script_id){if(!$B.options_parsed){$B.parse_options()}script_id=script_id||"python_script_"+$B.UUID();var filename=$B.script_path+"#"+script_id;$B.url2name[filename]=script_id;$B.imported[script_id]={};var root=__BRYTHON__.py2js({src:src,filename:filename},script_id,script_id,__BRYTHON__.builtins_scope);return root.to_js()}$B.getPythonModule=function(name){return $B.imported[name]};$B.python_to_js=function(src,script_id){return"(function() {\n"+from_py(src,script_id)+"\nreturn locals}())"};$B.pythonToJS=$B.python_to_js;var fakeScript=$B.fakeScript=function(filename){this.options={}};fakeScript.prototype.getAttribute=function(key){return this.options[key]??null};fakeScript.prototype.dispatchEvent=function(){};$B.runPythonSource=function(src,options){var script_id;if(options){if(typeof options=="string"){script_id=options}else if(options.constructor===Object){if(options.hasOwnProperty("id")){script_id=options.id;delete options.id}}else{console.debug("invalid options argument:",options)}}var script=new fakeScript,url=$B.script_path=globalThis.location.href.split("#")[0];if(options){for(var[key,value]of Object.entries(options)){script.options[key]=value}}script_id=script_id??"python_script_"+$B.UUID();$B.run_script(script,src,script_id,url,true);return $B.imported[script_id]}})(__BRYTHON__);__BRYTHON__.ast_classes={Add:"",And:"",AnnAssign:"target,annotation,value?,simple",Assert:"test,msg?",Assign:"targets*,value,type_comment?",AsyncFor:"target,iter,body*,orelse*,type_comment?",AsyncFunctionDef:"name,args,body*,decorator_list*,returns?,type_comment?,type_params*",AsyncWith:"items*,body*,type_comment?",Attribute:"value,attr,ctx",AugAssign:"target,op,value",Await:"value",BinOp:"left,op,right",BitAnd:"",BitOr:"",BitXor:"",BoolOp:"op,values*",Break:"",Call:"func,args*,keywords*",ClassDef:"name,bases*,keywords*,body*,decorator_list*,type_params*",Compare:"left,ops*,comparators*",Constant:"value,kind?",Continue:"",Del:"",Delete:"targets*",Dict:"keys*,values*",DictComp:"key,value,generators*",Div:"",Eq:"",ExceptHandler:"type?,name?,body*",Expr:"value",Expression:"body",FloorDiv:"",For:"target,iter,body*,orelse*,type_comment?",FormattedValue:"value,conversion,format_spec?",FunctionDef:"name,args,body*,decorator_list*,returns?,type_comment?,type_params*",FunctionType:"argtypes*,returns",GeneratorExp:"elt,generators*",Global:"names*",Gt:"",GtE:"",If:"test,body*,orelse*",IfExp:"test,body,orelse",Import:"names*",ImportFrom:"module?,names*,level?",In:"",Interactive:"body*",Invert:"",Is:"",IsNot:"",JoinedStr:"values*",LShift:"",Lambda:"args,body",List:"elts*,ctx",ListComp:"elt,generators*",Load:"",Lt:"",LtE:"",MatMult:"",Match:"subject,cases*",MatchAs:"pattern?,name?",MatchClass:"cls,patterns*,kwd_attrs*,kwd_patterns*",MatchMapping:"keys*,patterns*,rest?",MatchOr:"patterns*",MatchSequence:"patterns*",MatchSingleton:"value",MatchStar:"name?",MatchValue:"value",Mod:"",Module:"body*,type_ignores*",Mult:"",Name:"id,ctx",NamedExpr:"target,value",Nonlocal:"names*",Not:"",NotEq:"",NotIn:"",Or:"",ParamSpec:"name,default_value?",Pass:"",Pow:"",RShift:"",Raise:"exc?,cause?",Return:"value?",Set:"elts*",SetComp:"elt,generators*",Slice:"lower?,upper?,step?",Starred:"value,ctx",Store:"",Sub:"",Subscript:"value,slice,ctx",Try:"body*,handlers*,orelse*,finalbody*",TryStar:"body*,handlers*,orelse*,finalbody*",Tuple:"elts*,ctx",TypeAlias:"name,type_params*,value",TypeIgnore:"lineno,tag",TypeVar:"name,bound?,default_value?",TypeVarTuple:"name,default_value?",UAdd:"",USub:"",UnaryOp:"op,operand",While:"test,body*,orelse*",With:"items*,body*,type_comment?",Yield:"value?",YieldFrom:"value",alias:"name,asname?",arg:"arg,annotation?,type_comment?",arguments:"posonlyargs*,args*,vararg?,kwonlyargs*,kw_defaults*,kwarg?,defaults*",boolop:["And","Or"],cmpop:["Eq","NotEq","Lt","LtE","Gt","GtE","Is","IsNot","In","NotIn"],comprehension:"target,iter,ifs*,is_async",excepthandler:["ExceptHandler"],expr:["BoolOp","NamedExpr","BinOp","UnaryOp","Lambda","IfExp","Dict","Set","ListComp","SetComp","DictComp","GeneratorExp","Await","Yield","YieldFrom","Compare","Call","FormattedValue","JoinedStr","Constant","Attribute","Subscript","Starred","Name","List","Tuple","Slice"],expr_context:["Load","Store","Del"],keyword:"arg?,value",match_case:"pattern,guard?,body*",mod:["Module","Interactive","Expression","FunctionType"],operator:["Add","Sub","Mult","MatMult","Div","Mod","Pow","LShift","RShift","BitOr","BitXor","BitAnd","FloorDiv"],pattern:["MatchValue","MatchSingleton","MatchSequence","MatchMapping","MatchClass","MatchStar","MatchAs","MatchOr"],stmt:["FunctionDef","AsyncFunctionDef","ClassDef","Return","Delete","Assign","TypeAlias","AugAssign","AnnAssign","For","AsyncFor","While","If","With","AsyncWith","Match","Raise","Try","TryStar","Assert","Import","ImportFrom","Global","Nonlocal","Expr","Pass","Break","Continue"],type_ignore:["TypeIgnore"],type_param:["TypeVar","ParamSpec","TypeVarTuple"],unaryop:["Invert","Not","UAdd","USub"],withitem:"context_expr,optional_vars?"};(function($B){$B.stdlib={};var pylist=["VFS_import","__future__","_aio","_codecs","_codecs_jp","_collections","_collections_abc","_colorize","_compat_pickle","_compression","_contextvars","_csv","_dummy_thread","_frozen_importlib","_functools","_imp","_io","_markupbase","_multibytecodec","_operator","_py_abc","_pydatetime","_pydecimal","_queue","_signal","_socket","_sre","_struct","_sysconfigdata","_sysconfigdata_0_brython_","_testcapi","_thread","_threading_local","_typing","_weakref","_weakrefset","abc","antigravity","argparse","ast","asyncio","atexit","base64","bdb","binascii","bisect","browser.ajax","browser.highlight","browser.idbcache","browser.indexed_db","browser.local_storage","browser.markdown","browser.object_storage","browser.session_storage","browser.svg","browser.template","browser.timer","browser.ui","browser.webcomponent","browser.websocket","browser.worker","calendar","cmath","cmd","code","codecs","codeop","colorsys","configparser","contextlib","contextvars","copy","copyreg","csv","dataclasses","datetime","decimal","difflib","doctest","enum","errno","external_import","faulthandler","fnmatch","formatter","fractions","functools","gc","genericpath","getopt","getpass","gettext","glob","gzip","heapq","hmac","imp","inspect","interpreter","io","ipaddress","itertools","keyword","linecache","locale","mimetypes","ntpath","numbers","opcode","operator","optparse","os","pathlib","pdb","pickle","pkgutil","platform","posixpath","pprint","profile","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","re1","reprlib","secrets","select","selectors","shlex","shutil","signal","site","site-packages.__future__","site-packages.docs","site-packages.header","site-packages.test_sp","socket","sre_compile","sre_constants","sre_parse","stat","statistics","string","stringprep","struct","subprocess","symtable","sys","sysconfig","tabnanny","tarfile","tb","tempfile","test.namespace_pkgs.module_and_namespace_package.a_test","textwrap","this","threading","time","timeit","token","tokenize","traceback","turtle","types","typing","uuid","warnings","weakref","webbrowser","zipfile","zipimport","zlib"];for(var i=0;i":"RARROW",".":"DOT","...":"ELLIPSIS","/":"SLASH","//":"DOUBLESLASH","//=":"DOUBLESLASHEQUAL","/=":"SLASHEQUAL",":":"COLON",":=":"COLONEQUAL",";":"SEMI","<":"LESS","<<":"LEFTSHIFT","<<=":"LEFTSHIFTEQUAL","<=":"LESSEQUAL","=":"EQUAL","==":"EQEQUAL",">":"GREATER",">=":"GREATEREQUAL",">>":"RIGHTSHIFT",">>=":"RIGHTSHIFTEQUAL","@":"AT","@=":"ATEQUAL","[":"LSQB","]":"RSQB","^":"CIRCUMFLEX","^=":"CIRCUMFLEXEQUAL","{":"LBRACE","|":"VBAR","|=":"VBAREQUAL","}":"RBRACE","~":"TILDE"};function ISTERMINAL(x){return x=NT_OFFSET}function ISEOF(x){return x==ENDMARKER}})(__BRYTHON__);(function($B){var _b_=$B.builtins;function is_whitespace(char){return" \n\r\t\f".includes(char)}var unprintable_re=/\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}|\p{Zl}|\p{Zp}|\p{Zs}/u;const Other_ID_Start=[6277,6278,8472,8494,12443,12444].map((x=>String.fromCodePoint(x)));function is_ID_Start(char){return/\p{Letter}/u.test(char)||/\p{Nl}/u.test(char)||char=="_"||Other_ID_Start.includes(char)}const Other_ID_Continue=[183,903,4969,4976,4977,6618,8204,8205,12539,65381].map((x=>String.fromCodePoint(x)));function is_ID_Continue(char){return is_ID_Start(char)||/\p{Mn}|\p{Mc}|\p{Nd}|\p{Pc}/u.test(char)||Other_ID_Continue.includes(char)}$B.is_XID_Start=function(cp){let char=String.fromCodePoint(cp);if(!is_ID_Start(char)){return false}var norm=char.normalize("NFKC");if(!is_ID_Start(norm[0])){return false}for(let char of norm.substr(1)){if(!is_ID_Continue(char)){return false}}return true};$B.is_XID_Continue=function(cp){let char=String.fromCodePoint(cp);if(!is_ID_Continue(char)){return false}var norm=char.normalize("NFKC");for(let char of norm.substr(1)){if(!is_ID_Continue(char)){return false}}return true};$B.in_unicode_category=function(category,cp){if(isNaN(cp)){return false}try{var re=new RegExp("\\p{"+category+"}","u");return re.test(String.fromCodePoint(cp))}catch(err){return in_unicode_category(category,cp)}};function in_unicode_category(category,cp){var table=$B.unicode[category],start=0,end=table.length-1,len=table.length,ix=Math.floor(len/2),nb=0;var first=table[start],item=typeof first=="number"?first:first[0];if(cplast){return false}}else if(last[0]+last[1]100){console.log("infinite loop for",cp);alert()}item=table[ix];if(typeof item!="number"){item=item[0]}if(item==cp){return true}else if(item>cp){end=ix}else{start=ix}len=Math.floor((end-start)/2);if(end-start==1){break}ix=start+len}var step=table[start][2];if(step===undefined){return table[start][0]+table[start][1]>cp}return table[start][0]+step*table[start][1]>cp&&(cp-table[start][0])%step==0}const FSTRING_START="FSTRING_START",FSTRING_MIDDLE="FSTRING_MIDDLE",FSTRING_END="FSTRING_END";function ord(char){if(char.length==1){return char.charCodeAt(0)}var code=65536;code+=(char.charCodeAt(0)&1023)<<10;code+=char.charCodeAt(1)&1023;return code}function $last(array){return array[array.length-1]}var ops=".,:;+-*/%~^|&=<>[](){}@",op2=["**","//",">>","<<"],augm_op="+-*/%^|&=<>@",closing={"}":"{","]":"[",")":"("};function Token(type,string,lineno,col_offset,end_lineno,end_col_offset,line){var res={type:type,string:string,line:line,lineno:lineno,col_offset:col_offset,end_lineno:end_lineno,end_col_offset:end_col_offset};res.num_type=$B.py_tokens[type];if(type=="OP"){res.num_type=$B.py_tokens[$B.EXACT_TOKEN_TYPES[string]]}else if(type=="ENCODING"){res.num_type=$B.py_tokens.ENCODING}res.bytes=res.string;return res}function get_comment(parser,src,pos,line_num,line_start,token_name,line){var start=pos,ix;var t=[];while(true){if(pos>=src.length||(ix="\r\n".indexOf(src[pos]))>-1){if(parser&&parser.flags&$B.PyCF_TYPE_COMMENTS){var comment=src.substring(start-1,pos),mo=/^#\s*type\s*:(.*)/.exec(comment);if(mo){var is_type_ignore=false;if(mo[1].startsWith("ignore")){if(mo[1].length==6){is_type_ignore=true}else{var char=mo[1][6];if(char.charCodeAt(0)<=128&&/[a-zA-Z0-9]/.exec(char)===null){is_type_ignore=true}}}if(is_type_ignore){t.push(Token("TYPE_IGNORE",comment,line_num,start-line_start,line_num,pos-line_start+1,line))}else{t.push(Token("TYPE_COMMENT",comment,line_num,start-line_start,line_num,pos-line_start+1,line))}return{t:t,pos:pos}}}t.push(Token("COMMENT",src.substring(start-1,pos),line_num,start-line_start,line_num,pos-line_start+1,line));if(ix!==undefined){var nb=1;if(src[pos]=="\r"&&src[pos+1]=="\n"){nb++}else if(src[pos]===undefined){nb=0}t.push(Token(token_name,src.substr(pos,nb),line_num,pos-line_start+1,line_num,pos-line_start+nb+1,line));if(src[pos]===undefined){t.push(Token("NEWLINE","\n",line_num,pos-line_start+1,line_num,pos-line_start+2,""))}pos+=nb}return{t:t,pos:pos}}pos++}}function test_num(num_type,char){switch(num_type){case"":return $B.in_unicode_category("Nd",ord(char));case"x":return"0123456789abcdef".includes(char.toLowerCase());case"b":return"01".includes(char);case"o":return"01234567".includes(char);default:throw Error("unknown num type "+num_type)}}function nesting_level(token_modes){var ix=token_modes.length-1;while(ix>=0){var mode=token_modes[ix];if(mode.nesting!==undefined){return mode.nesting}ix--}}$B.tokenizer=function*(src,filename,mode,parser){var string_prefix=/^(r|u|R|U|f|F|fr|Fr|fR|FR|rf|rF|Rf|RF)$/,bytes_prefix=/^(b|B|br|Br|bR|BR|rb|rB|Rb|RB)$/;src=src.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(mode!="eval"&&!src.endsWith("\n")){src+="\n"}var lines=src.split("\n"),linenum=0,line_at={};for(let i=0,len=src.length;i=55296&&cp<=56319){cp=ord(src.substr(pos,2));char=src.substr(pos,2);pos++}pos++;if(token_mode!=save_mode){if(token_mode=="fstring"){fstring_buffer="";fstring_escape=false}else if(token_mode=="format_specifier"){format_specifier=""}}save_mode=token_mode;if(token_mode=="fstring"){if(char==token_mode.quote){if(fstring_escape){fstring_buffer+="\\"+char;fstring_escape=false;continue}if(token_mode.triple_quote){if(src.substr(pos,2)!=token_mode.quote.repeat(2)){fstring_buffer+=char;continue}char=token_mode.quote.repeat(3);pos+=2}if(fstring_buffer.length>0){yield Token(FSTRING_MIDDLE,fstring_buffer,line_num,fstring_start,line_num,fstring_start+fstring_buffer.length,line)}yield Token(FSTRING_END,char,line_num,pos-line_start,line_num,pos-line_start+1,line);token_modes.pop();token_mode=$B.last(token_modes);state=null;continue}else if(char=="{"){if(src.charAt(pos)=="{"){fstring_buffer+=char;pos++;continue}else{if(fstring_buffer.length>0){yield Token(FSTRING_MIDDLE,fstring_buffer,line_num,fstring_start,line_num,fstring_start+fstring_buffer.length,line)}token_mode="regular_within_fstring";fstring_expr_start=pos-line_start;state=null;token_modes.push(token_mode)}}else if(char=="}"){if(src.charAt(pos)=="}"){fstring_buffer+=char;pos++;continue}else{yield Token("OP",char,line_num,pos-line_start,line_num,pos-line_start+1,line);continue}}else if(char=="\\"){if(token_mode.raw){fstring_buffer+=char+char}else{if(fstring_escape){fstring_buffer+="\\"+char}fstring_escape=!fstring_escape}continue}else{if(fstring_escape){fstring_buffer+="\\"}fstring_buffer+=char;fstring_escape=false;if(char=="\n"){line_num++}continue}}else if(token_mode=="format_specifier"){if(char==quote){if(format_specifier.length>0){yield Token(FSTRING_MIDDLE,format_specifier,line_num,fstring_start,line_num,fstring_start+format_specifier.length,line);token_modes.pop();token_mode=$B.last(token_modes);continue}}else if(char=="{"){yield Token(FSTRING_MIDDLE,format_specifier,line_num,fstring_start,line_num,fstring_start+format_specifier.length,line);token_mode="regular_within_fstring";fstring_expr_start=pos-line_start;state=null;token_modes.push(token_mode)}else if(char=="}"){yield Token(FSTRING_MIDDLE,format_specifier,line_num,fstring_start,line_num,fstring_start+format_specifier.length,line);yield Token("OP",char,line_num,pos-line_start,line_num,pos-line_start+1,line);if(braces.length==0||$B.last(braces).char!=="{"){throw Error("wrong braces")}braces.pop();token_modes.pop();token_mode=$B.last(token_modes);continue}else{format_specifier+=char;continue}}switch(state){case"line_start":line=get_line_at(pos-1);line_start=pos;line_num++;if(mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos-1))){yield Token("NL",mo[0],line_num,0,line_num,mo[0].length,line);pos+=mo[0].length-1;continue}else if(char=="#"){comment=get_comment(parser,src,pos,line_num,line_start,"NL",line);for(var item of comment.t){yield item}pos=comment.pos;state="line_start";continue}indent=0;if(char==" "){indent=1}else if(char=="\t"){indent=8}if(indent){var broken=false;while(pos0&&" \t".includes(src[pos])){console.log("indentation error 479");$B.raise_error_known_location(_b_.IndentationError,filename,line_num,pos-line_start,line_num,pos-line_start+1,line,"unindent does not match any outer indentation level")}if(src[pos]==" "){indent++}else if(src[pos]=="\t"){indent+=8}else if(src[pos]=="\\"&&src[pos+1]=="\n"){pos++;line_start=pos+2;line_num++;line=get_line_at(pos+2);broken=true}else{break}pos++}if(pos==src.length){line_num--;break}if(src[pos]=="#"){comment=get_comment(parser,src,pos+1,line_num,line_start,"NL",line);for(var item of comment.t){yield item}pos=comment.pos;continue}else if(src[pos]=="\\"){if(/^\f?(\r\n|\r|\n)/.exec(src[pos+1])){line_num++;pos++;continue}else{$B.raise_error_known_location(_b_.SyntaxError,filename,line_num,pos+2-line_start,line_num,pos+3-line_start,line,"unexpected character after line continuation character")}}else if(mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos))){yield Token("NL","",line_num,pos-line_start+1,line_num,pos-line_start+1+mo[0].length,line);pos+=mo[0].length;continue}if(indents.length==0||indent>$last(indents)){indents.push(indent);yield Token("INDENT","",line_num,0,line_num,indent,line)}else if(indent<$last(indents)){var ix=indents.indexOf(indent);if(ix==-1){var message="unindent does not match "+"any outer indentation level";$B.raise_error_known_location(_b_.IndentationError,filename,line_num,0,line_num,0,line,message)}for(var i=indents.length-1;i>ix;i--){indents.pop();yield Token("DEDENT","",line_num,indent,line_num,indent,line)}}state=null}else{while(indents.length>0){indents.pop();yield Token("DEDENT","",line_num,indent,line_num,indent,line)}state=null;pos--}break;case null:switch(char){case'"':case"'":quote=char;triple_quote=src[pos]==char&&src[pos+1]==char;string_start=[line_num,pos-line_start,line_start];if(triple_quote){pos+=2}escaped=false;state="STRING";string="";prefix="";break;case"#":var token_name=braces.length>0?"NL":"NEWLINE";comment=get_comment(parser,src,pos,line_num,line_start,token_name,line);for(var item of comment.t){yield item}pos=comment.pos;if(braces.length==0){state="line_start"}else{state=null;line_num++;line_start=pos+1;line=get_line_at(pos)}break;case"0":state="NUMBER";number=char;num_type="";if(src[pos]&&"xbo".includes(src[pos].toLowerCase())){number+=src[pos];num_type=src[pos].toLowerCase();pos++}else if(src[pos]){var pos1=pos;while(pos1=3){yield Token("OP","...",line_num,dot_pos,line_num,dot_pos+3,line);op=op.substr(3)}for(var i=0;i0?"NL":"NEWLINE";mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos-1));yield Token(token_name,mo[0],line_num,pos-line_start,line_num,pos-line_start+mo[0].length,line);pos+=mo[0].length-1;if(token_name=="NEWLINE"){state="line_start"}else{line_num++;line_start=pos+1;line=get_line_at(pos)}break;default:if($B.is_XID_Start(ord(char))){state="NAME";name=char}else if($B.in_unicode_category("Nd",ord(char))){state="NUMBER";num_type="";number=char}else if(ops.includes(char)){if(token_mode=="regular_within_fstring"&&(char==":"||char=="}")){if(char==":"){if(nesting_level(token_modes)==braces.length-1){let colon=Token("OP",char,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line);colon.metadata=src.substr(line_start+fstring_expr_start,pos-line_start-fstring_expr_start-1);yield colon;token_modes.pop();token_mode="format_specifier";token_modes.push(token_mode);continue}}else{let closing_brace=Token("OP",char,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line);closing_brace.metadata=src.substring(line_start+fstring_expr_start,pos-1);yield closing_brace;token_modes.pop();token_mode=token_modes[token_modes.length-1];if(braces.length==0||$B.last(braces).char!=="{"){throw Error("wrong braces")}braces.pop();continue}}var op=char;if(op2.includes(char+src[pos])){op=char+src[pos];pos++}if(src[pos]=="="&&(op.length==2||augm_op.includes(op))){op+=src[pos];pos++}else if(char=="-"&&src[pos]==">"||char==":"&&src[pos]=="="){op+=src[pos];pos++}if("[({".includes(char)){braces.push({char:char,pos:pos,line_num:line_num,line_start:line_start,line:line})}else if("])}".includes(char)){if(braces.length&&$last(braces).char==closing[char]){braces.pop()}else{braces.push({char:char,pos:pos,line_num:line_num,line_start:line_start,line:line})}}yield Token("OP",op,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line)}else if(char=="!"){if(src[pos]=="="){yield Token("OP","!=",line_num,pos-line_start,line_num,pos-line_start+2,line);pos++}else{let token=Token("OP",char,line_num,pos-line_start,line_num,pos-line_start+1,line);token.metadata=src.substring(line_start+fstring_start+2,pos-1);yield token}}else if(char==" "||char=="\t"){}else{var cp=char.codePointAt(0),err_msg="invalid";if(unprintable_re.exec(char)){err_msg+=" non-printable"}var unicode=cp.toString(16).toUpperCase();while(unicode.length<4){unicode="0"+unicode}err_msg+=` character '${char}' (U+${unicode})`;if(char=="$"||char=="`"){err_msg="invalid syntax"}var err_token=Token("ERRORTOKEN",char,line_num,pos-line_start,line_num,pos-line_start+1,line);$B.raise_error_known_token(_b_.SyntaxError,filename,err_token,err_msg)}}break;case"NAME":if($B.is_XID_Continue(ord(char))){name+=char}else if(char=='"'||char=="'"){if(string_prefix.exec(name)||bytes_prefix.exec(name)){state="STRING";quote=char;triple_quote=src[pos]==quote&&src[pos+1]==quote;prefix=name;if(triple_quote){pos+=2}if(prefix.toLowerCase().includes("f")){fstring_start=pos-line_start-name.length;token_mode=new String("fstring");token_mode.nesting=braces.length;token_mode.quote=quote;token_mode.triple_quote=triple_quote;token_mode.raw=prefix.toLowerCase().includes("r");token_modes.push(token_mode);var s=triple_quote?quote.repeat(3):quote;var end_col=fstring_start+name.length+s.length;yield Token(FSTRING_START,prefix+s,line_num,fstring_start,line_num,end_col,line);continue}escaped=false;string_start=[line_num,pos-line_start-name.length,line_start];string=""}else{yield Token("NAME",name,line_num,pos-line_start-name.length,line_num,pos-line_start,line);state=null;pos--}}else{yield Token("NAME",name,line_num,pos-line_start-name.length,line_num,pos-line_start,line);state=null;pos--}break;case"STRING":switch(char){case quote:if(!escaped){var string_line=line;if(line_num>string_start[0]){string_line=src.substring(string_start[2]-1,pos+2)}var full_string;if(!triple_quote){full_string=prefix+quote+string+quote;yield Token("STRING",full_string,string_start[0],string_start[1],line_num,pos-line_start+1,string_line);state=null}else if(char+src.substr(pos,2)==quote.repeat(3)){full_string=prefix+quote.repeat(3)+string+quote.repeat(3);yield Token("STRING",full_string,string_start[0],string_start[1],line_num,pos-line_start+3,string_line);pos+=2;state=null}else{string+=char}}else{string+=char}escaped=false;break;case"\r":case"\n":if(!escaped&&!triple_quote){var msg=`unterminated string literal `+`(detected at line ${line_num})`,line_num=string_start[0],col_offset=string_start[1];$B.raise_error_known_location(_b_.SyntaxError,filename,line_num,col_offset,line_num,col_offset,line,msg)}string+=char;line_num++;line_start=pos+1;if(char=="\r"&&src[pos]=="\n"){string+=src[pos];line_start++;pos++}line=get_line_at(pos);escaped=false;break;case"\\":string+=char;escaped=!escaped;break;default:escaped=false;string+=char;break}break;case"NUMBER":if(test_num(num_type,char)){number+=char}else if(char=="_"&&!number.endsWith(".")){if(number.endsWith("_")){throw SyntaxError("consecutive _ in number")}else if(src[pos]===undefined||!test_num(num_type,src[pos])){yield Token("NUMBER",number,line_num,pos-line_start-number.length,line_num,pos-line_start,line);state=null;pos--}else{number+=char}}else if(char=="."&&!number.includes(char)){number+=char}else if(char.toLowerCase()=="e"&&!number.toLowerCase().includes("e")){if("+-".includes(src[pos])||$B.in_unicode_category("Nd",ord(src[pos]))){number+=char}else{yield Token("NUMBER",number,line_num,pos-line_start-number.length,line_num,pos-line_start,line);state=null;pos--}}else if((char=="+"||char=="-")&&number.toLowerCase().endsWith("e")){number+=char}else if(char.toLowerCase()=="j"){number+=char;yield Token("NUMBER",number,line_num,pos-line_start-number.length+1,line_num,pos-line_start+1,line);state=null}else if(char.match(/\p{Letter}/u)){$B.raise_error_known_location(_b_.SyntaxError,filename,line_num,pos-line_start-number.length,line_num,pos-line_start,line,"invalid decimal literal")}else{yield Token("NUMBER",number,line_num,pos-line_start-number.length,line_num,pos-line_start,line);state=null;pos--}break}}switch(state){case"line_start":line_num++;break;case"NAME":yield Token("NAME",name,line_num,pos-line_start-name.length+1,line_num,pos-line_start+1,line);break;case"NUMBER":yield Token("NUMBER",number,line_num,pos-line_start-number.length+1,line_num,pos-line_start+1,line);break;case"STRING":line_num=string_start[0];line=lines[line_num-1];var msg=`unterminated ${triple_quote?"triple-quoted ":""}`+`string literal (detected at line ${line_num})`,col_offset=string_start[1];$B.raise_error_known_location(_b_.SyntaxError,filename,line_num,col_offset,line_num,col_offset,line,msg)}if(!src.endsWith("\n")&&state!=line_start){yield Token("NEWLINE","",line_num,pos-line_start+1,line_num,pos-line_start+1,line+"\n");line_num++}while(indents.length>0){indents.pop();yield Token("DEDENT","",line_num,0,line_num,0,"")}yield Token("ENDMARKER","",line_num,0,line_num,0,"")}})(__BRYTHON__);(function($B){var binary_ops={"+":"Add","-":"Sub","*":"Mult","/":"Div","//":"FloorDiv","%":"Mod","**":"Pow","<<":"LShift",">>":"RShift","|":"BitOr","^":"BitXor","&":"BitAnd","@":"MatMult"};var boolean_ops={and:"And",or:"Or"};var comparison_ops={"==":"Eq","!=":"NotEq","<":"Lt","<=":"LtE",">":"Gt",">=":"GtE",is:"Is",is_not:"IsNot",in:"In",not_in:"NotIn"};var unary_ops={unary_inv:"Invert",unary_pos:"UAdd",unary_neg:"USub",unary_not:"Not"};var op_types=$B.op_types=[binary_ops,boolean_ops,comparison_ops,unary_ops];var _b_=$B.builtins;var ast=$B.ast={};for(var kl in $B.ast_classes){var args=$B.ast_classes[kl],body="";if(typeof args=="string"){if(args.length>0){for(var arg of args.split(",")){if(arg.endsWith("*")){arg=arg.substr(0,arg.length-1);body+=` this.${arg} = $B.$list(${arg} === undefined ? [] : ${arg})\n`}else if(arg.endsWith("?")){arg=arg.substr(0,arg.length-1);body+=` this.${arg} = ${arg}\n`}else{body+=` this.${arg} = ${arg}\n`}}}var arg_list=args.replace(/[*?]/g,"").split(",");ast[kl]=Function(...arg_list,body);ast[kl]._fields=args.split(",")}else{ast[kl]=args.map((x=>ast[x]))}ast[kl].$name=kl}$B.ast_js_to_py=function(obj){$B.create_python_ast_classes();if(obj===undefined){return _b_.None}else if(Array.isArray(obj)){return $B.$list(obj.map($B.ast_js_to_py))}else{var class_name=obj.constructor.$name,py_class=$B.python_ast_classes[class_name],py_ast_obj={__class__:py_class};if(py_class===undefined){return obj}for(var field of py_class._fields){py_ast_obj[field]=$B.ast_js_to_py(obj[field])}py_ast_obj._attributes=$B.fast_tuple([]);for(var loc of["lineno","col_offset","end_lineno","end_col_offset"]){if(obj[loc]!==undefined){py_ast_obj[loc]=obj[loc];py_ast_obj._attributes.push(loc)}}return py_ast_obj}};$B.ast_py_to_js=function(obj){if(obj===undefined||obj===_b_.None){return undefined}else if(Array.isArray(obj)){return obj.map($B.ast_py_to_js)}else if(typeof obj=="string"){return obj}else{var class_name=$B.class_name(obj),js_class=$B.ast[class_name];if(js_class===undefined){return obj}var js_ast_obj=new js_class;for(var field of js_class._fields){if(field.endsWith("?")||field.endsWith("*")){field=field.substr(0,field.length-1)}js_ast_obj[field]=$B.ast_py_to_js(obj[field])}for(var loc of["lineno","col_offset","end_lineno","end_col_offset"]){if(obj[loc]!==undefined){js_ast_obj[loc]=obj[loc]}}return js_ast_obj}};$B.create_python_ast_classes=function(){if($B.python_ast_classes){return}$B.python_ast_classes={};for(var klass in $B.ast_classes){$B.python_ast_classes[klass]=function(kl){var _fields,raw_fields;if(typeof $B.ast_classes[kl]=="string"){if($B.ast_classes[kl]==""){raw_fields=_fields=[]}else{raw_fields=$B.ast_classes[kl].split(",");_fields=raw_fields.map((x=>x.endsWith("*")||x.endsWith("?")?x.substr(0,x.length-1):x))}}var cls=$B.make_class(kl),$defaults={},slots={},nb_args=0;if(raw_fields){for(let i=0,len=_fields.length;i2){console.log("wrong js indent");console.log(res)}level=0}try{res+=(add_spaces?indentation.repeat(level):"")+line+"\n"}catch(err){console.log(res);throw err}if(line.endsWith("{")){level++}else if(add_closing_brace){level--;if(level<0){level=0}try{res+=indentation.repeat(level)+"}\n"}catch(err){console.log(res);throw err}}last_is_backslash=line.endsWith("\\");last_is_var_and_comma=line.endsWith(",")&&(line.startsWith("var ")||last_is_var_and_comma)}return res};function get_docstring(node){var doc_string=_b_.None;if(node.body.length>0){var firstchild=node.body[0];if(firstchild instanceof $B.ast.Constant&&typeof firstchild.value=="string"){doc_string=firstchild.value}}return doc_string}var s_escaped='abfnrtvxuU"0123456789'+"'"+"\\",is_escaped={};for(var i=0;i>10)+String.fromCharCode(56320|value&1023)}function test_escape(text,antislash_pos){var seq_end,mo;mo=/^[0-7]{1,3}/.exec(text.substr(antislash_pos+1));if(mo){return[String.fromCharCode(parseInt(mo[0],8)),1+mo[0].length]}switch(text[antislash_pos+1]){case"x":mo=/^[0-9A-F]{0,2}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=2){seq_end=antislash_pos+mo[0].length+1;$token.value.start[1]=seq_end;throw Error("(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\xXX escape")}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]}break;case"u":mo=/^[0-9A-F]{0,4}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=4){seq_end=antislash_pos+mo[0].length+1;$token.value.start[1]=seq_end;throw Error("(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\uXXXX escape")}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]}break;case"U":mo=/^[0-9A-F]{0,8}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=8){seq_end=antislash_pos+mo[0].length+1;$token.value.start[1]=seq_end;throw Error("(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\uXXXX escape")}else{let value=parseInt(mo[0],16);if(value>1114111){throw Error("invalid unicode escape "+mo[0])}else if(value>=65536){return[SurrogatePair(value),2+mo[0].length]}else{return[String.fromCharCode(value),2+mo[0].length]}}}}$B.test_escape=test_escape;function unindent(src){var lines=src.split("\n"),line,global_indent,indent,first,unindented_lines=[];var min_indent;for(var line of lines){if(/^\s*$/.exec(line)){continue}indent=line.match(/^\s*/)[0].length;if(indent==0){return src}if(min_indent===undefined){min_indent=indent}if(indent0;options.python_extension=options.python_extension||".py";if($B.$options.args){$B.__ARGV=$B.$options.args}else{$B.__ARGV=_b_.list.$factory([])}$B.options_parsed=true;return options};if(!($B.isWebWorker||$B.isNode)){var startup_observer=new MutationObserver((function(mutations){for(var mutation of mutations){for(var addedNode of mutation.addedNodes){addPythonScript(addedNode)}}}));startup_observer.observe(document.documentElement,{childList:true,subtree:true})}var brython_options=$B.brython_options={};var python_scripts=[];if(!$B.isWebWorker){python_scripts=python_scripts.concat(Array.from(document.querySelectorAll('script[type="text/python"]'))).concat(Array.from(document.querySelectorAll('script[type="text/python3"]')));var onload;addEventListener("DOMContentLoaded",(function(ev){if(ev.target.body){onload=ev.target.body.onload}if(!onload){ev.target.body.onload=function(){return brython()}}else{ev.target.body.onload=function(){onload();if(!status.brython_called){brython()}}}}));class BrythonOptions extends HTMLElement{constructor(){super()}connectedCallback(){for(var attr of this.getAttributeNames()){brython_options[attr]=convert_option(attr,this.getAttribute(attr))}}}customElements.define("brython-options",BrythonOptions)}var defined_ids={},script_to_id=new Map,id_to_script={};function addPythonScript(addedNode){if(addedNode.tagName=="SCRIPT"&&(addedNode.type=="text/python"||addedNode.type=="text/python3")){python_scripts.push(addedNode)}}var status={brython_called:false,first_unnamed_script:true};$B.dispatch_load_event=function(script){script.dispatchEvent(new Event("load"))};function injectPythonScript(addedNode){if(addedNode.tagName=="SCRIPT"&&addedNode.type=="text/python"){set_script_id(addedNode);run_scripts([addedNode])}}function set_script_id(script){if(script_to_id.has(script)){}else if(script.id){if(defined_ids[script.id]){throw Error("Brython error : Found 2 scripts with the "+"same id '"+script.id+"'")}else{defined_ids[script.id]=true}script_to_id.set(script,script.id)}else{if(script.className==="webworker"){throw _b_.AttributeError.$factory("webworker script has no attribute 'id'")}if(status.first_unnamed_script){script_to_id.set(script,"__main__");status.first_unnamed_script=false}else{script_to_id.set(script,"__main__"+$B.UUID())}}var id=script_to_id.get(script);id_to_script[id]=script;return id}var brython=$B.parser.brython=function(options){$B.$options=$B.parse_options(options);if(!($B.isWebWorker||$B.isNode)){if(!status.brython_called){status.brython_called=true;startup_observer.disconnect();var inject_observer=new MutationObserver((function(mutations){for(var mutation of mutations){for(var addedNode of mutation.addedNodes){injectPythonScript(addedNode)}}}));inject_observer.observe(document.documentElement,{childList:true,subtree:true})}}else if($B.isNode){return}for(var python_script of python_scripts){set_script_id(python_script)}var scripts=[];$B.script_path=_window.location.href.split("#")[0];var $href=$B.script_path=_window.location.href.split("#")[0],$href_elts=$href.split("/");$href_elts.pop();if($B.isWebWorker||$B.isNode){$href_elts.pop()}$B.curdir=$href_elts.join("/");var kk=Object.keys(_window);var ids=$B.get_page_option("ids");if(ids!==undefined){if(!Array.isArray(ids)){throw _b_.ValueError.$factory("ids is not a list")}if(ids.length==0){}for(var id of ids){var script=document.querySelector(`script[id="${id}"]`);if(script){set_script_id(script);scripts.push(script)}else{console.log(`no script with id '${id}'`);throw _b_.KeyError.$factory(`no script with id '${id}'`)}}}else if($B.isWebWorker){}else{scripts=python_scripts.slice()}run_scripts(scripts)};function convert_option(option,value){if(option=="debug"){if(typeof value=="string"&&value.match(/^\d+$/)){return parseInt(value)}else if(typeof value=="number"){return value}else{if(value!==null&&value!==undefined){console.debug(`Invalid value for debug: ${value}`)}}}else if(option=="cache"||option=="indexeddb"||option=="static_stdlib_import"){if(value=="1"||value.toLowerCase()=="true"){return true}else if(value=="0"||value.toLowerCase()=="false"){return false}else{console.debug(`Invalid value for ${option}: ${value}`)}}else if(option=="ids"||option=="pythonpath"||option=="args"){if(typeof value=="string"){if(value.trim().length==0){return[]}return value.trim().split(/\s+/)}}return value}const default_option={args:[],cache:false,debug:1,indexeddb:true,python_extension:".py",static_stdlib_import:true};$B.get_filename=function(){if($B.count_frames()>0){return $B.get_frame_at(0).__file__}};$B.get_filename_for_import=function(){var filename=$B.get_filename();if($B.import_info[filename]===undefined){$B.make_import_paths(filename)}return filename};$B.get_page_option=function(option){option=option.toLowerCase();if($B.$options.hasOwnProperty(option)){return $B.$options[option]}else if(brython_options.hasOwnProperty(option)){return brython_options[option]}else{return default_option[option]}};$B.get_option=function(option,err){var filename=$B.script_filename;if(err&&err.$frame_obj){filename=$B.get_frame_at(0,err.$frame_obj).__file__}else{filename=$B.get_filename()}return $B.get_option_from_filename(option,filename)};$B.get_option_from_filename=function(option,filename){if(filename===undefined||!$B.scripts[filename]){return $B.get_page_option(option)}var value=$B.scripts[filename].getAttribute(option);if(value!==null){return convert_option(option,value)}else{return $B.get_page_option(option)}};function run_scripts(_scripts){var webworkers=_scripts.filter((script=>script.className==="webworker")),scripts=_scripts.filter((script=>script.className!=="webworker"));var module_name,filename;if(scripts.length>0||$B.isWebWorker){if($B.get_page_option("indexedDB")&&$B.has_indexedDB&&$B.hasOwnProperty("VFS")){$B.tasks.push([$B.idb_open])}}var src;for(var worker of webworkers){if(worker.src){$B.tasks.push([$B.ajax_load_script,{script:worker,name:worker.id,url:worker.src,is_ww:true}])}else{$B.webworkers[worker.id]=worker;filename=$B.script_filename=$B.strip_host($B.script_path+"#"+worker.id);var source=worker.innerText||worker.textContent;source=unindent(source);source=source.replace(/^\n/,"");$B.url2name[filename]=worker.id;$B.file_cache[filename]=source;$B.scripts[filename]=worker;$B.dispatch_load_event(worker)}}for(var script of scripts){module_name=script_to_id.get(script);if(script.src){$B.tasks.push([$B.ajax_load_script,{script:script,name:module_name,url:script.src,id:script.id}])}else{filename=$B.script_filename=$B.strip_host($B.script_path+"#"+module_name);src=script.innerHTML||script.textContent;src=unindent(src);src=src.replace(/^\n/,"");if(src.endsWith("\n")){src=src.substr(0,src.length-1)}$B.tasks.push([$B.run_script,script,src,module_name,$B.script_path,true])}}$B.loop()}$B.run_script=function(script,src,name,url,run_loop){var filename=$B.script_filename=$B.strip_host(url+"#"+name);var script_elts=url.split("/");script_elts.pop();$B.script_dir=script_elts.join("/");$B.file_cache[filename]=src;$B.url2name[filename]=name;$B.scripts[filename]=script;$B.make_import_paths(filename);_b_.__debug__=$B.get_option("debug")>0;var root,js;try{root=$B.py2js({src:src,filename:filename},name,name);js=root.to_js();if($B.get_option_from_filename("debug",filename)>1){console.log($B.format_indent(js,0))}}catch(err){console.log("err",err);return $B.handle_error($B.exception(err))}var _script={__doc__:get_docstring(root._ast),js:js,__name__:name,__file__:url,script_element:script};$B.tasks.push(["execute",_script]);if(run_loop){$B.loop()}};$B.brython=brython})(__BRYTHON__);globalThis.brython=__BRYTHON__.brython;if(__BRYTHON__.isNode){global.__BRYTHON__=__BRYTHON__;module.exports={__BRYTHON__:__BRYTHON__}}(function($B){var _b_=$B.builtins;if($B.VFS_timestamp&&$B.VFS_timestamp>$B.timestamp){$B.timestamp=$B.VFS_timestamp}function idb_load(evt,module){var res=evt.target.result;var debug=$B.get_page_option("debug");if(res===undefined||res.timestamp!=$B.timestamp||$B.VFS[module]&&res.source_ts!==$B.VFS[module].timestamp){if($B.VFS[module]!==undefined){var elts=$B.VFS[module],ext=elts[0],source=elts[1];if(ext==".py"){var is_package=elts.length==4,__package__;if(is_package){__package__=module}else{var parts=module.split(".");parts.pop();__package__=parts.join(".")}$B.imported[module]=$B.module.$factory(module,"",__package__);$B.url2name[module]=module;try{$B.py2js({src:source,filename:module},module,module)}catch(err){$B.handle_error(err)}delete $B.imported[module];if(debug>1){console.log("precompile",module)}}else{console.log("bizarre",module,ext)}}else{}}else{if(res.is_package){$B.precompiled[module]=[res.content]}else{$B.precompiled[module]=res.content}if(res.imports.length>0){if(debug>1){console.log(module,"imports",res.imports)}var subimports=res.imports.split(",");for(var i=0;i0){let module=outdated.pop(),req=store.delete(module);req.onsuccess=function(mod){return function(){if($B.get_page_option("debug")>1){console.info("delete outdated",mod)}report_remove_outdated(mod);remove_outdated(db,outdated,callback)}}(module)}else{report_close();callback()}}$B.idb_open_promise=function(){return new Promise((function(resolve,reject){$B.idb_name="brython-cache";var idb_cx=$B.idb_cx=indexedDB.open($B.idb_name);idb_cx.onsuccess=function(){var db=idb_cx.result;var tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),record,outdated=[];var openCursor=store.openCursor();openCursor.onerror=function(){reject("open cursor error")};openCursor.onsuccess=function(evt){var cursor=evt.target.result;if(cursor){record=cursor.value;if(record.timestamp==$B.timestamp){if(!$B.VFS||!$B.VFS[record.name]||$B.VFS[record.name].timestamp==record.source_ts){if(record.is_package){$B.precompiled[record.name]=[record.content]}else{$B.precompiled[record.name]=record.content}}else{outdated.push(record.name)}}else{outdated.push(record.name)}cursor.continue()}else{remove_outdated(db,outdated,resolve)}}};idb_cx.onupgradeneeded=function(){var db=idb_cx.result,store=db.createObjectStore("modules",{keyPath:"name"});store.onsuccess=resolve};idb_cx.onerror=function(){$B.idb_cx=null;$B.idb_name=null;$B.$options.indexeddb=false;reject("could not open indexedDB database")}}))};$B.idb_open=function(){$B.idb_name="brython-cache";var idb_cx=$B.idb_cx=indexedDB.open($B.idb_name);idb_cx.onsuccess=function(){var db=idb_cx.result;if($B.get_page_option("debug")>1){console.info("using indexedDB for stdlib modules cache")}var tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),record,outdated=[];var openCursor=store.openCursor();openCursor.onerror=function(evt){console.log("open cursor error",evt)};openCursor.onsuccess=function(evt){var cursor=evt.target.result;if(cursor){record=cursor.value;if(record.timestamp==$B.timestamp){if(!$B.VFS||!$B.VFS[record.name]||$B.VFS[record.name].timestamp==record.source_ts){if(record.is_package){$B.precompiled[record.name]=[record.content]}else{$B.precompiled[record.name]=record.content}if($B.get_page_option("debug")>1){console.info("load from cache",record.name)}}else{outdated.push(record.name)}}else{outdated.push(record.name)}cursor.continue()}else{if($B.get_page_option("debug")>1){console.log("done")}remove_outdated(db,outdated,loop)}}};idb_cx.onupgradeneeded=function(){console.info("upgrade needed");var db=idb_cx.result,store=db.createObjectStore("modules",{keyPath:"name"});store.onsuccess=loop};idb_cx.onerror=function(){console.info("could not open indexedDB database");$B.idb_cx=null;$B.idb_name=null;$B.$options.indexeddb=false;loop()};idb_cx.onversionchange=function(){console.log("version change")}};$B.ajax_load_script=function(s){var script=s.script,url=s.url,name=s.name,rel_path=url.substr($B.script_dir.length+1);if($B.files&&$B.files.hasOwnProperty(rel_path)){var src=atob($B.files[rel_path].content);$B.tasks.splice(0,0,[$B.run_script,script,src,name,url,true]);loop()}else if($B.protocol!="file"){var filename=$B.script_filename=$B.strip_host(url);$B.scripts[filename]=script;var req=new XMLHttpRequest,cache=$B.get_option("cache"),qs=cache?"":(url.search(/\?/)>-1?"&":"?")+Date.now();req.open("GET",url+qs,true);req.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){var src=this.responseText;if(s.is_ww){$B.webworkers[name]=script;$B.file_cache[filename]=src;$B.dispatch_load_event(script)}else{$B.tasks.splice(0,0,[$B.run_script,script,src,name,url,true])}loop()}else if(this.status==404){throw Error(url+" not found")}}};req.send()}else{throw _b_.IOError.$factory("can't load external script at "+script.url+" (Ajax calls not supported with protocol file:///)")}};function add_jsmodule(module,source){source+="\nvar $locals_"+module.replace(/\./g,"_")+" = $module";$B.precompiled[module]=source}$B.inImported=function(module){if($B.imported.hasOwnProperty(module)){}else if(__BRYTHON__.VFS&&__BRYTHON__.VFS.hasOwnProperty(module)){var elts=__BRYTHON__.VFS[module];var ext=elts[0],source=elts[1];if(ext==".py"){if($B.idb_cx){$B.tasks.splice(0,0,[idb_get,module])}}else{add_jsmodule(module,source)}}else{console.log("bizarre",module)}loop()};function report_remove_outdated(mod){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent("precompile",{detail:`remove outdated ${mod} from cache`}))}}function report_close(){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent("precompile",{detail:"close"}))}}function report_done(){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent("brython_done",{detail:_b_.dict.$from_js($B.$options)}))}}var loop=$B.loop=function(){if($B.tasks.length==0){report_done();return}var task=$B.tasks.shift(),func=task[0],args=task.slice(1);if(func=="execute"){let script=task[1],script_id=script.__name__.replace(/\./g,"_"),module=$B.module.$factory(script.__name__);module.__file__=script.__file__;module.__doc__=script.__doc__;$B.imported[script_id]=module;try{var modobj=new Function(script.js+`\nreturn locals`)();for(var key in modobj){if(!key.startsWith("$")){module[key]=modobj[key]}}$B.dispatch_load_event(script.script_element)}catch(err){if(err.__class__===undefined){if(err.$py_exc){err=err.$py_exc}else{$B.freeze(err);var stack=err.$stack,frame_obj=err.$frame_obj,linenums=err.$linenums;var lineNumber=err.lineNumber;if(lineNumber!==undefined){console.log("around line",lineNumber);console.log(script.js.split("\n").slice(lineNumber-4,lineNumber).join("\n"))}$B.print_stack();err=_b_.RuntimeError.$factory(err+"");err.$stack=stack;err.$frame_obj=frame_obj;err.$linenums=linenums}}$B.handle_error(err)}loop()}else{try{func.apply(null,args)}catch(err){$B.handle_error(err)}}};$B.tasks=[];$B.has_indexedDB=self.indexedDB!==undefined})(__BRYTHON__);(function($B){var _b_=$B.builtins,_window=globalThis,isWebWorker="undefined"!==typeof WorkerGlobalScope&&"function"===typeof importScripts&&navigator instanceof WorkerNavigator;function missing_required_kwonly(fname,args){var plural=args.length==1?"":"s",arg_list;args=args.map((x=>`'${x}'`));if(args.length==1){arg_list=args[0]}else if(args.length==2){arg_list=args[0]+" and "+args[1]}else{arg_list=args.slice(0,args.length-1).join(", ")+", and "+args[args.length-1]}throw _b_.TypeError.$factory(fname+"() "+`missing ${args.length} required keyword-only argument${plural}: `+arg_list)}function missing_required_pos(fname,args){var plural=args.length==1?"":"s",arg_list;args=args.map((x=>`'${x}'`));if(args.length==1){arg_list=args[0]}else if(args.length==2){arg_list=args[0]+" and "+args[1]}else{arg_list=args.slice(0,args.length-1).join(", ")+", and "+args[args.length-1]}throw _b_.TypeError.$factory(fname+"() "+`missing ${args.length} required positional argument${plural}: `+arg_list)}function multiple_values(fname,arg){throw _b_.TypeError.$factory(fname+"() "+`got multiple values for argument '${arg}'`)}function pos_only_passed_as_keyword(fname,arg){return _b_.TypeError.$factory(fname+`() got some positional-only arguments passed as keyword arguments:`+` '${arg}'`)}function too_many_pos_args(fname,kwarg,arg_names,nb_kwonly,defaults,args,slots){var nb_pos=args.length,last=$B.last(args);if(last!==null&&last!==undefined&&last.$kw){if(!kwarg){var kw=$B.parse_kwargs(last.$kw,fname);for(var k in kw){if(!slots.hasOwnProperty(k)){var suggestion=$B.offer_suggestions_for_unexpected_keyword_error(arg_names,k);throw unexpected_keyword(fname,k,suggestion)}}}nb_pos--}var nb_def=defaults.length;var expected=arg_names.length-nb_kwonly,plural=expected==1?"":"s";if(nb_def){expected=`from ${expected-nb_def} to ${expected}`;plural="s"}var verb=nb_pos==1?"was":"were";return _b_.TypeError.$factory(fname+"() takes "+`${expected} positional argument${plural} but ${nb_pos} ${verb} given`)}function unexpected_keyword(fname,k,suggestion){var msg=`${fname}() got an unexpected keyword argument '${k}'`;if(suggestion!==_b_.None){msg+=`. Did you mean: '${suggestion}'?`}return _b_.TypeError.$factory(msg)}var empty={};function args0(f,args){var arg_names=f.$infos.arg_names,code=f.$infos.__code__,slots={};for(var arg_name of arg_names){slots[arg_name]=empty}return $B.parse_args(args,f.$infos.__name__,code.co_argcount,slots,arg_names,f.$infos.__defaults__,f.$infos.__kwdefaults__,f.$infos.vararg,f.$infos.kwarg,code.co_posonlyargcount,code.co_kwonlyargcount)}function args0_NEW(fct,args){const LAST_ARGS=args[args.length-1];const HAS_KW=LAST_ARGS!==undefined&&LAST_ARGS!==null&&LAST_ARGS.$kw!==undefined;let ARGS_POS_COUNT=args.length,ARGS_NAMED=null;if(HAS_KW){--ARGS_POS_COUNT;ARGS_NAMED=LAST_ARGS.$kw}const result={};const $INFOS=fct.$infos,$CODE=$INFOS.__code__,PARAMS_NAMES=$INFOS.arg_names,PARAMS_POS_COUNT=$CODE.co_argcount,PARAMS_NAMED_COUNT=$CODE.co_kwonlyargcount,PARAMS_VARARGS_NAME=$INFOS.vararg,PARAMS_KWARGS_NAME=$INFOS.kwarg,PARAMS_POS_DEFAULTS=$INFOS.__defaults__,PARAMS_POS_DEFAULTS_COUNT=PARAMS_POS_DEFAULTS.length,PARAMS_POS_DEFAULTS_OFFSET=PARAMS_POS_COUNT-PARAMS_POS_DEFAULTS_COUNT;const min=Math.min(ARGS_POS_COUNT,PARAMS_POS_COUNT);let offset=0;for(;offsetPARAMS_POS_COUNT){args0(fct,args);throw new Error("Too much positional arguments given (args0 should have raised an error) !")}if(ARGS_NAMED===null){if(offset=nb_pos_or_kw){if(vararg){varargs.push(arg)}else{throw too_many_pos_args(fname,kwarg,arg_names,nb_kwonly,defaults,args,slots)}}else{if(i0){throw missing_required_kwonly(fname,missing_kwonly)}if(!kwarg){for(var k in kw){if(!slots.hasOwnProperty(k)){var suggestion=$B.offer_suggestions_for_unexpected_keyword_error(arg_names,k);throw unexpected_keyword(fname,k,suggestion)}}}for(var k in kw){if(kw[k]===empty){continue}if(!slots.hasOwnProperty(k)){if(kwarg){extra_kw[k]=kw[k]}}else if(slots[k]!==empty){if(posonly_set[k]&&kwarg){extra_kw[k]=kw[k]}else{throw multiple_values(fname,k)}}else{slots[k]=kw[k]}}if(kwarg){slots[kwarg]=_b_.dict.$from_js(extra_kw)}if(vararg){slots[vararg]=$B.fast_tuple(varargs)}return slots};$B.parse_kwargs=function(kw_args,fname){var kwa=kw_args[0];for(var i=1,len=kw_args.length;i0||y!==undefined&&y.$kw){throw _b_.TypeError.$factory(name+"() takes no keyword arguments")}};$B.check_nb_args_no_kw=function(name,expected,args){var len=args.length,last=args[len-1];if(last&&last.$kw){if(last.$kw.length==2&&Object.keys(last.$kw[0]).length==0){len--}else{throw _b_.TypeError.$factory(name+"() takes no keyword arguments")}}if(len!=expected){if(expected==0){throw _b_.TypeError.$factory(name+"() takes no argument"+" ("+len+" given)")}else{throw _b_.TypeError.$factory(name+"() takes exactly "+expected+" argument"+(expected<2?"":"s")+" ("+len+" given)")}}};$B.get_class=function(obj){if(obj===null){return $B.imported.javascript.NullType}if(obj===undefined){return $B.imported.javascript.UndefinedType}var klass=obj.__class__||obj.$tp_class;if(klass===undefined){switch(typeof obj){case"number":if(Number.isInteger(obj)){return _b_.int}break;case"string":return _b_.str;case"boolean":return _b_.bool;case"function":if(!obj.$js_func){return $B.function}case"object":if(Array.isArray(obj)){return $B.js_array}else if(obj instanceof $B.str_dict){return _b_.dict}else if(typeof Node!=="undefined"&&obj instanceof Node){if(obj.tagName){return $B.imported["browser.html"][obj.tagName]||$B.DOMNode}return $B.DOMNode}else if(obj instanceof Event){return $B.DOMEvent}break}}if(klass===undefined){return $B.get_jsobj_class(obj)}return klass};$B.class_name=function(obj){var klass=$B.get_class(obj);if(klass===$B.JSObj){return"Javascript "+obj.constructor.name}else{return klass.__name__}};$B.unpack_mapping=function*(func,obj){var klass=$B.get_class(obj);var getitem=$B.$getattr(klass,"__getitem__",null);if(getitem===null){throw _b_.TypeError.$factory(`'${$B.class_name(obj)}' object `+"is not subscriptable")}getitem=$B.$call(getitem);var key_func=$B.$getattr(klass,"keys",null);if(key_func===null){var f=`${func.$infos.__module__}.${func.$infos.__name__}`;throw _b_.TypeError.$factory(`${f}() argument after **`+` must be a mapping, not ${$B.class_name(obj)}`)}var keys=$B.$call($B.$getattr(klass,"keys"))(obj);for(var key of $B.make_js_iterator(keys)){if(!_b_.isinstance(key,_b_.str)){throw _b_.TypeError.$factory("keywords must be strings")}yield{key:key,value:getitem(obj,key)}}};$B.make_js_iterator=function(iterator,frame,lineno){var set_lineno=$B.set_lineno;if(frame===undefined){if($B.frame_obj===null){set_lineno=function(){}}else{frame=$B.frame_obj.frame;lineno=frame.$lineno}}if(iterator.__class__===_b_.range){var obj={ix:iterator.start};if(iterator.step>0){return{[Symbol.iterator](){return this},next(){set_lineno(frame,lineno);if(obj.ix>=iterator.stop){return{done:true,value:null}}var value=obj.ix;obj.ix+=iterator.step;return{done:false,value:value}}}}else{return{[Symbol.iterator](){return this},next(){set_lineno(frame,lineno);if(obj.ix<=iterator.stop){return{done:true,value:null}}var value=obj.ix;obj.ix+=iterator.step;return{done:false,value:value}}}}}if(iterator[Symbol.iterator]&&!iterator.$is_js_array){var it=iterator[Symbol.iterator]();return{[Symbol.iterator](){return this},next(){set_lineno(frame,lineno);return it.next()}}}var next_func=$B.$getattr(_b_.iter(iterator),"__next__",null);if(next_func!==null){next_func=$B.$call(next_func);return{[Symbol.iterator](){return this},next(){set_lineno(frame,lineno);try{var value=next_func();return{done:false,value:value}}catch(err){if($B.is_exc(err,[_b_.StopIteration])){return{done:true,value:null}}throw err}}}}};$B.unpacker=function(obj,nb_targets,has_starred){var position,position_rank=3;if(has_starred){var nb_after_starred=arguments[3];position_rank++}position=$B.decode_position(arguments[position_rank]);var t=_b_.list.$factory(obj),right_length=t.length,left_length=nb_targets+(has_starred?nb_after_starred-1:0);if(!has_starred&&right_lengthleft_length){var exc=_b_.ValueError.$factory("too many values to unpack "+`(expected ${left_length})`);if(position){$B.set_exception_offsets(exc,position)}throw exc}t.index=-1;t.read_one=function(){t.index++;return t[t.index]};t.read_rest=function(){t.index++;var res=t.slice(t.index,t.length-nb_after_starred);t.index=t.length-nb_after_starred-1;return $B.$list(res)};return t};$B.set_lineno=function(frame,lineno){frame.$lineno=lineno;if(frame.$f_trace!==_b_.None){$B.trace_line()}return true};$B.get_method_class=function(method,ns,qualname,refs){var klass=ns;if(method.$infos&&method.$infos.$class){return method.$infos.$class}for(var ref of refs){if(klass[ref]===undefined){return $B.make_class(qualname)}klass=klass[ref]}return klass};$B.warn=function(klass,message,filename,token){var warning=klass.$factory(message);warning.filename=filename;if(klass===_b_.SyntaxWarning){warning.lineno=token.lineno;warning.offset=token.col_offset;warning.end_lineno=token.end_lineno;warning.end_offset=token.end_coloffset;warning.text=token.line;warning.args[1]=$B.fast_tuple([filename,warning.lineno,warning.offset,warning.text,warning.end_lineno,warning.end_offset])}$B.imported._warnings.warn(warning)};function index_error(obj){var type=typeof obj=="string"?"string":"list";throw _b_.IndexError.$factory(type+" index out of range")}$B.$getitem=function(obj,item,position){var is_list=Array.isArray(obj)&&obj.__class__===_b_.list,is_dict=obj.__class__===_b_.dict&&!obj.$jsobj;if(typeof item=="number"){if(is_list||typeof obj=="string"){item=item>=0?item:obj.length+item;if(obj[item]!==undefined){return obj[item]}else{index_error(obj)}}}else if(item.valueOf&&typeof item.valueOf()=="string"&&is_dict){return _b_.dict.$getitem(obj,item)}if(obj.$is_class){if(!Array.isArray(item)){item=$B.fast_tuple([item])}if(obj===_b_.type){return $B.$class_getitem(obj,item)}var class_gi=$B.$getattr(obj,"__class_getitem__",_b_.None);if(class_gi!==_b_.None){return $B.$call(class_gi)(item)}else if(obj.__class__){class_gi=$B.$getattr(obj.__class__,"__getitem__",_b_.None);if(class_gi!==_b_.None){return class_gi(obj,item)}else{throw _b_.TypeError.$factory("type '"+$B.$getattr(obj,"__qualname__")+"' is not subscriptable")}}}if(is_list){return _b_.list.$getitem(obj,item)}if(is_dict){return _b_.dict.$getitem(obj,item)}var gi=$B.$getattr(obj.__class__||$B.get_class(obj),"__getitem__",_b_.None);if(gi!==_b_.None){return gi(obj,item)}var exc=_b_.TypeError.$factory("'"+$B.class_name(obj)+"' object is not subscriptable");if(position){$B.set_exception_offsets(exc,$B.decode_position(position))}throw exc};$B.getitem_slice=function(obj,slice){var res;if(Array.isArray(obj)&&obj.__class__===_b_.list){if(slice.start===_b_.None&&slice.stop===_b_.None){if(slice.step===_b_.None||slice.step==1){res=obj.slice()}else if(slice.step==-1){res=obj.slice().reverse()}}else if(slice.step===_b_.None){if(slice.start===_b_.None){slice.start=0}if(slice.stop===_b_.None){slice.stop=obj.length}if(typeof slice.start=="number"&&typeof slice.stop=="number"){if(slice.start<0){slice.start+=obj.length}if(slice.stop<0){slice.stop+=obj.length}res=obj.slice(slice.start,slice.stop)}}if(res){res.__class__=obj.__class__;return res}else{return _b_.list.$getitem(obj,slice)}}else if(typeof obj=="string"){return _b_.str.__getitem__(obj,slice)}return $B.$getattr($B.get_class(obj),"__getitem__")(obj,slice)};$B.$getattr_pep657=function(obj,attr,position){try{return $B.$getattr(obj,attr)}catch(err){$B.set_exception_offsets(err,$B.decode_position(position));throw err}};$B.set_list_slice=function(obj,start,stop,value){if(start===null){start=0}else{start=$B.$GetInt(start);if(start<0){start=Math.max(0,start+obj.length)}}if(stop===null){stop=obj.length}stop=$B.$GetInt(stop);if(stop<0){stop=Math.max(0,stop+obj.length)}var res=_b_.list.$factory(value);obj.splice.apply(obj,[start,stop-start].concat(res))};$B.set_list_slice_step=function(obj,start,stop,step,value){if(step===null||step==1){return $B.set_list_slice(obj,start,stop,value)}if(step==0){throw _b_.ValueError.$factory("slice step cannot be zero")}step=$B.$GetInt(step);if(start===null){start=step>0?0:obj.length-1}else{start=$B.$GetInt(start)}if(stop===null){stop=step>0?obj.length:-1}else{stop=$B.$GetInt(stop)}var repl=_b_.list.$factory(value),j=0,test,nb=0;if(step>0){test=function(i){return istop}}for(var i=start;test(i);i+=step){nb++}if(nb!=repl.length){throw _b_.ValueError.$factory("attempt to assign sequence of size "+repl.length+" to extended slice of size "+nb)}for(var i=start;test(i);i+=step){obj[i]=repl[j];j++}};$B.$setitem=function(obj,item,value){if(Array.isArray(obj)&&obj.__class__===undefined&&!obj.$is_js_array&&typeof item=="number"&&!$B.$isinstance(obj,_b_.tuple)){if(item<0){item+=obj.length}if(obj[item]===undefined){throw _b_.IndexError.$factory("list assignment index out of range")}obj[item]=value;return}else if(obj.__class__===_b_.dict){_b_.dict.$setitem(obj,item,value);return}else if(obj.__class__===_b_.list){return _b_.list.$setitem(obj,item,value)}var si=$B.$getattr(obj.__class__||$B.get_class(obj),"__setitem__",null);if(si===null||typeof si!="function"){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object does not support item assignment")}return si(obj,item,value)};$B.$delitem=function(obj,item){if(Array.isArray(obj)&&obj.__class__===_b_.list&&typeof item=="number"&&!$B.$isinstance(obj,_b_.tuple)){if(item<0){item+=obj.length}if(obj[item]===undefined){throw _b_.IndexError.$factory("list deletion index out of range")}obj.splice(item,1);return}else if(obj.__class__===_b_.dict){if(obj.$is_namespace){Object.defineProperty(obj.$jsobj,item,{get(){throw $B.name_error(item)},set(value){Object.defineProperty(obj.$jsobj,item,{value:value});return _b_.None}})}else{_b_.dict.__delitem__(obj,item)}return}else if(obj.__class__===_b_.list){return _b_.list.__delitem__(obj,item)}var di=$B.$getattr(obj.__class__||$B.get_class(obj),"__delitem__",null);if(di===null){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object doesn't support item deletion")}return di(obj,item)};function num_result_type(x,y){var is_int,is_float,x_num,y_num;if(typeof x=="number"){x_num=x;if(typeof y=="number"){is_int=true;y_num=y}else if(y.__class__===_b_.float){is_float=true;y_num=y.value}}else if(x.__class__===_b_.float){x_num=x.value;if(typeof y=="number"){y_num=y;is_float=true}else if(y.__class__===_b_.float){is_float=true;y_num=y.value}}return{is_int:is_int,is_float:is_float,x:x_num,y:y_num}}$B.augm_assign=function(left,op,right){var res_type=num_result_type(left,right);if(res_type.is_int||res_type.is_float){var z;switch(op){case"+=":z=res_type.x+res_type.y;break;case"-=":z=res_type.x-res_type.y;break;case"*=":z=res_type.x*res_type.y;break;case"/=":z=res_type.x/res_type.y;break}if(z){if(res_type.is_int&&Number.isSafeInteger(z)){return z}else if(res_type.res_is_float){return $B.fast_float(z)}}}else if(op=="*="){if(typeof left=="number"&&typeof right=="string"){return left<=0?"":right.repeat(left)}else if(typeof left=="string"&&typeof right=="number"){return right<=0?"":left.repeat(right)}}else if(op=="+="){if(typeof left=="string"&&typeof right=="string"){return left+right}}var op1=op.substr(0,op.length-1),method=$B.op2method.augmented_assigns[op],augm_func=$B.$getattr(left,"__"+method+"__",null);if(augm_func!==null){var res=$B.$call(augm_func)(right);if(res===_b_.NotImplemented){throw _b_.TypeError.$factory(`unsupported operand type(s)`+` for ${op}: '${$B.class_name(left)}' `+`and '${$B.class_name(right)}'`)}return res}else{var method1=$B.op2method.operations[op1];if(method1===undefined){method1=$B.op2method.binary[op1]}return $B.rich_op(`__${method1}__`,left,right)}};$B.$is=function(a,b){if((a===undefined||a===$B.Undefined)&&(b===undefined||b===$B.Undefined)){return true}if(a===null){return b===null}if(b===null){return a===null}if(a.__class__===_b_.float&&b.__class__===_b_.float){if(isNaN(a.value)&&isNaN(b.value)){return true}return a.value==b.value}if(a===_b_.int&&b==$B.long_int||a===$B.long_int&&b===_b_.int){return true}return a===b};$B.is_or_equals=function(x,y){return $B.$is(x,y)||$B.rich_comp("__eq__",x,y)};$B.member_func=function(obj){var klass=$B.get_class(obj),contains=$B.$getattr(klass,"__contains__",null);if(contains!==null){contains=$B.$call(contains);return contains.bind(null,obj)}try{var iterator=$B.make_js_iterator(obj);return function(key){try{for(var item of iterator){if($B.is_or_equals(key,item)){return true}}return false}catch(err){return false}}}catch(err){var getitem=$B.$getattr(klass,"__getitem__",null);if(getitem!==null){return function(key){var i=-1;while(true){i++;try{var item=getitem(obj,i);if($B.is_or_equals(key,item)){return true}}catch(err){if($B.$is_exc(err,[_b_.StopIteration])){return false}throw err}}}}else{throw _b_.TypeError.$factory("argument of type "+`'${$B.class_name(obj)}' is not iterable`)}}};$B.$is_member=function(item,_set){return $B.member_func(_set)(item)};$B.$call=function(callable,position){callable=$B.$call1(callable);if(position){return function(){try{return callable.apply(null,arguments)}catch(exc){position=$B.decode_position(position);$B.set_exception_offsets(exc,position);throw exc}}}return callable};$B.$call1=function(callable){if(callable.__class__===$B.method){return callable}else if(callable.__class__===_b_.staticmethod){return callable.__func__}else if(callable.$factory){return callable.$factory}else if(callable.$is_class){return callable.$factory=$B.$instance_creator(callable)}else if(callable.$is_js_class){return callable.$factory=function(){return new callable(...arguments)}}else if(callable.$in_js_module){return function(){var res=callable(...arguments);return res===undefined?_b_.None:res}}else if(callable.$is_func||typeof callable=="function"){if(callable.$infos&&callable.$infos.__code__&&callable.$infos.__code__.co_flags&32){$B.frame_obj.frame.$has_generators=true}if(callable.$is_async){if($B.frame_obj!==null){var frame=$B.frame_obj.frame;frame.$async=callable}}return callable}try{return $B.$getattr(callable,"__call__")}catch(err){throw _b_.TypeError.$factory("'"+$B.class_name(callable)+"' object is not callable")}};var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or"];var ropsigns=["+","-","*","/","//","%","**","<<",">>","&","^","|"];$B.make_rmethods=function(klass){for(var r_opname of r_opnames){if(klass["__r"+r_opname+"__"]===undefined&&klass["__"+r_opname+"__"]){klass["__r"+r_opname+"__"]=function(name){return function(self,other){return klass["__"+name+"__"](other,self)}}(r_opname)}}};$B.UUID=function(){return $B.$py_UUID++};$B.$GetInt=function(value){if(typeof value=="number"||value.constructor===Number){return value}else if(typeof value==="boolean"){return value?1:0}else if($B.$isinstance(value,_b_.int)){return value}else if($B.$isinstance(value,_b_.float)){return value.valueOf()}if(!value.$is_class){try{var v=$B.$getattr(value,"__int__")();return v}catch(e){}try{var v=$B.$getattr(value,"__index__")();return v}catch(e){}}throw _b_.TypeError.$factory("'"+$B.class_name(value)+"' object cannot be interpreted as an integer")};$B.to_num=function(obj,methods){var expected_class={__complex__:_b_.complex,__float__:_b_.float,__index__:_b_.int,__int__:_b_.int};var klass=obj.__class__||$B.get_class(obj);for(var i=0;i$B.recursion_limit){var exc=_b_.RecursionError.$factory("maximum recursion depth exceeded");$B.set_exc(exc,frame);throw exc}frame.__class__=$B.frame;frame.__file__=__file__;frame.$lineno=lineno;frame.$f_trace=_b_.None;frame.$has_generators=!!frame[1].$has_generators;$B.frame_obj={prev:$B.frame_obj,frame:frame,count:count+1};if($B.tracefunc!==_b_.None){if(frame[4]===$B.tracefunc||$B.tracefunc.$infos&&frame[4]&&frame[4]===$B.tracefunc.$infos.__func__){$B.tracefunc.$frame_id=frame[0];frame.$f_trace=_b_.None;return}else{var frame_obj=$B.frame_obj;while(frame_obj!==null){if(frame_obj.frame[0]==$B.tracefunc.$frame_id){frame.$f_trace=_b_.None;return}frame_obj=frame_obj.prev}try{var res=$B.tracefunc(frame,"call",_b_.None);var frame_obj=$B.frame_obj;while(frame_obj!==null){if(frame_obj.frame[4]==res){return _b_.None}frame_obj=frame_obj.prev}frame.$f_trace=res;return}catch(err){$B.set_exc(err,frame);$B.frame_obj=$B.frame_obj.prev;err.$in_trace_func=true;throw err}}}};$B.trace_exception=function(){var frame=$B.frame_obj.frame;if(frame[0]==$B.tracefunc.$current_frame_id){return _b_.None}var trace_func=frame.$f_trace,exc=frame[1].$current_exception;return trace_func(frame,"exception",$B.fast_tuple([exc.__class__,exc,$B.traceback.$factory(exc)]))};$B.trace_line=function(){var frame=$B.frame_obj.frame;if(frame[0]==$B.tracefunc.$current_frame_id){return _b_.None}var trace_func=frame.$f_trace;if(trace_func===undefined){console.log("trace line, frame",frame)}return trace_func(frame,"line",_b_.None)};$B.trace_return=function(value){var frame=$B.frame_obj.frame,trace_func=frame.$f_trace;if(frame[0]==$B.tracefunc.$current_frame_id){return _b_.None}trace_func(frame,"return",value)};$B.leave_frame=function(arg){if($B.frame_obj===null){return}if(arg&&arg.value!==undefined&&$B.tracefunc!==_b_.None){if($B.frame_obj.frame.$f_trace===undefined){$B.frame_obj.frame.$f_trace=$B.tracefunc}if($B.frame_obj.frame.$f_trace!==_b_.None){$B.trace_return(arg.value)}}var frame=$B.frame_obj.frame;if(frame.$coroutine){if(!frame.$coroutine.$sent){var cname=frame.$coroutine.$func.$infos.__name__;var message=_b_.RuntimeWarning.$factory(`coroutine '${cname}' was never awaited`);message.lineno=frame.$coroutine.$lineno;$B.imported._warnings.warn(message)}}$B.frame_obj=$B.frame_obj.prev;if(frame.$has_generators){for(var key in frame[1]){if(frame[1][key]&&frame[1][key].__class__===$B.generator){var gen=frame[1][key];if(gen.$frame===undefined){continue}var ctx_managers=gen.$frame[1].$context_managers;if(ctx_managers){for(var cm of ctx_managers){$B.$call($B.$getattr(cm,"__exit__"))(_b_.None,_b_.None,_b_.None)}}}}}delete frame[1].$current_exception;return _b_.None};$B.trace_return_and_leave=function(frame,return_value){if(frame.$f_trace!==_b_.None){$B.trace_return(return_value)}return $B.leave_frame()};$B.push_frame=function(frame){var count=$B.frame_obj===null?0:$B.frame_obj.count;return{prev:$B.frame_obj,frame:frame,count:count+1}};var reversed_op={__lt__:"__gt__",__le__:"__ge__",__gt__:"__lt__",__ge__:"__le__"};var method2comp={__lt__:"<",__le__:"<=",__gt__:">",__ge__:">="};$B.rich_comp=function(op,x,y){if(x===undefined){throw _b_.RuntimeError.$factory("error in rich comp")}var x1=x!==null&&x.valueOf?x.valueOf():x,y1=y!==null&&y.valueOf?y.valueOf():y;if(typeof x1=="number"&&typeof y1=="number"&&x.__class__===undefined&&y.__class__===undefined){switch(op){case"__eq__":return x1==y1;case"__ne__":return x1!=y1;case"__le__":return x1<=y1;case"__lt__":return x1=y1;case"__gt__":return x1>y1}}var res;if(x!==null&&(x.$is_class||x.$factory)){if(op=="__eq__"){return x===y}else if(op=="__ne__"){return!(x===y)}else{throw _b_.TypeError.$factory("'"+method2comp[op]+"' not supported between instances of '"+$B.class_name(x)+"' and '"+$B.class_name(y)+"'")}}var x_class_op=$B.$call($B.$getattr($B.get_class(x),op)),rev_op=reversed_op[op]||op,y_rev_func;if(x!==null&&x.__class__&&y!==null&&y.__class__){if(y.__class__.__mro__.indexOf(x.__class__)>-1){y_rev_func=$B.$getattr(y,rev_op);res=$B.$call(y_rev_func)(x);if(res!==_b_.NotImplemented){return res}}}res=x_class_op(x,y);if(res!==_b_.NotImplemented){return res}if(y_rev_func===undefined){y_rev_func=$B.$call($B.$getattr($B.get_class(y),rev_op));res=y_rev_func(y,x);if(res!==_b_.NotImplemented){return res}}if(op=="__eq__"){return _b_.False}else if(op=="__ne__"){return _b_.True}throw _b_.TypeError.$factory("'"+method2comp[op]+"' not supported between instances of '"+$B.class_name(x)+"' and '"+$B.class_name(y)+"'")};var opname2opsign={__sub__:"-",__xor__:"^",__mul__:"*",__and__:"&",__or__:"|"};$B.rich_op=function(op,x,y,position){try{return $B.rich_op1(op,x,y)}catch(exc){if(position){$B.set_exception_offsets(exc,$B.decode_position(position))}throw exc}};$B.rich_op1=function(op,x,y){var res_is_int,res_is_float,x_num,y_num;if(typeof x=="number"){x_num=x;if(typeof y=="number"){res_is_int=true;y_num=y}else if(y.__class__===_b_.float){res_is_float=true;y_num=y.value}}else if(x.__class__===_b_.float){x_num=x.value;if(typeof y=="number"){y_num=y;res_is_float=true}else if(y.__class__===_b_.float){res_is_float=true;y_num=y.value}}if(res_is_int||res_is_float){var z;switch(op){case"__add__":z=x_num+y_num;break;case"__sub__":z=x_num-y_num;break;case"__mul__":z=x_num*y_num;break;case"__pow__":if(res_is_int&&y_num>=0){return _b_.int.$int_or_long(BigInt(x_num)**BigInt(y_num))}break;case"__truediv__":if(y_num==0){throw _b_.ZeroDivisionError.$factory("division by zero")}z=x_num/y_num;return{__class__:_b_.float,value:z}}if(z){if(res_is_int&&Number.isSafeInteger(z)){return z}else if(res_is_float){return{__class__:_b_.float,value:z}}}}else if(typeof x=="string"&&typeof y=="string"&&op=="__add__"){return x+y}var x_class=x.__class__||$B.get_class(x),y_class=y.__class__||$B.get_class(y),rop="__r"+op.substr(2),method;if(x_class===y_class){if(x_class===_b_.int){return _b_.int[op](x,y)}else if(x_class===_b_.bool){return(_b_.bool[op]||_b_.int[op])(x,y)}try{method=$B.$call($B.$getattr(x_class,op))}catch(err){if(err.__class__===_b_.AttributeError){var kl_name=$B.class_name(x);throw _b_.TypeError.$factory("unsupported operand type(s) "+"for "+opname2opsign[op]+": '"+kl_name+"' and '"+kl_name+"'")}throw err}return method(x,y)}if(_b_.issubclass(y_class,x_class)){var reflected_left=$B.$getattr(x_class,rop,false),reflected_right=$B.$getattr(y_class,rop,false);if(reflected_right&&reflected_left&&reflected_right!==reflected_left){return reflected_right(y,x)}}var res;try{var attr=$B.$getattr(x,op);method=$B.$getattr(x_class,op)}catch(err){if(err.__class__!==_b_.AttributeError){throw err}res=$B.$call($B.$getattr(y,rop))(x);if(res!==_b_.NotImplemented){return res}throw _b_.TypeError.$factory(`unsupported operand type(s) for ${$B.method_to_op[op]}:`+` '${$B.class_name(x)}' and '${$B.class_name(y)}'`)}res=method(x,y);if(res===_b_.NotImplemented){try{method=$B.$getattr(y_class,rop)}catch(err){if(err.__class__!==_b_.AttributeError){throw err}throw _b_.TypeError.$factory(`unsupported operand type(s) for ${$B.method_to_op[op]}:`+` '${$B.class_name(x)}' and '${$B.class_name(y)}'`)}res=method(y,x);if(res===_b_.NotImplemented){throw _b_.TypeError.$factory(`unsupported operand type(s) for ${$B.method_to_op[op]}:`+` '${$B.class_name(x)}' and '${$B.class_name(y)}'`)}return res}else{return res}};$B.is_none=function(o){return o===undefined||o===null||o==_b_.None};var repr_stack=new Set;$B.repr={enter:function(obj){var obj_id=_b_.id(obj);if(repr_stack.has(obj_id)){return true}else{repr_stack.add(obj_id);if(repr_stack.size>$B.recursion_limit){repr_stack.clear();throw _b_.RecursionError.$factory("maximum recursion depth "+"exceeded while getting the repr of an object")}}},leave:function(obj){repr_stack.delete(_b_.id(obj))}}})(__BRYTHON__);(function($B){var _b_=$B.builtins;var object={__name__:"object",__qualname__:"object",$is_class:true,$native:true};object.__delattr__=function(self,attr){if(self.__dict__&&$B.$isinstance(self.__dict__,_b_.dict)&&_b_.dict.$contains_string(self.__dict__,attr)){_b_.dict.$delete_string(self.__dict__,attr);return _b_.None}else if(self.__dict__===undefined&&self[attr]!==undefined){delete self[attr];return _b_.None}else{var klass=self.__class__;if(klass){var prop=$B.$getattr(klass,attr);if(prop.__class__===_b_.property){if(prop.__delete__!==undefined){prop.__delete__(self);return _b_.None}}}}throw $B.attr_error(attr,self)};object.__dir__=function(self){var objects;if(self.$is_class){objects=[self].concat(self.__mro__)}else{var klass=self.__class__||$B.get_class(self);objects=[self,klass].concat(klass.__mro__)}var res=[];for(var i=0,len=objects.length;i2){console.log("error in get.apply",err);console.log("get attr",attr,"of",obj);console.log("res",res);console.log("__get__",__get__);console.log(__get__+"")}throw err}}if(__get__===null&&typeof res=="function"){__get__=function(x){return x}}if(__get__!==null){res.__name__=attr;if(attr=="__new__"||res.__class__===$B.builtin_function_or_method){res.$type="staticmethod"}var res1=__get__.apply(null,[res,obj,klass]);if($test){console.log("res",res,"res1",res1)}if(typeof res1=="function"){if(res1.__class__===$B.method){return res}if(res.$type=="staticmethod"){return res}else{var self=res.__class__===$B.method?klass:obj,method=function(){var args=[self];for(var i=0,len=arguments.length;i0||_b_.dict.__len__($.kwargs)>0){throw _b_.TypeError.$factory("object() takes no parameters")}var res=Object.create(null);res.__class__=cls;res.__dict__=$B.obj_dict({});return res}};object.$no_new_init=function(cls){var res=Object.create(null);res.__class__=cls;res.__dict__=$B.obj_dict({});return res};object.__new__=function(cls,...args){if(cls===undefined){throw _b_.TypeError.$factory("object.__new__(): not enough arguments")}var init_func=$B.$getattr(cls,"__init__");if(init_func===object.__init__){if(args.length>0){throw _b_.TypeError.$factory("object() takes no parameters")}}var res=Object.create(null);$B.update_obj(res,{__class__:cls,__dict__:$B.obj_dict({})});return res};object.__ne__=function(self,other){if(self===other){return false}var eq=$B.$getattr(self.__class__||$B.get_class(self),"__eq__",null);if(eq!==null){var res=$B.$call(eq)(self,other);if(res===_b_.NotImplemented){return res}return!$B.$bool(res)}return _b_.NotImplemented};object.__reduce__=function(self){if(!self.__dict__){throw _b_.TypeError.$factory(`cannot pickle '${$B.class_name(self)}' object`)}if($B.imported.copyreg===undefined){$B.$import("copyreg")}var res=[$B.imported.copyreg._reconstructor];var D=$B.get_class(self),B=object;for(var klass of D.__mro__){if(klass.__module__=="builtins"){B=klass;break}}var args=$B.$list([D,B]);if(B===object){args.push(_b_.None)}else{args.push($B.$call(B)(self))}res.push($B.fast_tuple(args));var d=$B.empty_dict();for(var attr of _b_.dict.$keys_string(self.__dict__)){_b_.dict.$setitem(d,attr,_b_.dict.$getitem_string(self.__dict__,attr))}res.push(d);return _b_.tuple.$factory(res)};function getNewArguments(self,klass){var newargs_ex=$B.$getattr(self,"__getnewargs_ex__",null);if(newargs_ex!==null){let newargs=newargs_ex();if(!newargs||newargs.__class__!==_b_.tuple){throw _b_.TypeError.$factory("__getnewargs_ex__ should "+`return a tuple, not '${$B.class_name(newargs)}'`)}if(newargs.length!=2){throw _b_.ValueError.$factory("__getnewargs_ex__ should "+`return a tuple of length 2, not ${newargs.length}`)}let args=newargs[0],kwargs=newargs[1];if(!args||args.__class__!==_b_.tuple){throw _b_.TypeError.$factory("first item of the tuple returned "+`by __getnewargs_ex__ must be a tuple, not '${$B.class_name(args)}'`)}if(!kwargs||kwargs.__class__!==_b_.dict){throw _b_.TypeError.$factory("second item of the tuple returned "+`by __getnewargs_ex__ must be a dict, not '${$B.class_name(kwargs)}'`)}return{args:args,kwargs:kwargs}}let newargs=klass.$getnewargs,args;if(!newargs){newargs=$B.$getattr(klass,"__getnewargs__",null)}if(newargs){args=newargs(self);if(!args||args.__class__!==_b_.tuple){throw _b_.TypeError.$factory("__getnewargs__ should "+`return a tuple, not '${$B.class_name(args)}'`)}return{args:args}}}object.__reduce_ex__=function(self,protocol){var klass=$B.get_class(self);if($B.imported.copyreg===undefined){$B.$import("copyreg")}if(protocol<2){return $B.$call($B.imported.copyreg._reduce_ex)(self,protocol)}var reduce=$B.$getattr(klass,"__reduce__");if(reduce!==object.__reduce__){return $B.$call(reduce)(self)}var res=[$B.imported.copyreg.__newobj__];var arg2=[klass];var newargs=getNewArguments(self,klass);if(newargs){arg2=arg2.concat(newargs.args)}res.push($B.fast_tuple(arg2));var d=$B.empty_dict(),nb=0;if(self.__dict__){for(var item of _b_.dict.$iter_items(self.__dict__)){if(item.key=="__class__"||item.key.startsWith("$")){continue}_b_.dict.$setitem(d,item.key,item.value);nb++}}if(nb==0){d=_b_.None}res.push(d);var list_like_iterator=_b_.None;if($B.$getattr(klass,"append",null)!==null&&$B.$getattr(klass,"extend",null)!==null){list_like_iterator=_b_.iter(self)}res.push(list_like_iterator);var key_value_iterator=_b_.None;if($B.$isinstance(self,_b_.dict)){key_value_iterator=_b_.dict.items(self)}res.push(key_value_iterator);return _b_.tuple.$factory(res)};object.__repr__=function(self){if(self===object){return""}if(self.__class__===_b_.type){return""}var module=self.__class__.__module__;if(module!==undefined&&!module.startsWith("$")&&module!=="builtins"){return"<"+self.__class__.__module__+"."+$B.class_name(self)+" object>"}else{return"<"+$B.class_name(self)+" object>"}};object.__setattr__=function(self,attr,val){if(val===undefined){throw _b_.TypeError.$factory("can't set attributes of built-in/extension type 'object'")}else if(self.__class__===object){if(object[attr]===undefined){throw $B.attr_error(attr,self)}else{throw _b_.AttributeError.$factory("'object' object attribute '"+attr+"' is read-only")}}if(self.__dict__){_b_.dict.$setitem(self.__dict__,attr,val)}else{self[attr]=val}return _b_.None};object.__setattr__.__get__=function(obj){return function(attr,val){object.__setattr__(obj,attr,val)}};object.__setattr__.__str__=function(){return"method object.setattr"};object.__str__=function(self){if(self===undefined||self.$kw){throw _b_.TypeError.$factory("descriptor '__str__' of 'object' "+"object needs an argument")}var klass=self.__class__||$B.get_class(self);var repr_func=$B.$getattr(klass,"__repr__");return $B.$call(repr_func).apply(null,arguments)};object.__subclasshook__=function(){return _b_.NotImplemented};object.$factory=function(){if(arguments.length>0||arguments.length==1&&arguments[0].$kw&&Object.keys(arguments[0].$kw).length>0){throw _b_.TypeError.$factory("object() takes no arguments")}var res={__class__:object},args=[res];object.__init__.apply(null,args);return res};$B.set_func_names(object,"builtins");_b_.object=object})(__BRYTHON__);(function($B){var _b_=$B.builtins;const TPFLAGS={STATIC_BUILTIN:1<<1,MANAGED_WEAKREF:1<<3,MANAGED_DICT:1<<4,SEQUENCE:1<<5,MAPPING:1<<6,DISALLOW_INSTANTIATION:1<<7,IMMUTABLETYPE:1<<8,HEAPTYPE:1<<9,BASETYPE:1<<10,HAVE_VECTORCALL:1<<11,READY:1<<12,READYING:1<<13,HAVE_GC:1<<14,METHOD_DESCRIPTOR:1<<17,VALID_VERSION_TAG:1<<19,IS_ABSTRACT:1<<20,MATCH_SELF:1<<22,LONG_SUBCLASS:1<<24,LIST_SUBCLASS:1<<25,TUPLE_SUBCLASS:1<<26,BYTES_SUBCLASS:1<<27,UNICODE_SUBCLASS:1<<28,DICT_SUBCLASS:1<<29,BASE_EXC_SUBCLASS:1<<30,TYPE_SUBCLASS:1<<31,HAVE_FINALIZE:1<<0,HAVE_VERSION_TAG:1<<18};$B.$class_constructor=function(class_name,class_obj_proxy,metaclass,resolved_bases,bases,kwargs,static_attributes,firstlineno){var dict;if(class_obj_proxy instanceof $B.str_dict){dict=$B.empty_dict();dict.$strings=class_obj_proxy}else{dict=class_obj_proxy.$target}var module=class_obj_proxy.__module__;for(var base of bases){if(base.__flags__!==undefined&&!(base.__flags__&TPFLAGS.BASETYPE)){throw _b_.TypeError.$factory("type 'bool' is not an acceptable base type")}}var extra_kwargs={};if(kwargs){for(let i=0;i0){if(bases[0].__class__===undefined){if(typeof bases[0]=="function"){if(bases.length!=1){throw _b_.TypeError.$factory("A Brython class "+"can inherit at most 1 Javascript constructor")}$B.set_func_names(bases[0],module);return $B.JSMeta}else{throw _b_.TypeError.$factory("Argument of "+class_name+" is not a class (type '"+$B.class_name(bases[0])+"')")}}for(var base of bases){var mc=base.__class__;if(metaclass===undefined){metaclass=mc}else if(mc===metaclass||_b_.issubclass(metaclass,mc)){}else if(_b_.issubclass(mc,metaclass)){metaclass=mc}else if(metaclass.__bases__&&metaclass.__bases__.indexOf(mc)==-1){throw _b_.TypeError.$factory("metaclass conflict: the "+"metaclass of a derived class must be a (non-"+"strict) subclass of the metaclasses of all its bases")}}}else{metaclass=metaclass||_b_.type}return metaclass};function set_attr_if_absent(dict,attr,value){try{$B.$getitem(dict,attr)}catch(err){$B.$setitem(dict,attr,value)}}$B.make_class_namespace=function(metaclass,class_name,module,qualname,bases){var class_dict=_b_.dict.$literal([["__module__",module],["__qualname__",qualname]]);if(metaclass!==_b_.type){var prepare=$B.$getattr(metaclass,"__prepare__",_b_.None);if(prepare!==_b_.None){class_dict=$B.$call(prepare)(class_name,bases);set_attr_if_absent(class_dict,"__module__",module);set_attr_if_absent(class_dict,"__qualname__",qualname)}}if(class_dict.__class__===_b_.dict){if(class_dict.$all_str){return class_dict.$strings}return new Proxy(class_dict,{get:function(target,prop){if(prop=="__class__"){return _b_.dict}else if(prop=="$target"){return target}if(_b_.dict.$contains_string(target,prop)){return _b_.dict.$getitem_string(target,prop)}return undefined},set:function(target,prop,value){_b_.dict.$setitem(target,prop,value)}})}else{var setitem=$B.$getattr(class_dict,"__setitem__"),getitem=$B.$getattr(class_dict,"__getitem__");return new Proxy(class_dict,{get:function(target,prop){if(prop=="__class__"){return $B.get_class(target)}else if(prop=="$target"){return target}try{return getitem(prop)}catch(err){return undefined}},set:function(target,prop,value){setitem(prop,value);return _b_.None}})}};$B.resolve_mro_entries=function(bases){var new_bases=[],has_mro_entries=false;for(var base of bases){if(!$B.$isinstance(base,_b_.type)){var mro_entries=$B.$getattr(base,"__mro_entries__",_b_.None);if(mro_entries!==_b_.None){has_mro_entries=true;var entries=_b_.list.$factory(mro_entries(bases));new_bases=new_bases.concat(entries)}else{new_bases.push(base)}}else{new_bases.push(base)}}return has_mro_entries?new_bases:bases};$B.make_class=function(qualname,factory){var A={__class__:type,__bases__:[_b_.object],__mro__:[_b_.object],__name__:qualname,__qualname__:qualname,$is_class:true};A.$factory=factory;return A};var type=$B.make_class("type",(function(){var missing={},$=$B.args("type",3,{kls:null,bases:null,cl_dict:null},["kls","bases","cl_dict"],arguments,{bases:missing,cl_dict:missing},null,"kw"),kls=$.kls,bases=$.bases,cl_dict=$.cl_dict,kw=$.kw;var kwarg={};for(var item of _b_.dict.$iter_items(kw)){kwarg[item.key]=item.value}var kwargs={$kw:[kwarg]};if(cl_dict===missing){if(bases!==missing){throw _b_.TypeError.$factory("type() takes 1 or 3 arguments")}var res=$B.get_class(kls);if(res===$B.long_int){return _b_.int}return res}else{var module=$B.frame_obj.frame[2],resolved_bases=$B.resolve_mro_entries(bases),metaclass=$B.get_metaclass(kls,module,resolved_bases);return type.__call__(metaclass,kls,resolved_bases,cl_dict,kwargs)}}));type.__class__=type;var classmethod=_b_.classmethod=$B.make_class("classmethod",(function(func){$B.check_nb_args_no_kw("classmethod",1,arguments);return{__class__:classmethod,__func__:func}}));classmethod.__get__=function(){var $=$B.args("classmethod",3,{self:null,obj:null,cls:null},["self","obj","cls"],arguments,{cls:_b_.None},null,null),self=$.self,obj=$.obj,cls=$.cls;if(cls===_b_.None||cls===undefined){cls=$B.get_class(obj)}var func_class=$B.get_class(self.__func__),candidates=[func_class].concat(func_class.__mro__);for(var candidate of candidates){if(candidate===$B.function){break}if(candidate.__get__){return candidate.__get__(self.__func__,cls,cls)}}return $B.method.$factory(self.__func__,cls)};$B.set_func_names(classmethod,"builtins");var staticmethod=_b_.staticmethod=$B.make_class("staticmethod",(function(func){return{__class__:staticmethod,__func__:func}}));staticmethod.__call__=function(self){return $B.$call(self.__func__)};staticmethod.__get__=function(self){return self.__func__};$B.set_func_names(staticmethod,"builtins");$B.getset_descriptor=$B.make_class("getset_descriptor",(function(klass,attr,getter,setter){var res={__class__:$B.getset_descriptor,__doc__:_b_.None,cls:klass,attr:attr,getter:getter,setter:setter};return res}));$B.getset_descriptor.__get__=function(self,obj,klass){if(obj===_b_.None){return self}return self.getter(self,obj,klass)};$B.getset_descriptor.__set__=function(self,klass,value){return self.setter(self,klass,value)};$B.getset_descriptor.__repr__=function(self){return``};$B.set_func_names($B.getset_descriptor,"builtins");type.$call=function(klass,new_func,init_func){return function(){var instance=new_func.bind(null,klass).apply(null,arguments);if($B.$isinstance(instance,klass)){init_func.bind(null,instance).apply(null,arguments)}return instance}};type.$call_no_new_init=function(klass,init_func){return function(){var instance=_b_.object.$no_new_init(klass);init_func(instance,...arguments);return instance}};type.$call_no_init=function(klass,new_func){return new_func.bind(null,klass)};type.__call__=function(){var extra_args=[],klass=arguments[0];for(var i=1,len=arguments.length;i1){console.log("warning: no attribute $infos for",res,"klass",klass,"attr",attr)}if($test){console.log("res is function",res)}if(attr=="__new__"||res.__class__===$B.builtin_function_or_method){res.$type="staticmethod"}if((attr=="__class_getitem__"||attr=="__init_subclass__")&&res.__class__!==_b_.classmethod){res=_b_.classmethod.$factory(res);return _b_.classmethod.__get__(res,_b_.None,klass)}if(res.__class__===$B.method){return res.__get__(null,klass)}else{if($test){console.log("return res",res)}return res}}else{return res}}};type.__hash__=function(cls){return _b_.hash(cls)};type.__init__=function(){if(arguments.length==0){throw _b_.TypeError.$factory("descriptor '__init__' of 'type' "+"object needs an argument")}};type.__init_subclass__=function(){var $=$B.args("__init_subclass__",1,{cls:null},["cls"],arguments,{},"args","kwargs");if($.args.length>0){throw _b_.TypeError.$factory(`${$.cls.__qualname__}.__init_subclass__ takes no arguments `+`(${$.args.length} given)`)}if(_b_.dict.__len__($.kwargs)>0){throw _b_.TypeError.$factory(`${$.cls.__qualname__}.__init_subclass__() `+`takes no keyword arguments`)}return _b_.None};_b_.object.__init_subclass__=type.__init_subclass__;type.__instancecheck__=function(cls,instance){var kl=instance.__class__||$B.get_class(instance);if(kl===cls){return true}else{for(var i=0;i"};type.__ror__=function(){var len=arguments.length;if(len!=1){throw _b_.TypeError.$factory(`expected 1 argument, got ${len}`)}return _b_.NotImplemented};function update_subclasses(kls,name,alias,value){for(var subclass of kls.$subclasses){if(!subclass.hasOwnProperty(name)){subclass[alias]=value;update_subclasses(subclass,name,alias,value)}}}type.__setattr__=function(kls,attr,value){var $test=false;if($test){console.log("kls is class",type)}if(type[attr]&&type[attr].__get__&&type[attr].__set__){type[attr].__set__(kls,value);return _b_.None}if(kls.__module__=="builtins"){throw _b_.TypeError.$factory(`cannot set '${attr}' attribute of immutable type '`+kls.__qualname__+"'")}kls[attr]=value;var mp=kls.__dict__||$B.$getattr(kls,"__dict__");_b_.dict.$setitem(mp,attr,value);switch(attr){case"__init__":case"__new__":kls.$factory=$B.$instance_creator(kls);break;case"__bases__":kls.__mro__=_b_.type.mro(kls);break;case"__setattr__":var initial_value=kls.$tp_setattr;kls.$tp_setattr=value;update_subclasses(kls,"__setattr__","$tp_setattr",value);break}if($test){console.log("after setattr",kls)}return _b_.None};type.$mro=function(cls){if(cls===undefined){throw _b_.TypeError.$factory("unbound method type.mro() needs an argument")}var bases=cls.__bases__,seqs=[],pos1=0;for(var base of bases){let bmro=[],pos=0;if(base===undefined||base.__mro__===undefined){if(base.__class__===undefined){return[_b_.object]}else{console.log("error for base",base);console.log("cls",cls)}}bmro[pos++]=base;var _tmp=base.__mro__;if(_tmp){if(_tmp[0]===base){_tmp.splice(0,1)}for(var k=0;k<_tmp.length;k++){bmro[pos++]=_tmp[k]}}seqs[pos1++]=bmro}seqs[pos1++]=bases.slice();var mro=[cls],mpos=1;while(1){let non_empty=[],pos=0;for(let i=0;i0){non_empty[pos++]=seqs[i]}}if(non_empty.length==0){break}let candidate;for(let i=0;i-1){not_head[pos++]=s}}if(not_head.length>0){candidate=null}else{break}}if(candidate===null){throw _b_.TypeError.$factory("inconsistent hierarchy, no C3 MRO is possible")}mro[mpos++]=candidate;for(let i=0;i-1};$B.set_func_names(type,"builtins");type.__init_subclass__=_b_.classmethod.$factory(type.__init_subclass__);_b_.type=type;var property=_b_.property=$B.make_class("property",(function(fget,fset,fdel,doc){var res={__class__:property};property.__init__(res,fget,fset,fdel,doc);return res}));property.__init__=function(){var $=$B.args("__init__",5,{self:null,fget:null,fset:null,fdel:null,doc:null},["self","fget","fset","fdel","doc"],arguments,{fget:_b_.None,fset:_b_.None,fdel:_b_.None,doc:_b_.None},null,null),self=$.self,fget=$.fget,fset=$.fset,fdel=$.fdel,doc=$.doc;self.__doc__=doc;if($B.$getattr&&doc===_b_.None){self.__doc__=$B.$getattr(fget,"__doc__",doc)}self.$type=fget.$type;self.fget=fget;self.fset=fset;self.fdel=fdel;self.$is_property=true;if(fget&&fget.$attrs){for(var key in fget.$attrs){self[key]=fget.$attrs[key]}}self.__delete__=fdel;self.getter=function(fget){return property.$factory(fget,self.fset,self.fdel,self.__doc__)};self.setter=function(fset){return property.$factory(self.fget,fset,self.fdel,self.__doc__)};self.deleter=function(fdel){return property.$factory(self.fget,self.fset,fdel,self.__doc__)}};property.__get__=function(self,kls){if(self.fget===undefined){throw _b_.AttributeError.$factory("unreadable attribute")}return $B.$call(self.fget)(kls)};property.__new__=function(cls){return{__class__:cls}};property.__set__=function(self,obj,value){if(self.fset===undefined){var name=self.fget.$infos.__name__;var msg=`property '${name}' of '${$B.class_name(obj)}' object `+"has no setter";throw _b_.AttributeError.$factory(msg)}$B.$getattr(self.fset,"__call__")(obj,value)};$B.set_func_names(property,"builtins");var wrapper_descriptor=$B.wrapper_descriptor=$B.make_class("wrapper_descriptor");wrapper_descriptor.__text_signature__={__get__:function(){return"(self, /, *args, **kwargs)"}};$B.set_func_names(wrapper_descriptor,"builtins");type.__call__.__class__=wrapper_descriptor;$B.$instance_creator=function(klass){var test=false;if(test){console.log("instance creator of",klass)}if(klass.prototype&&klass.prototype.constructor==klass){return function(){return new klass(...arguments)}}if(klass.__abstractmethods__&&$B.$bool(klass.__abstractmethods__)){return function(){var ams=Array.from($B.make_js_iterator(klass.__abstractmethods__));ams.sort();var msg=(ams.length>1?"s ":" ")+ams.join(", ");throw _b_.TypeError.$factory("Can't instantiate abstract class interface "+"with abstract method"+msg)}}var metaclass=klass.__class__||$B.get_class(klass),call_func,factory;if(metaclass===_b_.type){var new_func=type.__getattribute__(klass,"__new__"),init_func=type.__getattribute__(klass,"__init__");if(init_func===_b_.object.__init__){if(new_func===_b_.object.__new__){factory=_b_.object.$new(klass)}else{factory=new_func.bind(null,klass)}}else if(new_func===_b_.object.__new__){factory=type.$call_no_new_init(klass,init_func)}else{factory=type.$call(klass,new_func,init_func)}}else{call_func=_b_.type.__getattribute__(metaclass,"__call__");if(call_func.$is_class){factory=$B.$call(call_func)}else{factory=call_func.bind(null,klass)}}factory.__class__=$B.function;factory.$infos={__name__:klass.__name__,__module__:klass.__module__};return factory};var method_wrapper=$B.method_wrapper=$B.make_class("method_wrapper",(function(attr,klass,method){var f=function(){return method.apply(null,arguments)};f.$infos={__name__:attr,__module__:klass.__module__};return f}));method_wrapper.__str__=method_wrapper.__repr__=function(self){return""};var member_descriptor=$B.member_descriptor=$B.make_class("member_descriptor",(function(attr,cls){return{__class__:member_descriptor,cls:cls,attr:attr}}));member_descriptor.__delete__=function(self,kls){if(kls.$slot_values===undefined||!kls.$slot_values.hasOwnProperty(self.attr)){throw _b_.AttributeError.$factory(self.attr)}kls.$slot_values.delete(self.attr)};member_descriptor.__get__=function(self,kls){if(kls===_b_.None){return self}if(kls.$slot_values===undefined||!kls.$slot_values.has(self.attr)){throw $B.attr_error(self.attr,kls)}return kls.$slot_values.get(self.attr)};member_descriptor.__set__=function(self,kls,value){if(kls.$slot_values===undefined){kls.$slot_values=new Map}kls.$slot_values.set(self.attr,value)};member_descriptor.__str__=member_descriptor.__repr__=function(self){return""};$B.set_func_names(member_descriptor,"builtins");var method=$B.method=$B.make_class("method",(function(func,cls){var f=function(){return $B.$call(func).bind(null,cls).apply(null,arguments)};f.__class__=method;if(typeof func!=="function"){console.log("method from func w-o $infos",func,"all",$B.$call(func))}f.$infos=func.$infos||{};f.$infos.__func__=func;f.$infos.__self__=cls;f.$infos.__dict__=$B.empty_dict();return f}));method.__eq__=function(self,other){return self.$infos!==undefined&&other.$infos!==undefined&&self.$infos.__func__===other.$infos.__func__&&self.$infos.__self__===other.$infos.__self__};method.__ne__=function(self,other){return!$B.method.__eq__(self,other)};method.__get__=function(self){var f=function(){return self(...arguments)};f.__class__=$B.method_wrapper;f.$infos=method.$infos;return f};method.__getattribute__=function(self,attr){var infos=self.$infos;if(infos&&infos[attr]){if(attr=="__code__"){var res={__class__:$B.Code};for(var key in infos.__code__){res[key]=infos.__code__[key]}return res}else{return infos[attr]}}else if(method.hasOwnProperty(attr)){return _b_.object.__getattribute__(self,attr)}else{return $B.function.__getattribute__(self.$infos.__func__,attr)}};method.__repr__=method.__str__=function(self){return""};method.__setattr__=function(self,key){if(key=="__class__"){throw _b_.TypeError.$factory("__class__ assignment only supported "+"for heap types or ModuleType subclasses")}throw $B.attr_error(key,self)};$B.set_func_names(method,"builtins");$B.method_descriptor=$B.make_class("method_descriptor");$B.classmethod_descriptor=$B.make_class("classmethod_descriptor");_b_.object.__class__=type;$B.make_iterator_class=function(name){var klass={__class__:_b_.type,__mro__:[_b_.object],__name__:name,__qualname__:name,$factory:function(items){return{__class__:klass,__dict__:$B.empty_dict(),counter:-1,items:items,len:items.length,$builtin_iterator:true}},$is_class:true,$iterator_class:true,__iter__:function(self){self.counter=self.counter===undefined?-1:self.counter;self.len=self.items.length;return self},__len__:function(self){return self.items.length},__next__:function(self){if(typeof self.test_change=="function"){var message=self.test_change();if(message){throw _b_.RuntimeError.$factory(message)}}self.counter++;if(self.counter$B.fast_tuple(self.items)));$B.GenericAlias.__call__=function(self,...args){return self.origin_class.$factory.apply(null,args)};$B.GenericAlias.__eq__=function(self,other){if(!$B.$isinstance(other,$B.GenericAlias)){return false}return $B.rich_comp("__eq__",self.origin_class,other.origin_class)&&$B.rich_comp("__eq__",self.items,other.items)};$B.GenericAlias.__getitem__=function(self,item){throw _b_.TypeError.$factory("descriptor '__getitem__' for '"+self.origin_class.__name__+"' objects doesn't apply to a '"+$B.class_name(item)+"' object")};$B.GenericAlias.__mro_entries__=function(self){return $B.fast_tuple([self.origin_class])};$B.GenericAlias.__new__=function(origin_class,items){var res={__class__:$B.GenericAlias,__mro__:[origin_class],origin_class:origin_class,items:items,$is_class:true};return res};$B.GenericAlias.__or__=function(){var $=$B.args("__or__",2,{self:null,other:null},["self","other"],arguments,{},null,null);return $B.UnionType.$factory([$.self,$.other])};$B.GenericAlias.__origin__=_b_.property.$factory((self=>self.origin_class));$B.GenericAlias.__parameters__=_b_.property.$factory((function(){return $B.fast_tuple([])}));$B.GenericAlias.__repr__=function(self){var items=Array.isArray(self.items)?self.items:[self.items];var reprs=[];for(var item of items){if(item===_b_.Ellipsis){reprs.push("...")}else{if(item.$is_class){reprs.push(item.__name__)}else{reprs.push(_b_.repr(item))}}}var iv=$B.$getattr(self.origin_class,"__infer_variance__",true);var prefix=iv?"":"~";return prefix+$B.$getattr(self.origin_class,"__qualname__")+"["+reprs.join(", ")+"]"};$B.GenericAlias.__type_params__=_b_.property.$factory((function(self){return $B.$getattr(self.origin_class,"__type_params__")}));$B.set_func_names($B.GenericAlias,"types");$B.UnionType=$B.make_class("UnionType",(function(items){return{__class__:$B.UnionType,items:items}}));$B.UnionType.__args__=_b_.property.$factory((self=>$B.fast_tuple(self.items)));$B.UnionType.__eq__=function(self,other){if(!$B.$isinstance(other,$B.UnionType)){return _b_.NotImplemented}return _b_.list.__eq__(self.items,other.items)};$B.UnionType.__or__=function(self,other){var items=self.items.slice();if(!items.includes(other)){items.push(other)}return $B.UnionType.$factory(items)};$B.UnionType.__parameters__=_b_.property.$factory((()=>$B.fast_tuple([])));$B.UnionType.__repr__=function(self){var t=[];for(var item of self.items){if(item.$is_class){var s=item.__name__;if(item.__module__!=="builtins"){s=item.__module__+"."+s}t.push(s)}else{t.push(_b_.repr(item))}}return t.join(" | ")};$B.set_func_names($B.UnionType,"types")})(__BRYTHON__);(function($B){var _b_=$B.builtins;_b_.__debug__=false;$B.$comps={">":"gt",">=":"ge","<":"lt","<=":"le"};$B.$inv_comps={">":"lt",">=":"le","<":"gt","<=":"ge"};var check_nb_args=$B.check_nb_args,check_no_kw=$B.check_no_kw,check_nb_args_no_kw=$B.check_nb_args_no_kw;var NoneType=$B.NoneType={$factory:function(){return None},__bool__:function(){return False},__class__:_b_.type,__hash__:function(){return 0},__module__:"builtins",__mro__:[_b_.object],__name__:"NoneType",__qualname__:"NoneType",__repr__:function(){return"None"},__str__:function(){return"None"},$is_class:true};NoneType.__setattr__=function(self,attr){return no_set_attr(NoneType,attr)};var None=_b_.None={__class__:NoneType};None.__doc__=None;NoneType.__doc__=None;for(var $op in $B.$comps){var key=$B.$comps[$op];switch(key){case"ge":case"gt":case"le":case"lt":NoneType["__"+key+"__"]=function(){return function(){return _b_.NotImplemented}}($op)}}for(var $func in None){if(typeof None[$func]=="function"){None[$func].__str__=function(f){return function(){return""}}($func)}}$B.set_func_names(NoneType,"builtins");_b_.__build_class__=function(){throw _b_.NotImplementedError.$factory("__build_class__")};_b_.abs=function(obj){check_nb_args_no_kw("abs",1,arguments);var klass=obj.__class__||$B.get_class(obj);try{var method=$B.$getattr(klass,"__abs__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("Bad operand type for abs(): '"+$B.class_name(obj)+"'")}throw err}return $B.$call(method)(obj)};_b_.aiter=function(async_iterable){return $B.$call($B.$getattr(async_iterable,"__aiter__"))()};_b_.all=function(obj){check_nb_args_no_kw("all",1,arguments);var iterable=iter(obj);while(1){try{var elt=next(iterable);if(!$B.$bool(elt)){return false}}catch(err){return true}}};_b_.anext=function(){var missing={},$=$B.args("anext",2,{async_iterator:null,_default:null},["async_iterator","_default"],arguments,{_default:missing},null,null);var awaitable=$B.$call($B.$getattr($.async_iterator,"__anext__"))();return awaitable.catch((function(err){if($B.is_exc(err,[_b_.StopAsyncIteration])){if($._default!==missing){return $._default}}throw err}))};_b_.any=function(obj){check_nb_args_no_kw("any",1,arguments);for(var elt of $B.make_js_iterator(obj)){if($B.$bool(elt)){return true}}return false};_b_.ascii=function(obj){check_nb_args_no_kw("ascii",1,arguments);var res=repr(obj),res1="",cp;for(var i=0;i=0){return prefix+value.toString(base)}return"-"+prefix+(-value).toString(base)}function bin_hex_oct(base,obj){if($B.$isinstance(obj,_b_.int)){return $builtin_base_convert_helper(obj,base)}else{try{var klass=obj.__class__||$B.get_class(obj),method=$B.$getattr(klass,"__index__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object cannot be interpreted as an integer")}throw err}var res=$B.$call(method)(obj);return $builtin_base_convert_helper(res,base)}}_b_.bin=function(obj){check_nb_args_no_kw("bin",1,arguments);return bin_hex_oct(2,obj)};_b_.breakpoint=function(){$B.$import("sys",[]);var missing={},hook=$B.$getattr($B.imported.sys,"breakpointhook",missing);if(hook===missing){throw _b_.RuntimeError.$factory("lost sys.breakpointhook")}return $B.$call(hook).apply(null,arguments)};_b_.callable=function(obj){check_nb_args_no_kw("callable",1,arguments);return _b_.hasattr(obj,"__call__")};_b_.chr=function(i){check_nb_args_no_kw("chr",1,arguments);i=$B.PyNumber_Index(i);if(i<0||i>1114111){throw _b_.ValueError.$factory("Outside valid range")}else if(i>=65536&&i<=1114111){var code=i-65536,s=String.fromCodePoint(55296|code>>10)+String.fromCodePoint(56320|code&1023);return $B.make_String(s,[0])}else{return String.fromCodePoint(i)}};var code=_b_.code=$B.make_class("code");code.__repr__=code.__str__=function(_self){return``};code.__getattribute__=function(self,attr){if(attr=="co_positions"){return()=>$B.$list([$B.$list([0,0,0,0])])}return self[attr]};$B.set_func_names(code,"builtins");_b_.compile=function(){var $=$B.args("compile",7,{source:null,filename:null,mode:null,flags:null,dont_inherit:null,optimize:null,_feature_version:null},["source","filename","mode","flags","dont_inherit","optimize","_feature_version"],arguments,{flags:0,dont_inherit:false,optimize:-1,_feature_version:0},null,null);var module_name="$exec_"+$B.UUID();$.__class__=code;$.co_flags=$.flags;$.co_name="";var filename=$.co_filename=$.filename;var interactive=$.mode=="single"&&$.flags&512;$B.file_cache[filename]=$.source;$B.url2name[filename]=module_name;if($.flags&$B.PyCF_TYPE_COMMENTS){}if($B.$isinstance($.source,_b_.bytes)){var encoding="utf-8",lfpos=$.source.source.indexOf(10),first_line,second_line;if(lfpos==-1){first_line=$.source}else{first_line=_b_.bytes.$factory($.source.source.slice(0,lfpos))}first_line=_b_.bytes.decode(first_line,"latin-1");var encoding_re=/^[\t\f]*#.*?coding[:=][\t]*([-_.a-zA-Z0-9]+)/;var mo=first_line.match(encoding_re);if(mo){encoding=mo[1]}else if(lfpos>-1){var rest=$.source.source.slice(lfpos+1);lfpos=rest.indexOf(10);if(lfpos>-1){second_line=_b_.bytes.$factory(rest.slice(0,lfpos))}else{second_line=_b_.bytes.$factory(rest)}second_line=_b_.bytes.decode(second_line,"latin-1");mo=second_line.match(encoding_re);if(mo){encoding=mo[1]}}$.source=_b_.bytes.decode($.source,encoding)}if(!$B.$isinstance(filename,[_b_.bytes,_b_.str])){$B.warn(_b_.DeprecationWarning,`path should be string, bytes, or os.PathLike, `+`not ${$B.class_name(filename)}`)}if(interactive&&!$.source.endsWith("\n")){var lines=$.source.split("\n"),last_line=$B.last(lines);if(last_line.startsWith(" ")){var msg="unexpected EOF while parsing",exc=_b_.SyntaxError.$factory();exc.filename=filename;exc.lineno=exc.end_lineno=lines.length-1;exc.offset=0;exc.end_offset=last_line.length-1;exc.text=last_line;exc.args=[msg,$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset])];throw exc}}if($.source.__class__&&$.source.__class__.__module__=="ast"){$B.imported._ast._validate($.source);$._ast=$.source;delete $.source;return $}var _ast,parser;try{var parser_mode=$.mode=="eval"?"eval":"file";parser=new $B.Parser($.source,filename,parser_mode);parser.flags=$.flags;_ast=$B._PyPegen.run_parser(parser)}catch(err){if($.mode=="single"){var tester=parser.tokens[parser.tokens.length-2];if(tester&&(tester.type=="NEWLINE"&&$.flags&$B.PyCF_ALLOW_INCOMPLETE_INPUT||tester.type=="DEDENT"&&$.flags&512)){err.__class__=_b_._IncompleteInputError;err.args[0]="incomplete input"}}throw err}if($.mode=="single"&&_ast.body.length==1&&_ast.body[0]instanceof $B.ast.Expr){parser=new $B.Parser($.source,filename,"eval");_ast=$B._PyPegen.run_parser(parser);$.single_expression=true}if($.flags==$B.PyCF_ONLY_AST){delete $B.url2name[filename];let res=$B.ast_js_to_py(_ast);res.$js_ast=_ast;return res}delete $B.url2name[filename];$._ast=$B.ast_js_to_py(_ast);$._ast.$js_ast=_ast;var future=$B.future_features(_ast,filename);var symtable=$B._PySymtable_Build(_ast,filename,future);$B.js_from_root({ast:_ast,symtable:symtable,filename:filename,src:$.source});return $};_b_.debug=$B.debug>0;_b_.delattr=function(obj,attr){check_nb_args_no_kw("delattr",2,arguments);if(typeof attr!="string"){throw _b_.TypeError.$factory("attribute name must be string, not '"+$B.class_name(attr)+"'")}return $B.$getattr(obj,"__delattr__")(attr)};$B.$delete=function(name,is_global){function del(obj){if(obj.__class__===$B.generator){obj.js_gen.return()}}var found=false,frame=$B.frame_obj.frame;if(!is_global){if(frame[1][name]!==undefined){found=true;del(frame[1][name]);delete frame[1][name]}}else{if(frame[2]!=frame[0]&&frame[3][name]!==undefined){found=true;del(frame[3][name]);delete frame[3][name]}}if(!found){throw $B.name_error(name)}};_b_.dir=function(obj){if(obj===undefined){var locals=_b_.locals();return _b_.sorted(locals)}check_nb_args_no_kw("dir",1,arguments);var klass=obj.__class__||$B.get_class(obj);if(obj.$is_class){var dir_func=$B.$getattr(obj.__class__,"__dir__");return $B.$call(dir_func)(obj)}try{let res=$B.$call($B.$getattr(klass,"__dir__"))(obj);res=_b_.list.$factory(res);return res}catch(err){if($B.get_option("debug")>2){console.log("error in dir, obj",obj,"klass",klass,$B.$getattr(klass,"__dir__"),err.message)}throw err}};_b_.divmod=function(x,y){check_nb_args_no_kw("divmod",2,arguments);try{return $B.rich_op("__divmod__",x,y)}catch(err){if($B.is_exc(err,[_b_.TypeError])){return _b_.tuple.$factory([$B.rich_op("__floordiv__",x,y),$B.rich_op("__mod__",x,y)])}throw err}};var enumerate=_b_.enumerate=$B.make_class("enumerate",(function(){var $ns=$B.args("enumerate",2,{iterable:null,start:null},["iterable","start"],arguments,{start:0},null,null),_iter=iter($ns["iterable"]),start=$ns["start"];return{__class__:enumerate,__name__:"enumerate iterator",counter:start-1,iter:_iter,start:start}}));enumerate.__class_getitem__=$B.$class_getitem;enumerate.__iter__=function(self){self.counter=self.start-1;return self};enumerate.__next__=function(self){self.counter++;return $B.fast_tuple([self.counter,next(self.iter)])};$B.set_func_names(enumerate,"builtins");$B.LOCALS_PROXY=Symbol("locals_proxy");enumerate.__class_getitem__=_b_.classmethod.$factory(enumerate.__class_getitem__);var $$eval=_b_.eval=function(){var $=$B.args("eval",4,{src:null,globals:null,locals:null,mode:null},["src","globals","locals","mode"],arguments,{globals:_b_.None,locals:_b_.None,mode:"eval"},null,null,4),src=$.src,_globals=$.globals,_locals=$.locals,mode=$.mode;if($.src.mode&&$.src.mode=="single"&&["",""].indexOf($.src.filename)>-1){_b_.print(">",$.src.source.trim())}var filename="";if(src.__class__===code){filename=src.filename}else if(!src.valueOf||typeof src.valueOf()!=="string"){throw _b_.TypeError.$factory(`${mode}() arg 1 must be a string,`+" bytes or code object")}else{src=src.valueOf()}var __name__="exec";if(_globals!==_b_.None&&_globals.__class__==_b_.dict&&_b_.dict.$contains_string(_globals,"__name__")){__name__=_b_.dict.$getitem_string(_globals,"__name__")}$B.url2name[filename]=__name__;var frame=$B.frame_obj.frame;$B.exec_scope=$B.exec_scope||{};if(typeof src=="string"&&src.endsWith("\\\n")){var exc=_b_.SyntaxError.$factory("unexpected EOF while parsing");var lines=src.split("\n"),line=lines[lines.length-2];exc.args=["unexpected EOF while parsing",[filename,lines.length-1,1,line]];exc.filename=filename;exc.text=line;throw exc}var local_name=("locals_"+__name__).replace(/\./g,"_"),global_name=("globals_"+__name__).replace(/\./g,"_"),exec_locals={},exec_globals={};if(_globals===_b_.None){if(frame[1]===frame[3]){global_name+="_globals";exec_locals=exec_globals=frame[3]}else{if(mode=="exec"){exec_locals=$B.clone(frame[1]);for(var attr in frame[3]){exec_locals[attr]=frame[3][attr]}exec_globals=exec_locals}else{exec_locals=frame[1];exec_globals=frame[3]}}}else{if(_globals.__class__!==_b_.dict){throw _b_.TypeError.$factory(`${mode}() globals must be `+"a dict, not "+$B.class_name(_globals))}exec_globals={};if(_globals.$jsobj){exec_globals=_globals.$jsobj}else{exec_globals=_globals.$jsobj={};for(var key of _b_.dict.$keys_string(_globals)){_globals.$jsobj[key]=_b_.dict.$getitem_string(_globals,key);if(key=="__name__"){__name__=_globals.$jsobj[key]}}_globals.$all_str=false}if(exec_globals.__builtins__===undefined){exec_globals.__builtins__=_b_.__builtins__}if(_locals===_b_.None){exec_locals=exec_globals}else{if(_locals===_globals){global_name+="_globals";exec_locals=exec_globals}else if(_locals.$jsobj){for(let key in _locals.$jsobj){exec_globals[key]=_locals.$jsobj[key]}}else{if(_locals.$jsobj){exec_locals=_locals.$jsobj}else{var klass=$B.get_class(_locals),getitem=$B.$call($B.$getattr(klass,"__getitem__")),setitem=$B.$call($B.$getattr(klass,"__setitem__"));exec_locals=new Proxy(_locals,{get(target,prop){if(prop=="$target"){return target}else if(prop==$B.LOCALS_PROXY){return true}try{return getitem(target,prop)}catch(err){return undefined}},set(target,prop,value){return setitem(target,prop,value)}})}}}}var save_frame_obj=$B.frame_obj;var _ast;frame=[__name__,exec_locals,__name__,exec_globals];frame.is_exec_top=true;$B.enter_frame(frame,filename,1);var _frame_obj=$B.frame_obj;if(src.__class__===code){_ast=src._ast;if(_ast.$js_ast){_ast=_ast.$js_ast}else{_ast=$B.ast_py_to_js(_ast)}}try{if(!_ast){var _mode=mode=="eval"?"eval":"file";var parser=new $B.Parser(src,filename,_mode);_ast=$B._PyPegen.run_parser(parser)}var future=$B.future_features(_ast,filename),symtable=$B._PySymtable_Build(_ast,filename,future),js_obj=$B.js_from_root({ast:_ast,symtable:symtable,filename:filename,src:src,namespaces:{local_name:local_name,exec_locals:exec_locals,global_name:global_name,exec_globals:exec_globals}}),js=js_obj.js}catch(err){if(err.args){if(err.args[1]){exec_locals.$lineno=err.args[1][1]}}else{console.log("JS Error",err.message)}$B.frame_obj=save_frame_obj;throw err}if(mode=="eval"){js=`var __file__ = '${filename}'\n`+`var locals = ${local_name}\nreturn ${js}`}else if(src.single_expression){js=`var __file__ = '${filename}'\n`+`var result = ${js}\n`+`if(result !== _b_.None){\n`+`_b_.print(result)\n`+`}`}try{var exec_func=new Function("$B","_b_",local_name,global_name,"frame","_frame_obj",js)}catch(err){if($B.get_option("debug")>1){console.log("eval() error\n",$B.format_indent(js,0));console.log("-- python source\n",src)}$B.frame_obj=save_frame_obj;throw err}try{var res=exec_func($B,_b_,exec_locals,exec_globals,frame,_frame_obj)}catch(err){if($B.get_option("debug")>2){console.log("Python code\n",src,"\nexec func",$B.format_indent(exec_func+"",0),"\n filename",filename,"\n name from filename",$B.url2name[filename],"\n local_name",local_name,"\n exec_locals",exec_locals,"\n global_name",global_name,"\n exec_globals",exec_globals,"\n frame",frame,"\n _ast",_ast,"\n js",js,"\n err",err.__class__,err.args,err.$frame_obj)}$B.frame_obj=save_frame_obj;throw err}if(_globals!==_b_.None&&!_globals.$jsobj){for(var _key in exec_globals){if(!_key.startsWith("$")){_b_.dict.$setitem(_globals,_key,exec_globals[_key])}}}$B.frame_obj=save_frame_obj;return res};$$eval.$is_func=true;var exec=_b_.exec=function(){var $=$B.args("exec",3,{src:null,globals:null,locals:null},["src","globals","locals"],arguments,{globals:_b_.None,locals:_b_.None},null,null,1),src=$.src,globals=$.globals,locals=$.locals;$$eval(src,globals,locals,"exec");return _b_.None};exec.$is_func=true;var exit=_b_.exit=function(){throw _b_.SystemExit};exit.__repr__=exit.__str__=function(){return"Use exit() or Ctrl-Z plus Return to exit"};var filter=_b_.filter=$B.make_class("filter",(function(func,iterable){check_nb_args_no_kw("filter",2,arguments);iterable=iter(iterable);if(func===_b_.None){func=$B.$bool}return{__class__:filter,func:func,iterable:iterable}}));filter.__iter__=function(self){return self};filter.__next__=function(self){while(true){var _item=next(self.iterable);if(self.func(_item)){return _item}}};$B.set_func_names(filter,"builtins");_b_.format=function(){var $=$B.args("format",2,{value:null,format_spec:null},["value","format_spec"],arguments,{format_spec:""},null,null),value=$.value;var klass=value.__class__||$B.get_class(value);try{var method=$B.$getattr(klass,"__format__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.NotImplementedError("__format__ is not implemented "+"for object '"+_b_.str.$factory(value)+"'")}throw err}return $B.$call(method)(value,$.format_spec)};function attr_error(attr,obj){var cname=$B.get_class(obj);var msg="bad operand type for unary #: '"+cname+"'";switch(attr){case"__neg__":throw _b_.TypeError.$factory(msg.replace("#","-"));case"__pos__":throw _b_.TypeError.$factory(msg.replace("#","+"));case"__invert__":throw _b_.TypeError.$factory(msg.replace("#","~"));case"__call__":throw _b_.TypeError.$factory("'"+cname+"'"+" object is not callable");default:throw $B.attr_error(attr,obj)}}_b_.getattr=function(){var missing={};var $=$B.args("getattr",3,{obj:null,attr:null,_default:null},["obj","attr","_default"],arguments,{_default:missing},null,null);if(!$B.$isinstance($.attr,_b_.str)){throw _b_.TypeError.$factory("attribute name must be string, "+`not '${$B.class_name($.attr)}'`)}return $B.$getattr($.obj,_b_.str.$to_string($.attr),$._default===missing?undefined:$._default)};$B.search_in_mro=function(klass,attr){if(klass.hasOwnProperty(attr)){return klass[attr]}var mro=klass.__mro__;for(var i=0,len=mro.length;i-1}))}break;case"__mro__":if(obj.__mro__){return _b_.tuple.$factory([obj].concat(obj.__mro__))}else if(obj.__dict__&&_b_.dict.$contains_string(obj.__dict__,"__mro__")){return _b_.dict.$getitem_string(obj.__dict__,"__mro__")}throw $B.attr_error(attr,obj);case"__subclasses__":if(klass.$factory||klass.$is_class){var subclasses=obj.$subclasses||[];return function(){return $B.$list(subclasses)}}break}if(typeof obj=="function"){var value=obj[attr];if(value!==undefined){if(attr=="__module__"){return value}}}if(!is_class&&klass.$native){if(obj.$method_cache&&obj.$method_cache[attr]){return obj.$method_cache[attr]}if($test){console.log("native class",klass,klass[attr])}if(klass[attr]===undefined){var object_attr=_b_.object[attr];if($test){console.log("object attr",object_attr)}if(object_attr!==undefined){klass[attr]=object_attr}else{if($test){console.log("obj[attr]",obj[attr])}var attrs=obj.__dict__;if(attrs&&_b_.dict.$contains_string(attrs,attr)){return _b_.dict.$getitem_string(attrs,attr)}if(_default===undefined){throw $B.attr_error(attr,obj)}return _default}}else if(["__name__","__qualname__"].includes(attr)){attr_error(attr,obj)}if(klass.$descriptors&&klass.$descriptors[attr]!==undefined){return klass[attr](obj)}if(typeof klass[attr]=="function"){var func=klass[attr];if(attr=="__new__"){func.$type="staticmethod"}if(func.$type=="staticmethod"){return func}var self=klass[attr].__class__==$B.method?klass:obj,method=klass[attr].bind(null,self);method.__class__=$B.method;method.$infos={__func__:func,__name__:attr,__self__:self,__qualname__:klass.__qualname__+"."+attr};if(typeof obj=="object"){obj.__class__=klass;obj.$method_cache=obj.$method_cache||{};if(obj.$method_cache){obj.$method_cache[attr]=method}}return method}else if(klass[attr].__class__===_b_.classmethod){return _b_.classmethod.__get__(klass[attr],obj,klass)}else if(klass[attr]!==undefined){return klass[attr]}attr_error(rawname,klass)}var attr_func;if(is_class){if($test){console.log("obj is class",obj);console.log("is a type ?",_b_.isinstance(klass,_b_.type));console.log("is type",klass===_b_.type)}if(klass===_b_.type){attr_func=_b_.type.__getattribute__}else{attr_func=$B.$call($B.$getattr(klass,"__getattribute__"))}if($test){console.log("attr func",attr_func)}}else{attr_func=klass.__getattribute__;if(attr_func===undefined){for(var cls of klass.__mro__){attr_func=cls["__getattribute__"];if(attr_func!==undefined){break}}}if($test){console.log("attr func",attr_func)}}if(typeof attr_func!=="function"){console.log(attr+" is not a function "+attr_func,klass)}var odga=_b_.object.__getattribute__;if($test){console.log("attr_func is odga ?",attr_func,attr_func===odga,"\n","\nobj[attr]",obj[attr])}if(attr_func===odga){res=obj[attr];if(Array.isArray(obj)&&Array.prototype[attr]!==undefined){res=undefined}else if(res===null){return null}else if(res!==undefined){if($test){console.log(obj,attr,obj[attr],res.__set__||res.$is_class)}if(res.$is_property){return _b_.property.__get__(res)}if(res.__set__===undefined||res.$is_class){if($test){console.log("return",res,res+"",res.__set__,res.$is_class)}return res}}}var getattr;try{res=attr_func(obj,attr);if($test){console.log("result of attr_func",res)}}catch(err){if($test){console.log("attr_func raised error",err.__class__,err.args,err.name)}if(klass===$B.module){getattr=obj.__getattr__;if($test){console.log("use module getattr",getattr);console.log(getattr+"")}if(getattr){try{return getattr(attr)}catch(err){if($test){console.log("encore erreur",err)}if(_default!==undefined){return _default}throw err}}}getattr=$B.search_in_mro(klass,"__getattr__");if($test){console.log("try getattr",getattr)}if(getattr){if($test){console.log("try with getattr",getattr)}try{return getattr(obj,attr)}catch(err){if(_default!==undefined){return _default}throw err}}if(_default!==undefined){return _default}throw err}if(res!==undefined){return res}if(_default!==undefined){return _default}attr_error(rawname,is_class?obj:klass)};_b_.globals=function(){check_nb_args_no_kw("globals",0,arguments);var res=$B.obj_dict($B.frame_obj.frame[3]);res.$jsobj.__BRYTHON__=$B.jsobj2pyobj($B);res.$is_namespace=true;return res};_b_.hasattr=function(obj,attr){check_nb_args_no_kw("hasattr",2,arguments);try{$B.$getattr(obj,attr);return true}catch(err){return false}};_b_.hash=function(obj){check_nb_args_no_kw("hash",1,arguments);return $B.$hash(obj)};$B.$hash=function(obj){if(obj.__hashvalue__!==undefined){return obj.__hashvalue__}if(typeof obj==="boolean"){return obj?1:0}if(obj.$is_class||obj.__class__===_b_.type||obj.__class__===$B.function){return obj.__hashvalue__=$B.$py_next_hash--}if(typeof obj=="string"){return _b_.str.__hash__(obj)}else if(typeof obj=="number"){return obj}else if(typeof obj=="boolean"){return obj?1:0}else if(obj.__class__===_b_.float){return _b_.float.$hash_func(obj)}var klass=obj.__class__||$B.get_class(obj);if(klass===undefined){throw _b_.TypeError.$factory("unhashable type: '"+_b_.str.$factory($B.jsobj2pyobj(obj))+"'")}var hash_method=_b_.type.__getattribute__(klass,"__hash__",_b_.None);if(hash_method===_b_.None){throw _b_.TypeError.$factory("unhashable type: '"+$B.class_name(obj)+"'")}function check_int(v){if(!Number.isInteger(v)&&!$B.$isinstance(v,_b_.int)){throw _b_.TypeError.$factory("__hash__ method should return an integer")}return v}var res;if(hash_method.$infos.__func__===_b_.object.__hash__){if(_b_.type.__getattribute__(klass,"__eq__")!==_b_.object.__eq__){throw _b_.TypeError.$factory("unhashable type: '"+$B.class_name(obj)+"'","hash")}else{return obj.__hashvalue__=check_int(_b_.object.__hash__(obj))}}else{return check_int($B.$call(hash_method)(obj))}};var help=_b_.help=function(obj){if(obj===undefined){obj="help"}if(typeof obj=="string"){var lib_url="https://docs.python.org/3/library";var parts=obj.split("."),head=[],url;while(parts.length>0){head.push(parts.shift());if($B.stdlib[head.join(".")]){url=head.join(".")}else{break}}if(url){var doc_url;if(["browser","javascript","interpreter"].indexOf(obj.split(".")[0])>-1){doc_url="/static_doc/"+($B.language=="fr"?"fr":"en")}else{doc_url=lib_url}window.open(`${doc_url}/${url}.html#`+obj);return}if(_b_[obj]){if(obj==obj.toLowerCase()){url=lib_url+`/functions.html#${obj}`}else if(["False","True","None","NotImplemented","Ellipsis","__debug__"].indexOf(obj)>-1){url=lib_url+`/constants.html#${obj}`}else if(_b_[obj].$is_class&&_b_[obj].__bases__.indexOf(_b_.Exception)>-1){url=lib_url+`/exceptions.html#${obj}`}if(url){window.open(url);return}}$B.$import("pydoc");return $B.$call($B.$getattr($B.imported.pydoc,"help"))(obj)}if(obj.__class__===$B.module){return help(obj.__name__)}try{_b_.print($B.$getattr(obj,"__doc__"))}catch(err){return""}};help.__repr__=help.__str__=function(){return"Type help() for interactive help, or help(object) "+"for help about object."};_b_.hex=function(obj){check_nb_args_no_kw("hex",1,arguments);return bin_hex_oct(16,obj)};_b_.id=function(obj){check_nb_args_no_kw("id",1,arguments);if(obj.$id!==undefined){return obj.$id}else if($B.$isinstance(obj,[_b_.str,_b_.int,_b_.float])&&!$B.$isinstance(obj,$B.long_int)){return $B.$getattr(_b_.str.$factory(obj),"__hash__")()}else{return obj.$id=$B.UUID()}};_b_.__import__=function(){var $=$B.args("__import__",5,{name:null,globals:null,locals:null,fromlist:null,level:null},["name","globals","locals","fromlist","level"],arguments,{globals:None,locals:None,fromlist:_b_.tuple.$factory(),level:0},null,null);return $B.$__import__($.name,$.globals,$.locals,$.fromlist)};_b_.input=function(msg){var res=prompt(msg||"")||"";if($B.imported["sys"]&&$B.imported["sys"].ps1){var ps1=$B.imported["sys"].ps1,ps2=$B.imported["sys"].ps2;if(msg==ps1||msg==ps2){console.log(msg,res)}}return res};_b_.isinstance=function(obj,cls){check_nb_args_no_kw("isinstance",2,arguments);return $B.$isinstance(obj,cls)};$B.$isinstance=function(obj,cls){if(obj===null){return cls===$B.imported.javascript.NullType}if(obj===undefined){return false}var kls;if(Array.isArray(cls)){for(kls of cls){if($B.$isinstance(obj,kls)){return true}}return false}if(cls.__class__===$B.UnionType){for(kls of cls.items){if($B.$isinstance(obj,kls)){return true}}return false}if(cls.__class__===$B.GenericAlias){throw _b_.TypeError.$factory("isinstance() arg 2 cannot be a parameterized generic")}if(!cls.__class__&&!cls.$is_class){if(!$B.$getattr(cls,"__instancecheck__",false)){throw _b_.TypeError.$factory("isinstance() arg 2 must be a type "+"or tuple of types")}}if(cls===_b_.int&&(obj===True||obj===False)){return true}if(cls===_b_.bool){switch(typeof obj){case"string":return false;case"number":return false;case"boolean":return true}}var klass=obj.__class__;if(klass==undefined){if(typeof obj=="string"){if(cls==_b_.str){return true}else if($B.builtin_classes.includes(cls)){return false}}else if(typeof obj=="number"&&Number.isFinite(obj)){if(Number.isFinite(obj)&&cls==_b_.int){return true}}klass=$B.get_class(obj)}if(klass===undefined){return false}if(klass===cls){return true}var mro=klass.__mro__;for(var i=0;i-1){return true}var sch=$B.$getattr(classinfo.__class__||$B.get_class(classinfo),"__subclasscheck__",_b_.None);if(sch==_b_.None){return false}return sch(classinfo,klass)};var iterator_class=$B.make_class("iterator",(function(getitem){return{__class__:iterator_class,getitem:getitem,counter:-1}}));iterator_class.__next__=function(self){self.counter++;try{return self.getitem(self.counter)}catch(err){throw _b_.StopIteration.$factory("")}};$B.set_func_names(iterator_class,"builtins");const callable_iterator=$B.make_class("callable_iterator",(function(func,sentinel){return{__class__:callable_iterator,func:func,sentinel:sentinel}}));callable_iterator.__iter__=function(self){return self};callable_iterator.__next__=function(self){var res=self.func();if($B.rich_comp("__eq__",res,self.sentinel)){throw _b_.StopIteration.$factory()}return res};$B.set_func_names(callable_iterator,"builtins");$B.$iter=function(obj,sentinel){if(sentinel===undefined){var klass=obj.__class__||$B.get_class(obj);try{var _iter=$B.$call($B.$getattr(klass,"__iter__"))}catch(err){if(err.__class__===_b_.AttributeError){try{var gi_method=$B.$call($B.$getattr(klass,"__getitem__")),gi=function(i){return gi_method(obj,i)},len;return iterator_class.$factory(gi)}catch(err){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object is not iterable")}}throw err}var res=$B.$call(_iter)(obj);try{$B.$getattr(res,"__next__")}catch(err){if($B.$isinstance(err,_b_.AttributeError)){throw _b_.TypeError.$factory("iter() returned non-iterator of type '"+$B.class_name(res)+"'")}}return res}else{return callable_iterator.$factory(obj,sentinel)}};var iter=_b_.iter=function(){var $=$B.args("iter",1,{obj:null},["obj"],arguments,{},"args","kw"),sentinel;if($.args.length>0){sentinel=$.args[0]}return $B.$iter($.obj,sentinel)};var len=_b_.len=function(obj){check_nb_args_no_kw("len",1,arguments);var klass=obj.__class__||$B.get_class(obj);try{var method=$B.$getattr(klass,"__len__")}catch(err){throw _b_.TypeError.$factory("object of type '"+$B.class_name(obj)+"' has no len()")}let res=$B.$call(method)(obj);if(!$B.$isinstance(res,_b_.int)){throw _b_.TypeError.$factory(`'${$B.class_name(res)}' object cannot be interpreted as an integer`)}if(!$B.rich_comp("__ge__",res,0)){throw _b_.ValueError.$factory("ValueError: __len__() should return >= 0")}return res};_b_.locals=function(){check_nb_args("locals",0,arguments);var locals_obj=$B.frame_obj.frame[1];var class_locals=locals_obj.$target;if(class_locals){return class_locals}var res=$B.obj_dict($B.clone(locals_obj),(function(key){return key.startsWith("$")}));res.$is_namespace=true;return res};var map=_b_.map=$B.make_class("map",(function(){var $=$B.args("map",2,{func:null,it1:null},["func","it1"],arguments,{},"args",null),func=$B.$call($.func);var iter_args=[$B.make_js_iterator($.it1)];for(var arg of $.args){iter_args.push($B.make_js_iterator(arg))}return{__class__:map,args:iter_args,func:func}}));map.__iter__=function(self){return self};map.__next__=function(self){var args=[];for(var iter of self.args){var arg=iter.next();if(arg.done){throw _b_.StopIteration.$factory("")}args.push(arg.value)}return self.func.apply(null,args)};$B.set_func_names(map,"builtins");function $extreme(args,op){var $op_name="min";if(op==="__gt__"){$op_name="max"}var $=$B.args($op_name,0,{},[],args,{},"args","kw");var has_default=false,func=false;for(var item of _b_.dict.$iter_items($.kw)){switch(item.key){case"key":func=item.value;func=func===_b_.None?func:$B.$call(func);break;case"default":var default_value=item.value;has_default=true;break;default:throw _b_.TypeError.$factory("'"+item.key+"' is an invalid keyword argument for this function")}}if(!func||func===_b_.None){func=x=>x}if($.args.length==0){throw _b_.TypeError.$factory($op_name+" expected 1 arguments, got 0")}else if($.args.length==1){var $iter=$B.make_js_iterator($.args[0]),res=null,x_value,extr_value;for(var x of $iter){if(res===null){extr_value=func(x);res=x}else{x_value=func(x);if($B.rich_comp(op,x_value,extr_value)){res=x;extr_value=x_value}}}if(res===null){if(has_default){return default_value}else{throw _b_.ValueError.$factory($op_name+"() arg is an empty sequence")}}else{return res}}else{if(has_default){throw _b_.TypeError.$factory("Cannot specify a default for "+$op_name+"() with multiple positional arguments")}var _args;if($B.last(args).$kw){_args=[$.args].concat($B.last(args))}else{_args=[$.args]}return $extreme.call(null,_args,op)}}_b_.max=function(){return $extreme(arguments,"__gt__")};var memoryview=_b_.memoryview=$B.make_class("memoryview",(function(obj){check_nb_args_no_kw("memoryview",1,arguments);if(obj.__class__===memoryview){return obj}if($B.get_class(obj).$buffer_protocol){return{__class__:memoryview,obj:obj,format:"B",itemsize:1,ndim:1,shape:_b_.tuple.$factory([_b_.len(obj)]),strides:_b_.tuple.$factory([1]),suboffsets:_b_.tuple.$factory([]),c_contiguous:true,f_contiguous:true,contiguous:true}}else{throw _b_.TypeError.$factory("memoryview: a bytes-like object "+"is required, not '"+$B.class_name(obj)+"'")}}));memoryview.$match_sequence_pattern=true,memoryview.$buffer_protocol=true;memoryview.$not_basetype=true;memoryview.__eq__=function(self,other){if(other.__class__!==memoryview){return false}return $B.$getattr(self.obj,"__eq__")(other.obj)};memoryview.__getitem__=function(self,key){var res;if($B.$isinstance(key,_b_.int)){var start=key*self.itemsize;if(self.format=="I"){res=self.obj.source[start];var coef=256;for(var i=1;i<4;i++){res+=self.obj.source[start+i]*coef;coef*=256}return res}else if("B".indexOf(self.format)>-1){if(key>self.obj.source.length-1){throw _b_.KeyError.$factory(key)}return self.obj.source[key]}else{return self.obj.source[key]}}res=self.obj.__class__.__getitem__(self.obj,key);if(key.__class__===_b_.slice){return memoryview.$factory(res)}};memoryview.__len__=function(self){return len(self.obj)/self.itemsize};memoryview.__setitem__=function(self,key,value){try{$B.$setitem(self.obj,key,value)}catch(err){throw _b_.TypeError.$factory("cannot modify read-only memory")}};memoryview.cast=function(self,format){switch(format){case"B":return memoryview.$factory(self.obj);case"I":var res=memoryview.$factory(self.obj),objlen=len(self.obj);res.itemsize=4;res.format="I";if(objlen%4!=0){throw _b_.TypeError.$factory("memoryview: length is not "+"a multiple of itemsize")}return res}};memoryview.hex=function(self){var res="",bytes=_b_.bytes.$factory(self);bytes.source.forEach((function(item){res+=item.toString(16)}));return res};memoryview.tobytes=function(self){return{__class__:_b_.bytes,source:self.obj.source}};memoryview.tolist=function(self){if(self.itemsize==1){return _b_.list.$factory(_b_.bytes.$factory(self.obj))}else if(self.itemsize==4){if(self.format=="I"){var res=[];for(var i=0;i=65536&&code<=131071||code>=131072&&code<=196607||code>=196608&&code<=262143||code>=851968&&code<=917503||code>=917504&&code<=1048575){return code}}throw _b_.TypeError.$factory("ord() expected a character, but "+"string of length "+c.length+" found")}switch($B.get_class(c)){case _b_.str:if(c.length==1){return c.charCodeAt(0)}throw _b_.TypeError.$factory("ord() expected a character, but "+"string of length "+c.length+" found");case _b_.bytes:case _b_.bytearray:if(c.source.length==1){return c.source[0]}throw _b_.TypeError.$factory("ord() expected a character, but "+"string of length "+c.source.length+" found");default:throw _b_.TypeError.$factory("ord() expected a character, but "+$B.class_name(c)+" was found")}};var complex_modulo=()=>_b_.ValueError.$factory("complex modulo");var all_ints=()=>_b_.TypeError.$factory("pow() 3rd argument not "+"allowed unless all arguments are integers");_b_.pow=function(){var $=$B.args("pow",3,{x:null,y:null,mod:null},["x","y","mod"],arguments,{mod:None},null,null),x=$.x,y=$.y,z=$.mod;if(z===_b_.None){return $B.rich_op("__pow__",x,y)}else{if($B.$isinstance(x,_b_.int)){if($B.$isinstance(y,_b_.float)){throw all_ints()}else if($B.$isinstance(y,_b_.complex)){throw complex_modulo()}else if($B.$isinstance(y,_b_.int)){if($B.$isinstance(z,_b_.complex)){throw complex_modulo()}else if(!$B.$isinstance(z,_b_.int)){throw all_ints()}}return _b_.int.__pow__(x,y,z)}else if($B.$isinstance(x,_b_.float)){throw all_ints()}else if($B.$isinstance(x,_b_.complex)){throw complex_modulo()}}};var $print=_b_.print=function(){var $ns=$B.args("print",0,{},[],arguments,{},"args","kw");var kw=$ns["kw"],end=_b_.dict.get(kw,"end","\n"),sep=_b_.dict.get(kw,"sep"," "),file=_b_.dict.get(kw,"file",$B.get_stdout());var args=$ns["args"],writer=$B.$getattr(file,"write");for(var i=0,len=args.length;i-1){has_slot=true;break}}}if(!has_slot){throw $B.attr_error(attr,klass)}}}if($test){console.log("attr",attr,"use _setattr",_setattr)}if(!_setattr){if(obj[attr]!==undefined){obj[attr]=value}else if(obj.__dict__===undefined){throw _b_.AttributeError.$factory(`'${$B.class_name(obj)}' `+`object has no attribute '${attr}' and no __dict__ for `+`setting new attributes`)}else{_b_.dict.$setitem(obj.__dict__,attr,value)}if($test){console.log("no setattr, obj",obj)}}else{if($test){console.log("apply _setattr",obj,attr)}_setattr(obj,attr,value)}return None};_b_.sorted=function(){var $=$B.args("sorted",1,{iterable:null},["iterable"],arguments,{},null,"kw");var _list=_b_.list.$factory($.iterable),args=[_list].concat(Array.from(arguments).slice(1));_b_.list.sort.apply(null,args);return _list};_b_.sum=function(){var $=$B.args("sum",2,{iterable:null,start:null},["iterable","start"],arguments,{start:0},null,null),iterable=$.iterable,start=$.start;if($B.$isinstance(start,[_b_.str,_b_.bytes])){throw _b_.TypeError.$factory("sum() can't sum bytes"+" [use b''.join(seq) instead]")}var res=start;iterable=iter(iterable);while(true){try{var _item=next(iterable);res=$B.rich_op("__add__",res,_item)}catch(err){if(err.__class__===_b_.StopIteration){break}else{throw err}}}return res};$B.missing_super2=function(obj){obj.$missing=true;return obj};var $$super=_b_.super=$B.make_class("super",(function(_type,object_or_type){var no_object_or_type=object_or_type===undefined;if(_type===undefined&&object_or_type===undefined){var frame=$B.frame_obj.frame,pyframe=$B.imported["_sys"]._getframe(),code=$B.frame.f_code.__get__(pyframe),co_varnames=code.co_varnames;if(co_varnames.length>0){_type=frame[1].__class__;if(_type===undefined){throw _b_.RuntimeError.$factory("super(): no arguments")}object_or_type=frame[1][code.co_varnames[0]]}else{throw _b_.RuntimeError.$factory("super(): no arguments")}}if(!no_object_or_type&&Array.isArray(object_or_type)){object_or_type=object_or_type[0]}var $arg2;if(object_or_type!==undefined){if(object_or_type===_type||object_or_type.$is_class&&_b_.issubclass(object_or_type,_type)){$arg2="type"}else if($B.$isinstance(object_or_type,_type)){$arg2="object"}else{throw _b_.TypeError.$factory("super(type, obj): obj must be an instance "+"or subtype of type")}}return{__class__:$$super,__thisclass__:_type,__self_class__:object_or_type,$arg2:$arg2}}));$$super.__get__=function(self,instance){return $$super.$factory(self.__thisclass__,instance)};$$super.__getattribute__=function(self,attr){if(self.__thisclass__.$is_js_class){if(attr=="__init__"){return function(){mro[0].$js_func.call(self.__self_class__,...arguments)}}}var object_or_type=self.__self_class__,mro=self.$arg2=="type"?object_or_type.__mro__:$B.get_class(object_or_type).__mro__;var search_start=mro.indexOf(self.__thisclass__)+1,search_classes=mro.slice(search_start);var $test=attr=="new";if($test){console.log("super.__ga__, self",self,"search classes",search_classes)}var f;for(var klass of search_classes){if(klass===undefined){console.log("klass undef in super",self);console.log("mro",mro)}if(klass[attr]!==undefined){f=klass[attr];break}}if(f===undefined){if($$super[attr]!==undefined){return function(x){return function(){var args=[x];for(var i=0,len=arguments.length;i";if(self.__self_class__!==undefined){res+=", <"+self.__self_class__.__class__.__name__+" object>"}else{res+=", NULL"}return res+">"};$B.set_func_names($$super,"builtins");_b_.vars=function(){var def={},$=$B.args("vars",1,{obj:null},["obj"],arguments,{obj:def},null,null);if($.obj===def){return _b_.locals()}else{try{return $B.$getattr($.obj,"__dict__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("vars() argument must have __dict__ attribute")}throw err}}};var $Reader=$B.make_class("Reader");$Reader.__bool__=function(){return true};$Reader.__enter__=function(self){return self};$Reader.__exit__=function(self){$Reader.close(self)};$Reader.__init__=function(_self,initial_value=""){_self.$content=initial_value;_self.$counter=0};$Reader.__iter__=function(self){return iter($Reader.readlines(self))};$Reader.__len__=function(self){return self.lines.length};$Reader.__new__=function(cls){return{__class__:cls}};$Reader.close=function(self){self.closed=true};$Reader.flush=function(){return None};$Reader.read=function(){var $=$B.args("read",2,{self:null,size:null},["self","size"],arguments,{size:-1},null,null),self=$.self,size=$B.$GetInt($.size);if(self.closed===true){throw _b_.ValueError.$factory("I/O operation on closed file")}var len=_b_.len(self.$content);if(size<0){size=len-self.$counter}var res;if(self.$binary){res=_b_.bytes.$factory(self.$content.source.slice(self.$counter,self.$counter+size))}else{res=self.$content.substr(self.$counter,size)}self.$counter+=size;return res};$Reader.readable=function(){return true};function make_lines(self){if(self.$lines===undefined){if(!self.$binary){self.$lines=self.$content.split("\n");if($B.last(self.$lines)==""){self.$lines.pop()}self.$lines=self.$lines.map((x=>x+"\n"))}else{var lines=[],pos=0,source=self.$content.source,len=source.length;while(pos-1){rest=rest.slice(0,size)}self.$counter=self.$content.source.length;return _b_.bytes.$factory(rest)}else{var line_source=self.$content.source.slice(self.$counter,ix+1);if(size>-1){line_source=line_source.slice(0,size)}result={__class__:_b_.bytes,source:line_source};self.$counter=ix+1;return result}}else{if(self.$counter==self.$content.length){return""}ix=self.$content.indexOf("\n",self.$counter);if(ix==-1){rest=self.$content.substr(self.$counter);if(size>-1){rest=rest.substr(0,size)}self.$counter=self.$content.length;return rest}else{result=self.$content.substring(self.$counter,ix+1);if(size>-1){result=result.substr(0,size)}self.$counter=ix+1;self.$lc+=1;return result}}};$Reader.readlines=function(){var $=$B.args("readlines",2,{self:null,hint:null},["self","hint"],arguments,{hint:-1},null,null),self=$.self,hint=$B.$GetInt($.hint);var nb_read=0;if(self.closed===true){throw _b_.ValueError.$factory("I/O operation on closed file")}self.$lc=self.$lc===undefined?-1:self.$lc;make_lines(self);var lines;if(hint<0){lines=self.$lines.slice(self.$lc+1)}else{lines=[];while(self.$lc-1;if(mode.search("w")>-1){result={$binary:is_binary,$content:is_binary?_b_.bytes.$factory():"",$encoding:encoding,closed:False,mode:mode,name:file};result.__class__=is_binary?$BufferedReader:$TextIOWrapper;$B.file_cache[file]=result.$content;return result}else if(["r","rb"].indexOf(mode)==-1){throw _b_.ValueError.$factory("Invalid mode '"+mode+"'")}if($B.$isinstance(file,_b_.str)){if($B.file_cache.hasOwnProperty($.file)){var f=$B.file_cache[$.file];result.content=f;if(is_binary&&typeof f=="string"){result.content=_b_.str.encode(f,"utf-8")}else if(f.__class__===_b_.bytes&&!is_binary){result.content=_b_.bytes.decode(f,encoding)}}else if($B.files&&$B.files.hasOwnProperty($.file)){var $res=atob($B.files[$.file].content);var source=[];for(const char of $res){source.push(char.charCodeAt(0))}result.content=_b_.bytes.$factory(source);if(!is_binary){try{result.content=_b_.bytes.decode(result.content,encoding)}catch(error){result.error=error}}}else if($B.protocol!="file"){var req=new XMLHttpRequest;req.overrideMimeType("text/plain;charset=x-user-defined");req.onreadystatechange=function(){if(this.readyState!=4){return}var status=this.status;if(status==404){result.error=_b_.FileNotFoundError.$factory(file)}else if(status!=200){result.error=_b_.IOError.$factory("Could not open file "+file+" : status "+status)}else{var bytes=[];for(var codePoint of this.response){var cp=codePoint.codePointAt(0);if(cp>63232){cp-=63232}bytes[bytes.length]=cp}result.content=_b_.bytes.$factory(bytes);if(!is_binary){try{result.content=_b_.bytes.decode(result.content,encoding)}catch(error){result.error=error}}}};var cache=$B.get_option("cache"),fake_qs=cache?"":"?foo="+(new Date).getTime();req.open("GET",encodeURI(file+fake_qs),false);req.send()}else{throw _b_.FileNotFoundError.$factory("cannot use 'open()' with protocol 'file'")}if(result.error!==undefined){throw result.error}var res={$binary:is_binary,$content:result.content,$counter:0,$encoding:encoding,$length:is_binary?result.content.source.length:result.content.length,closed:False,mode:mode,name:file};res.__class__=is_binary?$BufferedReader:$TextIOWrapper;return res}else{throw _b_.TypeError.$factory("invalid argument for open(): "+_b_.str.$factory(file))}};var zip=_b_.zip=$B.make_class("zip",(function(){var res={__class__:zip,items:[]};if(arguments.length==0){return res}var $ns=$B.args("zip",0,{},[],arguments,{},"args","kw");var _args=$ns["args"],strict=$B.$bool(_b_.dict.get($ns.kw,"strict",false));var iters=[];for(var arg of _args){iters.push($B.make_js_iterator(arg))}return{__class__:zip,iters:iters,strict:strict}}));zip.__iter__=function(self){return self};zip.__next__=function(self){var res=[],len=self.iters.length;for(var i=0;i0){throw _b_.ValueError.$factory(`zip() argument ${i+1} is longer than argument ${i}`)}else{for(var j=1;j!x.startsWith("$"))))};$B.function.__get__=function(self,obj){if(obj===_b_.None){return self}return $B.method.$factory(self,obj)};$B.function.__getattribute__=function(self,attr){if(self.$infos&&self.$infos[attr]!==undefined){if(attr=="__code__"){var res={__class__:code};for(var _attr in self.$infos.__code__){res[_attr]=self.$infos.__code__[_attr]}res.name=self.$infos.__name__;res.filename=self.$infos.__code__.co_filename;res.co_code=self+"";return res}else if(attr=="__annotations__"){return $B.obj_dict(self.$infos[attr])}else if(self.$infos.hasOwnProperty(attr)){return self.$infos[attr]}}else if(self.$infos&&self.$infos.__dict__&&_b_.dict.$contains_string(self.$infos.__dict__,attr)){return _b_.dict.$getitem_string(self.$infos.__dict__,attr)}else if(attr=="__closure__"){var free_vars=self.$infos.__code__.co_freevars;if(free_vars.length==0){return None}var cells=[];for(var i=0;i"}else{return""}};$B.function.__mro__=[_b_.object];$B.make_function_infos=function(f,__module__,__defaults__,__kwdefaults__,__doc__,arg_names,vararg,kwarg,co_argcount,co_filename,co_firstlineno,co_flags,co_freevars,co_kwonlyargcount,co_name,co_posonlyargcount,co_qualname,co_varnames){f.$is_func=true;f.$args_parser=$B.make_args_parser_and_parse;if(co_flags&$B.COMPILER_FLAGS.COROUTINE){f.$is_async=true}f.$infos={__module__:__module__,__defaults__:__defaults__,__kwdefaults__:__kwdefaults__,__doc__:__doc__,arg_names:arg_names,vararg:vararg,kwarg:kwarg};f.$infos.__name__=co_name;f.$infos.__qualname__=co_qualname;co_freevars.__class__=_b_.tuple;co_varnames.__class__=_b_.tuple;f.$infos.__code__={co_argcount:co_argcount,co_filename:co_filename,co_firstlineno:co_firstlineno,co_flags:co_flags,co_freevars:co_freevars,co_kwonlyargcount:co_kwonlyargcount,co_name:co_name,co_nlocals:co_varnames.length,co_posonlyargcount:co_posonlyargcount,co_qualname:co_qualname,co_varnames:co_varnames,co_positions:{}}};$B.make_args_parser=function(f){if(f.$infos===undefined||f.$infos.__code__===undefined){throw _b_.AttributeError.$factory(`cannot set defauts to ${_b_.str.$factory(f)}`)}const varnames=f.$infos.__code__.co_varnames,value=f.$infos.__defaults__,offset=f.$infos.__code__.co_argcount-value.length,$kwdefaults=new Map;var nb_kw_defaults=f.$infos.__kwdefaults__===_b_.None?0:_b_.dict.__len__(f.$infos.__kwdefaults__);if(f.$infos.__kwdefaults__!==_b_.None){const kwdef=f.$infos.__kwdefaults__;for(let kw of $B.make_js_iterator(kwdef)){$kwdefaults.set(kw,$B.$getitem(kwdef,kw))}}f.$kwdefaults=$kwdefaults;f.$kwdefaults_values=[...$kwdefaults.values()];f.$hasParams=new Set;var nb_args=f.$infos.__code__.co_argcount+f.$infos.__code__.co_kwonlyargcount+(f.$infos.kwargs?1:0);for(let i=0;i0){named_defaults=PARAMS_NAMED_DEFAULTS_COUNT>=PARAMS_NAMED_COUNT?DEFAULTS.ALL:DEFAULTS.SOME}const PARAMS_POSONLY_COUNT=$CODE.co_posonlyargcount;const PARAMS_POS_COUNT=$CODE.co_argcount-PARAMS_POSONLY_COUNT;let pos_defaults=DEFAULTS.NONE;if(PARAMS_POS_COUNT!==0&&value.length>0){pos_defaults=value.length>=PARAMS_POS_COUNT?DEFAULTS.ALL:DEFAULTS.SOME}let posonly_defaults=DEFAULTS.NONE;if(value.length>PARAMS_POS_COUNT){posonly_defaults=value.length>=$CODE.co_argcount?DEFAULTS.ALL:DEFAULTS.SOME}f.$args_parser=f.$infos.args_parser=$B.getArgs0(PARAMS_POSONLY_COUNT!==0,posonly_defaults,PARAMS_POS_COUNT!==0,pos_defaults,$INFOS.vararg!==null,PARAMS_NAMED_COUNT!==0,named_defaults,$INFOS.kwarg!==null);return f.$args_parser};$B.function.__setattr__=function(self,attr,value){if(attr=="__closure__"){throw _b_.AttributeError.$factory("readonly attribute")}else if(attr=="__defaults__"){if(value===_b_.None){value=[]}else if(!$B.$isinstance(value,_b_.tuple)){throw _b_.TypeError.$factory("__defaults__ must be set to a tuple object")}if(self.$infos){self.$infos.__defaults__=value;$B.make_args_parser(self)}else{throw _b_.AttributeError.$factory("cannot set attribute "+attr+" of "+_b_.str.$factory(self))}}else if(attr=="__kwdefaults__"){if(value===_b_.None){value=$B.empty_dict}else if(!$B.$isinstance(value,_b_.dict)){throw _b_.TypeError.$factory("__kwdefaults__ must be set to a dict object")}if(self.$infos){self.$infos.__kwdefaults__=value;$B.make_args_parser(self)}else{throw _b_.AttributeError.$factory("cannot set attribute "+attr+" of "+_b_.str.$factory(self))}}if(self.$infos[attr]!==undefined){self.$infos[attr]=value}else{self.$attrs=self.$attrs||{};self.$attrs[attr]=value}};$B.function.$factory=function(){};$B.set_func_names($B.function,"builtins");_b_.__BRYTHON__=__BRYTHON__;$B.builtin_funcs=["__build_class__","abs","aiter","all","anext","any","ascii","bin","breakpoint","callable","chr","compile","delattr","dir","divmod","eval","exec","exit","format","getattr","globals","hasattr","hash","help","hex","id","input","isinstance","issubclass","iter","len","locals","max","min","next","oct","open","ord","pow","print","quit","repr","round","setattr","sorted","sum","vars"];var builtin_function=$B.builtin_function_or_method=$B.make_class("builtin_function_or_method",(function(f){f.__class__=builtin_function;return f}));builtin_function.__getattribute__=$B.function.__getattribute__;builtin_function.__reduce_ex__=builtin_function.__reduce__=function(self){return self.$infos.__name__};builtin_function.__repr__=builtin_function.__str__=function(self){return""};$B.set_func_names(builtin_function,"builtins");var method_wrapper=$B.make_class("method_wrapper");method_wrapper.__repr__=method_wrapper.__str__=function(self){return""};$B.set_func_names(method_wrapper,"builtins");$B.builtin_classes=["bool","bytearray","bytes","classmethod","complex","dict","enumerate","filter","float","frozenset","int","list","map","memoryview","object","property","range","reversed","set","slice","staticmethod","str","super","tuple","type","zip"];var other_builtins=["Ellipsis","False","None","True","__debug__","__import__","copyright","credits","license","NotImplemented"];var builtin_names=$B.builtin_funcs.concat($B.builtin_classes).concat(other_builtins);for(var name of builtin_names){try{if($B.builtin_funcs.indexOf(name)>-1){_b_[name].__class__=builtin_function;_b_[name].$infos={__module__:"builtins",__name__:name,__qualname__:name}}}catch(err){}}_b_.object.__init__.__class__=$B.wrapper_descriptor;_b_.object.__new__.__class__=builtin_function})(__BRYTHON__);(function($B){var _b_=$B.builtins;var DEFAULT_MIN_MERGE=32;var DEFAULT_MIN_GALLOPING=7;var DEFAULT_TMP_STORAGE_LENGTH=256;var POWERS_OF_TEN=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9];function log10(x){if(x<1e5){if(x<100){return x<10?0:1}if(x<1e4){return x<1e3?2:3}return 4}if(x<1e7){return x<1e6?5:6}if(x<1e9){return x<1e8?7:8}return 9}function alphabeticalCompare(a,b){if(a===b){return 0}if(~~a===a&&~~b===b){if(a===0||b===0){return a=0){return-1}if(a>=0){return 1}a=-a;b=-b}var al=log10(a),bl=log10(b);var t=0;if(albl){b*=POWERS_OF_TEN[al-bl-1];a/=10;t=1}if(a===b){return t}return a=DEFAULT_MIN_MERGE){r|=n&1;n>>=1}return n+r}function makeAscendingRun(array,lo,hi,compare){var runHi=lo+1;if(runHi===hi){return 1}if(compare(array[runHi++],array[lo])<0){while(runHi=0){runHi++}}return runHi-lo}function reverseRun(array,lo,hi){hi--;while(lo>>1;if(compare(pivot,array[mid])<0){right=mid}else{left=mid+1}}var n=start-left;switch(n){case 3:array[left+3]=array[left+2];case 2:array[left+2]=array[left+1];case 1:array[left+1]=array[left];break;default:while(n>0){array[left+n]=array[left+n-1];n--}}array[left]=pivot}}function gallopLeft(value,array,start,length,hint,compare){var lastOffset=0,maxOffset=0,offset=1;if(compare(value,array[start+hint])>0){maxOffset=length-hint;while(offset0){lastOffset=offset;offset=(offset<<1)+1;if(offset<=0){offset=maxOffset}}if(offset>maxOffset){offset=maxOffset}lastOffset+=hint;offset+=hint}else{maxOffset=hint+1;while(offsetmaxOffset){offset=maxOffset}var tmp=lastOffset;lastOffset=hint-offset;offset=hint-tmp}lastOffset++;while(lastOffset>>1);if(compare(value,array[start+m])>0){lastOffset=m+1}else{offset=m}}return offset}function gallopRight(value,array,start,length,hint,compare){var lastOffset=0,maxOffset=0,offset=1;if(compare(value,array[start+hint])<0){maxOffset=hint+1;while(offsetmaxOffset){offset=maxOffset}var tmp=lastOffset;lastOffset=hint-offset;offset=hint-tmp}else{maxOffset=length-hint;while(offset=0){lastOffset=offset;offset=(offset<<1)+1;if(offset<=0){offset=maxOffset}}if(offset>maxOffset){offset=maxOffset}lastOffset+=hint;offset+=hint}lastOffset++;while(lastOffset>>1);if(compare(value,array[start+m])<0){offset=m}else{lastOffset=m+1}}return offset}var TIM_SORT_ASSERTION="TimSortAssertion";var TimSortAssertion=function(message){this.name=TIM_SORT_ASSERTION;this.message=message};var TimSort=function(array,compare){var self={array:array,compare:compare,minGallop:DEFAULT_MIN_GALLOPING,length:array.length,tmpStorageLength:DEFAULT_TMP_STORAGE_LENGTH,stackLength:0,runStart:null,runLength:null,stackSize:0,pushRun:function(runStart,runLength){this.runStart[this.stackSize]=runStart;this.runLength[this.stackSize]=runLength;this.stackSize+=1},mergeRuns:function(){while(this.stackSize>1){var n=this.stackSize-2;if(n>=1&&this.runLength[n-1]<=this.runLength[n]+this.runLength[n+1]||n>=2&&this.runLength[n-2]<=this.runLength[n]+this.runLength[n-1]){if(this.runLength[n-1]this.runLength[n+1]){break}this.mergeAt(n)}},forceMergeRuns:function(){while(this.stackSize>1){var n=this.stackSize-2;if(n>0&&this.runLength[n-1]=DEFAULT_MIN_GALLOPING||count2>=DEFAULT_MIN_GALLOPING);if(exit){break}if(minGallop<0){minGallop=0}minGallop+=2}this.minGallop=minGallop;if(minGallop<1){this.minGallop=1}if(length1===1){for(let i=0;i=0;i--){array[customDest+i]=array[customCursor+i]}array[dest]=tmp[cursor2];return}var minGallop=this.minGallop;while(true){let count1=0,count2=0,exit=false;do{if(compare(tmp[cursor2],array[cursor1])<0){array[dest--]=array[cursor1--];count1++;count2=0;if(--length1===0){exit=true;break}}else{array[dest--]=tmp[cursor2--];count2++;count1=0;if(--length2===1){exit=true;break}}}while((count1|count2)=0;i--){array[customDest+i]=array[customCursor+i]}if(length1===0){exit=true;break}}array[dest--]=tmp[cursor2--];if(--length2===1){exit=true;break}count2=length2-gallopLeft(array[cursor1],tmp,0,length2,length2-1,compare);if(count2!==0){dest-=count2;cursor2-=count2;length2-=count2;customDest=dest+1;customCursor=cursor2+1;for(let i=0;i=DEFAULT_MIN_GALLOPING||count2>=DEFAULT_MIN_GALLOPING);if(exit){break}if(minGallop<0){minGallop=0}minGallop+=2}this.minGallop=minGallop;if(minGallop<1){this.minGallop=1}if(length2===1){dest-=length1;cursor1-=length1;customDest=dest+1;customCursor=cursor1+1;for(let i=length1-1;i>=0;i--){array[customDest+i]=array[customCursor+i]}array[dest]=tmp[cursor2]}else if(length2==0){throw new TimSortAssertion("mergeHigh preconditions were not respected")}else{customCursor=dest-(length2-1);for(let i=0;i>>1}self.tmp=new Array(self.tmpStorageLength);self.stackLength=self.length<120?5:self.length<1542?10:self.length<119151?19:40;self.runStart=new Array(self.stackLength);self.runLength=new Array(self.stackLength);return self};function tim_sort(array,compare,lo,hi){if(!Array.isArray(array)){throw _b_.TypeError.$factory("Can only sort arrays")}if(!compare){compare=alphabeticalCompare}else if(typeof compare!=="function"){hi=lo;lo=compare;compare=alphabeticalCompare}if(!lo){lo=0}if(!hi){hi=array.length}var remaining=hi-lo;if(remaining<2){return}var runLength=0;if(remainingminRun){force=minRun}binaryInsertionSort(array,lo,lo+force,lo+runLength,compare);runLength=force}ts.pushRun(lo,runLength);ts.mergeRuns();remaining-=runLength;lo+=runLength}while(remaining!==0);ts.forceMergeRuns()}function tim_sort_safe(array,compare){try{tim_sort(array,compare,0,array.length)}catch(e){if(e.name==TIM_SORT_ASSERTION){array.sort(compare)}else{throw e}}}$B.$TimSort=tim_sort_safe;$B.$AlphabeticalCompare=alphabeticalCompare})(__BRYTHON__);(function($B){var _b_=$B.builtins;$B.del_exc=function(frame){delete frame[1].$current_exception};$B.set_exc=function(exc,frame){if(frame===undefined){var msg="Internal error: no frame for exception "+_b_.repr(exc);console.error(["Traceback (most recent call last):",$B.print_stack(exc.$frame_obj),msg].join("\n"));if($B.get_option("debug",exc)>1){console.log(exc.args);console.log(exc.stack)}throw Error(msg)}else{frame[1].$current_exception=$B.exception(exc)}};$B.set_exc_and_trace=function(frame,exc){$B.set_exc(exc,frame);if(!exc.$in_trace_func&&frame.$f_trace!==_b_.None){frame.$f_trace=$B.trace_exception()}};$B.set_exc_and_leave=function(frame,exc){$B.set_exc_and_trace(frame,exc);$B.leave_frame()};$B.get_exc=function(){var frame=$B.frame_obj.frame;return frame[1].$current_exception};$B.set_exception_offsets=function(exc,position){exc.$positions=exc.$positions||{};exc.$positions[$B.frame_obj.count-1]=position;return exc};$B.$raise=function(arg,cause){var active_exc=$B.get_exc();if(arg===undefined){if(active_exc!==undefined){throw active_exc}throw _b_.RuntimeError.$factory("No active exception to reraise")}else{if($B.$isinstance(arg,_b_.BaseException)){if(arg.__class__===_b_.StopIteration&&$B.frame_obj.frame.$is_generator){arg=_b_.RuntimeError.$factory("generator raised StopIteration")}arg.__context__=active_exc===undefined?_b_.None:active_exc;arg.__cause__=cause||_b_.None;arg.__suppress_context__=cause!==undefined;throw arg}else if(arg.$is_class&&_b_.issubclass(arg,_b_.BaseException)){if(arg===_b_.StopIteration){if($B.frame_obj.frame[1].$is_generator){throw _b_.RuntimeError.$factory("generator raised StopIteration")}}var exc=$B.$call(arg)();exc.__context__=active_exc===undefined?_b_.None:active_exc;exc.__cause__=cause||_b_.None;exc.__suppress_context__=cause!==undefined;throw exc}else{throw _b_.TypeError.$factory("exceptions must derive from BaseException")}}};$B.print_stack=function(frame_obj){var stack=make_frames_stack(frame_obj||$B.frame_obj);var trace=[];for(var frame of stack){var lineno=frame.$lineno,filename=frame.__file__;if(lineno!==undefined){var local=frame[0]==frame[2]?"":frame[0];trace.push(` File "${filename}" line ${lineno}, in ${local}`);var src=$B.file_cache[filename];if(src){var lines=src.split("\n"),line=lines[lineno-1];trace.push(" "+line.trim())}}}return trace.join("\n")};$B.last_frame=function(){var frame=$B.frame_obj.frame;return`file ${frame.__file__} line ${frame.$lineno}`};$B.count_frames=function(frame_obj){frame_obj=frame_obj||$B.frame_obj;return frame_obj==null?0:frame_obj.count};$B.get_frame_at=function(pos,frame_obj){frame_obj=frame_obj||$B.frame_obj;var nb=frame_obj.count-pos-1;for(var i=0;i"};frame.f_builtins={__get__:function(_self){return $B.$getattr(_self[3].__builtins__,"__dict__")}};frame.f_code={__get__:function(_self){var res;if(_self[4]){res=_self[4].$infos.__code__}else if(_self.f_code){res=_self.f_code}else{res={co_name:_self[0]==_self[2]?"":_self[0],co_filename:_self.__file__,co_varnames:$B.fast_tuple([])};res.co_qualname=res.co_name}res.__class__=_b_.code;return res}};frame.f_globals={__get__:function(_self){if(_self.f_globals){return _self.f_globals}else if(_self.f_locals&&_self[1]==_self[3]){return _self.f_globals=_self.f_locals}else{return _self.f_globals=$B.obj_dict(_self[3])}}};frame.f_lineno={__get__:function(_self){return _self.$lineno}};frame.f_locals={__get__:function(_self){if(_self.f_locals){return _self.f_locals}else if(_self.f_globals&&_self[1]==_self[3]){return _self.f_locals=_self.f_globals}else{return _self.f_locals=$B.obj_dict(_self[1])}}};frame.f_trace={__get__:function(_self){return _self.$f_trace}};$B.set_func_names(frame,"builtins");$B._frame=frame;$B.deep_copy=function(stack){var res=[];for(const s of stack){var item=[s[0],{},s[2],{}];if(s[4]!==undefined){item.push(s[4])}for(const i of[1,3]){for(var key in s[i]){item[i][key]=s[i][key]}}res.push(item)}return res};$B.restore_frame_obj=function(frame_obj,locals){$B.frame_obj=frame_obj;$B.frame_obj.frame[1]=locals};$B.make_linenums=function(frame_obj){var res=[];frame_obj=frame_obj||$B.frame_obj;while(frame_obj!==null){res.push(frame_obj.frame.$lineno);frame_obj=frame_obj.prev}return res.reverse()};var make_frames_stack=$B.make_frames_stack=function(frame_obj){var stack=[];while(frame_obj!==null){stack[stack.length]=frame_obj.frame;frame_obj=frame_obj.prev}stack.reverse();return stack};$B.freeze=function(err){if(err.$frame_obj===undefined){err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums()}err.__traceback__=traceback.$factory(err)};$B.exception=function(js_exc){var exc;if(!js_exc.__class__){if(js_exc.$py_exc){return js_exc.$py_exc}if($B.get_option("debug",exc)>1){console.log("Javascript error",js_exc)}var msg=js_exc.name+": "+js_exc.message;exc=_b_.JavascriptError.$factory(msg);exc.$js_exc=js_exc;if($B.is_recursion_error(js_exc)){msg="maximum recursion depth exceeded";exc=_b_.RecursionError.$factory(msg)}exc.__cause__=_b_.None;exc.__context__=_b_.None;exc.__suppress_context__=false;exc.args=_b_.tuple.$factory([msg]);exc.$py_error=true;js_exc.$py_exc=exc;$B.freeze(exc)}else{exc=js_exc;$B.freeze(exc)}return exc};$B.is_exc=function(exc,exc_list){if(exc.__class__===undefined){exc=$B.exception(exc)}var this_exc_class=exc.$is_class?exc:exc.__class__;for(var i=0;i1){res+=", "+_b_.repr($B.fast_tuple(self.args.slice(1)))}return res+")"};_b_.BaseException.__str__=function(self){if(self.args.length>0&&self.args[0]!==_b_.None){return _b_.str.$factory(self.args[0])}return""};_b_.BaseException.__new__=function(cls){var err=_b_.BaseException.$factory();err.__class__=cls;err.__dict__=$B.empty_dict();return err};_b_.BaseException.__getattr__=function(self,attr){if(attr=="__context__"){var frame=$B.frame_obj.frame,ctx=frame[1].$current_exception;return ctx||_b_.None}else{throw $B.attr_error(attr,self)}};_b_.BaseException.add_note=function(self,note){if(!$B.$isinstance(note,_b_.str)){throw _b_.TypeError.$factory("note must be a str, not "+`'${$B.class_name(note)}'`)}if(self.__notes__!==undefined){self.__notes__.push(note)}else{self.__notes__=$B.$list([note])}};_b_.BaseException.with_traceback=function(_self,tb){_self.__traceback__=tb;return _self};$B.set_func_names(_b_.BaseException,"builtins");make_builtin_exception(["SystemExit","KeyboardInterrupt","GeneratorExit","Exception"],_b_.BaseException);make_builtin_exception("JavascriptError",_b_.Exception);make_builtin_exception(["ArithmeticError","AssertionError","BufferError","EOFError","LookupError","MemoryError","OSError","ReferenceError","RuntimeError","SystemError","TypeError","ValueError","Warning"],_b_.Exception);make_builtin_exception("StopIteration",_b_.Exception,"value");make_builtin_exception("StopAsyncIteration",_b_.Exception,"value");make_builtin_exception("ImportError",_b_.Exception,"name");make_builtin_exception("SyntaxError",_b_.Exception,"msg");make_builtin_exception(["FloatingPointError","OverflowError","ZeroDivisionError"],_b_.ArithmeticError);make_builtin_exception("ModuleNotFoundError",_b_.ImportError,"name");make_builtin_exception(["IndexError","KeyError"],_b_.LookupError);make_builtin_exception(["BlockingIOError","ChildProcessError","ConnectionError","FileExistsError","FileNotFoundError","InterruptedError","IsADirectoryError","NotADirectoryError","PermissionError","ProcessLookupError","TimeoutError"],_b_.OSError);make_builtin_exception(["BrokenPipeError","ConnectionAbortedError","ConnectionRefusedError","ConnectionResetError"],_b_.ConnectionError);make_builtin_exception(["NotImplementedError","RecursionError","PythonFinalizationError"],_b_.RuntimeError);make_builtin_exception(["IndentationError","_IncompleteInputError"],_b_.SyntaxError,"msg");make_builtin_exception("TabError",_b_.IndentationError);make_builtin_exception("UnicodeError",_b_.ValueError);make_builtin_exception(["UnicodeDecodeError","UnicodeEncodeError","UnicodeTranslateError"],_b_.UnicodeError);make_builtin_exception(["DeprecationWarning","PendingDeprecationWarning","RuntimeWarning","SyntaxWarning","UserWarning","FutureWarning","ImportWarning","UnicodeWarning","BytesWarning","ResourceWarning","EncodingWarning"],_b_.Warning);make_builtin_exception(["EnvironmentError","IOError","VMSError","WindowsError"],_b_.OSError);_b_.AttributeError=$B.make_class("AttributeError",(function(){var $=$B.args("AttributeError",3,{msg:null,name:null,obj:null},["msg","name","obj"],arguments,{msg:_b_.None,name:_b_.None,obj:_b_.None},"*",null);var err=Error();err.__class__=_b_.AttributeError;err.__traceback__=_b_.None;err.$py_error=true;err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums();err.args=$B.fast_tuple($.msg===_b_.None?[]:[$.msg]);err.name=$.name;err.obj=$.obj;if(err.obj===undefined){console.log("pas de obj",$)}err.__cause__=_b_.None;err.__context__=_b_.None;err.__suppress_context__=false;return err}));_b_.AttributeError.__bases__=[_b_.Exception];_b_.AttributeError.__mro__=_b_.type.$mro(_b_.AttributeError);_b_.AttributeError.__str__=function(self){return self.args[0]};$B.set_func_names(_b_.AttributeError,"builtins");$B.attr_error=function(name,obj){var msg;if(obj.$is_class){msg=`type object '${obj.__name__}'`}else{msg=`'${$B.class_name(obj)}' object`}msg+=` has no attribute '${name}'`;return _b_.AttributeError.$factory({$kw:[{name:name,obj:obj,msg:msg}]})};_b_.NameError=$B.make_class("NameError",(function(){var $=$B.args("NameError",2,{message:null,name:null},["message","name"],arguments,{message:_b_.None,name:_b_.None},"*",null,1);var err=Error();err.__class__=_b_.NameError;err.__traceback__=_b_.None;err.$py_error=true;err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums();err.args=$B.fast_tuple($.message===_b_.None?[]:[$.message]);err.name=$.name;err.__cause__=_b_.None;err.__context__=_b_.None;err.__suppress_context__=false;return err}));_b_.NameError.__bases__=[_b_.Exception];_b_.NameError.__mro__=_b_.type.$mro(_b_.NameError).slice(1);_b_.NameError.__str__=function(self){return self.args[0]};$B.set_func_names(_b_.NameError,"builtins");make_builtin_exception("UnboundLocalError",_b_.NameError);_b_.UnboundLocalError.__str__=function(self){return self.args[0]};$B.set_func_names(_b_.UnboundLocalError,"builtins");$B.name_error=function(name){var exc=_b_.NameError.$factory(`name '${name}' is not defined`);exc.name=name;exc.$frame_obj=$B.frame_obj;return exc};$B.recursion_error=function(frame){var exc=_b_.RecursionError.$factory("maximum recursion depth exceeded");$B.set_exc(exc,frame);$B.freeze(exc);return exc};var MAX_CANDIDATE_ITEMS=750,MOVE_COST=2,CASE_COST=1,SIZE_MAX=65535;function LEAST_FIVE_BITS(n){return n&31}function levenshtein_distance(a,b,max_cost){if(a==b){return 0}if(a.lengthmax_cost){return max_cost+1}var buffer=[];for(var i=0;imax_cost){return max_cost+1}}return result}function substitution_cost(a,b){if(LEAST_FIVE_BITS(a)!=LEAST_FIVE_BITS(b)){return MOVE_COST}if(a==b){return 0}if(a.toLowerCase()==b.toLowerCase()){return CASE_COST}return MOVE_COST}function calculate_suggestions(dir,name){if(dir.length>=MAX_CANDIDATE_ITEMS){return null}var suggestion_distance=2**52,suggestion=null;for(var item of dir){var max_distance=(name.length+item.length+3)*MOVE_COST/6;max_distance=Math.min(max_distance,suggestion_distance-1);var current_distance=levenshtein_distance(name,item,max_distance);if(current_distance>max_distance){continue}if(!suggestion||current_distance!x.startsWith("$")));var suggestion=calculate_suggestions(locals,name);if(suggestion){return suggestion}if(frame[2]!=frame[0]){var globals=Object.keys(frame[3]).filter((x=>!x.startsWith("$")));suggestion=calculate_suggestions(globals,name);if(suggestion){return suggestion}}if(frame[4]&&frame[4].$is_method){var instance_name=frame[4].$infos.__code__.co_varnames[0],instance=frame[1][instance_name];if(_b_.hasattr(instance,name)){return`self.${name}`}}return _b_.None};$B.offer_suggestions_for_unexpected_keyword_error=function(arg_names,key){if(key===_b_.None){return _b_.None}var suggestions=calculate_suggestions(arg_names,key);return suggestions||_b_.None};_b_.BaseExceptionGroup=$B.make_class("BaseExceptionGFroup",(function(){var missing={},$=$B.args("BaseExceptionGroup",2,{message:null,exceptions:null},["message","exceptions"],arguments,{exceptions:missing},null,null);var err=Error();err.args=$B.fast_tuple(Array.from(arguments));err.__class__=_b_.BaseExceptionGroup;err.__traceback__=_b_.None;err.$py_error=true;err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums();err.message=$.message;err.exceptions=$.exceptions===missing?[]:$.exceptions;if(err.exceptions!==_b_.None){var exc_list=_b_.list.$factory(err.exceptions);var all_exceptions=true;for(var exc of exc_list){if(!$B.$isinstance(exc,_b_.Exception)){all_exceptions=false;break}}if(all_exceptions){err.__class__=_b_.ExceptionGroup}}err.__cause__=_b_.None;err.__context__=_b_.None;err.__suppress_context__=false;return err}));_b_.BaseExceptionGroup.__bases__=[_b_.BaseException];_b_.BaseExceptionGroup.__class_getitem__=$B.$class_getitem;_b_.BaseExceptionGroup.__mro__=_b_.type.$mro(_b_.BaseExceptionGroup);_b_.BaseExceptionGroup.__str__=function(self){return`${self.message} (${self.exceptions.length} sub-exception`+`${self.exceptions.length>1?"s":""})`};_b_.BaseExceptionGroup.split=function(self,condition){var matching_excs=[],non_matching_excs=[];for(var exc of self.exceptions){if($B.$isinstance(exc,_b_.BaseExceptionGroup)){var subsplit=_b_.BaseExceptionGroup.split(exc,condition),matching=subsplit[0],non_matching=subsplit[1];if(matching===_b_.None){non_matching_excs.push(exc)}else if(matching.exceptions.length==exc.exceptions.length){matching_excs.push(exc)}else{if(matching.exceptions.length>0){matching_excs=matching_excs.concat(matching)}if(non_matching.exceptions.length>0){non_matching_excs=non_matching_excs.concat(non_matching)}}}else if(condition(exc)){matching_excs.push(exc)}else{non_matching_excs.push(exc)}}if(matching_excs.length==0){matching_excs=_b_.None}if(non_matching_excs.length==0){non_matching_excs=_b_.None}var res=[];for(var item of[matching_excs,non_matching_excs]){var eg=_b_.BaseExceptionGroup.$factory(self.message,item);eg.__cause__=self.__cause__;eg.__context__=self.__context__;eg.__traceback__=self.__traceback__;res.push(eg)}return $B.fast_tuple(res)};_b_.BaseExceptionGroup.subgroup=function(self,condition){return _b_.BaseExceptionGroup.split(self,condition)[0]};$B.set_func_names(_b_.BaseExceptionGroup,"builtins");_b_.BaseExceptionGroup.__class_getitem__=_b_.classmethod.$factory(_b_.BaseExceptionGroup.__class_getitem__);_b_.ExceptionGroup=$B.make_class("ExceptionGFroup",(function(){var missing={},$=$B.args("ExceptionGroup",2,{message:null,exceptions:null},["message","exceptions"],arguments,{exceptions:missing},null,null);var err=Error();err.args=$B.fast_tuple(Array.from(arguments));err.__class__=_b_.ExceptionGroup;err.__traceback__=_b_.None;err.$py_error=true;err.$frame_obj=$B.frame_obj;err.$linenums=$B.make_linenums();err.message=$.message;err.exceptions=$.exceptions===missing?[]:$.exceptions;if(err.exceptions!==_b_.None){var exc_list=_b_.list.$factory(err.exceptions);for(var exc of exc_list){if(!$B.$isinstance(exc,_b_.Exception)){throw _b_.TypeError.$factory("Cannot nest BaseExceptions in an ExceptionGroup")}}}err.__cause__=_b_.None;err.__context__=_b_.None;err.__suppress_context__=false;return err}));_b_.ExceptionGroup.__bases__=[_b_.BaseExceptionGroup,_b_.Exception];_b_.ExceptionGroup.__mro__=_b_.type.$mro(_b_.ExceptionGroup);$B.set_func_names(_b_.ExceptionGroup,"builtins");function trace_from_stack(err){function handle_repeats(src,count_repeats){if(count_repeats>0){var len=trace.length;for(var i=0;i<2;i++){if(src){trace.push(trace[len-2]);trace.push(trace[len-1])}else{trace.push(trace[len-1])}count_repeats--;if(count_repeats==0){break}}if(count_repeats>0){trace.push(`[Previous line repeated ${count_repeats} more`+` time${count_repeats>1?"s":""}]`)}}}var trace=[],save_filename,save_lineno,save_scope,count_repeats=0,stack=err.$frame_obj===undefined?[]:make_frames_stack(err.$frame_obj),linenos=err.$linenums;for(let frame_num=0,len=stack.length;frame_num":frame[0];if(filename==save_filename&&scope==save_scope&&lineno==save_lineno){count_repeats++;continue}handle_repeats(src,count_repeats);save_filename=filename;save_lineno=lineno;save_scope=scope;count_repeats=0;var src=$B.file_cache[filename];trace.push(` File "${filename}", line ${lineno}, in `+(frame[0]==frame[2]?"":frame[0]));if(src){var lines=src.split("\n"),line=lines[lineno-1];if(line){trace.push(" "+line.trim())}else{console.log("no line",line);console.log("lineno",lineno);console.log("filename",filename)}if(err.$positions!==undefined&&line){var position=err.$positions[frame_num],trace_line="";if(position&&(position[1]!=position[0]||position[2]-position[1]!=line.trim().length||position[3])){var indent=line.length-line.trimLeft().length;var paddings=[position[0]-indent,position[1]-position[0],position[2]-position[1]];for(var padding in paddings){if(padding<0){console.log("wrong values, position",position,"indent",indent);paddings[paddings.indexOf(padding)]=0}}trace_line+=" "+" ".repeat(paddings[0])+"~".repeat(paddings[1])+"^".repeat(paddings[2]);if(position[3]!==undefined){trace_line+="~".repeat(position[3]-position[2])}trace.push(trace_line)}}}else{console.log("no src for filename",filename)}}if(count_repeats>1){let len=trace.length;for(let i=0;i<2;i++){if(src){trace.push(trace[len-2]);trace.push(trace[len-1])}else{trace.push(trace[len-1])}}trace.push(`[Previous line repeated ${count_repeats-2} more times]`)}return trace.join("\n")+"\n"}$B.error_trace=function(err){var trace="",stack=err.$frame_obj===undefined?[]:make_frames_stack(err.$frame_obj);if($B.get_option("debug",err)>1){console.log("handle error",err.__class__,err.args);console.log("stack",stack);console.log(err.stack)}if(stack.length>0){trace="Traceback (most recent call last):\n"}if(err.__class__===_b_.SyntaxError||err.__class__===_b_.IndentationError){err.$frame_obj=err.$frame_obj===null?null:err.$frame_obj.prev;trace+=trace_from_stack(err);var filename=err.filename,line=err.text,indent=line.length-line.trimLeft().length;trace+=` File "${filename}", line ${err.args[1][1]}\n`+` ${line.trim()}\n`;if(err.__class__!==_b_.IndentationError&&err.text){if($B.get_option("debug",err)>1){console.log("error args",err.args[1]);console.log("err line",line);console.log("indent",indent)}var start=err.offset-indent-1,end_offset=err.end_offset-1+(err.end_offset==err.offset?1:0),marks=" "+" ".repeat(Math.max(0,start)),nb_marks=1;if(err.end_lineno){if(err.end_lineno>err.lineno){nb_marks=line.length-start-indent}else{nb_marks=end_offset-start-indent}if(nb_marks==0&&err.end_offset==line.substr(indent).length){nb_marks=1}}marks+="^".repeat(nb_marks)+"\n";trace+=marks}trace+=`${err.__class__.__name__}: ${err.args[0]}`}else if(err.__class__!==undefined){var name=$B.class_name(err);trace+=trace_from_stack(err);var args_str=_b_.str.$factory(err);trace+=name+(args_str?": "+args_str:"");var save_frame_obj=$B.frame_obj;$B.frame_obj=err.$frame_obj;if(err.__class__===_b_.NameError){let suggestion=$B.offer_suggestions_for_name_error(err);if(suggestion!==_b_.None&&suggestion!==err.name){trace+=`. Did you mean: '${suggestion}'?`}if($B.stdlib_module_names.indexOf(err.name)>-1){trace+=`. Did you forget to import '${err.name}'?`}}else if(err.__class__===_b_.AttributeError){let suggestion=$B.offer_suggestions_for_attribute_error(err);if(suggestion!==_b_.None){trace+=`. Did you mean: '${suggestion}'?`}}else if(err.__class__===_b_.ImportError){if(err.$suggestion!==_b_.None){trace+=`. Did you mean: '${err.$suggestion}'?`}}$B.frame_obj=save_frame_obj}else{trace=err+""}if(err.$js_exc){trace+="\n";if($B.get_option("debug",err)>1){trace+=err.$js_exc.stack}}return trace};$B.get_stderr=function(){return $B.imported.sys?$B.imported.sys.stderr:$B.imported._sys.stderr};$B.get_stdout=function(){return $B.imported.sys?$B.imported.sys.stdout:$B.imported._sys.stdout};$B.show_error=function(err){var trace=$B.error_trace($B.exception(err));try{var stderr=$B.get_stderr();$B.$getattr(stderr,"write")(trace);var flush=$B.$getattr(stderr,"flush",_b_.None);if(flush!==_b_.None){flush()}}catch(print_exc_err){console.debug(trace)}};$B.handle_error=function(err){if(err.$handled){return}err.$handled=true;$B.show_error(err);throw err}})(__BRYTHON__);(function($B){var _b_=$B.builtins,None=_b_.None,range={__class__:_b_.type,__mro__:[_b_.object],__qualname__:"range",$is_class:true,$native:true,$match_sequence_pattern:true,$not_basetype:true,$descriptors:{start:true,step:true,stop:true}};range.__contains__=function(self,other){if(range.__len__(self)==0){return false}try{other=$B.int_or_bool(other)}catch(err){try{range.index(self,other);return true}catch(err){return false}}var start=_b_.int.$to_bigint(self.start),stop=_b_.int.$to_bigint(self.stop),step=_b_.int.$to_bigint(self.step);other=_b_.int.$to_bigint(other);var sub=other-start,fl=sub/step,res=step*fl;if(res==sub){if(stop>start){return other>=start&&stop>other}else{return start>=other&&other>stop}}else{return false}};range.__delattr__=function(){throw _b_.AttributeError.$factory("readonly attribute")};range.__eq__=function(self,other){if($B.$isinstance(other,range)){var len=range.__len__(self);if(!$B.rich_comp("__eq__",len,range.__len__(other))){return false}if(len==0){return true}if(!$B.rich_comp("__eq__",self.start,other.start)){return false}if(len==1){return true}return $B.rich_comp("__eq__",self.step,other.step)}return false};function compute_item(r,i){var len=range.__len__(r);if(len==0){return r.start}else if(i>len){return r.stop}return $B.rich_op("__add__",r.start,$B.rich_op("__mul__",r.step,i))}range.__getitem__=function(self,rank){if($B.$isinstance(rank,_b_.slice)){var norm=_b_.slice.$conv_for_seq(rank,range.__len__(self)),substep=$B.rich_op("__mul__",self.step,norm.step),substart=compute_item(self,norm.start),substop=compute_item(self,norm.stop);return range.$factory(substart,substop,substep)}if(typeof rank!="number"){rank=$B.$GetInt(rank)}if($B.rich_comp("__gt__",0,rank)){rank=$B.rich_op("__add__",rank,range.__len__(self))}var res=$B.rich_op("__add__",self.start,$B.rich_op("__mul__",rank,self.step));if($B.rich_comp("__gt__",self.step,0)&&($B.rich_comp("__ge__",res,self.stop)||$B.rich_comp("__gt__",self.start,res))||$B.rich_comp("__gt__",0,self.step)&&($B.rich_comp("__ge__",self.stop,res)||$B.rich_comp("__gt__",res,self.start))){throw _b_.IndexError.$factory("range object index out of range")}return res};range.__hash__=function(self){var len=range.__len__(self);if(len==0){return _b_.hash(_b_.tuple.$factory([0,None,None]))}if(len==1){return _b_.hash(_b_.tuple.$factory([1,self.start,None]))}return _b_.hash(_b_.tuple.$factory([len,self.start,self.step]))};var RangeIterator=$B.make_class("range_iterator",(function(obj){return{__class__:RangeIterator,obj:obj}}));RangeIterator.__iter__=function(self){return self};RangeIterator.__next__=function(self){return _b_.next(self.obj)};$B.set_func_names(RangeIterator,"builtins");range.__iter__=function(self){var res={__class__:range,start:self.start,stop:self.stop,step:self.step};if(self.$safe){res.$counter=self.start-self.step}else{res.$counter=$B.rich_op("__sub__",self.start,self.step)}return RangeIterator.$factory(res)};range.__len__=function(self){var len,start=_b_.int.$to_bigint(self.start),stop=_b_.int.$to_bigint(self.stop),step=_b_.int.$to_bigint(self.step);if(self.step>0){if(self.start>=self.stop){return 0}len=1n+(stop-start-1n)/step}else{if(self.stop>=self.start){return 0}len=1n+(start-stop-1n)/-step}return _b_.int.$int_or_long(len)};range.__next__=function(self){if(self.$safe){self.$counter+=self.step;if(self.step>0&&self.$counter>=self.stop||self.step<0&&self.$counter<=self.stop){throw _b_.StopIteration.$factory("")}}else{self.$counter=$B.rich_op("__add__",self.$counter,self.step);if($B.rich_comp("__gt__",self.step,0)&&$B.rich_comp("__ge__",self.$counter,self.stop)||$B.rich_comp("__gt__",0,self.step)&&$B.rich_comp("__ge__",self.stop,self.$counter)){throw _b_.StopIteration.$factory("")}}return self.$counter};range.__reversed__=function(self){var n=$B.rich_op("__sub__",range.__len__(self),1);return range.$factory($B.rich_op("__add__",self.start,$B.rich_op("__mul__",n,self.step)),$B.rich_op("__sub__",self.start,self.step),$B.rich_op("__mul__",-1,self.step))};range.__repr__=function(self){$B.builtins_repr_check(range,arguments);var res="range("+_b_.str.$factory(self.start)+", "+_b_.str.$factory(self.stop);if(self.step!=1){res+=", "+_b_.str.$factory(self.step)}return res+")"};range.__setattr__=function(){throw _b_.AttributeError.$factory("readonly attribute")};range.start=function(self){return self.start};range.step=function(self){return self.step},range.stop=function(self){return self.stop};range.count=function(self,ob){if($B.$isinstance(ob,[_b_.int,_b_.float,_b_.bool])){return _b_.int.$factory(range.__contains__(self,ob))}else{var comp=function(other){return $B.rich_comp("__eq__",ob,other)},it=range.__iter__(self),_next=RangeIterator.__next__,nb=0;while(true){try{if(comp(_next(it))){nb++}}catch(err){if($B.$isinstance(err,_b_.StopIteration)){return nb}throw err}}}};range.index=function(){var $=$B.args("index",2,{self:null,other:null},["self","other"],arguments,{},null,null),self=$.self,other=$.other;try{other=$B.int_or_bool(other)}catch(err){var comp=function(x){return $B.rich_comp("__eq__",other,x)},it=range.__iter__(self),_next=RangeIterator.__next__,nb=0;while(true){try{if(comp(_next(it))){return nb}nb++}catch(err){if($B.$isinstance(err,_b_.StopIteration)){throw _b_.ValueError.$factory(_b_.str.$factory(other)+" not in range")}throw err}}}var sub=$B.rich_op("__sub__",other,self.start),fl=$B.rich_op("__floordiv__",sub,self.step),res=$B.rich_op("__mul__",self.step,fl);if($B.rich_comp("__eq__",res,sub)){if($B.rich_comp("__gt__",self.stop,self.start)&&$B.rich_comp("__ge__",other,self.start)&&$B.rich_comp("__gt__",self.stop,other)||$B.rich_comp("__ge__",self.start,self.stop)&&$B.rich_comp("__ge__",self.start,other)&&$B.rich_comp("__gt__",other,self.stop)){return fl}else{throw _b_.ValueError.$factory(_b_.str.$factory(other)+" not in range")}}else{throw _b_.ValueError.$factory(_b_.str.$factory(other)+" not in range")}};range.$factory=function(){var $=$B.args("range",3,{start:null,stop:null,step:null},["start","stop","step"],arguments,{start:null,stop:null,step:null},null,null),start=$.start,stop=$.stop,step=$.step,safe;if(stop===null&&step===null){if(start==null){throw _b_.TypeError.$factory("range expected 1 arguments, got 0")}stop=$B.PyNumber_Index(start);safe=typeof stop==="number";return{__class__:range,start:0,stop:stop,step:1,$is_range:true,$safe:safe}}if(step===null){step=1}start=$B.PyNumber_Index(start);stop=$B.PyNumber_Index(stop);step=$B.PyNumber_Index(step);if(step==0){throw _b_.ValueError.$factory("range arg 3 must not be zero")}safe=typeof start=="number"&&typeof stop=="number"&&typeof step=="number";return{__class__:range,start:start,stop:stop,step:step,$is_range:true,$safe:safe}};$B.set_func_names(range,"builtins");var slice={__class__:_b_.type,__mro__:[_b_.object],__qualname__:"slice",$is_class:true,$native:true,$not_basetype:true,$descriptors:{start:true,step:true,stop:true}};slice.__eq__=function(self,other){var conv1=conv_slice(self),conv2=conv_slice(other);return conv1[0]==conv2[0]&&conv1[1]==conv2[1]&&conv1[2]==conv2[2]};slice.__repr__=function(self){$B.builtins_repr_check(slice,arguments);return"slice("+_b_.str.$factory(self.start)+", "+_b_.str.$factory(self.stop)+", "+_b_.str.$factory(self.step)+")"};slice.__setattr__=function(){throw _b_.AttributeError.$factory("readonly attribute")};function conv_slice(self){var attrs=["start","stop","step"],res=[];for(var i=0;i=0;i--){if(cars.indexOf(self.source[i])==-1){break}}return bytes.$factory(self.source.slice(0,i+1))}function invalid(other){return!$B.$isinstance(other,[bytes,bytearray])}var bytearray={__class__:_b_.type,__mro__:[_b_.object],__qualname__:"bytearray",$buffer_protocol:true,$is_class:true};var mutable_methods=["__delitem__","clear","copy","count","index","pop","remove","reverse"];for(var method of mutable_methods){bytearray[method]=function(m){return function(self){var args=[self.source],pos=1;for(var i=1,len=arguments.length;i255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}var pos=arg;if(arg<0){pos=self.source.length+pos}if(pos>=0&&pos=0;i--){if(!$B.$isinstance($temp[i],_b_.int)){throw _b_.TypeError.$factory("an integer is required")}else if($temp[i]>255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}self.source.splice(start,0,$temp[i])}}catch(err){throw _b_.TypeError.$factory("can only assign an iterable")}}else{throw _b_.TypeError.$factory("list indices must be integer, not "+$B.class_name(arg))}};bytearray.append=function(self,b){if(arguments.length!=2){throw _b_.TypeError.$factory("append takes exactly one argument ("+(arguments.length-1)+" given)")}if(!$B.$isinstance(b,_b_.int)){throw _b_.TypeError.$factory("an integer is required")}if(b>255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}self.source[self.source.length]=b};bytearray.extend=function(self,b){if(self.in_iteration){throw _b_.BufferError.$factory("Existing exports of data: object "+"cannot be re-sized")}if(b.__class__===bytearray||b.__class__===bytes){self.source=self.source.concat(b.source);return _b_.None}for(var item of $B.make_js_iterator(b)){bytearray.append(self,$B.PyNumber_Index(item))}return _b_.None};bytearray.insert=function(self,pos,b){if(arguments.length!=3){throw _b_.TypeError.$factory("insert takes exactly 2 arguments ("+(arguments.length-1)+" given)")}if(!$B.$isinstance(b,_b_.int)){throw _b_.TypeError.$factory("an integer is required")}if(b>255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}_b_.list.insert(self.source,pos,b)};bytearray.$factory=function(){var args=[bytearray];for(var i=0,len=arguments.length;i-1}if(self.source.length=0&&pos0){stop=Math.min(stop,self.source.length);if(stop<=start){return bytes.$factory([])}for(let i=start;i=start){return bytes.$factory([])}stop=Math.max(0,stop);for(let i=start;i>=stop;i+=step){res[pos++]=self.source[i]}}return bytes.$factory(res)}else if($B.$isinstance(arg,_b_.bool)){return self.source.__getitem__(_b_.int.$factory(arg))}};bytes.$getnewargs=function(self){return $B.fast_tuple([bytes_value(self)])};bytes.__getnewargs__=function(){return bytes.$getnewargs($B.single_arg("__getnewargs__","self",arguments))};bytes.__gt__=function(self,other){if(invalid(other)){return _b_.NotImplemented}return _b_.list.__gt__(self.source,other.source)};bytes.__hash__=function(self){if(self===undefined){return bytes.__hashvalue__||$B.$py_next_hash--}var hash=1;for(var i=0,len=self.source.length;i=0&&item<256){source.push(item)}else{throw _b_.ValueError.$factory("bytes must be in range (0, 256)")}}}return{__class__:$.cls,source:source}};bytes.$new=function(cls,source,encoding,errors){var self={__class__:cls},int_list=[],pos=0;if(source===undefined){}else if(typeof source=="number"||$B.$isinstance(source,_b_.int)){let i=source;while(i--){int_list[pos++]=0}}else{if(typeof source=="string"||$B.$isinstance(source,_b_.str)){if(encoding===undefined){throw _b_.TypeError.$factory("string argument without an encoding")}int_list=encode(source,encoding||"utf-8",errors||"strict")}else{if(encoding!==undefined){console.log("encoding",encoding);throw _b_.TypeError.$factory("encoding without a string argument")}if(Array.isArray(source)){int_list=source}else{try{int_list=_b_.list.$factory(source)}catch(err){var bytes_method=$B.$getattr(source,"__bytes__",_b_.None);if(bytes_method===_b_.None){throw _b_.TypeError.$factory("cannot convert "+`'${$B.class_name(source)}' object to bytes`)}var res=$B.$call(bytes_method)();if(!$B.$isinstance(res,_b_.bytes)){throw _b_.TypeError.$factory(`__bytes__ returned `+`non-bytes (type ${$B.class_name(res)})`)}return res}for(let i=0;i255){throw _b_.ValueError.$factory("bytes must be in range"+"(0, 256)")}}}}}self.source=int_list;self.encoding=encoding;self.errors=errors;return self};bytes.__repr__=bytes.__str__=function(self){var t=$B.special_string_repr,res="";for(var i=0,len=self.source.length;i=128){var hx=s.toString(16);hx=(hx.length==1?"0":"")+hx;res+="\\x"+hx}else if(s=="\\".charCodeAt(0)){res+="\\\\"}else{res+=String.fromCharCode(s)}}if(res.indexOf("'")>-1&&res.indexOf('"')==-1){return'b"'+res+'"'}else{return"b'"+res.replace(new RegExp("'","g"),"\\'")+"'"}};bytes.capitalize=function(self){var src=self.source,len=src.length,buffer=src.slice();if(buffer[0]>96&&buffer[0]<123){buffer[0]-=32}for(var i=1;i64&&buffer[i]<91){buffer[i]+=32}}return bytes.$factory(buffer)};bytes.center=function(){var $=$B.args("center",3,{self:null,width:null,fillbyte:null},["self","width","fillbyte"],arguments,{fillbyte:bytes.$factory([32])},null,null);var diff=$.width-$.self.source.length;if(diff<=0){return bytes.$factory($.self.source)}var ljust=bytes.ljust($.self,$.self.source.length+Math.floor(diff/2),$.fillbyte);return bytes.rjust(ljust,$.width,$.fillbyte)};bytes.count=function(){var $=$B.args("count",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:-1},null,null);var n=0,index=-1,len=0;if(typeof $.sub=="number"){if($.sub<0||$.sub>255)throw _b_.ValueError.$factory("byte must be in range(0, 256)");len=1}else if(!$.sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.sub)+"'")}else if(!$.sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.sub)+"'")}else{len=$.sub.source.length}do{index=bytes.find($.self,$.sub,Math.max(index+len,$.start),$.end);if(index!=-1){n++}}while(index!=-1);return n};bytes.decode=function(){var $=$B.args("decode",3,{self:null,encoding:null,errors:null},["self","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null);switch($.errors){case"strict":case"ignore":case"replace":case"surrogateescape":case"surrogatepass":case"xmlcharrefreplace":case"backslashreplace":return decode($.self,$.encoding,$.errors);default:}};bytes.endswith=function(){var $=$B.args("endswith",4,{self:null,suffix:null,start:null,end:null},["self","suffix","start","end"],arguments,{start:-1,end:-1},null,null);if($B.$isinstance($.suffix,bytes)){var end=$.end==-1?$.self.source.length:$.end;var res=true;for(let i=$.suffix.source.length-1,len=$.suffix.source.length;i>=0&&res;--i){res=$.self.source[end-len+i]==$.suffix.source[i]}return res}else if($B.$isinstance($.suffix,_b_.tuple)){for(let i=0;i<$.suffix.length;++i){if($B.$isinstance($.suffix[i],bytes)){if(bytes.endswith($.self,$.suffix[i],$.start,$.end)){return true}}else{throw _b_.TypeError.$factory("endswith first arg must be "+"bytes or a tuple of bytes, not "+$B.class_name($.suffix))}}return false}else{throw _b_.TypeError.$factory("endswith first arg must be bytes "+"or a tuple of bytes, not "+$B.class_name($.suffix))}};bytes.expandtabs=function(){var $=$B.args("expandtabs",2,{self:null,tabsize:null},["self","tabsize"],arguments,{tabsize:8},null,null);var tab_spaces=[];for(let i=0;i<$.tabsize;++i){tab_spaces.push(32)}var buffer=$.self.source.slice();for(let i=0;i255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}return self.source.slice(0,end==-1?undefined:end).indexOf(sub,start)}else if(!sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name(sub)+"'")}else if(!sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name(sub)+"'")}end=end==-1?self.source.length:Math.min(self.source.length,end);var len=sub.source.length;for(var i=start;i<=end-len;i++){var chunk=self.source.slice(i,i+len),found=true;for(var j=0;jstring.length){throw _b_.ValueError.$factory("non-hexadecimal number found "+"in fromhex() arg")}source.push(_b_.int.$factory(string.substr(i,2),16))}return $.cls.$factory(source)};bytes.hex=function(){var $=$B.args("hex",3,{self:null,sep:null,bytes_per_sep:null},["self","sep","bytes_per_sep"],arguments,{sep:"",bytes_per_sep:1},null,null),self=$.self,sep=$.sep,bytes_per_sep=$.bytes_per_sep,res="",digits="0123456789abcdef",bps=bytes_per_sep,jstart=bps,len=self.source.length;if(bytes_per_sep<0){bps=-bytes_per_sep;jstart=bps}else if(bytes_per_sep==0){sep=""}else{jstart=len%bps;if(jstart==0){jstart=bps}}for(var i=0,j=jstart;i>4];res+=digits[c&15]}return res};bytes.index=function(){var $=$B.args("index",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:-1},null,null);var index=bytes.find($.self,$.sub,$.start,$.end);console.log("index",index);if(index==-1){throw _b_.ValueError.$factory("subsection not found")}return index};bytes.isalnum=function(){var $=$B.args("isalnum",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,res=len>0;for(var i=0;i96&&src[i]<123||src[i]>64&&src[i]<91||src[i]>47&&src[i]<58}return res};bytes.isalpha=function(){var $=$B.args("isalpha",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,res=len>0;for(var i=0;i96&&src[i]<123||src[i]>64&&src[i]<91}return res};bytes.isdigit=function(){var $=$B.args("isdigit",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,res=len>0;for(let i=0;i47&&src[i]<58}return res};bytes.islower=function(){var $=$B.args("islower",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,res=false;for(let i=0;i96&&src[i]<123;if(src[i]>64&&src[i]<91){return false}}return res};bytes.isspace=function(){var $=$B.args("isspace",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length;for(let i=0;i64&&src[i]<91;if(src[i]>96&&src[i]<123){return false}}return res};bytes.istitle=function(){var $=$B.args("istitle",1,{self:null},["self"],arguments,{},null,null),self=$.self;var src=self.source,len=src.length,current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false;for(var i=0;i96&&src[i]<123;is_uppercase=src[i]>64&&src[i]<91;current_char_is_letter=is_lowercase||is_uppercase;if(current_char_is_letter&&(prev_char_was_letter&&is_uppercase)||!prev_char_was_letter&&is_lowercase){return false}prev_char_was_letter=current_char_is_letter}return true};bytes.join=function(){var $ns=$B.args("join",2,{self:null,iterable:null},["self","iterable"],arguments,{}),self=$ns["self"],iterable=$ns["iterable"];var next_func=$B.$getattr(_b_.iter(iterable),"__next__"),res=self.__class__.$factory(),empty=true;while(true){try{var item=next_func();if(empty){empty=false}else{res=bytes.__add__(res,self)}res=bytes.__add__(res,item)}catch(err){if($B.$isinstance(err,_b_.StopIteration)){break}throw err}}return res};var _lower=function(char_code){if(char_code>=65&&char_code<=90){return char_code+32}else{return char_code}};bytes.lower=function(self){var _res=[],pos=0;for(var i=0,len=self.source.length;i=0?$.count:src.length;if(!$.old.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.old)+"'")}else if(!$.old.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.sep)+"'")}if(!$.new.__class__){throw _b_.TypeError.$factory("second argument must be a bytes-like "+"object, not '"+$B.class_name($.old)+"'")}else if(!$.new.__class__.$buffer_protocol){throw _b_.TypeError.$factory("second argument must be a bytes-like "+"object, not '"+$B.class_name($.sep)+"'")}for(var i=0;i255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")}return $.self.source.slice(start,$.end==-1?undefined:$.end).lastIndexOf(sub)+start}else if(!sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name($.sub)+"'")}else if(!sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+"object, not '"+$B.class_name(sub)+"'")}end=end==-1?self.source.length:Math.min(self.source.length,end);var len=sub.source.length;for(var i=end-len;i>=start;--i){var chunk=self.source.slice(i,i+len),found=true;for(var j=0;jstart){res.push(bytes.$factory(src.slice(start,stop)))}return $B.$list(res)};bytes.splitlines=function(){var $=$B.args("splitlines",2,{self:null,keepends:null},["self","keepends"],arguments,{keepends:false},null,null);if(!$B.$isinstance($.keepends,[_b_.bool,_b_.int])){throw _b_.TypeError("integer argument expected, got "+$B.get_class($.keepends).__name)}var keepends=_b_.int.$factory($.keepends),res=$B.$list([]),source=$.self.source,start=0,pos=0;if(!source.length){return res}while(pos96&&buffer[i]<123){buffer[i]-=32}else if(buffer[i]>64&&buffer[i]<91){buffer[i]+=32}}return bytes.$factory(buffer)};bytes.title=function(self){var src=self.source,len=src.length,buffer=src.slice(),current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false;for(var i=0;i96&&buffer[i]<123;is_uppercase=buffer[i]>64&&buffer[i]<91;current_char_is_letter=is_lowercase||is_uppercase;if(current_char_is_letter){if(prev_char_was_letter&&is_uppercase){buffer[i]+=32}else if(!prev_char_was_letter&&is_lowercase){buffer[i]-=32}}prev_char_was_letter=current_char_is_letter}return bytes.$factory(buffer)};bytes.translate=function(self,table,_delete){if(_delete===undefined){_delete=[]}else if($B.$isinstance(_delete,bytes)){_delete=_delete.source}else{throw _b_.TypeError.$factory("Type "+$B.get_class(_delete).__name+" doesn't support the buffer API")}var res=[],pos=0;if($B.$isinstance(table,bytes)&&table.source.length==256){for(var i=0,len=self.source.length;i-1){continue}res[pos++]=table.source[self.source[i]]}}return bytes.$factory(res)};var _upper=function(char_code){if(char_code>=97&&char_code<=122){return char_code-32}else{return char_code}};bytes.upper=function(self){var _res=[],pos=0;for(var i=0,len=self.source.length;i>5==6){if(b[pos+1]===undefined){err_info=[byte,pos,"end"]}else if((b[pos+1]&192)!=128){err_info=[byte,pos,"continuation"]}if(err_info!==null){if(errors=="ignore"){pos++}else{throw _b_.UnicodeDecodeError.$factory("'utf-8' codec can't decode byte 0x"+err_info[0].toString(16)+" in position "+err_info[1]+(err_info[2]=="end"?": unexpected end of data":": invalid continuation byte"))}}else{let cp=byte&31;cp<<=6;cp+=b[pos+1]&63;s+=String.fromCodePoint(cp);pos+=2}}else if(byte>>4==14){if(b[pos+1]===undefined){err_info=[byte,pos,"end",pos+1]}else if((b[pos+1]&192)!=128){err_info=[byte,pos,"continuation",pos+2]}else if(b[pos+2]===undefined){err_info=[byte,pos+"-"+(pos+1),"end",pos+2]}else if((b[pos+2]&192)!=128){err_info=[byte,pos,"continuation",pos+3]}if(err_info!==null){if(errors=="ignore"){pos=err_info[3]}else if(errors=="surrogateescape"){for(let i=pos;i>3==30){if(b[pos+1]===undefined){err_info=[byte,pos,"end",pos+1]}else if((b[pos+1]&192)!=128){err_info=[byte,pos,"continuation",pos+2]}else if(b[pos+2]===undefined){err_info=[byte,pos+"-"+(pos+1),"end",pos+2]}else if((b[pos+2]&192)!=128){err_info=[byte,pos,"continuation",pos+3]}else if(b[pos+3]===undefined){err_info=[byte,pos+"-"+(pos+1)+"-"+(pos+2),"end",pos+3]}if(err_info!==null){if(errors=="ignore"){pos=err_info[3]}else if(errors=="surrogateescape"){for(let i=pos;i")}}return decoded}return s};var encode=$B.encode=function(){var $=$B.args("encode",3,{s:null,encoding:null,errors:null},["s","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null),s=$.s,encoding=$.encoding,errors=$.errors;var t=[],pos=0,enc=normalise(encoding);switch(enc){case"utf-8":case"utf_8":case"utf8":if(globalThis.TextEncoder){var encoder=new TextEncoder("utf-8",{fatal:true});try{var array=encoder.encode(s);return fast_bytes(Array.from(array))}catch(err){}}for(let i=0,len=s.length;i>6),128+(cp&63))}else if(cp<=65535){t.push(224+(cp>>12),128+((cp&4095)>>6),128+(cp&63))}else{console.log("4 bytes")}}break;case"latin":case"latin1":case"latin-1":case"latin_1":case"L1":case"iso8859_1":case"iso_8859_1":case"8859":case"cp819":case"windows1252":for(let i=0,len=s.length;i>2>other_size){return set_copy_and_difference(so,other)}var result=make_new_set();if(other_is_dict){for(let entry of set_iter_with_hash(so)){if(!_b_.dict.$lookup_by_key(other,entry.item,entry.hash).found){set_add(result,entry.item,entry.hash)}}return result}for(let entry of set_iter_with_hash(so)){if(!set_contains(other,entry.item,entry.hash)){set_add(result,entry.item,entry.hash)}}result.__class__=so.__class__;return result}function set_difference_update(so,other){if(so===other){return set.clear(so)}if($B.$isinstance(other,[set,frozenset])){for(let entry of set_iter_with_hash(other)){set_discard_entry(so,entry.item,entry.hash)}}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(other)){set_discard_entry(so,entry.key,entry.hash)}}else{var iterator=$B.make_js_iterator(other);for(let key of iterator){set_discard_key(so,key)}}}const DISCARD_NOTFOUND=0;function set_discard_entry(so,key,hash){var entry=set_lookkey(so,key,hash);if(!entry){return DISCARD_NOTFOUND}if(so.$store[entry.hash]!==undefined){set_remove(so,entry.hash,entry.index)}}function set_discard_key(so,key){return set_discard_entry(so,key)}function*set_iter(so){var ordered_keys=Object.keys(so.$store).sort();for(var hash of ordered_keys){if(so.$store[hash]!==undefined){for(var item of so.$store[hash]){yield item}}}}function*set_iter_with_hash(so){for(var hash in so.$store){if(so.$store[hash]!==undefined){for(var item of so.$store[hash]){yield{item:item,hash:hash}}}}}function set_remove(so,hash,index){so.$store[hash].splice(index,1);if(so.$store[hash].length==0){delete so.$store[hash]}so.$used--}function set_intersection(so,other){if(so===other){return set_copy(so)}var result=make_new_set_base_type(so);if($B.$isinstance(other,[set,frozenset])){if(other.$used>so.$used){var tmp=so;so=other;other=tmp}for(let entry of set_iter_with_hash(other)){if(set_contains(so,entry.item,entry.hash)){set_add(result,entry.item,entry.hash)}}}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(other)){if(set_contains(so,entry.key,entry.hash)){set_add(result,entry.key,entry.hash)}}}else{let iterator=$B.make_js_iterator(other);for(var other_item of iterator){var test=set_contains(so,other_item);if(test){set_add(result,other_item)}}}return result}function set_intersection_multi(so,args){var result=set_copy(so);if(args.length==0){return result}for(var other of args){result=set_intersection(result,other)}return result}function set_lookkey(so,key,hash){if(hash===undefined){try{hash=$B.$hash(key)}catch(err){if($B.$isinstance(key,set)){hash=$B.$hash(frozenset.$factory(key))}else{throw err}}}var items=so.$store[hash];if(items===undefined){return false}for(var index=0,len=so.$store[hash].length;index0){set.clear(self)}set.update(self,iterable);return _b_.None};var set_iterator=$B.make_class("set_iterator",(function(so){return{__class__:set_iterator,so:so,it:set_iter(so),version:so.$version}}));set_iterator.__iter__=function(self){return self};set_iterator.__length_hint__=function(self){return self.so.$used};set_iterator.__next__=function(self){var res=self.it.next();if(res.done){throw _b_.StopIteration.$factory()}if(self.so.$version!=self.version){throw _b_.RuntimeError.$factory("Set changed size during iteration")}return res.value};set_iterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([set_make_items(self.so)])])};$B.set_func_names(set_iterator,"builtins");set.__iter__=function(self){return set_iterator.$factory(self)};function set_make_items(so){var items=[];for(var hash in so.$store){items=items.concat(so.$store[hash])}return $B.$list(items)}set.__le__=function(self,other){if($B.$isinstance(other,[set,frozenset])){return set.issubset(self,other)}return _b_.NotImplemented};set.__len__=function(self){return self.$used};set.__lt__=function(self,other){if($B.$isinstance(other,[set,frozenset])){return set.__le__(self,other)&&set.__len__(self)1){throw _b_.TypeError.$factory(`set.pop() takes no arguments`+` (${arguments.length-1} given)`)}for(var hash in self.$store){break}if(hash===undefined){throw _b_.KeyError.$factory("pop from an empty set")}var item;item=self.$store[hash].pop();if(self.$store[hash].length==0){delete self.$store[hash]}self.$used--;self.$version++;return item};set.remove=function(){var $=$B.args("remove",2,{self:null,item:null},["self","item"],arguments,{},null,null),self=$.self,item=$.item;var result=set_discard_entry(self,item);if(result==DISCARD_NOTFOUND){throw _b_.KeyError.$factory(item)}self.$version++;return _b_.None};set.symmetric_difference_update=function(){var $=$B.args("symmetric_difference_update",2,{self:null,s:null},["self","s"],arguments,{},null,null),self=$.self,s=$.s;return set_symmetric_difference_update(self,s)};set.update=function(self){var $=$B.args("update",1,{self:null},["self"],arguments,{},"args",null);for(var iterable of $.args){if(Array.isArray(iterable)){for(let i=0;iset.__len__(other)){return false}for(let entry of set_iter_with_hash(self)){if(!set_lookkey(other,entry.item,entry.hash)){return false}}return true}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(self)){if(!set_lookkey(other,entry.key,entry.hash)){return false}}return true}else{var member_func=$B.member_func(other);for(let entry of set_iter_with_hash(self)){if(!member_func(entry.item)){return false}}return true}};set.issuperset=function(){var $=$B.args("issuperset",2,{self:null,other:null},["self","other"],arguments,{},"args",null),self=$.self,other=$.other;if($B.$isinstance(other,[set,frozenset])){return set.issubset(other,self)}else{return set.issubset(set.$factory(other),self)}};set.__iand__=function(self,other){if(!$B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented}set.intersection_update(self,other);return self};set.__isub__=function(self,other){if(!$B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented}set_difference_update(self,other);return self};set.__ixor__=function(self,other){if(!$B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented}set.symmetric_difference_update(self,other);return self};set.__ior__=function(self,other){if(!$B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented}set.update(self,other);return self};set.$literal=function(items){let res=make_new_set(set);for(let item of items){if(item.constant){set_add(res,item.constant[0],item.constant[1])}else if(item.starred){for(let _item of $B.make_js_iterator(item.starred)){set_add(res,_item)}}else{set_add(res,item.item)}}return res};set.$factory=function(){var args=[set].concat(Array.from(arguments)),self=set.__new__.apply(null,args);set.__init__(self,...arguments);return self};$B.set_func_names(set,"builtins");set.__class_getitem__=_b_.classmethod.$factory(set.__class_getitem__);var frozenset=$B.make_class("frozenset");frozenset.$native=true;for(var attr in set){switch(attr){case"add":case"clear":case"discard":case"pop":case"remove":case"update":break;default:if(frozenset[attr]==undefined){if(typeof set[attr]=="function"){frozenset[attr]=function(x){return function(){return set[x].apply(null,arguments)}}(attr)}else{frozenset[attr]=set[attr]}}}}frozenset.__hash__=function(self){if(self===undefined){return frozenset.__hashvalue__||$B.$py_next_hash--}if(self.__hashvalue__!==undefined){return self.__hashvalue__}var _hash=1927868237;_hash*=self.$used;for(var entry of set_iter_with_hash(self)){var _h=entry.hash;_hash^=(_h^89869747^_h<<16)*3644798167}_hash=_hash*69069+907133923;if(_hash==-1){_hash=590923713}return self.__hashvalue__=_hash};frozenset.__init__=function(){return _b_.None};frozenset.__new__=function(cls,iterable){if(cls===undefined){throw _b_.TypeError.$factory("frozenset.__new__(): not enough arguments")}var self=make_new_set(cls);if(iterable===undefined){return self}$B.check_nb_args_no_kw("__new__",2,arguments);if(cls===frozenset&&iterable.__class__===frozenset){return iterable}set.update(self,iterable);return self};frozenset.__repr__=function(self){$B.builtins_repr_check(frozenset,arguments);return set_repr(self)};frozenset.copy=function(self){if(self.__class__===frozenset){return self}return set_copy(self)};frozenset.$factory=function(){var args=[frozenset].concat(Array.from(arguments)),self=frozenset.__new__.apply(null,args);frozenset.__init__(self,...arguments);return self};$B.set_func_names(frozenset,"builtins");_b_.set=set;_b_.frozenset=frozenset})(__BRYTHON__);(function($B){var _b_=$B.builtins,_window=globalThis;var Module=$B.module=$B.make_class("module",(function(name,doc,$package){return{$tp_class:Module,__builtins__:_b_.__builtins__,__name__:name,__doc__:doc||_b_.None,__package__:$package||_b_.None}}));Module.__dir__=function(self){if(self.__dir__){return $B.$call(self.__dir__)()}var res=[];for(var key in self){if(key.startsWith("$")||key=="__class__"){continue}res[res.length]=key}return $B.$list(res.sort())};Module.__new__=function(cls,name,doc,$package){return{__class__:cls,__builtins__:_b_.__builtins__,__name__:name,__doc__:doc||_b_.None,__package__:$package||_b_.None}};Module.__repr__=Module.__str__=function(self){var res=""};Module.__setattr__=function(self,attr,value){if(self.__name__=="__builtins__"){$B.builtins[attr]=value}else{self[attr]=value}};$B.set_func_names(Module,"builtins");$B.make_import_paths=function(filename){var filepath=$B.script_domain?$B.script_domain+"/"+filename:filename;var elts=filepath.split("/");elts.pop();var script_dir=elts.join("/"),path=[$B.brython_path+"Lib",$B.brython_path+"libs",script_dir,$B.brython_path+"Lib/site-packages"];var meta_path=[],path_hooks=[];if($B.use_VFS){meta_path.push($B.finders.VFS)}var static_stdlib_import=$B.get_option_from_filename("static_stdlib_import",filename);if(static_stdlib_import!==false&&$B.protocol!="file"){meta_path.push($B.finders.stdlib_static);if(path.length>3){path.shift();path.shift()}}var pythonpath=$B.get_option_from_filename("pythonpath",filename);if(pythonpath){var ix=path.indexOf(script_dir);if(ix===-1){console.log("bizarre, script_dir",script_dir,"not in path",path)}else{var fullpaths=[];for(var p of pythonpath){if(p=="."){fullpaths.push(script_dir)}else if(p.startsWith("/")){fullpaths.push($B.script_domain+p)}else if(p.split("://")[0].startsWith("http")){fullpaths.push(p)}else if(!p.startsWith($B.script_domain)){fullpaths.push(script_dir+"/"+p)}else{fullpaths.push(p)}}path.splice(ix,1,...fullpaths)}}if($B.protocol!=="file"){meta_path.push($B.finders.path);path_hooks.push($B.url_hook)}$B.import_info[filename]={meta_path:meta_path,path_hooks:path_hooks,path:path}};function $download_module(mod,url){var xhr=new XMLHttpRequest,fake_qs="?v="+(new Date).getTime(),res=null,mod_name=mod.__name__;if($B.get_option("cache")){xhr.open("GET",url,false)}else{xhr.open("GET",url+fake_qs,false)}var timer=_window.setTimeout((function(){xhr.abort()}),5e3);xhr.send();if($B.$CORS){if(xhr.status==200||xhr.status==0){res=xhr.responseText}else{res=_b_.ModuleNotFoundError.$factory("No module named '"+mod_name+"'")}}else{if(xhr.readyState==4){if(xhr.status==200){res=xhr.responseText;mod.$last_modified=xhr.getResponseHeader("Last-Modified")}else{console.info("Trying to import "+mod_name+", not found at url "+url);res=_b_.ModuleNotFoundError.$factory("No module named '"+mod_name+"'")}}}_window.clearTimeout(timer);if(res==null){throw _b_.ModuleNotFoundError.$factory("No module named '"+mod_name+"' (res is null)")}if(res.constructor===Error){throw res}return res}$B.$download_module=$download_module;$B.addToImported=function(name,modobj){$B.imported[name]=modobj;if(modobj===undefined){throw _b_.ImportError.$factory("imported not set by module")}modobj.__class__=Module;modobj.__name__=name;for(var attr in modobj){if(typeof modobj[attr]=="function"){modobj[attr].$infos={__module__:name,__name__:attr,__qualname__:attr};modobj[attr].$in_js_module=true}else if($B.$isinstance(modobj[attr],_b_.type)&&!modobj[attr].hasOwnProperty("__module__")){modobj[attr].__module__=name}}};function run_js(module_contents,path,_module){try{new Function(module_contents)()}catch(err){throw $B.exception(err)}var modobj=$B.imported[_module.__name__];if(modobj===undefined){throw _b_.ImportError.$factory("imported not set by module")}modobj.__class__=Module;modobj.__name__=_module.__name__;for(var attr in modobj){if(typeof modobj[attr]=="function"){modobj[attr].$infos={__module__:_module.__name__,__name__:attr,__qualname__:attr};modobj[attr].$in_js_module=true}else if($B.$isinstance(modobj[attr],_b_.type)&&!modobj[attr].hasOwnProperty("__module__")){modobj[attr].__module__=_module.__name__}}return true}function run_py(module_contents,path,module,compiled){var filename=module.__file__;$B.file_cache[filename]=module_contents;$B.url2name[filename]=module.__name__;var root,js,mod_name=module.__name__,src;if(!compiled){src={src:module_contents,filename:filename,imported:true};try{root=$B.py2js(src,module,module.__name__,$B.builtins_scope)}catch(err){err.$frame_obj=$B.frame_obj;if($B.get_option("debug",err)>1){console.log("error in imported module",module);console.log("stack",$B.make_frames_stack(err.$frame_obj))}throw err}}try{js=compiled?module_contents:root.to_js();if($B.get_option("debug")==10){console.log("code for module "+module.__name__);console.log($B.format_indent(js,0))}src=js;js="var $module = (function(){\n"+js;var prefix="locals_";js+="return "+prefix;js+=module.__name__.replace(/\./g,"_")+"})(__BRYTHON__)\n"+"return $module";var module_id=prefix+module.__name__.replace(/\./g,"_");var mod=new Function(module_id,js)(module)}catch(err){err.$frame_obj=err.$frame_obj||$B.frame_obj;if($B.get_option("debug",err)>2){console.log(err+" for module "+module.__name__);console.log("module",module);console.log(root);if($B.get_option("debug",err)>1){console.log($B.format_indent(js,0))}for(let attr in err){console.log(attr,err[attr])}console.log("message: "+err.$message);console.log("filename: "+err.fileName);console.log("linenum: "+err.lineNumber);console.log(js.split("\n").slice(err.lineNumber-3,err.lineNumber+3).join("\n"));console.log(err.stack)}throw err}var imports=Object.keys(root.imports).join(",");try{for(let attr in mod){module[attr]=mod[attr]}module.__initializing__=false;$B.imported[module.__name__]=module;return{content:src,name:mod_name,imports:imports,is_package:module.$is_package,path:path,timestamp:$B.timestamp,source_ts:module.__spec__.loader_state.timestamp}}catch(err){console.log(""+err+" "+" for module "+module.__name__);for(let attr in err){console.log(attr+" "+err[attr])}if($B.get_option("debug")>0){console.log("line info "+__BRYTHON__.line_info)}throw err}}$B.run_py=run_py;$B.run_js=run_js;var ModuleSpec=$B.make_class("ModuleSpec",(function(fields){fields.__class__=ModuleSpec;return fields}));ModuleSpec.__str__=ModuleSpec.__repr__=function(self){var res=`ModuleSpec(name='${self.name}', `+`loader=${_b_.str.$factory(self.loader)}, `+`origin='${self.origin}'`;if(self.submodule_search_locations!==_b_.None){res+=`, submodule_search_locations=`+`${_b_.str.$factory(self.submodule_search_locations)}`}return res+")"};$B.set_func_names(ModuleSpec,"builtins");function parent_package(mod_name){var parts=mod_name.split(".");parts.pop();return parts.join(".")}var VFSFinder=$B.make_class("VFSFinder",(function(){return{__class__:VFSFinder}}));VFSFinder.find_spec=function(cls,fullname){var stored,is_package,timestamp;if(!$B.use_VFS){return _b_.None}stored=$B.VFS[fullname];if(stored===undefined){return _b_.None}is_package=stored[3]||false;timestamp=stored.timestamp;if(stored){var is_builtin=$B.builtin_module_names.indexOf(fullname)>-1;return ModuleSpec.$factory({name:fullname,loader:VFSLoader.$factory(),origin:is_builtin?"built-in":"brython_stdlib",submodule_search_locations:is_package?$B.$list([]):_b_.None,loader_state:{stored:stored,timestamp:timestamp},cached:_b_.None,parent:is_package?fullname:parent_package(fullname),has_location:_b_.False})}};$B.set_func_names(VFSFinder,"");for(let method in VFSFinder){if(typeof VFSFinder[method]=="function"){VFSFinder[method]=_b_.classmethod.$factory(VFSFinder[method])}}const VFSLoader=$B.make_class("VFSLoader",(function(){return{__class__:VFSLoader}}));VFSLoader.create_module=function(){return _b_.None};VFSLoader.exec_module=function(self,modobj){var stored=modobj.__spec__.loader_state.stored,timestamp=modobj.__spec__.loader_state.timestamp;var ext=stored[0],module_contents=stored[1],imports=stored[2];modobj.$is_package=stored[3]||false;var path="VFS."+modobj.__name__;path+=modobj.$is_package?"/__init__.py":ext;modobj.__file__=path;$B.file_cache[modobj.__file__]=$B.VFS[modobj.__name__][1];$B.url2name[modobj.__file__]=modobj.__name__;if(ext==".js"){run_js(module_contents,modobj.__path__,modobj)}else if($B.precompiled.hasOwnProperty(modobj.__name__)){if($B.get_option("debug")>1){console.info("load",modobj.__name__,"from precompiled")}var parts=modobj.__name__.split(".");for(var i=0;i";mod.__package__=parent;mod.$is_package=true}else{let elts=parent.split(".");elts.pop();mod.__package__=elts.join(".")}mod.__file__=path;try{var parent_id=parent.replace(/\./g,"_"),prefix="locals_";mod_js+="return "+prefix+parent_id;var $module=new Function(prefix+parent_id,mod_js)(mod)}catch(err){if($B.get_option("debug")>1){console.log("error in module",mod);console.log(err);for(var k in err){console.log(k,err[k])}console.log(Object.keys($B.imported));console.log(modobj,"mod_js",mod_js)}throw err}for(var attr in $module){mod[attr]=$module[attr]}$module.__file__=path;if(i>0){$B.builtins.setattr($B.imported[parts.slice(0,i).join(".")],parts[i],$module)}}return $module}else{var mod_name=modobj.__name__;if($B.get_option("debug")>1){console.log("run Python code from VFS",mod_name)}var path=$B.brython_path+"/"+modobj.__file__;var record=run_py(module_contents,path,modobj);record.imports=imports.join(",");record.is_package=modobj.$is_package;record.timestamp=$B.timestamp;record.source_ts=timestamp;$B.precompiled[mod_name]=record.is_package?[record.content]:record.content;let elts=mod_name.split(".");if(elts.length>1){elts.pop()}if($B.get_page_option("indexeddb")&&$B.indexedDB&&$B.idb_name){var idb_cx=indexedDB.open($B.idb_name);idb_cx.onsuccess=function(evt){var db=evt.target.result,tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),request=store.put(record);request.onsuccess=function(){if($B.get_option("debug")>1){console.info(modobj.__name__,"stored in db")}};request.onerror=function(){console.info("could not store "+modobj.__name__)}}}}};$B.set_func_names(VFSLoader,"builtins");var StdlibStaticFinder=$B.make_class("StdlibStaticFinder",(function(){return{__class__:StdlibStaticFinder}}));StdlibStaticFinder.find_spec=function(self,fullname){if($B.stdlib&&$B.get_option("static_stdlib_import")){var address=$B.stdlib[fullname];if(address===undefined){var elts=fullname.split(".");if(elts.length>1){elts.pop();var $package=$B.stdlib[elts.join(".")];if($package&&$package[1]){address=["py"]}}}if(address!==undefined){var ext=address[0],is_pkg=address[1]!==undefined,path=$B.brython_path+(ext=="py"?"Lib/":"libs/")+fullname.replace(/\./g,"/"),metadata={ext:ext,is_package:is_pkg,path:path+(is_pkg?"/__init__.py":ext=="py"?".py":".js"),address:address},_module=Module.$factory(fullname);metadata.code=$download_module(_module,metadata.path);var res=ModuleSpec.$factory({name:fullname,loader:PathLoader.$factory(),origin:metadata.path,submodule_search_locations:is_pkg?$B.$list([path]):_b_.None,loader_state:metadata,cached:_b_.None,parent:is_pkg?fullname:parent_package(fullname),has_location:_b_.True});return res}}return _b_.None};$B.set_func_names(StdlibStaticFinder,"");for(let method in StdlibStaticFinder){if(typeof StdlibStaticFinder[method]=="function"){StdlibStaticFinder[method]=_b_.classmethod.$factory(StdlibStaticFinder[method])}}StdlibStaticFinder.$factory=function(){return{__class__:StdlibStaticFinder}};var PathFinder=$B.make_class("PathFinder",(function(){return{__class__:PathFinder}}));PathFinder.find_spec=function(cls,fullname,path){if($B.VFS&&$B.VFS[fullname]){return _b_.None}if($B.is_none(path)){path=get_info("path")}for(var i=0,li=path.length;i");for(let method in PathFinder){if(typeof PathFinder[method]=="function"){PathFinder[method]=_b_.classmethod.$factory(PathFinder[method])}}var PathEntryFinder=$B.make_class("PathEntryFinder",(function(path_entry,hint){return{__class__:PathEntryFinder,path_entry:path_entry,hint:hint}}));PathEntryFinder.find_spec=function(self,fullname){var loader_data={},notfound=true,hint=self.hint,base_path=self.path_entry+fullname.match(/[^.]+$/g)[0],modpaths=[],py_ext=$B.get_option("python_extension");var tryall=hint===undefined;if(tryall||hint=="py"){modpaths=modpaths.concat([[base_path+py_ext,"py",false],[base_path+"/__init__"+py_ext,"py",true]])}for(var j=0;notfound&&j-1){meta_path.splice(path_ix,1)}}for(var i=0,len=meta_path.length;i0;if(modobj==_b_.None){import_error(mod_name)}if(modobj===undefined){if($B.is_none(fromlist)){fromlist=[]}for(var i=0,modsep="",_mod_name="",len=parsed_name.length-1,__path__=_b_.None;i<=len;++i){var _parent_name=_mod_name;_mod_name+=modsep+parsed_name[i];modsep=".";modobj=$B.imported[_mod_name];if($test){console.log("iter",i,_mod_name,"\nmodobj",modobj,"\n__path__",__path__,Array.isArray(__path__));alert()}if(modobj==_b_.None){import_error(_mod_name)}else if(modobj===undefined){try{import_engine(_mod_name,__path__,from_stdlib)}catch(err){delete $B.imported[_mod_name];throw err}if($B.is_none($B.imported[_mod_name])){import_error(_mod_name)}else{if(_parent_name){_b_.setattr($B.imported[_parent_name],parsed_name[i],$B.imported[_mod_name])}}}else if($B.imported[_parent_name]&&$B.imported[_parent_name][parsed_name[i]]===undefined){_b_.setattr($B.imported[_parent_name],parsed_name[i],$B.imported[_mod_name])}if(i0){return $B.imported[mod_name]}else{let package_name=mod_name;while(parsed_name.length>1){var module=parsed_name.pop();package_name=parsed_name.join(".");if($B.imported[package_name]===undefined){$B.$import(package_name,[],{},locals);$B.imported[package_name][module]=$B.imported[mod_name];mod_name=module}}return $B.imported[package_name]}};$B.$import=function(mod_name,fromlist,aliases,locals){var test=false;if(test){console.log("import",mod_name,fromlist,aliases)}if(mod_name=="_frozen_importlib_external"){let alias=aliases[mod_name]||mod_name;$B.$import_from("importlib",["_bootstrap_external"],{_bootstrap_external:alias},0,locals);let _bootstrap=$B.imported.importlib._bootstrap,_bootstrap_external=$B.imported.importlib["_bootstrap_external"];_bootstrap_external._set_bootstrap_module(_bootstrap);_bootstrap._bootstap_external=_bootstrap_external;let _frozen_importlib=$B.imported._frozen_importlib;if(_frozen_importlib){_frozen_importlib._bootstrap_external=_bootstrap_external}return}var level=0,frame=$B.frame_obj.frame,current_module=frame[2],parts=current_module.split(".");while(mod_name.length>0&&mod_name.startsWith(".")){level++;mod_name=mod_name.substr(1);if(parts.length==0){throw _b_.ImportError.$factory("Parent module '' not loaded, "+"cannot perform relative import")}current_module=parts.join(".");parts.pop()}if(level>0){mod_name=current_module+(mod_name.length>0?"."+mod_name:"")}parts=mod_name.split(".");if(mod_name[mod_name.length-1]=="."){parts.pop()}var norm_parts=[],prefix=true;for(var p of parts){if(prefix&&p==""){var elt=norm_parts.pop();if(elt===undefined){throw _b_.ImportError.$factory("Parent module '' not loaded, "+"cannot perform relative import")}}else{prefix=false;norm_parts.push(p)}}mod_name=norm_parts.join(".");fromlist=fromlist===undefined?[]:fromlist;aliases=aliases===undefined?{}:aliases;locals=locals===undefined?{}:locals;if(test){console.log("step 2, mod_name",mod_name,"fromlist",fromlist)}if($B.get_option("debug")==10){console.log("$import "+mod_name);console.log("use VFS ? "+$B.use_VFS);console.log("use static stdlib paths ? "+$B.get_option("static_stdlib_import"))}var current_frame=$B.frame_obj.frame,_globals=current_frame[3],__import__=_globals["__import__"],globals=$B.obj_dict(_globals);if(__import__===undefined){__import__=$B.$__import__}var importer=typeof __import__=="function"?__import__:$B.$getattr(__import__,"__call__");if(test){console.log("use importer",importer,"mod_name",mod_name,"fromlist",fromlist)}var modobj=importer(mod_name,globals,undefined,fromlist,0);if(test){console.log("step 3, mod_name",mod_name,"fromlist",fromlist);console.log("modobj",modobj)}if(!fromlist||fromlist.length==0){let alias=aliases[mod_name];if(alias){locals[alias]=$B.imported[mod_name]}else{locals[norm_parts[0]]=modobj}}else{var __all__=fromlist,thunk={};if(fromlist&&fromlist[0]=="*"){if(test){console.log("import *",modobj)}__all__=$B.$getattr(modobj,"__all__",thunk);if(__all__!==thunk){aliases={}}}if(__all__===thunk){for(var attr in modobj){if(attr[0]!=="_"){locals[attr]=modobj[attr]}}}else{for(let name of __all__){var alias=aliases[name]||name;try{locals[alias]=$B.$getattr(modobj,name);if(locals[alias]&&locals[alias].$js_func){locals[alias]=locals[alias].$js_func}}catch($err1){if(!$B.is_exc($err1,[_b_.AttributeError])){throw $err1}try{$B.$getattr(__import__,"__call__")(mod_name+"."+name,globals,undefined,[],0);locals[alias]=$B.$getattr(modobj,name)}catch($err3){if(mod_name==="__future__"){var exc=_b_.SyntaxError.$factory("future feature "+name+" is not defined");throw exc}var $frame=[mod_name,modobj,mod_name,modobj],suggestion=$B.offer_suggestions_for_name_error({name:name},$frame);if($err3.$py_error){$err3.__class__=_b_.ImportError;$err3.args[0]=`cannot import name '${name}' `+`from '${mod_name}'`;if(modobj.__file__){$err3.args[0]+=` (${modobj.__file__})`}$err3.$suggestion=suggestion;throw $err3}if($B.get_option("debug")>1){console.log($err3);console.log($B.frame_obj.frame)}throw _b_.ImportError.$factory("cannot import name '"+name+"'")}}}}return locals}};$B.$import_from=function(module,names,aliases,level,locals){var current_module_name=$B.frame_obj.frame[2],parts=current_module_name.split("."),relative=level>0,current_module;if(relative){current_module=$B.imported[parts.join(".")];if(current_module===undefined){throw _b_.ImportError.$factory("attempted relative import with no known parent package")}if(!current_module.$is_package){if(parts.length==1){throw _b_.ImportError.$factory("attempted relative import with no known parent package")}else{parts.pop();current_module=$B.imported[parts.join(".")]}}while(level>0){current_module=$B.imported[parts.join(".")];if(!current_module.$is_package){throw _b_.ImportError.$factory("attempted relative import with no known parent package")}level--;parts.pop()}if(module){var submodule=current_module.__name__+"."+module;$B.$import(submodule,[],{},{});current_module=$B.imported[submodule]}if(names.length>0&&names[0]=="*"){for(var key in current_module){if(key.startsWith("$")||key.startsWith("_")){continue}locals[key]=current_module[key]}}else{for(var name of names){var alias=aliases[name]||name;if(current_module[name]!==undefined){locals[alias]=current_module[name]}else{var sub_module=current_module.__name__+"."+name;$B.$import(sub_module,[],{},{});locals[alias]=$B.imported[sub_module]}}}}else{$B.$import(module,names,aliases,locals)}};$B.import_all=function(locals,module){for(var attr in module){if("_$".indexOf(attr.charAt(0))==-1){locals[attr]=module[attr]}}};$B.$meta_path=[VFSFinder,StdlibStaticFinder,PathFinder];$B.finders={VFS:VFSFinder,stdlib_static:StdlibStaticFinder,path:PathFinder};function optimize_import_for_path(path,filetype){if(path.slice(-1)!="/"){path=path+"/"}var value=filetype=="none"?_b_.None:url_hook(path,filetype);$B.path_importer_cache[path]=value}var Loader={__class__:$B.$type,__mro__:[_b_.object],__name__:"Loader"};var _importlib_module={__class__:Module,__name__:"_importlib",Loader:Loader,VFSFinder:VFSFinder,StdlibStatic:StdlibStaticFinder,ImporterPath:PathFinder,UrlPathFinder:url_hook,optimize_import_for_path:optimize_import_for_path};_importlib_module.__repr__=_importlib_module.__str__=function(){return""};$B.imported["_importlib"]=_importlib_module})(__BRYTHON__);(function($B){var _b_=$B.builtins;var escape2cp=$B.escape2cp={b:"\b",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v"};$B.surrogates=function(s){var s1="",escaped=false;for(var char of s){if(escaped){var echar=escape2cp[char];if(echar!==undefined){s1+=echar}else{s1+="\\"+char}escaped=false}else if(char=="\\"){escaped=true}else{s1+=char}}var surrogates=[],j=0;for(var i=0,len=s1.length;i=65536){surrogates.push(j);i++}j++}return surrogates};$B.String=function(s){var srg=$B.surrogates(s);return srg.length==0?s:$B.make_String(s,srg)};$B.make_String=function(s,surrogates){var res=new String(s);res.__class__=str;res.surrogates=surrogates;return res};function pypos2jspos(s,pypos){if(s.surrogates===undefined){return pypos}var nb=0;while(s.surrogates[nb]' requires "+"string as left operand, not "+$B.class_name(item))}[_self,item]=to_string([_self,item]);return _self.includes(item)};str.__delitem__=function(){throw _b_.TypeError.$factory("'str' object doesn't support item deletion")};str.__dir__=_b_.object.__dir__;str.__eq__=function(_self,other){if($B.$isinstance(other,str)){[_self,other]=to_string([_self,other]);return _self+""==other+""}return _b_.NotImplemented};function preformat(_self,fmt){if(fmt.empty){return _b_.str.$factory(_self)}if(fmt.type&&fmt.type!="s"){throw _b_.ValueError.$factory("Unknown format code '"+fmt.type+"' for object of type 'str'")}return _self}str.__format__=function(_self,format_spec){[_self,format_spec]=to_string([_self,format_spec]);var fmt=new $B.parse_format_spec(format_spec,_self);if(fmt.sign!==undefined){throw _b_.ValueError.$factory("Sign not allowed in string format specifier")}if(fmt.precision){_self=_self.substr(0,fmt.precision)}fmt.align=fmt.align||"<";return $B.format_width(preformat(_self,fmt),fmt)};str.__getitem__=function(_self,arg){_self=to_string(_self);if($B.$isinstance(arg,_b_.int)){var len=str.__len__(_self);var pos=arg;if(arg<0){pos+=len}if(pos>=0&&pos=65536){return $B.String(_self.substr(jspos,2))}else{return _self[jspos]}}throw _b_.IndexError.$factory("string index out of range")}if($B.$isinstance(arg,_b_.slice)){return _b_.str.$getitem_slice(_self,arg)}if($B.$isinstance(arg,_b_.bool)){return _self.__getitem__(_b_.int.$factory(arg))}throw _b_.TypeError.$factory("string indices must be integers")};str.$getitem_slice=function(_self,slice){var len=str.__len__(_self),s=_b_.slice.$conv_for_seq(slice,len),start=pypos2jspos(_self,s.start),stop=pypos2jspos(_self,s.stop),step=s.step;var res="";if(step>0){if(stop<=start){return""}for(let i=start;i=start){return""}for(let i=start;i>stop;i+=step){res+=_self[i]}}return $B.String(res)};var prefix=2,suffix=3;str.$getnewargs=function(self){return $B.fast_tuple([to_string(self)])};str.__getnewargs__=function(){return str.$getnewargs($B.single_arg("__getnewargs__","self",arguments))};str.__hash__=function(_self){var s=to_string(_self);for(var i=0,h=0,len=s.length;imax_precision){throw _b_.OverflowError.$factory("precision too large")}var s;if(val.__class__===$B.long_int){s=$B.long_int.to_base(val,10)}else{s=val.toString()}if(precision-s.length>max_repeat){throw _b_.OverflowError.$factory("precision too large")}if(s[0]==="-"){return"-"+"0".repeat(Math.max(0,precision-s.length+1))+s.slice(1)}return"0".repeat(Math.max(0,precision-s.length))+s};var format_float_precision=function(val,upper,flags,modifier){var precision=flags.precision;if(isFinite(val)){return modifier(val,precision,flags,upper)}if(val===Infinity){val="inf"}else if(val===-Infinity){val="-inf"}else{val="nan"}if(upper){return val.toUpperCase()}return val};var format_sign=function(val,flags){if(flags.sign){if(val>=0||isNaN(val)||val===Number.POSITIVE_INFINITY){return"+"}}else if(flags.space){if(val>=0||isNaN(val)){return" "}}return""};var str_format=function(val,flags){flags.pad_char=" ";return format_padding(str.$factory(val),flags)};var num_format=function(val,flags){number_check(val,flags);if($B.$isinstance(val,_b_.float)){val=parseInt(val.value)}else if(!$B.$isinstance(val,_b_.int)){val=parseInt(val)}else if($B.$isinstance(val,_b_.bool)){val=val?1:0}var s=format_int_precision(val,flags);if(flags.pad_char==="0"){if(val<0){s=s.substring(1);return"-"+format_padding(s,flags,true)}var sign=format_sign(val,flags);if(sign!==""){return sign+format_padding(s,flags,true)}}return format_padding(format_sign(val,flags)+s,flags)};var repr_format=function(val,flags){flags.pad_char=" ";return format_padding(_b_.repr(val),flags)};var ascii_format=function(val,flags,type){flags.pad_char=" ";var ascii;if(type=="bytes"){var repr=_b_.repr(val);ascii=_b_.str.encode(repr,"ascii","backslashreplace");ascii=_b_.bytes.decode(ascii,"ascii")}else{ascii=_b_.ascii(val)}return format_padding(ascii,flags)};var _float_helper=function(val,flags){number_check(val,flags);if(flags.precision===undefined){if(!flags.decimal_point){flags.precision=6}else{flags.precision=0}}else{flags.precision=parseInt(flags.precision,10);validate_precision(flags.precision)}return $B.$isinstance(val,_b_.int)?val:val.value};var validate_precision=function(precision){if(precision>20){precision=20}};function handle_special_values(value,upper){var special;if(isNaN(value)){special=upper?"NAN":"nan"}else if(value==Number.POSITIVE_INFINITY){special=upper?"INF":"inf"}else if(value==Number.NEGATIVE_INFINITY){special=upper?"-INF":"-inf"}return special}var floating_point_format=function(val,upper,flags){val=_float_helper(val,flags);var special=handle_special_values(val,upper);if(special){return format_padding(format_sign(val,flags)+special,flags)}var p=flags.precision;if(p==0){p=1}var exp_format=val.toExponential(p-1),e_index=exp_format.indexOf("e"),exp=parseInt(exp_format.substr(e_index+1)),res;function remove_zeros(v){if(flags.alternate){return v}if(v.indexOf(".")>-1){while(v.endsWith("0")){v=v.substr(0,v.length-1)}if(v.endsWith(".")){v=v.substr(0,v.length-1)}}return v}if(-4<=exp&&exp-1){return BigInt(v).toString()}const mul=Math.pow(10,d);var is_neg=v<0;if(is_neg){v=-v}var res_floor=(Math.floor(v*mul)/mul).toFixed(d),res_ceil=(Math.ceil(v*mul)/mul).toFixed(d),res;if(v-res_floor==res_ceil-v){var last=res_floor[res_floor.length-1];res=last.match(/[02468]/)?res_floor:res_ceil}else{res=v-res_floor1){mant+="."+parts[0].substr(1)+(parts[1]||"")}else if(parts[1]){mant+="."+parts[1]}}mant=parseFloat(mant);mant=roundDownToFixed(parseFloat(mant),precision);if(parseFloat(mant)==10){parts=mant.split(".");parts[0]="1";mant=parts.join(".");exp=parseInt(exp)+(exp_sign=="+"?1:-1);if(exp==0){exp_sign="+"}}if(flags.alternate&&mant.indexOf(".")==-1){mant+="."}if(exp.toString().length==1){exp="0"+exp}return`${is_neg?"-":""}${mant}${upper?"E":"e"}${exp_sign}${exp}`};var floating_point_exponential_format=function(val,upper,flags){val=_float_helper(val,flags);return format_padding(format_sign(val,flags)+format_float_precision(val,upper,flags,_floating_exp_helper),flags)};$B.formatters={floating_point_format:floating_point_format,floating_point_decimal_format:floating_point_decimal_format,floating_point_exponential_format:floating_point_exponential_format};var signed_hex_format=function(val,upper,flags){var ret;if(!$B.$isinstance(val,_b_.int)){throw _b_.TypeError.$factory(`%X format: an integer is required, not ${$B.class_name(val)}`)}else if($B.$isinstance(val,_b_.bool)){val=val?1:0}if(val.__class__===$B.long_int){ret=val.value.toString(16)}else{ret=parseInt(val);ret=ret.toString(16)}ret=format_int_precision(ret,flags);if(upper){ret=ret.toUpperCase()}if(flags.pad_char==="0"){if(val<0){ret=ret.substring(1);ret="-"+format_padding(ret,flags,true)}var sign=format_sign(val,flags);if(sign!==""){ret=sign+format_padding(ret,flags,true)}}if(flags.alternate){if(ret.charAt(0)==="-"){if(upper){ret="-0X"+ret.slice(1)}else{ret="-0x"+ret.slice(1)}}else{if(upper){ret="0X"+ret}else{ret="0x"+ret}}}return format_padding(format_sign(val,flags)+ret,flags)};var octal_format=function(val,flags){number_check(val,flags);var ret;if(val.__class__===$B.long_int){ret=$B.long_int.to_base(8)}else{ret=parseInt(val);ret=ret.toString(8)}ret=format_int_precision(ret,flags);if(flags.pad_char==="0"){if(val<0){ret=ret.substring(1);ret="-"+format_padding(ret,flags,true)}var sign=format_sign(val,flags);if(sign!==""){ret=sign+format_padding(ret,flags,true)}}if(flags.alternate){if(ret.charAt(0)==="-"){ret="-0o"+ret.slice(1)}else{ret="0o"+ret}}return format_padding(ret,flags)};function series_of_bytes(val,flags){if(val.__class__&&val.__class__.$buffer_protocol){var it=_b_.iter(val),ints=[];while(true){try{ints.push(_b_.next(it))}catch(err){if(err.__class__===_b_.StopIteration){var b=_b_.bytes.$factory(ints);return format_padding(_b_.bytes.decode(b,"ascii"),flags)}throw err}}}else{try{var bytes_obj=$B.$getattr(val,"__bytes__")();return format_padding(_b_.bytes.decode(bytes_obj),flags)}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("%b does not accept '"+$B.class_name(val)+"'")}throw err}}}var single_char_format=function(val,flags,type){if(type=="bytes"){if($B.$isinstance(val,_b_.int)){if(val.__class__===$B.long_int||val<0||val>255){throw _b_.OverflowError.$factory("%c arg not in range(256)")}}else if($B.$isinstance(val,[_b_.bytes,_b_.bytearray])){if(val.source.length>1){throw _b_.TypeError.$factory("%c requires an integer in range(256) or a single byte")}val=val.source[0]}}else{if($B.$isinstance(val,_b_.str)){if(_b_.str.__len__(val)==1){return val}throw _b_.TypeError.$factory("%c requires int or char")}else if(!$B.$isinstance(val,_b_.int)){throw _b_.TypeError.$factory("%c requires int or char")}if(val.__class__===$B.long_int&&(val.value<0||val.value>=1114112)||(val<0||val>=1114112)){throw _b_.OverflowError.$factory("%c arg not in range(0x110000)")}}return format_padding(_b_.chr(val),flags)};var num_flag=function(c,flags){if(c==="0"&&!flags.padding&&!flags.decimal_point&&!flags.left){flags.pad_char="0";return}if(!flags.decimal_point){flags.padding=(flags.padding||"")+c}else{flags.precision=(flags.precision||"")+c}};var decimal_point_flag=function(val,flags){if(flags.decimal_point){throw new UnsupportedChar}flags.decimal_point=true};var neg_flag=function(val,flags){flags.pad_char=" ";flags.left=true};var space_flag=function(val,flags){flags.space=true};var sign_flag=function(val,flags){flags.sign=true};var alternate_flag=function(val,flags){flags.alternate=true};var char_mapping={b:series_of_bytes,s:str_format,d:num_format,i:num_format,u:num_format,o:octal_format,r:repr_format,a:ascii_format,g:function(val,flags){return floating_point_format(val,false,flags)},G:function(val,flags){return floating_point_format(val,true,flags)},f:function(val,flags){return floating_point_decimal_format(val,false,flags)},F:function(val,flags){return floating_point_decimal_format(val,true,flags)},e:function(val,flags){return floating_point_exponential_format(val,false,flags)},E:function(val,flags){return floating_point_exponential_format(val,true,flags)},x:function(val,flags){return signed_hex_format(val,false,flags)},X:function(val,flags){return signed_hex_format(val,true,flags)},c:single_char_format,0:function(val,flags){return num_flag("0",flags)},1:function(val,flags){return num_flag("1",flags)},2:function(val,flags){return num_flag("2",flags)},3:function(val,flags){return num_flag("3",flags)},4:function(val,flags){return num_flag("4",flags)},5:function(val,flags){return num_flag("5",flags)},6:function(val,flags){return num_flag("6",flags)},7:function(val,flags){return num_flag("7",flags)},8:function(val,flags){return num_flag("8",flags)},9:function(val,flags){return num_flag("9",flags)},"-":neg_flag," ":space_flag,"+":sign_flag,".":decimal_point_flag,"#":alternate_flag};var UnsupportedChar=function(){this.name="UnsupportedChar"};const conversion_flags="#0- +",length_modifiers="hlL",conversion_types="diouxXeEfFgGcrsa";function parse_mod_format(s,type,pos){var flags={pad_char:" "},len=s.length,start_pos=pos,mo;pos++;while(pos-1){flags.conversion_flag=char;if(char=="#"){flags.alternate=true}else if(char=="-"){flags.left=true}else if(char=="+"){flags.sign="+"}else if(char=="0"){flags.pad_char="0"}else if(char==" "){flags.space=true}pos++}else if(char=="*"){flags.padding="*";pos++}else if(mo=/^\d+/.exec(s.substr(pos))){flags.padding=mo[0];pos+=mo[0].length}else if(char=="."){pos++;if(s[pos]=="*"){flags.precision="*";pos++}else if(mo=/^\d+/.exec(s.substr(pos))){flags.precision=mo[0];pos+=mo[0].length}else{flags.precision="0"}}else if(length_modifiers.indexOf(char)>-1){flags.length_modifier=char;pos++}else if(conversion_types.indexOf(char)>-1||char=="b"&&type=="bytes"){if(type=="bytes"){if(char=="s"){char="b"}else if(char=="r"){char="a"}}flags.conversion_type=char;flags.end=pos;flags.string=s.substring(start_pos,pos+1);if(flags.left&&flags.pad_char=="0"){flags.pad_char=" "}return flags}else{throw _b_.ValueError.$factory(`invalid character in format: ${char}`)}}throw _b_.ValueError.$factory("invalid format")}function is_mapping(obj){return _b_.hasattr(obj,"keys")&&_b_.hasattr(obj,"__getitem__")}$B.printf_format=function(s,type,args){var argpos=null,getitem;if($B.$isinstance(args,_b_.tuple)){argpos=0}else{getitem=$B.$getattr(args,"__getitem__",_b_.None)}var ret="",nbph=0,pos=0,len=s.length;while(pos1){if(!$B.$isinstance(args,_b_.tuple)&&!is_mapping(args)){throw _b_.TypeError.$factory("not enough arguments for format string")}}var fmt=parse_mod_format(s,type,pos);pos=fmt.end+1;if(fmt.padding=="*"){if(args[argpos]===undefined){throw _b_.ValueError.$factory("no value for field width *")}fmt.padding=args[argpos];argpos++}if(fmt.precision=="*"){if(args[argpos]===undefined){throw _b_.ValueError.$factory("no value for precision *")}fmt.precision=args[argpos];argpos++}var func=char_mapping[fmt.conversion_type],value;if(fmt.mapping_key!==undefined){value=getitem(fmt.mapping_key)}else{if(argpos===null){value=args}else{value=args[argpos];if(value===undefined){throw _b_.TypeError.$factory("not enough arguments for format string")}argpos++}}ret+=func(value,fmt,type)}}if(argpos!==null){if(args.length>argpos){throw _b_.TypeError.$factory("not enough arguments for format string")}else if(args.length=127&&cp<160){cp=cp.toString(16);if(cp.length<2){cp="0"+cp}repl+="\\x"+cp}else if(cp>=768&&cp<=879){repl+="​"+chars[i]+" "}else if(cp.toString(16)=="feff"){repl+="\\ufeff"}else{repl+=chars[i]}}var res=repl;if(res.search('"')==-1&&res.search("'")==-1){return"'"+res+"'"}else if(_self.search('"')==-1){return'"'+res+'"'}var qesc=new RegExp("'","g");res="'"+res.replace(qesc,"\\'")+"'";return res};str.__rmod__=function(){var $=$B.args("__rmod__",2,{self:null,other:null},["self","other"],arguments,{},null,null);if(!$B.$isinstance($.other,str)){return _b_.NotImplemented}return str.__mod__($.other,$.self)};str.__rmul__=function(_self,other){_self=to_string(_self);if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other);var res="";while(other>0){res+=_self;other--}return res}return _b_.NotImplemented};str.__setattr__=function(_self,attr,value){if(typeof _self==="string"){if(str.hasOwnProperty(attr)){throw _b_.AttributeError.$factory("'str' object attribute '"+attr+"' is read-only")}else{throw _b_.AttributeError.$factory("'str' object has no attribute '"+attr+"'")}}_b_.dict.$setitem(_self.__dict__,attr,value);return _b_.None};str.__setitem__=function(){throw _b_.TypeError.$factory("'str' object does not support item assignment")};var combining=[];for(var cp=768;cp<=879;cp++){combining.push(String.fromCharCode(cp))}var combining_re=new RegExp("("+combining.join("|")+")","g");str.__str__=function(_self){_self=to_string(_self);var repl="",chars=to_chars(_self);if(chars.length==_self.length){return _self.replace(combining_re,"​$1")}for(var i=0;i=768&&cp<=879){repl+="​"+chars[i]}else{repl+=chars[i]}}return repl};var body=`var _b_ = __BRYTHON__.builtins\nif(typeof other !== typeof _self){\n return _b_.NotImplemented}else if(typeof _self == "string"){\n return _self > other}else{\n return _self.$brython_value > other.$brython_value}`;var comps={">":"gt",">=":"ge","<":"lt","<=":"le"};for(var op in comps){str[`__${comps[op]}__`]=Function("_self","other",body.replace(/>/gm,op))}str.capitalize=function(){var $=$B.args("capitalize",1,{self:self},["self"],arguments,{},null,null),_self=to_string($.self);if(_self.length==0){return""}return _self.charAt(0).toUpperCase()+_self.substr(1).toLowerCase()};str.casefold=function(){var $=$B.args("casefold",1,{self:self},["self"],arguments,{},null,null),res="",char,cf,_self=to_string($.self),chars=to_chars(_self);for(var i=0,len=chars.length;i=0){n++;pos+=sub.length}else{break}}return n};str.encode=function(){var $=$B.args("encode",3,{self:null,encoding:null,errors:null},["self","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null),_self=to_string($.self);if($.encoding=="rot13"||$.encoding=="rot_13"){var res="";for(var i=0,len=_self.length;i0){res+=" ";col++}break;case"\r":case"\n":res+=car;col=0;break;default:res+=car;col++;break}pos++}return res};str.find=function(){var $=$B.args("str.find",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:null},null,null),_self,sub;check_str($.sub);normalize_start_end($);[_self,sub]=to_string([$.self,$.sub]);var len=str.__len__(_self),sub_len=str.__len__(sub);if(sub_len==0&&$.start==len){return len}if(len+sub_len==0){return-1}var js_start=pypos2jspos(_self,$.start),js_end=pypos2jspos(_self,$.end),ix=_self.slice(js_start,js_end).indexOf(sub);if(ix==-1){return-1}return jspos2pypos(_self,js_start+ix)};$B.parse_format=function(fmt_string){var elts=fmt_string.split(":"),name,conv,spec,name_ext=[];if(elts.length==1){name=fmt_string}else{name=elts[0];spec=elts.splice(1).join(":")}elts=name.split("!");if(elts.length>1){name=elts[0];conv=elts[1]}if(name!==undefined){function name_repl(match){name_ext.push(match);return""}var name_ext_re=/\.[_a-zA-Z][_a-zA-Z0-9]*|\[[_a-zA-Z][_a-zA-Z0-9]*\]|\[[0-9]+\]/g;name=name.replace(name_ext_re,name_repl)}return{name:name,name_ext:name_ext,conv:conv,spec:spec||"",string:fmt_string}};$B.split_format=function(s){var pos=0,_len=s.length,car,text="",parts=[],rank=0;while(pos<_len){car=s.charAt(pos);if(car=="{"&&s.charAt(pos+1)=="{"){text+="{";pos+=2}else if(car=="}"&&s.charAt(pos+1)=="}"){text+="}";pos+=2}else if(car=="{"){parts.push(text);var end=pos+1,nb=1;while(end<_len){if(s.charAt(end)=="{"){nb++;end++}else if(s.charAt(end)=="}"){nb--;end++;if(nb==0){var fmt_string=s.substring(pos+1,end-1);var fmt_obj=$B.parse_format(fmt_string);fmt_obj.raw_name=fmt_obj.name;fmt_obj.raw_spec=fmt_obj.spec;if(!fmt_obj.name){fmt_obj.name=rank+"";rank++}if(fmt_obj.spec!==undefined){function replace_nested(name,key){if(key==""){return"{"+rank+++"}"}return"{"+key+"}"}fmt_obj.spec=fmt_obj.spec.replace(/\{(.*?)\}/g,replace_nested)}parts.push(fmt_obj);text="";break}}else{end++}}if(nb>0){throw _b_.ValueError.$factory("wrong format "+s)}pos=end}else{text+=car;pos++}}if(text){parts.push(text)}return parts};str.format=function(){var last_arg=$B.last(arguments),$,mapping,getitem;if(last_arg.$nat=="mapping"){mapping=last_arg.mapping;getitem=$B.$getattr(mapping,"__getitem__");var args=[];for(let i=0,len=arguments.length-1;i-1){let pos=parseInt(fmt.name);value=_b_.tuple.__getitem__($.$args,pos)}else{value=getitem(fmt.name)}for(var j=0;j-1){key=parseInt(key)}value=$B.$getattr(value,"__getitem__")(key)}}if(fmt.conv=="a"){value=_b_.ascii(value)}else if(fmt.conv=="r"){value=_b_.repr(value)}else if(fmt.conv=="s"){value=_b_.str.$factory(value)}if(value.$is_class||value.$factory){res+=value.__class__.__format__(value,fmt.spec)}else{res+=$B.$getattr(value,"__format__")(fmt.spec)}}return res};str.format_map=function(){var $=$B.args("format_map",2,{self:null,mapping:null},["self","mapping"],arguments,{},null,null),_self=to_string($.self);return str.format(_self,{$nat:"mapping",mapping:$.mapping})};str.index=function(){var res=str.find.apply(null,arguments);if(res===-1){throw _b_.ValueError.$factory("substring not found")}return res};str.isascii=function(){var $=$B.args("isascii",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);for(var i=0,len=_self.length;i127){return false}}return true};var unicode_categories_contain_character=function(categories,cp){for(var cat of categories){console.log(cat,cp);if($B.in_unicode_category(cat,cp)){return true}}return false};var alpha_categories=["Ll","Lu","Lm","Lt","Lo"];var alnum_categories=["Ll","Lu","Lm","Lt","Lo","Nd"];str.isalnum=function(){var $=$B.args("isalnum",1,{self:null},["self"],arguments,{},null,null);var _self=to_string($.self);if(_self.length==0){return false}for(var char of _self){if(!unicode_categories_contain_character(alnum_categories,_b_.ord(char))){return false}}return true};str.isalpha=function(){var $=$B.args("isalpha",1,{self:null},["self"],arguments,{},null,null);var _self=to_string($.self);if(_self.length==0){return false}for(var char of _self){if(!unicode_categories_contain_character(alpha_categories,_b_.ord(char))){return false}}return true};str.isdecimal=function(){var $=$B.args("isdecimal",1,{self:null},["self"],arguments,{},null,null),cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if(!$B.in_unicode_category("Nd",cp)){return false}}return _self.length>0};str.isdigit=function(){var $=$B.args("isdigit",1,{self:null},["self"],arguments,{},null,null),cp,_self=to_string($.self);for(var char of _self){if(/\p{Nd}/u.test(char)){continue}cp=_b_.ord(char);if(!$B.in_unicode_category("No_digits",cp)){return false}}return _self.length>0};str.isidentifier=function(){var $=$B.args("isidentifier",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);if(_self.length==0){return false}var chars=to_chars(_self);if(!$B.is_XID_Start(_b_.ord(chars[0]))){return false}else{for(var char of chars){var cp=_b_.ord(char);if(!$B.is_XID_Continue(cp)){return false}}}return true};str.islower=function(){var $=$B.args("islower",1,{self:null},["self"],arguments,{},null,null),has_cased=false,cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if($B.in_unicode_category("Ll",cp)){has_cased=true;continue}else if($B.in_unicode_category("Lu",cp)||$B.in_unicode_category("Lt",cp)){return false}}return has_cased};const numeric_re=/\p{Nd}|\p{Nl}|\p{No}/u;str.isnumeric=function(){var $=$B.args("isnumeric",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);for(var char of _self){if(!numeric_re.test(char)&&!$B.in_unicode_category("Lo_numeric",_b_.ord(char))){return false}}return _self.length>0};var unprintable_re=/\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}|\p{Zl}|\p{Zp}|\p{Zs}/u;str.isprintable=function(){var $=$B.args("isprintable",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);for(var char of _self){if(char==" "){continue}if(unprintable_re.test(char)){return false}}return true};str.isspace=function(){var $=$B.args("isspace",1,{self:null},["self"],arguments,{},null,null),cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if(!$B.in_unicode_category("Zs",cp)&&$B.unicode_bidi_whitespace.indexOf(cp)==-1){return false}}return _self.length>0};str.istitle=function(){var $=$B.args("istitle",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);return _self.length>0&&str.title(_self)==_self};str.isupper=function(){var $=$B.args("islower",1,{self:null},["self"],arguments,{},null,null),is_upper=false,cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if($B.in_unicode_category("Lu",cp)){is_upper=true;continue}else if($B.in_unicode_category("Ll",cp)||$B.in_unicode_category("Lt",cp)){return false}}return is_upper};str.join=function(){var $=$B.args("join",2,{self:null,iterable:null},["self","iterable"],arguments,{},null,null),_self=to_string($.self);var iterable=_b_.iter($.iterable),res=[],count=0;while(1){try{var obj2=_b_.next(iterable);if(!$B.$isinstance(obj2,str)){throw _b_.TypeError.$factory("sequence item "+count+": expected str instance, "+$B.class_name(obj2)+" found")}res.push(obj2)}catch(err){if($B.$isinstance(err,_b_.StopIteration)){break}else{throw err}}}return res.join(_self)};str.ljust=function(){var $=$B.args("ljust",3,{self:null,width:null,fillchar:null},["self","width","fillchar"],arguments,{fillchar:" "},null,null),_self=to_string($.self),len=str.__len__(_self);if($.width<=len){return _self}return _self+$.fillchar.repeat($.width-len)};str.lower=function(){var $=$B.args("lower",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);return _self.toLowerCase()};str.lstrip=function(){var $=$B.args("lstrip",2,{self:null,chars:null},["self","chars"],arguments,{chars:_b_.None},null,null),_self=$.self,chars=$.chars;if(chars===_b_.None){return _self.trimStart()}[_self,chars]=to_string([_self,chars]);while(_self.length>0){var flag=false;for(var char of chars){if(_self.startsWith(char)){_self=_self.substr(char.length);flag=true;break}}if(!flag){return $.self.surrogates?$B.String(_self):_self}}return""};str.maketrans=function(){var $=$B.args("maketrans",3,{x:null,y:null,z:null},["x","y","z"],arguments,{y:null,z:null},null,null);var _t=$B.empty_dict();if($.y===null&&$.z===null){if(!$B.$isinstance($.x,_b_.dict)){throw _b_.TypeError.$factory("maketrans only argument must be a dict")}var items=_b_.list.$factory(_b_.dict.items($.x));for(let i=0,len=items.length;i0&&str.endswith(_self,suffix)){return _self.substr(0,_self.length-suffix.length)}return _self.substr(0)};str.replace=function(){var $=$B.args("replace",4,{self:null,old:null,new:null,count:null},["self","old","new","count"],arguments,{count:-1},null,null),count=$.count,_self=$.self,old=$.old,_new=$.new;check_str(old,"replace() argument 1 ");check_str(_new,"replace() argument 2 ");if(!$B.$isinstance(count,[_b_.int,_b_.float])){throw _b_.TypeError.$factory("'"+$B.class_name(count)+"' object cannot be interpreted as an integer")}else if($B.$isinstance(count,_b_.float)){throw _b_.TypeError.$factory("integer argument expected, got float")}if(count==0){return _self}if(count.__class__==$B.long_int){count=parseInt(count.value)}[old,_new]=to_string([old,_new]);var elts;if(old==""){if(_new==""){return _self}if(_self==""){return _new}elts=_self.split("");if(count>-1&&elts.length>=count){var rest=elts.slice(count).join("");return _new+elts.slice(0,count).join(_new)+rest}else{return _new+elts.join(_new)+_new}}else{elts=str.split(_self,old,count)}var res=_self,pos=-1;if(old.length==0){res=_new;for(var i=0;i0){pos=res.indexOf(old,pos);if(pos<0){break}res=res.substr(0,pos)+_new+res.substr(pos+old.length);pos=pos+_new.length;count--}return res};str.rfind=function(){var $=$B.args("rfind",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:null},null,null),_self,sub;normalize_start_end($);check_str($.sub);[_self,sub]=to_string([$.self,$.sub]);var len=str.__len__(_self),sub_len=str.__len__(sub);if(sub_len==0){if($.js_start>len){return-1}else{return str.__len__(_self)}}var js_start=pypos2jspos(_self,$.start),js_end=pypos2jspos(_self,$.end),ix=_self.substring(js_start,js_end).lastIndexOf(sub);if(ix==-1){return-1}return jspos2pypos(_self,js_start+ix)-$.start};str.rindex=function(){var res=str.rfind.apply(null,arguments);if(res==-1){throw _b_.ValueError.$factory("substring not found")}return res};str.rjust=function(){var $=$B.args("rjust",3,{self:null,width:null,fillchar:null},["self","width","fillchar"],arguments,{fillchar:" "},null,null),_self=to_string($.self);var len=str.__len__(_self);if($.width<=len){return _self}return $B.String($.fillchar.repeat($.width-len)+_self)};str.rpartition=function(self,sep){var $=$B.args("rpartition",2,{self:null,sep:null},["self","sep"],arguments,{},null,null),_self;check_str($.sep);[_self,sep]=[$.self,$.sep];_self=reverse(_self),sep=reverse(sep);var items=str.partition(_self,sep).reverse();for(var i=0;i0){var flag=false;for(var char of chars){if(_self.endsWith(char)){_self=_self.substr(0,_self.length-char.length);flag=true;break}}if(!flag){return _self.surrogates?$B.String(_self):_self}}return""};str.split=function(){var $=$B.args("split",3,{self:null,sep:null,maxsplit:null},["self","sep","maxsplit"],arguments,{sep:_b_.None,maxsplit:-1},null,null),maxsplit=$.maxsplit,sep=$.sep,pos=0,_self=to_string($.self);if(maxsplit.__class__===$B.long_int){maxsplit=parseInt(maxsplit.value)}if(sep==""){throw _b_.ValueError.$factory("empty separator")}if(sep===_b_.None){let res=[];while(pos<_self.length&&_self.charAt(pos).search(/\s/)>-1){pos++}if(pos===_self.length-1){return $B.$list([_self])}let name="";while(1){if(_self.charAt(pos).search(/\s/)==-1){if(name==""){name=_self.charAt(pos)}else{name+=_self.charAt(pos)}}else{if(name!==""){res.push(name);if(maxsplit!==-1&&res.length==maxsplit+1){res.pop();res.push(name+_self.substr(pos));return res}name=""}}pos++;if(pos>_self.length-1){if(name){res.push(name)}break}}return $B.$list(res.map($B.String))}else{sep=to_string(sep);let res=[],s="",seplen=sep.length;if(maxsplit==0){return $B.$list([$.self])}while(pos<_self.length){if(_self.substr(pos,seplen)==sep){res.push(s);pos+=seplen;if(maxsplit>-1&&res.length>=maxsplit){res.push(_self.substr(pos));return res.map($B.String)}s=""}else{s+=_self.charAt(pos);pos++}}res.push(s);return $B.$list(res.map($B.String))}};str.splitlines=function(){var $=$B.args("splitlines",2,{self:null,keepends:null},["self","keepends"],arguments,{keepends:false},null,null);if(!$B.$isinstance($.keepends,[_b_.bool,_b_.int])){throw _b_.TypeError("integer argument expected, got "+$B.get_class($.keepends).__name)}var keepends=_b_.int.$factory($.keepends),res=$B.$list([]),start=0,pos=0,_self=to_string($.self);if(!_self.length){return res}while(pos<_self.length){if(_self.substr(pos,2)=="\r\n"){res.push(_self.slice(start,keepends?pos+2:pos));start=pos=pos+2}else if(_self[pos]=="\r"||_self[pos]=="\n"){res.push(_self.slice(start,keepends?pos+1:pos));start=pos=pos+1}else{pos++}}if(start<_self.length){res.push(_self.slice(start))}return $B.$list(res.map($B.String))};str.startswith=function(){var $=$B.args("startswith",4,{self:null,prefix:null,start:null,end:null},["self","prefix","start","end"],arguments,{start:0,end:null},null,null),_self;normalize_start_end($);var prefixes=$.prefix;if(!$B.$isinstance(prefixes,_b_.tuple)){prefixes=[prefixes]}_self=to_string($.self);prefixes=to_string(prefixes);var s=_self.substring($.start,$.end);for(var prefix of prefixes){if(!$B.$isinstance(prefix,str)){throw _b_.TypeError.$factory("endswith first arg must be str "+"or a tuple of str, not int")}if(s.substr(0,prefix.length)==prefix){return true}}return false};str.strip=function(){var $=$B.args("strip",2,{self:null,chars:null},["self","chars"],arguments,{chars:_b_.None},null,null);if($.chars===_b_.None){return $.self.trim()}return str.rstrip(str.lstrip($.self,$.chars),$.chars)};str.swapcase=function(self){var $=$B.args("swapcase",1,{self:self},["self"],arguments,{},null,null),res="",cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if($B.in_unicode_category("Ll",cp)){res+=char.toUpperCase()}else if($B.in_unicode_category("Lu",cp)){res+=char.toLowerCase()}else{res+=char}}return res};str.title=function(self){var $=$B.args("title",1,{self:self},["self"],arguments,{},null,null),state,cp,res="",_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);if($B.in_unicode_category("Ll",cp)){if(!state){res+=char.toUpperCase();state="word"}else{res+=char}}else if($B.in_unicode_category("Lu",cp)||$B.in_unicode_category("Lt",cp)){res+=state?char.toLowerCase():char;state="word"}else{state=null;res+=char}}return res};str.translate=function(){var $=$B.args("translate",2,{self:null,table:null},["self","table"],arguments,{},null,null),table=$.table,res=[],getitem=$B.$getattr(table,"__getitem__"),cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);try{var repl=getitem(cp);if(repl!==_b_.None){if(typeof repl=="string"){res.push(repl)}else if(typeof repl=="number"){res.push(String.fromCharCode(repl))}}}catch(err){res.push(char)}}return res.join("")};str.upper=function(){var $=$B.args("upper",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);return _self.toUpperCase()};str.zfill=function(){var $=$B.args("zfill",2,{self:null,width:null},["self","width"],arguments,{},null,null),_self=to_string($.self);var len=str.__len__(_self);if($.width<=len){return _self}switch(_self.charAt(0)){case"+":case"-":return _self.charAt(0)+"0".repeat($.width-len)+_self.substr(1);default:return"0".repeat($.width-len)+_self}};str.$factory=function(arg,encoding){if(arguments.length==0){return""}if(arg===undefined){return $B.UndefinedType.__str__()}else if(arg===null){return""}if(encoding!==undefined){var $=$B.args("str",3,{arg:null,encoding:null,errors:null},["arg","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null);encoding=$.encoding}if(typeof arg=="string"||arg instanceof String){return arg.toString()}else if(typeof arg=="number"&&Number.isInteger(arg)){return arg.toString()}try{if(arg.__class__&&arg.__class__===_b_.bytes&&encoding!==undefined){return _b_.bytes.decode(arg,$.encoding,$.errors)}var klass=arg.__class__||$B.get_class(arg);if(klass===undefined){return $B.JSObj.__str__($B.jsobj2pyobj(arg))}var method=$B.$getattr(klass,"__str__",null);if(method===null){method=$B.$getattr(klass,"__repr__")}}catch(err){console.log("no __str__ for",arg);console.log("err ",err);if($B.get_option("debug")>1){console.log(err)}console.log("Warning - no method __str__ or __repr__, "+"default to toString",arg);throw err}var res=$B.$call(method)(arg);if(typeof res=="string"||$B.$isinstance(res,str)){return res}throw _b_.TypeError.$factory("__str__ returned non-string "+`(type ${$B.class_name(res)})`)};$B.set_func_names(str,"builtins");_b_.str=str;$B.parse_format_spec=function(spec,obj){if(spec==""){this.empty=true}else{var pos=0,aligns="<>=^",digits="0123456789",types="bcdeEfFgGnosxX%",align_pos=aligns.indexOf(spec.charAt(0));if(align_pos!=-1){if(spec.charAt(1)&&aligns.indexOf(spec.charAt(1))!=-1){this.fill=spec.charAt(0);this.align=spec.charAt(1);pos=2}else{this.align=aligns[align_pos];this.fill=" ";pos++}}else{align_pos=aligns.indexOf(spec.charAt(1));if(spec.charAt(1)&&align_pos!=-1){this.align=aligns[align_pos];this.fill=spec.charAt(0);pos=2}}var car=spec.charAt(pos);if(car=="+"||car=="-"||car==" "){this.sign=car;pos++;car=spec.charAt(pos)}if(car=="z"){this.z=true;pos++;car=spec.charAt(pos)}if(car=="#"){this.alternate=true;pos++;car=spec.charAt(pos)}if(car=="0"){this.fill="0";if(align_pos==-1){this.align="="}pos++;car=spec.charAt(pos)}while(car&&digits.indexOf(car)>-1){if(this.width===undefined){this.width=car}else{this.width+=car}pos++;car=spec.charAt(pos)}if(this.width!==undefined){this.width=parseInt(this.width)}if(this.width===undefined&&car=="{"){var end_param_pos=spec.substr(pos).search("}");this.width=spec.substring(pos,end_param_pos);pos+=end_param_pos+1}if(car==","||car=="_"){this.comma=true;this.grouping_option=car;pos++;car=spec.charAt(pos);if(car==","||car=="_"){if(car==this.grouping_option){throw _b_.ValueError.$factory(`Cannot specify '${car}' with '${car}'.`)}else{throw _b_.ValueError.$factory("Cannot specify both ',' and '_'.")}}}if(car=="."){if(digits.indexOf(spec.charAt(pos+1))==-1){throw _b_.ValueError.$factory("Missing precision in format spec")}this.precision=spec.charAt(pos+1);pos+=2;car=spec.charAt(pos);while(car&&digits.indexOf(car)>-1){this.precision+=car;pos++;car=spec.charAt(pos)}this.precision=parseInt(this.precision)}if(car&&types.indexOf(car)>-1){this.type=car;pos++;car=spec.charAt(pos)}if(pos!==spec.length){var err_msg=`Invalid format specifier '${spec}'`;if(obj){err_msg+=` for object of type '${$B.class_name(obj)}'`}throw _b_.ValueError.$factory(err_msg)}}this.toString=function(){return(this.fill===undefined?"":_b_.str.$factory(this.fill))+(this.align||"")+(this.sign||"")+(this.alternate?"#":"")+(this.sign_aware?"0":"")+(this.width||"")+(this.comma?",":"")+(this.precision?"."+this.precision:"")+(this.type||"")}};$B.format_width=function(s,fmt){if(fmt.width&&s.length":return fill.repeat(missing)+s;case"=":if("+-".indexOf(s.charAt(0))>-1){return s.charAt(0)+fill.repeat(missing)+s.substr(1)}else{return fill.repeat(missing)+s}case"^":var left=parseInt(missing/2);return fill.repeat(left)+s+fill.repeat(missing-left)}}return s};function fstring_expression(start){this.type="expression";this.start=start;this.expression="";this.conversion=null;this.fmt=null}function fstring_error(msg,pos){var error=Error(msg);error.position=pos;throw error}$B.parse_fstring=function(string){var elts=[],pos=0,current="",ctype=null,nb_braces=0,expr_start,car;while(pos-1){if(current.expression.length==0){throw Error("f-string: empty expression not allowed")}if("ars".indexOf(string.charAt(i+1))==-1){throw Error("f-string: invalid conversion character:"+" expected 's', 'r', or 'a'")}else{current.conversion=string.charAt(i+1);i+=2}}else if(car=="("||car=="["){nb_paren++;current.expression+=car;i++}else if(car==")"||car=="]"){nb_paren--;current.expression+=car;i++}else if(car=='"'){if(string.substr(i,3)=='"""'){let end=string.indexOf('"""',i+3);if(end==-1){fstring_error("f-string: unterminated string",pos)}else{var trs=string.substring(i,end+3);trs=trs.replace("\n","\\n\\");current.expression+=trs;i=end+3}}else{let end=string.indexOf('"',i+1);if(end==-1){fstring_error("f-string: unterminated string",pos)}else{current.expression+=string.substring(i,end+1);i=end+1}}}else if(nb_paren==0&&car==":"){current.fmt=true;var cb=0,fmt_complete=false;for(var j=i+1;j-1?"\\":"")+last_char;if(ce.length==0||nb_paren>0||string.charAt(i+1)=="="||"=!<>:".search(last_char_re)>-1){current.expression+=car;i+=1}else{var tail=car;while(string.charAt(i+1).match(/\s/)){tail+=string.charAt(i+1);i++}elts.push(current.expression+tail);while(ce.match(/\s$/)){ce=ce.substr(0,ce.length-1)}current.expression=ce;ctype="debug";i++}}else{current.expression+=car;i++}}if(nb_braces>0){fstring_error("f-string: expected '}'",pos)}}}if(current.length>0){elts.push(current)}for(var elt of elts){if(typeof elt=="object"){if(elt.fmt_pos!==undefined&&elt.expression.charAt(elt.fmt_pos)!=":"){throw Error()}}}return elts};$B.codepoint2jsstring=function(i){if(i>=65536&&i<=1114111){var code=i-65536;return String.fromCodePoint(55296|code>>10)+String.fromCodePoint(56320|code&1023)}else{return String.fromCodePoint(i)}};$B.jsstring2codepoint=function(c){if(c.length==1){return c.charCodeAt(0)}var code=65536;code+=(c.charCodeAt(0)&1023)<<10;code+=c.charCodeAt(1)&1023;return code}})(__BRYTHON__);(function($B){var _b_=$B.builtins;function $err(op,other){var msg="unsupported operand type(s) for "+op+" : 'int' and '"+$B.class_name(other)+"'";throw _b_.TypeError.$factory(msg)}function int_value(obj){if(typeof obj=="boolean"){return obj?1:0}return obj.$brython_value!==undefined?obj.$brython_value:obj}function bigint_value(obj){if(typeof obj=="boolean"){return obj?1n:0n}else if(typeof obj=="number"){return BigInt(obj)}else if(obj.__class__===$B.long_int){return obj.value}else if($B.$isinstance(obj,_b_.int)){return bigint_value(obj.$brython_value)}}var int={__class__:_b_.type,__dir__:_b_.object.__dir__,__mro__:[_b_.object],__qualname__:"int",$is_class:true,$native:true,$descriptors:{numerator:true,denominator:true,imag:true,real:true},$is_int_subclass:true};var int_or_long=int.$int_or_long=function(bigint){var res=Number(bigint);return Number.isSafeInteger(res)?res:$B.fast_long_int(bigint)};int.$to_js_number=function(obj){if(typeof obj=="number"){return obj}else if(obj.__class__===$B.long_int){return Number(obj.value)}else if($B.$isinstance(obj,_b_.int)){return int.$to_js_value(obj.$brython_value)}return null};int.$to_bigint=bigint_value;int.$int_value=int_value;int.as_integer_ratio=function(){var $=$B.args("as_integer_ratio",1,{self:null},["self"],arguments,{},null,null);return $B.fast_tuple([$.self,1])};int.from_bytes=function(){var $=$B.args("from_bytes",3,{bytes:null,byteorder:null,signed:null},["bytes","byteorder","signed"],arguments,{byteorder:"big",signed:false},null,null);var x=$.bytes,byteorder=$.byteorder,signed=$.signed,_bytes,_len;if($B.$isinstance(x,[_b_.bytes,_b_.bytearray])){_bytes=x.source;_len=x.source.length}else{_bytes=_b_.list.$factory(x);_len=_bytes.length;for(let i=0;i<_len;i++){_b_.bytes.$factory([_bytes[i]])}}if(byteorder=="big"){_bytes.reverse()}else if(byteorder!="little"){throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")}var num=_bytes[0];if(signed&&num>=128){num=num-256}num=BigInt(num);var _mult=256n;for(let i=1;i<_len;i++){num+=_mult*BigInt(_bytes[i]);_mult*=256n}if(!signed){return int_or_long(num)}if(_bytes[_len-1]<128){return int_or_long(num)}return int_or_long(num-_mult)};int.to_bytes=function(){var $=$B.args("to_bytes",3,{self:null,len:null,byteorder:null,signed:null},["self","len","byteorder","signed"],arguments,{len:1,byteorder:"big",signed:false},null,null),self=$.self,len=$.len,byteorder=$.byteorder,signed=$.signed;if(!$B.$isinstance(len,_b_.int)){throw _b_.TypeError.$factory("integer argument expected, got "+$B.class_name(len))}if(["little","big"].indexOf(byteorder)==-1){throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")}if($B.$isinstance(self,$B.long_int)){return $B.long_int.to_bytes(self,len,byteorder,signed)}if(self<0){if(!signed){throw _b_.OverflowError.$factory("can't convert negative int to unsigned")}self=Math.pow(256,len)+self}var res=[],value=self;while(value>0){var quotient=Math.floor(value/256),rest=value-256*quotient;res.push(rest);if(res.length>len){throw _b_.OverflowError.$factory("int too big to convert")}value=quotient}while(res.length=0){res=fmt.sign+res}}return res}int.__format__=function(self,format_spec){var fmt=new $B.parse_format_spec(format_spec,self);if(fmt.type&&"eEfFgG%".indexOf(fmt.type)!=-1){return _b_.float.__format__($B.fast_float(self),format_spec)}fmt.align=fmt.align||">";var res=preformat(self,fmt);if(fmt.comma){var sign=res[0]=="-"?"-":"",rest=res.substr(sign.length),len=rest.length,nb=Math.ceil(rest.length/3),chunks=[];for(var i=0;iint_value(self);int.__init__=()=>_b_.None;int.__int__=self=>self;int.__invert__=function(self){if(Math.abs(self)<2**31){return~self}return $B.rich_op("__sub__",$B.rich_op("__mul__",self,-1),1)};int.__mod__=function(self,other){if($B.$isinstance(other,_b_.tuple)&&other.length==1){other=other[0]}if(other.__class__===$B.long_int){self=BigInt(self);other=other.value;if(other==0){throw _b_.ZeroDivisionError.$factory("integer division or modulo by zero")}return int_or_long((self%other+other)%other)}if($B.$isinstance(other,int)){other=int_value(other);if(other===false){other=0}else if(other===true){other=1}if(other==0){throw _b_.ZeroDivisionError.$factory("integer division or modulo by zero")}return(self%other+other)%other}return _b_.NotImplemented};int.__mul__=Function("self","other",op_model.replace(/\+/g,"*").replace(/add/g,"mul"));int.__ne__=function(self,other){var res=int.__eq__(self,other);return res===_b_.NotImplemented?res:!res};int.__neg__=function(self){var self_as_int=int_value(self);if(self_as_int.__class__===$B.long_int){return $B.long_int.__neg__(self_as_int)}return-self};int.__new__=function(cls,value,base){if(cls===undefined){throw _b_.TypeError.$factory("int.__new__(): not enough arguments")}else if(!$B.$isinstance(cls,_b_.type)){throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")}if(cls===int){return int.$factory(value,base)}if(cls===bool){throw _b_.TypeError.$factory("int.__new__(bool) is not safe, use bool.__new__()")}return{__class__:cls,__dict__:$B.empty_dict(),$brython_value:int.$factory(value,base),toString:function(){return value}}};int.__pos__=function(self){return self};function extended_euclidean(a,b){var d,u,v;if(b==0){return[a,1n,0n]}else{[d,u,v]=extended_euclidean(b,a%b);return[d,v,u-a/b*v]}}int.__pow__=function(self,other,z){if(!$B.$isinstance(other,int)){return _b_.NotImplemented}if(typeof other=="boolean"){other=other?1:0}if(typeof other=="number"||$B.$isinstance(other,int)){if(z!==undefined&&z!==_b_.None){self=bigint_value(self);other=bigint_value(other);z=bigint_value(z);if(z==1){return 0}var result=1n,exponent=other,base=self%z;if(base<0){base+=z}if(exponent<0){var gcd,inv,_;[gcd,inv,_]=extended_euclidean(self,z);if(gcd!=1){throw _b_.ValueError.$factory("not relative primes: "+self+" and "+z)}return int.__pow__(int_or_long(inv),int_or_long(-exponent),int_or_long(z))}while(exponent>0){if(exponent%2n==1n){result=result*base%z}exponent=exponent>>1n;base=base*base%z}return int_or_long(result)}else{if(typeof other=="number"){if(other>=0){return int_or_long(BigInt(self)**BigInt(other))}else{return $B.fast_float(Math.pow(self,other))}}else if(other.__class__===$B.long_int){if(other.value>=0){return int_or_long(BigInt(self)**other.value)}else{return $B.fast_float(Math.pow(self,other))}}else if($B.$isinstance(other,_b_.int)){return int_or_long(int.__pow__(self,other.$brython_value))}return _b_.NotImplemented}}if($B.$isinstance(other,_b_.float)){other=_b_.float.numerator(other);if(self>=0){return $B.fast_float(Math.pow(self,other))}else{return _b_.complex.__pow__($B.make_complex(self,0),other)}}else if($B.$isinstance(other,_b_.complex)){var preal=Math.pow(self,other.$real),ln=Math.log(self);return $B.make_complex(preal*Math.cos(ln),preal*Math.sin(ln))}var rpow=$B.$getattr(other,"__rpow__",_b_.None);if(rpow!==_b_.None){return rpow(self)}$err("**",other)};int.__repr__=function(self){$B.builtins_repr_check(int,arguments);var value=int_value(self),x=value.__class__===$B.long_int?value.value:value;if($B.int_max_str_digits!=0&&x>=10n**BigInt($B.int_max_str_digits)){throw _b_.ValueError.$factory(`Exceeds the limit `+`(${$B.int_max_str_digits}) for integer string conversion`)}return x.toString()};int.__setattr__=function(self,attr,value){if(typeof self=="number"||typeof self=="boolean"){var cl_name=$B.class_name(self);if(_b_.dir(self).indexOf(attr)>-1){throw _b_.AttributeError.$factory("attribute '"+attr+`' of '${cl_name}' objects is not writable`)}else{throw _b_.AttributeError.$factory(`'${cl_name}' object`+` has no attribute '${attr}'`)}}_b_.dict.$setitem(self.__dict__,attr,value);return _b_.None};int.__sub__=Function("self","other",op_model.replace(/\+/g,"-").replace(/__add__/g,"__sub__"));int.__truediv__=function(self,other){if($B.$isinstance(other,int)){other=int_value(other);if(other==0){throw _b_.ZeroDivisionError.$factory("division by zero")}if(other.__class__===$B.long_int){return $B.fast_float(self/parseInt(other.value))}return $B.fast_float(self/other)}return _b_.NotImplemented};int.bit_count=function(self){var s=_b_.bin(_b_.abs(self)),nb=0;for(var x of s){if(x=="1"){nb++}}return nb};int.bit_length=function(self){var s=_b_.bin(self);s=$B.$getattr(s,"lstrip")("-0b");return s.length};int.numerator=self=>int_value(self);int.denominator=()=>1;int.imag=()=>0;int.real=self=>self;for(var attr of["numerator","denominator","imag","real"]){int[attr].setter=function(x){return function(self){throw _b_.AttributeError.$factory(`attribute '${x}' of `+`'${$B.class_name(self)}' objects is not writable`)}}(attr)}var model=`var _b_ = __BRYTHON__.builtins\nif(typeof other == "number"){\n // transform into BigInt: JS converts numbers to 32 bits\n return _b_.int.$int_or_long(BigInt(self) & BigInt(other))}else if(typeof other == "boolean"){\n return self & (other ? 1 : 0)}else if(other.__class__ === $B.long_int){\n return _b_.int.$int_or_long(BigInt(self) & other.value)}else if($B.$isinstance(other, _b_.int)){\n // int subclass\n return _b_.int.__and__(self, other.$brython_value)}\nreturn _b_.NotImplemented`;int.__and__=Function("self","other",model);int.__lshift__=Function("self","other",model.replace(/&/g,"<<").replace(/__and__/g,"__lshift__"));int.__rshift__=Function("self","other",model.replace(/&/g,">>").replace(/__and__/g,"__rshift__"));int.__or__=Function("self","other",model.replace(/&/g,"|").replace(/__and__/g,"__or__"));int.__xor__=Function("self","other",model.replace(/&/g,"^").replace(/__and__/g,"__xor__"));int.__ge__=function(self,other){self=int_value(self);if(typeof other=="number"){return self>=other}else if(other!==null&&other.__class__===$B.long_int){return self>=other.value}else if(typeof other=="boolean"){return self>=other?1:0}else if($B.$isinstance(other,_b_.int)){return self>=other.$brython_value}return _b_.NotImplemented};int.__gt__=function(self,other){var res=int.__le__(self,other);return res===_b_.NotImplemented?res:!res};int.__le__=function(self,other){self=int_value(self);if(typeof other=="number"){return self<=other}else if(other!==null&&other.__class__===$B.long_int){return self<=other.value}else if(typeof other=="boolean"){return self<=other?1:0}else if($B.$isinstance(other,_b_.int)){return self<=other.$brython_value}return _b_.NotImplemented};int.__lt__=function(self,other){var res=int.__ge__(self,other);return res===_b_.NotImplemented?res:!res};var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or","divmod"];for(var r_opname of r_opnames){if(int["__r"+r_opname+"__"]===undefined&&int["__"+r_opname+"__"]){int["__r"+r_opname+"__"]=function(name){return function(self,other){if($B.$isinstance(other,int)){other=int_value(other);return int["__"+name+"__"](other,self)}return _b_.NotImplemented}}(r_opname)}}var $valid_digits=function(base){var digits="";if(base===0){return"0"}if(base<10){for(let i=0;i=2&&base<=36)){if(base!=0){throw _b_.ValueError.$factory("invalid base")}}function invalid(base){throw _b_.ValueError.$factory("invalid literal for int() with base "+base+": "+_b_.repr(initial_value))}if(typeof value!="string"){value=_b_.str.$to_string(value)}var _value=value.trim(),sign="";if(_value.startsWith("+")||_value.startsWith("-")){sign=_value[0];_value=_value.substr(1)}if(_value.length==2&&base==0&&(_value=="0b"||_value=="0o"||_value=="0x")){throw _b_.ValueError.$factory("invalid value")}if(_value.endsWith("_")){invalid(base)}if(value.indexOf("__")>-1){invalid(base)}if(_value.length>2){let _pre=_value.substr(0,2).toUpperCase();if(base==0){if(_pre=="0B"){base=2}else if(_pre=="0O"){base=8}else if(_pre=="0X"){base=16}else if(_value.startsWith("0")){_value=_value.replace(/_/g,"");if(_value.match(/^0+$/)){return 0}invalid(base)}}else if(_pre=="0X"&&base!=16){invalid(base)}else if(_pre=="0O"&&base!=8){invalid(base)}if(_pre=="0B"&&base==2||_pre=="0O"||_pre=="0X"){_value=_value.substr(2);if(_value.startsWith("_")){_value=_value.substr(1)}}}if(base==0){base=10}var _digits=$valid_digits(base),_re=new RegExp("^[+-]?["+_digits+"]"+"["+_digits+"_]*$","i"),match=_re.exec(_value),res;if(match===null){res=0;var digit;for(var char of _value){if(/\p{Nd}/u.test(char)){let cp=char.codePointAt(0);for(let start of $B.digits_starts){if(cp-start<10){digit=cp-start;break}}}else{if(base>10&&_digits.indexOf(char.toUpperCase())>-1){digit=char.toUpperCase().charCodeAt(0)-55}else{invalid(base)}}if(digit$B.int_max_str_digits){throw _b_.ValueError.$factory("Exceeds the limit "+`(${$B.int_max_str_digits}) for integer string conversion: `+`value has ${value.length} digits; use `+"sys.set_int_max_str_digits() to increase the limit.")}if(base==10){res=BigInt(_value)}else{base=BigInt(base);res=0n;let coef=1n,char;for(let i=_value.length-1;i>=0;i--){char=_value[i].toUpperCase();res+=coef*BigInt(_digits.indexOf(char));coef*=base}}}if(sign=="-"){res=-res}return int_or_long(res)};$B.set_func_names(int,"builtins");_b_.int=int;$B.$bool=function(obj,bool_class){if(obj===null||obj===undefined){return false}switch(typeof obj){case"boolean":return obj;case"number":case"string":if(obj){return true}return false;default:if(obj.$is_class){return true}var klass=$B.get_class(obj),missing={},bool_method=bool_class?$B.$getattr(klass,"__bool__",missing):$B.$getattr(obj,"__bool__",missing);var test=false;if(test){console.log("bool(obj)",obj,"bool_class",bool_class,"klass",klass,"apply bool method",bool_method);console.log("$B.$call(bool_method)",bool_method+"")}if(bool_method===missing){var len_method=$B.$getattr(klass,"__len__",missing);if(len_method===missing){return true}return _b_.len(obj)>0}else{var res=bool_class?$B.$call(bool_method)(obj):$B.$call(bool_method)();if(res!==true&&res!==false){throw _b_.TypeError.$factory("__bool__ should return "+"bool, returned "+$B.class_name(res))}if(test){console.log("bool method returns",res)}return res}}};var bool={__bases__:[int],__class__:_b_.type,__mro__:[int,_b_.object],__qualname__:"bool",$is_class:true,$not_basetype:true,$native:true,$descriptors:{numerator:true,denominator:true,imag:true,real:true}};bool.__and__=function(self,other){if($B.$isinstance(other,bool)){return self&&other}else if($B.$isinstance(other,int)){return int.__and__(bool.__index__(self),int.__index__(other))}return _b_.NotImplemented};bool.__float__=function(self){return self?$B.fast_float(1):$B.fast_float(0)};bool.__hash__=bool.__index__=bool.__int__=function(self){if(self.valueOf())return 1;return 0};bool.__neg__=function(self){return-$B.int_or_bool(self)};bool.__or__=function(self,other){if($B.$isinstance(other,bool)){return self||other}else if($B.$isinstance(other,int)){return int.__or__(bool.__index__(self),int.__index__(other))}return _b_.NotImplemented};bool.__pos__=$B.int_or_bool;bool.__repr__=function(self){$B.builtins_repr_check(bool,arguments);return self?"True":"False"};bool.__xor__=function(self,other){if($B.$isinstance(other,bool)){return self^other?true:false}else if($B.$isinstance(other,int)){return int.__xor__(bool.__index__(self),int.__index__(other))}return _b_.NotImplemented};bool.__invert__=function(self){$B.warn(_b_.DeprecationWarning,`Bitwise inversion '~' on bool is deprecated.This returns the bitwise inversion of the underlying int object and is usually not what you expect from negating a bool.Use the 'not' operator for boolean negation or ~int(x) if you really want the bitwise inversion of the underlying int.`);return int.__invert__(self)};bool.$factory=function(){var $=$B.args("bool",1,{x:null},["x"],arguments,{x:false},null,null,1);return $B.$bool($.x,true)};bool.__new__=function(cls,value){if(cls===undefined){throw _b_.TypeError.$factory("bool.__new__(): not enough arguments")}else if(!$B.$isinstance(cls,_b_.type)){throw _b_.TypeError.$factory(`bool.__new__(X): X is not a type object (${$B.class_name(cls)})`)}else if(!_b_.issubclass(cls,bool)){let class_name=$B.class_name(cls);throw _b_.TypeError.$factory(`bool.__new__(${class_name}): ${class_name} is not a subtype of bool`)}if(arguments.length>2){throw _b_.TypeError.$factory(`bool expected at most 1 argument, got ${arguments.length-1}`)}return bool.$factory(value)};bool.from_bytes=function(){var $=$B.args("from_bytes",3,{bytes:null,byteorder:null,signed:null},["bytes","byteorder","signed"],arguments,{byteorder:"big",signed:false},null,null);let int_result=int.from_bytes($.bytes,$.byteorder,$.signed);return bool.$factory(int_result)};bool.numerator=int.numerator;bool.denominator=int.denominator;bool.real=self=>self?1:0;bool.imag=int.imag;for(var attr of["real"]){bool[attr].setter=function(x){return function(self){throw _b_.AttributeError.$factory(`attribute '${x}' of `+`'${$B.class_name(self)}' objects is not writable`)}}(attr)}_b_.bool=bool;$B.set_func_names(bool,"builtins")})(__BRYTHON__);(function($B){var _b_=$B.builtins;var long_int={__class__:_b_.type,__mro__:[_b_.int,_b_.object],__qualname__:"int",$infos:{__module__:"builtins",__name__:"int"},$is_class:true,$native:true,$descriptors:{numerator:true,denominator:true,imag:true,real:true}};var int_or_long=_b_.int.$int_or_long;function preformat(self,fmt){if(fmt.empty){return _b_.str.$factory(self)}if(fmt.type&&"bcdoxXn".indexOf(fmt.type)==-1){throw _b_.ValueError.$factory("Unknown format code '"+fmt.type+"' for object of type 'int'")}var res;switch(fmt.type){case undefined:case"d":res=self.toString();break;case"b":res=(fmt.alternate?"0b":"")+BigInt(self.value).toString(2);break;case"c":res=_b_.chr(self);break;case"o":res=(fmt.alternate?"0o":"")+BigInt(self.value).toString(8);break;case"x":res=(fmt.alternate?"0x":"")+BigInt(self.value).toString(16);break;case"X":res=(fmt.alternate?"0X":"")+BigInt(self.value).toString(16).toUpperCase();break;case"n":return self}if(fmt.sign!==undefined){if((fmt.sign==" "||fmt.sign=="+")&&self>=0){res=fmt.sign+res}}return res}long_int.$to_js_number=function(self){return Number(self.value)};long_int.__format__=function(self,format_spec){var fmt=new $B.parse_format_spec(format_spec,self);if(fmt.type&&"eEfFgG%".indexOf(fmt.type)!=-1){return _b_.float.__format__(self,format_spec)}fmt.align=fmt.align||">";var res=preformat(self,fmt);if(fmt.comma){var sign=res[0]=="-"?"-":"",rest=res.substr(sign.length),len=rest.length,nb=Math.ceil(rest.length/3),chunks=[];for(var i=0;i0?self.value:-self.value)};long_int.__add__=function(self,other){if(typeof other=="number"){return int_or_long(self.value+BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value+other.value)}else if(typeof other=="boolean"){return int_or_long(self.value+(other?1n:0n))}else if($B.$isinstance(other,_b_.int)){return long_int.__add__(self,other.$brython_value)}return _b_.NotImplemented};long_int.__divmod__=function(self,other){var a=self.value,b=_b_.int.$to_bigint(other),quotient;if(a>=0&&b>0||a<=0&&b<0){quotient=a/b}else{quotient=a/b-1n}var rest=a-quotient*b;return $B.fast_tuple([int_or_long(quotient),int_or_long(rest)])};long_int.__eq__=function(self,other){if(other.__class__===$B.long_int){return self.value==other.value}else if(typeof other=="number"||typeof other=="boolean"){return false}else if($B.$isinstance(other,_b_.int)){return long_int.__eq__(self,other.$brython_value)}return _b_.NotImplemented};long_int.__float__=function(self){if(!isFinite(Number(self.value))){throw _b_.OverflowError.$factory("int too large to convert to float")}return $B.fast_float(Number(self.value))};long_int.__floordiv__=function(self,other){if(typeof other=="number"){return int_or_long(self.value/BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value/other.value)}else if(typeof other=="boolean"){return int_or_long(self.value/(other?1n:0n))}else if($B.$isinstance(other,_b_.int)){return int_or_long(self.value/other.$brython_value)}return _b_.NotImplemented};long_int.__ge__=function(self,other){if(typeof other=="number"){return self.value>=other}else if(other.__class__===$B.long_int){return self.value>=other.value}else if(typeof other=="boolean"){return self.value>=(other?1:0)}else if($B.$isinstance(other,_b_.int)){return self.value>=other.$brython_value}return _b_.NotImplemented};long_int.__gt__=function(self,other){var res=long_int.__le__(self,other);return res===_b_.NotImplemented?res:!res};long_int.__hash__=function(self){var modulus=2305843009213693951n,sign=self.value>=0?1n:-1n,self_pos=self.value*sign;var _hash=sign*(self_pos%modulus);return self.__hashvalue__=int_or_long(_hash)};long_int.__index__=function(self){return self};long_int.__invert__=function(self){return int_or_long(-1n-self.value)};long_int.__le__=function(self,other){if(typeof other=="number"){return self.value<=other}else if(other.__class__===$B.long_int){return self.value<=other.value}else if(typeof other=="boolean"){return self.value<=(other?1:0)}else if($B.$isinstance(other,_b_.int)){return self.value<=other.$brython_value}return _b_.NotImplemented};long_int.__lt__=function(self,other){var res=long_int.__ge__(self,other);return res===_b_.NotImplemented?res:!res};long_int.__lshift__=function(self,other){if(typeof other=="number"){return int_or_long(self.value<>BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value>>other.value)}else if(typeof other=="boolean"){return int_or_long(self.value>>(other?1n:0n))}else if($B.$isinstance(other,_b_.int)){return long_int.__rshift__(self,other.$brython_value)}return _b_.NotImplemented};long_int.__repr__=function(self){$B.builtins_repr_check($B.long_int,arguments);if($B.int_max_str_digits!=0&&self.value>=10n**BigInt($B.int_max_str_digits)){throw _b_.ValueError.$factory(`Exceeds the limit `+`(${$B.int_max_str_digits}) for integer string conversion`)}return self.value.toString()};long_int.__sub__=function(self,other){if(typeof other=="number"){return int_or_long(self.value-BigInt(other))}else if(typeof other=="boolean"){return int_or_long(self.value-(other?1n:0n))}else if(other.__class__===$B.long_int){return int_or_long(self.value-other.value)}else if($B.$isinstance(other,_b_.int)){return long_int.__sub__(self,other.$brython_value)}return _b_.NotImplemented};long_int.__truediv__=function(self,other){if(typeof other=="number"){return $B.fast_float(Number(self.value)/other)}else if(typeof other=="boolean"){return $B.fast_float(Number(self.value)*(other?1:0))}else if(other.__class__===$B.long_int){return $B.fast_float(Number(self.value)/Number(other.value))}else if($B.$isinstance(other,_b_.int)){return long_int.__truediv__(self,other.$brython_value)}return _b_.NotImplemented};long_int.bit_count=function(self){var s=self.value.toString(2),nb=0;for(var x of s){if(x=="1"){nb++}}return nb};long_int.bit_length=function(self){return self.value.toString(2).length};function _infos(self){var nbits=$B.long_int.bit_length(self),pow2=2n**BigInt(nbits-1),rest=BigInt(self.value)-pow2,relative_rest=new Number(rest/pow2);return{nbits:nbits,pow2:pow2,rest:rest,relative_rest:relative_rest}}long_int.$log2=function(x){if(x.value<0){throw _b_.ValueError.$factory("math domain error")}var infos=_infos(x);return _b_.float.$factory(infos.nbits-1+Math.log(1+infos.relative_rest/Math.LN2))};long_int.$log10=function(x){if(x.value<0){throw _b_.ValueError.$factory("math domain error")}var x_string=x.value.toString(),exp=x_string.length-1,mant=parseFloat(x_string[0]+"."+x_string.substr(1));return _b_.float.$factory(exp+Math.log10(mant))};long_int.numerator=self=>self;long_int.denominator=()=>1;long_int.imag=()=>0;long_int.real=self=>self;var body=`var $B = __BRYTHON__,\n _b_ = $B.builtins\nif(typeof other == "number"){\n return _b_.int.$int_or_long(self.value & BigInt(other))}else if(typeof other == "boolean"){\n return _b_.int.$int_or_long(self.value & (other ? 1n : 0n))}else if(other.__class__ === $B.long_int){\n return _b_.int.$int_or_long(self.value & other.value)}else if($B.$isinstance(other, _b_.int)){\n // int subclass\n return $B.long_int.__and__(self, other.$brython_value)}\nreturn _b_.NotImplemented`;long_int.__and__=Function("self","other",body);long_int.__or__=Function("self","other",body.replace(/&/g,"|").replace(/__and__/g,"__or__"));long_int.__xor__=Function("self","other",body.replace(/&/g,"^").replace(/__and__/g,"__xor__"));long_int.to_bytes=function(self,len,byteorder,signed){var res=[],v=self.value;if(!$B.$bool(signed)&&v<0){throw _b_.OverflowError.$factory("can't convert negative int to unsigned")}while(v>0){var quot=v/256n,rest=v-quot*256n;v=quot;res.push(Number(rest));if(res.length>len){throw _b_.OverflowError.$factory("int too big to convert")}}while(res.length10){for(let i=0;i0}};long_int.$factory=function(value,base){var is_digits=digits(base);for(let i=0;i=0;i--){char=value[i].toUpperCase();res+=coef*BigInt(is_digits[char]);coef*=base}}return{__class__:$B.long_int,value:res}};function extended_euclidean_algorithm(a,b){var s=0,old_s=1,t=1,old_t=0,r=b,old_r=a,quotient,tmp;while($B.rich_comp("__ne__",r,0)){quotient=$B.rich_op("__floordiv__",old_r,r);tmp=$B.rich_op("__sub__",old_r,$B.rich_op("__mul__",quotient,r));old_r=r;r=tmp;tmp=$B.rich_op("__sub__",old_s,$B.rich_op("__mul__",quotient,s));old_s=s;s=tmp;tmp=$B.rich_op("__sub__",old_t,$B.rich_op("__mul__",quotient,t));old_t=t;t=tmp}return[old_r,old_s,old_t]}function inverse_of(n,p){var gcd,x,y;[gcd,x,y]=extended_euclidean_algorithm(n,p);if($B.rich_comp("__ne__",gcd,1)){throw Error(`${n} has no multiplicative inverse '\n 'modulo ${p}`)}else{return $B.rich_op("__mod__",x,p)}}$B.inverse_of=inverse_of;$B.set_func_names(long_int,"builtins");$B.long_int=long_int;$B.fast_long_int=function(value){if(typeof value!=="bigint"){console.log("expected bigint, got",value);throw Error("not a big int")}return{__class__:$B.long_int,value:value}}})(__BRYTHON__);(function($B){var _b_=$B.builtins;function float_value(obj){return obj.__class__===float?obj:fast_float(obj.value)}var float={__class__:_b_.type,__dir__:_b_.object.__dir__,__qualname__:"float",$is_class:true,$native:true,$descriptors:{numerator:true,denominator:true,imag:true,real:true}};float.$float_value=float_value;float.$to_js_number=function(self){if(self.__class__===float){return self.value}else{return float.$to_js_number(self.value)}};float.numerator=self=>self;float.denominator=()=>1;float.imag=()=>0;float.real=self=>self;float.__float__=function(self){return self};$B.shift1_cache={};float.as_integer_ratio=function(self){if(isinf(self)){throw _b_.OverflowError.$factory("Cannot pass infinity to "+"float.as_integer_ratio.")}if(isnan(self)){throw _b_.ValueError.$factory("Cannot pass NaN to "+"float.as_integer_ratio.")}var tmp=frexp(self),fp=tmp[0],exponent=tmp[1];for(var i=0;i<300;i++){if(fp==Math.floor(fp)){break}else{fp*=2;exponent--}}var numerator=_b_.int.$factory(fp),py_exponent=_b_.abs(exponent),denominator=1,x;if($B.shift1_cache[py_exponent]!==undefined){x=$B.shift1_cache[py_exponent]}else{x=$B.$getattr(1,"__lshift__")(py_exponent);$B.shift1_cache[py_exponent]=x}py_exponent=x;if(exponent>0){numerator=$B.rich_op("__mul__",numerator,py_exponent)}else{denominator=py_exponent}return $B.fast_tuple([_b_.int.$factory(numerator),_b_.int.$factory(denominator)])};function check_self_is_float(x,method){if(x.__class__===_b_.float||$B.$isinstance(x,_b_.float)){return true}throw _b_.TypeError.$factory(`descriptor '${method}' requires a `+`'float' object but received a '${$B.class_name(x)}'`)}float.__abs__=function(self){check_self_is_float(self,"__abs__");return fast_float(Math.abs(self.value))};float.__bool__=function(self){check_self_is_float(self,"__bool__");return _b_.bool.$factory(self.value)};float.__ceil__=function(self){check_self_is_float(self,"__ceil__");if(isnan(self)){throw _b_.ValueError.$factory("cannot convert float NaN to integer")}else if(isinf(self)){throw _b_.OverflowError.$factory("cannot convert float infinity to integer")}return Math.ceil(self.value)};float.__divmod__=function(self,other){check_self_is_float(self,"__divmod__");if(!$B.$isinstance(other,[_b_.int,float])){return _b_.NotImplemented}return $B.fast_tuple([float.__floordiv__(self,other),float.__mod__(self,other)])};float.__eq__=function(self,other){check_self_is_float(self,"__eq__");if(isNaN(self.value)&&($B.$isinstance(other,float)&&isNaN(other.value))){return false}if($B.$isinstance(other,_b_.int)){return self.value==other}if($B.$isinstance(other,float)){return self.value==other.value}if($B.$isinstance(other,_b_.complex)){if(!$B.rich_comp("__eq__",0,other.$imag)){return false}return float.__eq__(self,other.$real)}return _b_.NotImplemented};float.__floor__=function(self){check_self_is_float(self,"__floor__");if(isnan(self)){throw _b_.ValueError.$factory("cannot convert float NaN to integer")}else if(isinf(self)){throw _b_.OverflowError.$factory("cannot convert float infinity to integer")}return Math.floor(self.value)};float.__floordiv__=function(self,other){check_self_is_float(self,"__floordiv__");if($B.$isinstance(other,float)){if(other.value==0){throw _b_.ZeroDivisionError.$factory("division by zero")}return fast_float(Math.floor(self.value/other.value))}if($B.$isinstance(other,_b_.int)){if(other.valueOf()==0){throw _b_.ZeroDivisionError.$factory("division by zero")}return fast_float(Math.floor(self.value/other))}return _b_.NotImplemented};const DBL_MANT_DIG=53,LONG_MAX=$B.MAX_VALUE,DBL_MAX_EXP=2**10,LONG_MIN=$B.MIN_VALUE,DBL_MIN_EXP=-1021;float.fromhex=function(klass,s){function hex_from_char(char){return parseInt(char,16)}function finished(){while(s[pos]&&s[pos].match(/\s/)){pos++}if(pos!=s.length){throw parse_error()}if(negate){x=float.__neg__(x)}return klass===_b_.float?x:$B.$call(klass)(x)}function overflow_error(){throw _b_.OverflowError.$factory("hexadecimal value too large to represent as a float")}function parse_error(){throw _b_.ValueError.$factory("invalid hexadecimal floating-point string")}function insane_length_error(){throw _b_.ValueError.$factory("hexadecimal string too long to convert")}s=s.trim();if(s.match(/^\+?inf(inity)?$/i)){return INF}else if(s.match(/^-inf(inity)?$/i)){return NINF}else if(s.match(/^[+-]?nan$/i)){return NAN}var pos=0,negate,ldexp=_b_.float.$funcs.ldexp;if(s[pos]=="-"){pos++;negate=1}else if(s[pos]=="+"){pos++}if(s.substr(pos,2).toLowerCase()=="0x"){pos+=2}var coeff_start=pos,coeff_end;while(hex_from_char(s[pos])>=0){pos++}var save_pos=pos;if(s[pos]=="."){pos++;while(hex_from_char(s[pos])>=0){pos++}coeff_end=pos-1}else{coeff_end=pos}var ndigits=coeff_end-coeff_start,fdigits=coeff_end-save_pos;if(ndigits==0){throw parse_error()}if(ndigits>Math.min(DBL_MIN_EXP-DBL_MANT_DIG-LONG_MIN/2,LONG_MAX/2+1-DBL_MAX_EXP)/4){throw insane_length_error()}var exp;if(s[pos]=="p"||s[pos]=="P"){pos++;var exp_start=pos;if(s[pos]=="-"||s[pos]=="+"){pos++}if(!("0"<=s[pos]&&s[pos]<="9")){throw parse_error()}pos++;while("0"<=s[pos]&&s[pos]<="9"){pos++}exp=parseInt(s.substr(exp_start))}else{exp=0}function HEX_DIGIT(j){if(!Number.isInteger(j)){throw Error("j pas entier")}return hex_from_char(s[j0&&HEX_DIGIT(ndigits-1)==0){ndigits--}if(ndigits==0||expLONG_MAX/2){console.log("overflow, exp",exp);throw overflow_error()}exp=exp-4*fdigits;var top_exp=exp+4*(ndigits-1);for(let digit=BigInt(HEX_DIGIT(ndigits-1));digit!=0;digit/=2n){top_exp++}if(top_expDBL_MAX_EXP){throw overflow_error()}var lsb=Math.max(top_exp,DBL_MIN_EXP)-DBL_MANT_DIG;var x=0;if(exp>=lsb){for(let i=ndigits-1;i>=0;i--){x=16*x+HEX_DIGIT(i)}x=ldexp($B.fast_float(x),exp);return finished()}var half_eps=1<<(lsb-exp-1)%4,key_digit=parseInt((lsb-exp-1)/4);for(let i=ndigits-1;i>key_digit;i--){x=16*x+HEX_DIGIT(i)}let digit=HEX_DIGIT(key_digit);x=16*x+(digit&16-2*half_eps);if((digit&half_eps)!=0){var round_up=0;if((digit&3*half_eps-1)!=0||half_eps==8&&key_digit+1=0;i--){if(HEX_DIGIT(i)!=0){round_up=1;break}}}if(round_up){x+=2*half_eps;if(top_exp==DBL_MAX_EXP&&x==ldexp(2*half_eps,DBL_MANT_DIG).value){throw overflow_error()}}}x=ldexp(x,exp+4*key_digit);return finished()};float.__getformat__=function(arg){if(arg=="double"||arg=="float"){return"IEEE, little-endian"}if(typeof arg!=="string"){throw _b_.TypeError.$factory(" __getformat__() argument must be str, not "+$B.class_name(arg))}throw _b_.ValueError.$factory("__getformat__() argument 1 must be "+"'double' or 'float'")};var format_sign=function(val,flags){switch(flags.sign){case"+":return val>=0||isNaN(val)?"+":"";case"-":return"";case" ":return val>=0||isNaN(val)?" ":""}if(flags.space){if(val>=0){return" "}}return""};function preformat(self,fmt){var value=self.value;if(fmt.empty){return _b_.str.$factory(self)}if(fmt.type&&"eEfFgGn%".indexOf(fmt.type)==-1){throw _b_.ValueError.$factory("Unknown format code '"+fmt.type+"' for object of type 'float'")}var special;if(isNaN(value)){special="efg".indexOf(fmt.type)>-1?"nan":"NAN"}else if(value==Number.POSITIVE_INFINITY){special="efg".indexOf(fmt.type)>-1?"inf":"INF"}else if(value==Number.NEGATIVE_INFINITY){special="efg".indexOf(fmt.type)>-1?"-inf":"-INF"}if(special){return format_sign(value,fmt)+special}if(fmt.precision===undefined&&fmt.type!==undefined){fmt.precision=6}if(fmt.type=="%"){value*=100}if(fmt.type=="e"){let res=value.toExponential(fmt.precision),exp=parseInt(res.substr(res.search("e")+1));if(Math.abs(exp)<10){res=res.substr(0,res.length-1)+"0"+res.charAt(res.length-1)}return res}var res;if(fmt.precision!==undefined){let prec=fmt.precision;if(prec==0){return Math.round(value)+""}res=$B.roundDownToFixed(value,prec);let pt_pos=res.indexOf(".");if(fmt.type!==undefined&&(fmt.type=="%"||fmt.type.toLowerCase()=="f")){if(pt_pos==-1){res+="."+"0".repeat(fmt.precision)}else{var missing=fmt.precision-res.length+pt_pos+1;if(missing>0){res+="0".repeat(missing)}}}else if(fmt.type&&fmt.type.toLowerCase()=="g"){let exp_fmt=preformat(self,{type:"e"}).split("e"),exp=parseInt(exp_fmt[1]);if(-4<=exp&&exp0){while(signif.endsWith("0")){signif=signif.substr(0,signif.length-1)}}if(signif.endsWith(".")){signif=signif.substr(0,signif.length-1)}parts[0]=signif}res=parts.join("e");if(fmt.type=="G"){res=res.toUpperCase()}return res}else if(fmt.type===undefined){fmt.type="g";res=preformat(self,fmt);if(res.indexOf(".")==-1){let exp=res.length-1;exp=exp<10?"0"+exp:exp;let is_neg=res.startsWith("-"),point_pos=is_neg?2:1,mant=res.substr(0,point_pos)+"."+res.substr(point_pos);return`${mant}e+${exp}`}fmt.type=undefined}else{let res1=value.toExponential(fmt.precision-1),exp=parseInt(res1.substr(res1.search("e")+1));if(exp<-4||exp>=fmt.precision-1){var elts=res1.split("e");while(elts[0].endsWith("0")){elts[0]=elts[0].substr(0,elts[0].length-1)}res=elts.join("e")}}}else{res=_b_.str.$factory(self)}if(fmt.type===undefined||"gGn".indexOf(fmt.type)!=-1){if(res.search("e")==-1){while(res.charAt(res.length-1)=="0"){res=res.substr(0,res.length-1)}}if(res.charAt(res.length-1)=="."){if(fmt.type===undefined){res+="0"}else{res=res.substr(0,res.length-1)}}}if(fmt.sign!==undefined){if((fmt.sign==" "||fmt.sign=="+")&&value>0){res=fmt.sign+res}}if(fmt.type=="%"){res+="%"}return res}float.__format__=function(self,format_spec){check_self_is_float(self,"__format__");var fmt=new $B.parse_format_spec(format_spec,self);return float.$format(self,fmt)};float.$format=function(self,fmt){fmt.align=fmt.align||">";var pf=preformat(self,fmt);if(fmt.z&&Object.is(parseFloat(pf),-0)){pf=pf.substr(1)}var raw=pf.split("."),_int=raw[0];if(fmt.comma){var len=_int.length,nb=Math.ceil(_int.length/3),chunks=[];for(var i=0;i1e4){$B.float_hash_cache.clear()}return self.__hashvalue__=x};function isninf(x){var x1=float_value(x).value;return x1==-Infinity||x1==Number.NEGATIVE_INFINITY}function isinf(x){var x1=float_value(x).value;return x1==Infinity||x1==-Infinity||x1==Number.POSITIVE_INFINITY||x1==Number.NEGATIVE_INFINITY}function isnan(x){var x1=float_value(x).value;return isNaN(x1)}function fabs(x){if(x==0){return fast_float(0)}return x>0?float.$factory(x):float.$factory(-x)}function frexp(x){var x1=x;if($B.$isinstance(x,float)){if(isnan(x)||isinf(x)){return[x,0]}x1=float_value(x).value}else if($B.$isinstance(x,$B.long_int)){var exp=x.value.toString(2).length,power=2n**BigInt(exp);return[$B.fast_float(Number(x.value)/Number(power)),exp]}if(x1==0){return[0,0]}var sign=1,ex=0,man=x1;if(man<0){sign=-sign;man=-man}while(man<.5){man*=2;ex--}while(man>=1){man*=.5;ex++}man*=sign;return[man,ex]}function ldexp(mantissa,exponent){if(isninf(mantissa)){return NINF}else if(isinf(mantissa)){return INF}if($B.$isinstance(mantissa,_b_.float)){mantissa=mantissa.value}if(mantissa==0){return ZERO}else if(isNaN(mantissa)){return NAN}if($B.$isinstance(exponent,$B.long_int)){if(exponent.value<0){return ZERO}else{throw _b_.OverflowError.$factory("overflow")}}else if(!isFinite(mantissa*Math.pow(2,exponent))){throw _b_.OverflowError.$factory("overflow")}var steps=Math.min(3,Math.ceil(Math.abs(exponent)/1023));var result=mantissa;for(var i=0;i=0){if(Number.isInteger(other)&&other%2==1){return self}return fast_float(0)}else if(self.value==Number.NEGATIVE_INFINITY&&!isNaN(other)){if(other%2==-1){return fast_float(-0)}else if(other<0){return fast_float(0)}else if(other%2==1){return fast_float(Number.NEGATIVE_INFINITY)}else{return fast_float(Number.POSITIVE_INFINITY)}}else if(self.value==Number.POSITIVE_INFINITY&&!isNaN(other)){return other>0?self:fast_float(0)}if(other==Number.NEGATIVE_INFINITY&&!isNaN(self.value)){return Math.abs(self.value)<1?fast_float(Number.POSITIVE_INFINITY):fast_float(0)}else if(other==Number.POSITIVE_INFINITY&&!isNaN(self.value)){return Math.abs(self.value)<1?fast_float(0):fast_float(Number.POSITIVE_INFINITY)}if(self.value<0&&!Number.isInteger(other)){return _b_.complex.__pow__($B.make_complex(self.value,0),fast_float(other))}return fast_float(Math.pow(self.value,other))}return _b_.NotImplemented};float.__repr__=function(self){$B.builtins_repr_check(float,arguments);self=self.value;if(self==Infinity){return"inf"}else if(self==-Infinity){return"-inf"}else if(isNaN(self)){return"nan"}else if(self===0){if(1/self===-Infinity){return"-0.0"}return"0.0"}var res=self+"";if(res.search(/[.eE]/)==-1){res+=".0"}var split_e=res.split(/e/i);if(split_e.length==2){let mant=split_e[0],exp=split_e[1];if(exp.startsWith("-")){let exp_str=parseInt(exp.substr(1))+"";if(exp_str.length<2){exp_str="0"+exp_str}return mant+"e-"+exp_str}}var x,y;[x,y]=res.split(".");var sign="";if(x[0]=="-"){x=x.substr(1);sign="-"}if(x.length>16){let exp=x.length-1,int_part=x[0],dec_part=x.substr(1)+y;while(dec_part.endsWith("0")){dec_part=dec_part.substr(0,dec_part.length-1)}let mant=int_part;if(dec_part.length>0){mant+="."+dec_part}return sign+mant+"e+"+exp}else if(x=="0"){let exp=0;while(exp3){let rest=y.substr(exp);exp=(exp+1).toString();while(rest.endsWith("0")){rest=rest.substr(0,res.length-1)}let mant=rest[0];if(rest.length>1){mant+="."+rest.substr(1)}if(exp.length==1){exp="0"+exp}return sign+mant+"e-"+exp}}return _b_.str.$factory(res)};float.__round__=function(){var $=$B.args("__round__",2,{self:null,ndigits:null},["self","ndigits"],arguments,{ndigits:_b_.None},null,null);return float.$round($.self,$.ndigits)};float.$round=function(x,ndigits){function overflow(){throw _b_.OverflowError.$factory("cannot convert float infinity to integer")}var no_digits=ndigits===_b_.None;if(isnan(x)){if(ndigits===_b_.None){throw _b_.ValueError.$factory("cannot convert float NaN to integer")}return NAN}else if(isninf(x)){return ndigits===_b_.None?overflow():NINF}else if(isinf(x)){return ndigits===_b_.None?overflow():INF}x=float_value(x);ndigits=ndigits===_b_.None?0:ndigits;if(ndigits==0){var res=Math.round(x.value);if(Math.abs(x.value-res)==.5){if(res%2){return res-1}}if(no_digits){return res}return $B.fast_float(res)}if(ndigits.__class__===$B.long_int){ndigits=Number(ndigits.value)}var pow1,pow2,y,z;if(ndigits>=0){if(ndigits>22){pow1=10**(ndigits-22);pow2=1e22}else{pow1=10**ndigits;pow2=1}y=x.value*pow1*pow2;if(!isFinite(y)){return x}}else{pow1=10**-ndigits;pow2=1;if(isFinite(pow1)){y=x.value/pow1}else{return ZERO}}z=Math.round(y);if(fabs(y-z).value==.5){z=2*Math.round(y/2)}if(ndigits>=0){z=z/pow2/pow1}else{z*=pow1}if(!isFinite(z)){throw _b_.OverflowError.$factory("overflow occurred during round")}return fast_float(z)};float.__setattr__=function(self,attr,value){if(self.__class__===float){if(float[attr]===undefined){throw _b_.AttributeError.$factory("'float' object has no attribute '"+attr+"'")}else{throw _b_.AttributeError.$factory("'float' object attribute '"+attr+"' is read-only")}}self[attr]=value;return _b_.None};float.__truediv__=function(self,other){if($B.$isinstance(other,_b_.int)){if(other.valueOf()==0){throw _b_.ZeroDivisionError.$factory("division by zero")}else if($B.$isinstance(other,$B.long_int)){return float.$factory(self.value/Number(other.value))}return float.$factory(self.value/other)}else if($B.$isinstance(other,float)){if(other.value==0){throw _b_.ZeroDivisionError.$factory("division by zero")}return float.$factory(self.value/other.value)}return _b_.NotImplemented};var op_func_body=`var $B = __BRYTHON__,\n _b_ = __BRYTHON__.builtins\n if($B.$isinstance(other, _b_.int)){\n if(typeof other == "boolean"){\n return other ? $B.fast_float(self.value - 1) : self\n }else if(other.__class__ === $B.long_int){\n return _b_.float.$factory(self.value - parseInt(other.value))\n }else{\n return $B.fast_float(self.value - other)\n }\n }\n if($B.$isinstance(other, _b_.float)){\n return $B.fast_float(self.value - other.value)\n }\n return _b_.NotImplemented`;var ops={"+":"add","-":"sub"};for(let op in ops){let body=op_func_body.replace(/-/gm,op);float[`__${ops[op]}__`]=Function("self","other",body)}var comp_func_body=`\nvar $B = __BRYTHON__,\n _b_ = $B.builtins\nif($B.$isinstance(other, _b_.int)){\n if(other.__class__ === $B.long_int){\n return self.value > parseInt(other.value)\n }\n return self.value > other.valueOf()}\nif($B.$isinstance(other, _b_.float)){\n return self.value > other.value}\nif($B.$isinstance(other, _b_.bool)) {\n return self.value > _b_.bool.__hash__(other)}\nif(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")) {\n return _b_.int.__gt__(self.value, $B.$GetInt(other))}\n// See if other has the opposite operator, eg <= for >\nvar inv_op = $B.$getattr(other, "__le__", _b_.None)\nif(inv_op !== _b_.None){\n return inv_op(self)}\nthrow _b_.TypeError.$factory(\n "unorderable types: float() > " + $B.class_name(other) + "()")\n`;for(let op in $B.$comps){let body=comp_func_body.replace(/>/gm,op).replace(/__gt__/gm,`__${$B.$comps[op]}__`).replace(/__le__/,`__${$B.$inv_comps[op]}__`);float[`__${$B.$comps[op]}__`]=Function("self","other",body)}var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or","divmod"];for(var r_opname of r_opnames){if(float["__r"+r_opname+"__"]===undefined&&float["__"+r_opname+"__"]){float["__r"+r_opname+"__"]=function(name){return function(self,other){var other_as_num=_b_.int.$to_js_number(other);if(other_as_num!==null){var other_as_float=$B.fast_float(other_as_num);return float["__"+name+"__"](other_as_float,self)}return _b_.NotImplemented}}(r_opname)}}function to_digits(s){var arabic_digits="٠١٢٣٤٥٦٧٨٩",res="";for(var i=0;i-1){res+=x}else{res+=s[i]}}return res}const fast_float=$B.fast_float=function(value){return{__class__:_b_.float,value:value}};float.$factory=function(value){if(value===undefined){return fast_float(0)}$B.check_nb_args_no_kw("float",1,arguments);switch(value){case true:return fast_float(1);case false:return fast_float(0)}var original_value=value;if(typeof value=="number"){return fast_float(value)}if(value.__class__===float){return value}if($B.$isinstance(value,_b_.memoryview)){value=_b_.memoryview.tobytes(value)}if($B.$isinstance(value,_b_.bytes)){try{value=$B.$getattr(value,"decode")("utf-8")}catch(err){throw _b_.ValueError.$factory("could not convert string to float: "+_b_.repr(original_value))}}if(typeof value=="string"){if(value.trim().length==0){throw _b_.ValueError.$factory(`could not convert string to float: ${_b_.repr(value)}`)}value=value.trim();switch(value.toLowerCase()){case"+inf":case"inf":case"+infinity":case"infinity":return fast_float(Number.POSITIVE_INFINITY);case"-inf":case"-infinity":return fast_float(Number.NEGATIVE_INFINITY);case"+nan":case"nan":return fast_float(Number.NaN);case"-nan":return fast_float(-Number.NaN);default:var parts=value.split("e");if(parts[1]){if(parts[1].startsWith("+")||parts[1].startsWith("-")){parts[1]=parts[1].substr(1)}}parts=parts[0].split(".").concat(parts.splice(1));for(var part of parts){if(part.startsWith("_")||part.endsWith("_")){throw _b_.ValueError.$factory("invalid float literal "+value)}}if(value.indexOf("__")>-1){throw _b_.ValueError.$factory("invalid float literal "+value)}value=value.charAt(0)+value.substr(1).replace(/_/g,"");value=to_digits(value);if(isFinite(value)){return fast_float(parseFloat(value))}else{throw _b_.TypeError.$factory("could not convert string to float: "+_b_.repr(original_value))}}}let klass=$B.get_class(value),float_method=$B.$getattr(klass,"__float__",null);if(float_method===null){var index_method=$B.$getattr(klass,"__index__",null);if(index_method===null){throw _b_.TypeError.$factory("float() argument must be a string or a "+"real number, not '"+$B.class_name(value)+"'")}let index=$B.$call(index_method)(value),index_klass=$B.get_class(index);if(index_klass===_b_.int){return fast_float(index)}else if(index_klass===$B.long_int){return $B.long_int.__float__(index)}else if(index_klass.__mro__.indexOf(_b_.int)>-1){let msg=`${$B.class_name(value)}.__index__ returned `+`non-int (type ${$B.class_name(index)}). The `+"ability to return an instance of a strict subclass"+" of int is deprecated, and may be removed in a "+"future version of Python.";$B.warn(_b_.DeprecationWarning,msg);return fast_float(index)}throw _b_.TypeError.$factory("__index__ returned non-int"+` (type ${$B.class_name(index)})`)}let res=$B.$call(float_method)(value);klass=$B.get_class(res);if(klass!==_b_.float){if(klass.__mro__.indexOf(_b_.float)>-1){let msg=`${$B.class_name(value)}.__float__ returned `+`non-float (type ${$B.class_name(res)}). The `+"ability to return an instance of a strict subclass"+" of float is deprecated, and may be removed in a "+"future version of Python.";$B.warn(_b_.DeprecationWarning,msg);return float.$factory(res.value)}throw _b_.TypeError.$factory("__float__ returned non-float"+` (type ${$B.class_name(res)})`)}return res};$B.set_func_names(float,"builtins");float.fromhex=_b_.classmethod.$factory(float.fromhex);_b_.float=float;$B.MAX_VALUE=fast_float(Number.MAX_VALUE);$B.MIN_VALUE=fast_float(22250738585072014e-324);const NINF=fast_float(Number.NEGATIVE_INFINITY),INF=fast_float(Number.POSITIVE_INFINITY),NAN=fast_float(Number.NaN),ZERO=fast_float(0)})(__BRYTHON__);(function($B){var _b_=$B.builtins;function $UnsupportedOpType(op,class1,class2){throw _b_.TypeError.$factory("unsupported operand type(s) for "+op+": '"+class1+"' and '"+class2+"'")}var complex={__class__:_b_.type,__dir__:_b_.object.__dir__,__qualname__:"complex",$is_class:true,$native:true,$descriptors:{real:true,imag:true}};complex.__abs__=function(self){var _rf=isFinite(self.$real.value),_if=isFinite(self.$imag.value);if(_rf&&isNaN(self.$imag.value)||_if&&isNaN(self.$real.value)||isNaN(self.$imag.value)&&isNaN(self.$real.value)){return $B.fast_float(NaN)}if(!_rf||!_if){return $B.fast_float(Infinity)}var mag=Math.sqrt(Math.pow(self.$real.value,2)+Math.pow(self.$imag.value,2));if(!isFinite(mag)&&_rf&&_if){throw _b_.OverflowError.$factory("absolute value too large")}return $B.fast_float(mag)};complex.__add__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value+other.$real.value,self.$imag.value+other.$imag.value)}if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other);return make_complex($B.rich_op("__add__",self.$real,other).value,self.$imag.value)}if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value+other.value,self.$imag.value)}return _b_.NotImplemented};complex.__bool__=function(self){return!$B.rich_comp("__eq__",self.$real,0)||!$B.rich_comp("__eq__",self.$imag,0)};complex.__complex__=function(self){if(self.__class__===complex){return self}return $B.make_complex(self.$real,self.$imag)};complex.__eq__=function(self,other){if($B.$isinstance(other,complex)){return self.$real.value==other.$real.value&&self.$imag.value==other.$imag.value}if($B.$isinstance(other,_b_.int)){if(self.$imag.value!=0){return false}return self.$real.value==other.valueOf()}if($B.$isinstance(other,_b_.float)){if(!$B.rich_comp("__eq__",0,self.$imag)){return false}return self.$real.value==other.value}return _b_.NotImplemented};const max_precision=2**31-4;complex.__format__=function(self,format_spec){if(format_spec.length==0){return _b_.str.$factory(self)}var fmt=new $B.parse_format_spec(format_spec,self),type=fmt.conversion_type;var skip_re,add_parens;if(type===undefined||"eEfFgGn".indexOf(type)>-1){if(fmt.precision>max_precision){throw _b_.ValueError.$factory("precision too big")}if(fmt.fill_char=="0"){throw _b_.ValueError.$factory("Zero padding is not allowed in complex format specifier")}if(fmt.align=="="){throw _b_.ValueError.$factory("'=' alignment flag is not allowed in complex format "+"specifier")}var re=self.$real.value,precision=parseInt(fmt.precision,10);if(type===undefined){type="r";if(re==0&&Object.is(re,0)){skip_re=1}else{add_parens=1}}else if(type=="n"){type="g"}if(precision<0){precision=6}else if(type=="r"){type="g"}var format=$B.clone(fmt);format.conversion_type=type;format.precision=precision;var res="";if(!skip_re){res+=_b_.float.$format(self.$real,format);if(self.$imag.value>=0){res+="+"}}var formatted_im=_b_.float.$format(self.$imag,format);var pos=-1,last_num;for(var char of formatted_im){pos++;if(char.match(/\d/)){last_num=pos}}formatted_im=formatted_im.substr(0,last_num+1)+"j"+formatted_im.substr(last_num+1);res+=formatted_im;if(add_parens){res="("+res+")"}return res}throw _b_.ValueError.$factory(`invalid type for complex: ${type}`)};complex.$getnewargs=function(self){return $B.fast_tuple([self.$real,self.$imag])};complex.__getnewargs__=function(){return complex.$getnewargs($B.single_arg("__getnewargs__","self",arguments))};complex.__hash__=function(self){return $B.$hash(self.$real)+$B.$hash(self.$imag)*1000003};complex.__init__=function(){return _b_.None};complex.__invert__=function(self){return~self};complex.__mro__=[_b_.object];complex.__mul__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value*other.$real.value-self.$imag.value*other.$imag.value,self.$imag.value*other.$real.value+self.$real.value*other.$imag.value)}else if($B.$isinstance(other,_b_.int)){return make_complex(self.$real.value*other.valueOf(),self.$imag.value*other.valueOf())}else if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value*other.value,self.$imag.value*other.value)}else if($B.$isinstance(other,_b_.bool)){if(other.valueOf()){return self}return make_complex(0,0)}$UnsupportedOpType("*",complex,other)};complex.__ne__=function(self,other){var res=complex.__eq__(self,other);return res===_b_.NotImplemented?res:!res};complex.__neg__=function(self){return make_complex(-self.$real.value,-self.$imag.value)};complex.__new__=function(cls){if(cls===undefined){throw _b_.TypeError.$factory("complex.__new__(): not enough arguments")}var res,missing={},$=$B.args("complex",3,{cls:null,real:null,imag:null},["cls","real","imag"],arguments,{real:0,imag:missing},null,null);cls=$.cls;var first=$.real,second=$.imag;if(typeof first=="string"){if(second!==missing){throw _b_.TypeError.$factory("complex() can't take second arg "+"if first is a string")}else{var arg=first;first=first.trim();if(first.startsWith("(")&&first.endsWith(")")){first=first.substr(1);first=first.substr(0,first.length-1)}var complex_re=/^\s*([+-]*[0-9_]*\.?[0-9_]*(e[+-]*[0-9_]*)?)([+-]?)([0-9_]*\.?[0-9_]*(e[+-]*[0-9_]*)?)(j?)\s*$/i;var parts=complex_re.exec(first);function to_num(s){var res=parseFloat(s.charAt(0)+s.substr(1).replace(/_/g,""));if(isNaN(res)){throw _b_.ValueError.$factory("could not convert string "+"to complex: '"+arg+"'")}return res}if(parts===null){throw _b_.ValueError.$factory("complex() arg is a malformed string")}if(parts[_real]&&parts[_imag].startsWith(".")&&parts[_sign]==""){throw _b_.ValueError.$factory("complex() arg is a malformed string")}else if(parts[_real]=="."||parts[_imag]=="."||parts[_real]==".e"||parts[_imag]==".e"||parts[_real]=="e"||parts[_imag]=="e"){throw _b_.ValueError.$factory("complex() arg is a malformed string")}else if(parts[_j]!=""){if(parts[_sign]==""){first=0;if(parts[_real]=="+"||parts[_real]==""){second=1}else if(parts[_real]=="-"){second=-1}else{second=to_num(parts[_real])}}else{first=to_num(parts[_real]);second=parts[_imag]==""?1:to_num(parts[_imag]);second=parts[_sign]=="-"?-second:second}}else{if(parts[_sign]&&parts[_imag]==""){throw _b_.ValueError.$factory("complex() arg is a malformed string")}first=to_num(parts[_real]);second=0}res=make_complex(first,second);res.__class__=cls;res.__dict__=$B.empty_dict();return res}}if(first.__class__===complex&&cls===complex&&second===missing){return first}var arg1=_convert(first),r,i;if(arg1===null){throw _b_.TypeError.$factory("complex() first argument must be a "+`string or a number, not '${$B.class_name(first)}'`)}if(typeof second=="string"){throw _b_.TypeError.$factory("complex() second arg can't be a string")}var arg2=_convert(second===missing?0:second);if(arg2===null){throw _b_.TypeError.$factory("complex() second argument must be a "+`number, not '${$B.class_name(second)}'`)}if(arg1.method=="__complex__"){if(arg2.method=="__complex__"){r=$B.rich_op("__sub__",arg1.result.$real,arg2.result.$imag);i=$B.rich_op("__add__",arg1.result.$imag,arg2.result.$real)}else{r=arg1.result.$real;i=$B.rich_op("__add__",arg1.result.$imag,arg2.result)}}else{if(arg2.method=="__complex__"){r=$B.rich_op("__sub__",arg1.result,arg2.result.$imag);i=arg2.result.$real}else{r=arg1.result;i=arg2.result}}res=make_complex(r,i);res.__class__=cls;res.__dict__=$B.empty_dict();return res};complex.__pos__=function(self){return self};function complex2expo(cx){var norm=Math.sqrt(cx.$real.value*cx.$real.value+cx.$imag.value*cx.$imag.value),sin=cx.$imag.value/norm,cos=cx.$real.value/norm,angle;if(cos==0){angle=sin==1?Math.PI/2:3*Math.PI/2}else if(sin==0){angle=cos==1?0:Math.PI}else{angle=Math.atan(sin/cos)}return{norm:norm,angle:angle}}function c_powi(x,n){if(n>0){return c_powu(x,n)}else{return c_quot(c_1,c_powu(x,-n))}}function c_powu(x,n){var mask=1,r=c_1,p=x;while(mask>0&&n>=mask){if(n&mask){r=c_prod(r,p)}mask<<=1;p=c_prod(p,p)}return r}function c_prod(a,b){return make_complex(a.$real.value*b.$real.value-a.$imag.value*b.$imag.value,a.$real.value*b.$imag.value+a.$imag.value*b.$real.value)}function c_quot(a,b){var abs_breal=Math.abs(b.$real.value),abs_bimag=Math.abs(b.$imag.value);if($B.rich_comp("__ge__",abs_breal,abs_bimag)){if(abs_breal==0){throw _b_.ZeroDivisionError.$factory()}else{let ratio=b.$imag.value/b.$real.value,denom=b.$real.value+b.$imag.value*ratio;return make_complex((a.$real.value+a.$imag.value*ratio)/denom,(a.$imag.value-a.$real.value*ratio)/denom)}}else if(abs_bimag>=abs_breal){let ratio=b.$real.value/b.$imag.value,denom=b.$real.value*ratio+b.$imag.value;if(b.$imag.value==0){throw _b_.ZeroDivisionError.$factory()}return make_complex((a.$real.value*ratio+a.$imag.value)/denom,(a.$imag.value*ratio-a.$real.value)/denom)}else{return $B.make_complex("nan","nan")}}complex.__pow__=function(self,other,mod){if(mod!==undefined&&mod!==_b_.None){throw _b_.ValueError.$factory("complex modulo")}if($B.rich_comp("__eq__",other,1)){var funcs=_b_.float.$funcs;if(funcs.isinf(self.$real)||funcs.isninf(self.$real)||funcs.isinf(self.$imag)||funcs.isninf(self.$imag)){throw _b_.OverflowError.$factory("complex exponentiation")}return self}var small_int=null;if($B.$isinstance(other,_b_.int)&&_b_.abs(other)<100){small_int=other}else if($B.$isinstance(other,_b_.float)&&Number.isInteger(other.value)&&Math.abs(other.value<100)){small_int=other.value}else if($B.$isinstance(other,complex)&&other.$imag.value==0&&Number.isInteger(other.$real.value)&&Math.abs(other.$real.value)<100){small_int=other.$real.value}if(small_int!==null){return c_powi(self,small_int)}if($B.$isinstance(other,_b_.float)){other=_b_.float.$to_js_number(other)}if(self.$real.value==0&&self.$imag.value==0){if($B.$isinstance(other,complex)&&(other.$imag.value!=0||other.$real.value<0)){throw _b_.ZeroDivisionError.$factory("0.0 to a negative or complex power")}return $B.make_complex(0,0)}var exp=complex2expo(self),angle=exp.angle,res=Math.pow(exp.norm,other);if($B.$isinstance(other,_b_.int)){return make_complex(res*Math.cos(angle*other),res*Math.sin(angle*other))}else if($B.$isinstance(other,_b_.float)){return make_complex(res*Math.cos(angle*other.value),res*Math.sin(angle*other.value))}else if($B.$isinstance(other,complex)){var x=other.$real.value,y=other.$imag.value;var pw=Math.pow(exp.norm,x)*Math.pow(Math.E,-y*angle),theta=y*Math.log(exp.norm)-x*angle;if(pw==Number.POSITIVE_INFINITY||pw===Number.NEGATIVE_INFINITY){throw _b_.OverflowError.$factory("complex exponentiation")}return make_complex(pw*Math.cos(theta),pw*Math.sin(theta))}else{throw _b_.TypeError.$factory("unsupported operand type(s) "+"for ** or pow(): 'complex' and '"+$B.class_name(other)+"'")}};complex.__radd__=function(self,other){if($B.$isinstance(other,_b_.bool)){other=other?1:0}if($B.$isinstance(other,_b_.int)){return make_complex(other+self.$real.value,self.$imag.value)}else if($B.$isinstance(other,_b_.float)){return make_complex(other.value+self.$real.value,self.$imag.value)}return _b_.NotImplemented};complex.__repr__=function(self){$B.builtins_repr_check(complex,arguments);var real=Number.isInteger(self.$real.value)?self.$real.value+"":_b_.str.$factory(self.$real),imag=Number.isInteger(self.$imag.value)?self.$imag.value+"":_b_.str.$factory(self.$imag);if(imag.endsWith(".0")){imag=imag.substr(0,imag.length-2)}if(Object.is(self.$imag.value,-0)){imag="-0"}var sign=imag.startsWith("-")?"":"+";if(self.$real.value==0){if(Object.is(self.$real.value,-0)){return"(-0"+sign+imag+"j)"}else{return imag+"j"}}if(self.$imag.value>0||isNaN(self.$imag.value)){return"("+real+"+"+imag+"j)"}if(self.$imag.value==0){if(1/self.$imag.value<0){return"("+real+"-0j)"}return"("+real+"+0j)"}return"("+real+sign+imag+"j)"};complex.__rmul__=function(self,other){if($B.$isinstance(other,_b_.bool)){other=other?1:0}if($B.$isinstance(other,_b_.int)){return make_complex(other*self.$real.value,other*self.$imag.value)}else if($B.$isinstance(other,_b_.float)){return make_complex(other.value*self.$real.value,other.value*self.$imag.value)}return _b_.NotImplemented};complex.__sub__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value-other.$real.value,self.$imag.value-other.$imag.value)}if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other);return make_complex(self.$real.value-other.valueOf(),self.$imag.value)}if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value-other.value,self.$imag.value)}return _b_.NotImplemented};complex.__truediv__=function(self,other){if($B.$isinstance(other,complex)){if(other.$real.value==0&&other.$imag.value==0){throw _b_.ZeroDivisionError.$factory("division by zero")}var _num=self.$real.value*other.$real.value+self.$imag.value*other.$imag.value,_div=other.$real.value*other.$real.value+other.$imag.value*other.$imag.value;var _num2=self.$imag.value*other.$real.value-self.$real.value*other.$imag.value;return make_complex(_num/_div,_num2/_div)}if($B.$isinstance(other,_b_.int)){if(!other.valueOf()){throw _b_.ZeroDivisionError.$factory("division by zero")}return complex.__truediv__(self,complex.$factory(other.valueOf()))}if($B.$isinstance(other,_b_.float)){if(!other.value){throw _b_.ZeroDivisionError.$factory("division by zero")}return complex.__truediv__(self,complex.$factory(other.value))}$UnsupportedOpType("//","complex",other.__class__)};complex.conjugate=function(self){return make_complex(self.$real.value,-self.$imag.value)};complex.__ior__=complex.__or__;var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or"];for(var r_opname of r_opnames){if(complex["__r"+r_opname+"__"]===undefined&&complex["__"+r_opname+"__"]){complex["__r"+r_opname+"__"]=function(name){return function(self,other){if($B.$isinstance(other,_b_.int)){other=make_complex(other,0);return complex["__"+name+"__"](other,self)}else if($B.$isinstance(other,_b_.float)){other=make_complex(other.value,0);return complex["__"+name+"__"](other,self)}else if($B.$isinstance(other,complex)){return complex["__"+name+"__"](other,self)}return _b_.NotImplemented}}(r_opname)}}var comp_func_body=`\n var _b_ = __BRYTHON__.builtins\n if(other === undefined || other == _b_.None){\n return _b_.NotImplemented\n }\n throw _b_.TypeError.$factory("no ordering relation " +\n "is defined for complex numbers")`;for(var $op in $B.$comps){complex["__"+$B.$comps[$op]+"__"]=Function("self","other",comp_func_body.replace(/>/gm,$op))}complex.real=function(self){return self.$real};complex.real.setter=function(){throw _b_.AttributeError.$factory("readonly attribute")};complex.imag=function(self){return self.$imag};complex.imag.setter=function(){throw _b_.AttributeError.$factory("readonly attribute")};var _real=1,_real_mantissa=2,_sign=3,_imag=4,_imag_mantissa=5,_j=6;var expected_class={__complex__:complex,__float__:_b_.float,__index__:_b_.int};function _convert(obj){var klass=obj.__class__||$B.get_class(obj);for(var method_name in expected_class){var missing={},method=$B.$getattr(klass,method_name,missing);if(method!==missing){var res=method(obj);if(!$B.$isinstance(res,expected_class[method_name])){throw _b_.TypeError.$factory(method_name+"returned non-"+expected_class[method_name].__name__+"(type "+$B.get_class(res)+")")}if(method_name=="__index__"&&$B.rich_comp("__gt__",res,__BRYTHON__.MAX_VALUE)){throw _b_.OverflowError.$factory("int too large to convert to float")}if(method_name=="__complex__"&&res.__class__!==complex){$B.warn(_b_.DeprecationWarning,"__complex__ returned "+`non-complex (type ${$B.class_name(res)}). `+"The ability to return an instance of a strict subclass "+"of complex is deprecated, and may be removed in a future "+"version of Python.")}return{result:res,method:method_name}}}return null}var make_complex=$B.make_complex=function(real,imag){return{__class__:complex,$real:_b_.float.$factory(real),$imag:_b_.float.$factory(imag)}};var c_1=make_complex(1,0);complex.$factory=function(){return complex.__new__(complex,...arguments)};$B.set_func_names(complex,"builtins");_b_.complex=complex})(__BRYTHON__);(function($B){var _b_=$B.builtins;var set_ops=["eq","le","lt","ge","gt","sub","rsub","and","rand","or","ror","xor","rxor"];function is_sublist(t1,t2){for(var i=0,ilen=t1.length;i-1){continue}else if(!_b_.hasattr(v.__class__,"__hash__")){return false}}return true};dict.$iter_items=function*(d){if(d.$all_str){for(let key in d.$strings){if(key!="$dict_strings"){yield{key:key,value:d.$strings[key]}}}}if(d.$jsobj){for(let key in d.$jsobj){if(!d.$exclude||!d.$exclude(key)){yield{key:key,value:d.$jsobj[key]}}}}else{var version=d.$version;for(var i=0,len=d._keys.length;i0};dict.__class_getitem__=$B.$class_getitem;dict.$lookup_by_key=function(d,key,hash){hash=hash===undefined?_b_.hash(key):hash;var indices=d.table[hash],index;if(indices!==undefined){for(var i=0,len=indices.length;ix!==undefined)))}return res};dict.$setitem_string=function(self,key,value){if(self.$all_str){self.$strings[key]=value;return _b_.None}else{var h=_b_.hash(key),indices=self.table[h];if(indices!==undefined){self._values[indices[0]]=value;return _b_.None}}var index=self._keys.length;self.$strings[key]=index;self._keys.push(key);self._values.push(value);self.$version++;return _b_.None};dict.$getitem=function(self,key,ignore_missing){if(self.$all_str){if(typeof key=="string"){if(self.$strings.hasOwnProperty(key)){return self.$strings[key]}}else{var hash_method=$B.$getattr($B.get_class(key),"__hash__");if(hash_method!==_b_.object.__hash__){convert_all_str(self);let lookup=dict.$lookup_by_key(self,key);if(lookup.found){return lookup.value}}}}else if(self.$jsobj){if(self.$exclude&&self.$exclude(key)){throw _b_.KeyError.$factory(key)}if(self.$jsobj.hasOwnProperty(key)){return self.$jsobj[key]}if(!self.table){throw _b_.KeyError.$factory(key)}}else{let lookup=dict.$lookup_by_key(self,key);if(lookup.found){return lookup.value}}if(!ignore_missing){if(self.__class__!==dict&&!ignore_missing){try{var missing_method=$B.$getattr(self.__class__,"__missing__",_b_.None)}catch(err){console.log(err)}if(missing_method!==_b_.None){return missing_method(self,key)}}}throw _b_.KeyError.$factory(key)};dict.__hash__=_b_.None;function init_from_list(self,args){var i=0;for(var item of args){if(item.length!=2){throw _b_.ValueError.$factory("dictionary "+`update sequence element #${i} has length ${item.length}; 2 is required`)}dict.$setitem(self,item[0],item[1]);i++}}dict.$set_string_no_duplicate=function(d,keys,string,value){if(typeof string!=="string"){throw _b_.TypeError.$factory("keywords must be strings")}if(keys.has(string)){throw _b_.TypeError.$factory("dict() got multiple values for keyword "+`argument '${string}'`)}d.$strings[string]=value;keys.add(string)};function add_mapping(d,obj){for(var entry of _b_.dict.$iter_items(obj)){dict.$setitem(d,entry.key,entry.value,entry.hash)}}function add_iterable(d,js_iterable){var i=0;for(var entry of js_iterable){var items=Array.from($B.make_js_iterator(entry));if(items.length!==2){throw _b_.ValueError.$factory("dictionary "+`update sequence element #${i} has length ${items.length}; 2 is required`)}dict.$setitem(d,items[0],items[1]);i++}}dict.__init__=function(self,first,second){if(first===undefined){return _b_.None}if(second===undefined){if(!first.$kw&&$B.$isinstance(first,$B.JSObj)){for(let key in first){dict.$setitem(self,key,first[key])}return _b_.None}else if(first.$kw){var keys=new Set;for(let item of first.$kw){if($B.$isinstance(item,dict)){for(let subitem of dict.$iter_items(item)){dict.$set_string_no_duplicate(self,keys,subitem.key,subitem.value)}}else{for(let key in item){dict.$set_string_no_duplicate(self,keys,key,item[key])}}}return _b_.None}else if(first[Symbol.iterator]){init_from_list(self,first);return _b_.None}else if(first.__class__===$B.generator){init_from_list(self,first.js_gen);return _b_.None}}var $=$B.args("dict",1,{self:null},["self"],arguments,{},"first","second");var args=$.first;if(args.length>1){if($B._experimental_dict){console.log("try dict(*args)");for(var arg of args){if(_b_.isinstance(arg,_b_.dict)){add_mapping(self,arg)}else{try{var js_iterable=$B.make_js_iterator(arg)}catch(err){console.log(arg);console.log(err);throw _b_.TypeError.$factory("expected mapping or "+`iterable, got ${$B.class_name(arg)}`)}add_iterable(self,js_iterable)}}}else{throw _b_.TypeError.$factory("dict expected at most 1 argument"+`, got ${args.length}`)}}else if(args.length==1){args=args[0];if(args.__class__===dict){for(let entry of dict.$iter_items(args)){dict.$setitem(self,entry.key,entry.value,entry.hash)}}else{var keys=$B.$getattr(args,"keys",null);if(keys!==null){var gi=$B.$getattr(args,"__getitem__",null);if(gi!==null){gi=$B.$call(gi);let kiter=_b_.iter($B.$call(keys)());while(true){try{let key=_b_.next(kiter),value=gi(key);dict.__setitem__(self,key,value)}catch(err){if(err.__class__===_b_.StopIteration){break}throw err}}}}else{if(!Array.isArray(args)){args=_b_.list.$factory(args)}init_from_list(self,args)}}}for(let item of _b_.dict.$iter_items($.second)){dict.$setitem(self,item.key,item.value)}return _b_.None};dict.__iter__=function(self){return _b_.iter(dict.keys(self))};dict.__ior__=function(self,other){dict.update(self,other);return self};dict.__len__=function(self){var _count=0;if(self.$all_str){return Object.keys(self.$strings).length}if(self.$jsobj){for(var attr in self.$jsobj){if(attr.charAt(0)!="$"&&(!self.$exclude||!self.$exclude(attr))){_count++}}return _count}for(var d of self._keys){if(d!==undefined){_count++}}return _count};dict.__ne__=function(self,other){var res=dict.__eq__(self,other);return res===_b_.NotImplemented?res:!res};dict.__new__=function(cls){if(cls===undefined){throw _b_.TypeError.$factory("int.__new__(): not enough arguments")}var instance=$B.empty_dict();instance.__class__=cls;if(cls!==dict){instance.__dict__=$B.empty_dict()}return instance};dict.__or__=function(self,other){if(!$B.$isinstance(other,dict)){return _b_.NotImplemented}var res=dict.copy(self);dict.update(res,other);return res};dict.__repr__=function(self){$B.builtins_repr_check(dict,arguments);if(self.$jsobj){return dict.__repr__(jsobj2dict(self.$jsobj,self.$exclude))}if($B.repr.enter(self)){return"{...}"}let res=[];for(let entry of dict.$iter_items(self)){res.push(_b_.repr(entry.key)+": "+_b_.repr(entry.value))}$B.repr.leave(self);return"{"+res.join(", ")+"}"};dict.$iter_items_reversed=function*(d){var version=d.$version;if(d.$all_str){for(var item of Object.entries(d.$strings).reverse()){yield $B.fast_tuple(item);if(d.$version!==version){throw _b_.RuntimeError.$factory("changed in iteration")}}}else{for(var i=d._keys.length-1;i>=0;i--){var key=d._keys[i];if(key!==undefined){yield $B.fast_tuple([key,d._values[i]]);if(d.$version!==version){throw _b_.RuntimeError.$factory("changed in iteration")}}}}if(d.$version!==version){throw _b_.RuntimeError.$factory("changed in iteration")}};dict.$iter_keys_reversed=function*(d){for(var entry of dict.$iter_items_reversed(d)){yield entry[0]}};dict.$iter_values_reversed=function*(d){for(var entry of dict.$iter_items_reversed(d)){yield entry[1]}};function make_reverse_iterator(name,iter_func){var klass=$B.make_class(name,(function(d){return{__class__:klass,d:d,iter:iter_func(d),make_iter:function(){return iter_func(d)}}}));klass.__iter__=function(self){self[Symbol.iterator]=self.make_iter;return self};klass.__next__=function(self){var res=self.iter.next();if(res.done){throw _b_.StopIteration.$factory("")}return res.value};klass.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])};$B.set_func_names(klass,"builtins");return klass}const dict_reversekeyiterator=make_reverse_iterator("dict_reversekeyiterator",dict.$iter_keys_reversed);dict.__reversed__=function(self){return dict_reversekeyiterator.$factory(self)};dict.__ror__=function(self,other){if(!$B.$isinstance(other,dict)){return _b_.NotImplemented}var res=dict.copy(other);dict.update(res,self);return res};dict.__setitem__=function(){var $=$B.args("__setitem__",3,{self:null,key:null,value:null},["self","key","value"],arguments,{},null,null);return dict.$setitem($.self,$.key,$.value)};function convert_all_str(d){d.$all_str=false;for(var key in d.$strings){dict.$setitem(d,key,d.$strings[key])}}dict.$setitem=function(self,key,value,$hash,from_setdefault){if(self[$B.JSOBJ]){value=$B.pyobj2jsobj(value);self[$B.JSOBJ][key]=value}if(self.$all_str){if(typeof key=="string"){var int=parseInt(key);if(isNaN(int)||int>=0){self.$strings[key]=value;return _b_.None}else{convert_all_str(self)}}else{convert_all_str(self)}}if(self.$jsobj){if(self.$from_js){value=$B.pyobj2jsobj(value)}if(self.$jsobj.__class__===_b_.type){self.$jsobj[key]=value;if(key=="__init__"||key=="__new__"){self.$jsobj.$factory=$B.$instance_creator(self.$jsobj)}}else{self.$jsobj[key]=value}return _b_.None}if(key instanceof String){key=key.valueOf()}var hash=$hash!==undefined?$hash:$B.$hash(key);var index;if(self.table[hash]===undefined){index=self._keys.length;self.table[hash]=[index]}else{if(!from_setdefault){var lookup=dict.$lookup_by_key(self,key,hash);if(lookup.found){self._values[lookup.index]=value;return _b_.None}}index=self._keys.length;if(self.table[hash]===undefined){self.table[hash]=[index]}else{self.table[hash].push(index)}}self._keys.push(key);self._values.push(value);self._hashes.push(hash);self.$version++;return _b_.None};$B.make_rmethods(dict);dict.clear=function(){var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null),self=$.self;self.table=Object.create(null);self._keys=[];self._values=[];self.$all_str=true;self.$strings=new $B.str_dict;if(self.$jsobj){for(var attr in self.$jsobj){if(attr.charAt(0)!=="$"&&attr!=="__class__"){delete self.$jsobj[attr]}}}self.$version++;return _b_.None};dict.copy=function(){var $=$B.args("copy",1,{self:null},["self"],arguments,{},null,null),self=$.self,res=$B.empty_dict();if(self.__class__===_b_.dict){$copy_dict(res,self);return res}var it=$B.make_js_iterator(self);for(var k of it){console.log("iteration yields key",k)}return res};dict.fromkeys=function(){var $=$B.args("fromkeys",3,{cls:null,keys:null,value:null},["cls","keys","value"],arguments,{value:_b_.None},null,null),keys=$.keys,value=$.value;var cls=$.cls,res=$B.$call(cls)(),klass=$B.get_class(res),keys_iter=$B.$iter(keys),setitem=klass===dict?dict.$setitem:$B.$getattr(klass,"__setitem__");while(1){try{var key=_b_.next(keys_iter);setitem(res,key,value)}catch(err){if($B.is_exc(err,[_b_.StopIteration])){return res}throw err}}};dict.get=function(){var $=$B.args("get",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:_b_.None},null,null);try{return dict.$getitem($.self,$.key,true)}catch(err){if($B.$isinstance(err,_b_.KeyError)){return $._default}else{throw err}}};var dict_items=$B.make_class("dict_items",(function(d){return{__class__:dict_items,dict:d,make_iter:function*(){for(var entry of dict.$iter_items(d)){yield $B.fast_tuple([entry.key,entry.value])}}}}));dict_items.__iter__=function(self){return dict_itemiterator.$factory(self.make_iter)};dict_items.__len__=function(self){return dict.__len__(self.dict)};dict_items.__reduce__=function(self){var items=$B.$list(Array.from(self.make_iter()));return $B.fast_tuple([_b_.iter,$B.fast_tuple([items])])};dict_items.__repr__=function(self){var items=Array.from(self.make_iter());items=items.map($B.fast_tuple);return"dict_items("+_b_.repr(items)+")"};const dict_reverseitemiterator=make_reverse_iterator("dict_reverseitemiterator",dict.$iter_items_reversed);dict_items.__reversed__=function(self){return dict_reverseitemiterator.$factory(self.dict)};make_view_comparison_methods(dict_items);$B.set_func_names(dict_items,"builtins");var dict_itemiterator=$B.make_class("dict_itemiterator",(function(make_iter){return{__class__:dict_itemiterator,iter:make_iter(),make_iter:make_iter}}));dict_itemiterator.__iter__=function(self){self[Symbol.iterator]=function(){return self.iter};return self};dict_itemiterator.__next__=function(self){var res=self.iter.next();if(res.done){throw _b_.StopIteration.$factory("")}return $B.fast_tuple(res.value)};dict_itemiterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])};$B.set_func_names(dict_itemiterator,"builtins");dict.items=function(self){$B.args("items",1,{self:null},["self"],arguments,{},null,null);return dict_items.$factory(self)};var dict_keys=$B.make_class("dict_keys",(function(d){return{__class__:dict_keys,dict:d,make_iter:function(){return dict.$iter_keys_check(d)}}}));dict_keys.__iter__=function(self){return dict_keyiterator.$factory(self.make_iter)};dict_keys.__len__=function(self){return dict.__len__(self.dict)};dict_keys.__reduce__=function(self){var items=$B.$list(Array.from(self.make_iter()));return $B.fast_tuple([_b_.iter,$B.fast_tuple([items])])};dict_keys.__repr__=function(self){var items=Array.from(self.make_iter());return"dict_keys("+_b_.repr(items)+")"};dict_keys.__reversed__=function(self){return dict_reversekeyiterator.$factory(self.dict)};make_view_comparison_methods(dict_keys);$B.set_func_names(dict_keys,"builtins");var dict_keyiterator=$B.make_class("dict_keyiterator",(function(make_iter){return{__class__:dict_keyiterator,iter:make_iter(),make_iter:make_iter}}));dict_keyiterator.__iter__=function(self){self[Symbol.iterator]=function(){return self.iter};return self};dict_keyiterator.__next__=function(self){var res=self.iter.next();if(res.done){throw _b_.StopIteration.$factory("")}return res.value};dict_keyiterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])};$B.set_func_names(dict_keyiterator,"builtins");dict.keys=function(self){$B.args("keys",1,{self:null},["self"],arguments,{},null,null);return dict_keys.$factory(self)};dict.pop=function(){var missing={},$=$B.args("pop",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:missing},null,null),self=$.self,key=$.key,_default=$._default;try{var res=dict.__getitem__(self,key);dict.__delitem__(self,key);return res}catch(err){if(err.__class__===_b_.KeyError){if(_default!==missing){return _default}throw err}throw err}};dict.popitem=function(self){$B.check_nb_args_no_kw("popitem",1,arguments);if(dict.__len__(self)==0){throw _b_.KeyError.$factory("'popitem(): dictionary is empty'")}if(self.$all_str){for(var key in self.$strings){}let res=$B.fast_tuple([key,self.$strings[key]]);delete self.$strings[key];self.$version++;return res}var index=self._keys.length-1;while(index>=0){if(self._keys[index]!==undefined){let res=$B.fast_tuple([self._keys[index],self._values[index]]);delete self._keys[index];delete self._values[index];self.$version++;return res}index--}};dict.setdefault=function(){var $=$B.args("setdefault",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:_b_.None},null,null),self=$.self,key=$.key,_default=$._default;_default=_default===undefined?_b_.None:_default;if(self.$all_str){if(!self.$strings.hasOwnProperty(key)){self.$strings[key]=_default}return self.$strings[key]}if(self.$jsobj){if(!self.$jsobj.hasOwnProperty(key)){self.$jsobj[key]=_default}return self.$jsobj[key]}var lookup=dict.$lookup_by_key(self,key);if(lookup.found){return lookup.value}var hash=lookup.hash;dict.$setitem(self,key,_default,hash,true);return _default};dict.update=function(){var $=$B.args("update",1,{self:null},["self"],arguments,{},"args","kw"),self=$.self,args=$.args,kw=$.kw;if(args.length>0){var o=args[0];if($B.$isinstance(o,dict)){if(o.$jsobj){o=jsobj2dict(o.$jsobj)}$copy_dict(self,o)}else if(_b_.hasattr(o,"keys")){var _keys=_b_.list.$factory($B.$call($B.$getattr(o,"keys"))());for(let i=0,len=_keys.length;i-1){continue}if(typeof dict[attr]=="function"){mappingproxy[attr]=function(key){return function(){return dict[key].apply(null,arguments)}}(attr)}else{mappingproxy[attr]=dict[attr]}}$B.set_func_names(mappingproxy,"builtins");function jsobj2dict(x,exclude){exclude=exclude||function(){return false};var d=$B.empty_dict();for(var attr in x){if(attr.charAt(0)!="$"&&!exclude(attr)){if(x[attr]===null){dict.$setitem(d,attr,_b_.None)}else if(x[attr]===undefined){continue}else if(x[attr].$jsobj===x){dict.$setitem(d,attr,d)}else{dict.$setitem(d,attr,$B.jsobj2pyobj(x[attr]))}}}return d}$B.obj_dict=function(obj,exclude){var klass=obj.__class__||$B.get_class(obj);if(!(obj instanceof $B.str_dict)&&klass!==undefined&&klass.$native){throw $B.attr_error("__dict__",obj)}var res={__class__:dict,$jsobj:obj,$exclude:exclude||function(){return false}};return res}})(__BRYTHON__);(function($B){var _b_=$B.builtins,isinstance=$B.$isinstance;function check_not_tuple(self,attr){if(self.__class__===tuple){throw $B.attr_error(attr,self)}}var list={__class__:_b_.type,__qualname__:"list",__mro__:[_b_.object],$is_class:true,$native:true,$match_sequence_pattern:true,__dir__:_b_.object.__dir__};list.__add__=function(self,other){if($B.get_class(self)!==$B.get_class(other)){var this_name=$B.class_name(self);var radd=$B.$getattr(other,"__radd__",null);if(radd===null){throw _b_.TypeError.$factory("can only concatenate "+this_name+' (not "'+$B.class_name(other)+'") to '+this_name)}return _b_.NotImplemented}var res=self.slice();for(const item of other){res.push(item)}if(isinstance(self,tuple)){return tuple.$factory(res)}else{return $B.$list(res)}};list.__bool__=function(self){return list.__len__(self)>0};list.__class_getitem__=$B.$class_getitem;list.__contains__=function(){var $=$B.args("__contains__",2,{self:null,item:null},["self","item"],arguments,{},null,null),self=$.self,item=$.item;for(var _item of self){if($B.is_or_equals(_item,item)){return true}}return false};list.__delitem__=function(self,arg){if(isinstance(arg,_b_.int)){let pos=arg;if(arg<0){pos=self.length+pos}if(pos>=0&&pos0?0:self.length}var stop=arg.stop;if(stop===_b_.None){stop=step>0?self.length:0}if(start<0){start=self.length+start}if(stop<0){stop=self.length+stop}let res=[],pos=0;if(step>0){if(stop>start){for(let i=start;istop;i+=step){if(self[i]!==undefined){res[pos++]=i}}res.reverse()}}let i=res.length;while(i--){self.splice(res[i],1)}return _b_.None}if(_b_.hasattr(arg,"__int__")||_b_.hasattr(arg,"__index__")){list.__delitem__(self,_b_.int.$factory(arg));return _b_.None}throw _b_.TypeError.$factory($B.class_name(self)+" indices must be integer, not "+$B.class_name(arg))};list.__eq__=function(self,other){if(other[$B.PYOBJ]){other=other[$B.PYOBJ]}var klass=isinstance(self,list)?list:tuple;if(isinstance(other,klass)){if(other.length==self.length){var i=self.length;while(i--){if(!$B.is_or_equals(self[i],other[i])){return false}}return true}return false}return _b_.NotImplemented};list.__getitem__=function(self,key){$B.check_nb_args_no_kw("__getitem__",2,arguments);return list.$getitem(self,key)};list.$getitem=function(self,key){var klass=self.__class__||$B.get_class(self);var factory=function(list_res){list_res.__class__=klass;return list_res};var int_key;try{int_key=$B.PyNumber_Index(key)}catch(err){}if(int_key!==undefined){let items=self.valueOf(),pos=int_key;if(int_key<0){pos=items.length+pos}if(pos>=0&&pos0){if(stop<=start){return factory(res)}for(let i=start;istart){return factory(res)}for(let i=start;i>stop;i+=step){res[pos++]=items[i]}return factory(res)}}throw _b_.TypeError.$factory($B.class_name(self)+" indices must be integer, not "+$B.class_name(key))};list.__ge__=function(self,other){if(!isinstance(other,list)){return _b_.NotImplemented}var res=list.__le__(other,self);if(res===_b_.NotImplemented){return res}return res};list.__gt__=function(self,other){if(!isinstance(other,list)){return _b_.NotImplemented}var res=list.__lt__(other,self);if(res===_b_.NotImplemented){return res}return res};list.__hash__=_b_.None;list.__iadd__=function(){var $=$B.args("__iadd__",2,{self:null,x:null},["self","x"],arguments,{},null,null);var x=list.$factory($.x);for(var i=0;i1){throw _b_.TypeError.$factory("expected at most 1 argument, got "+args.length)}if(_b_.dict.__len__(kw)>0){throw _b_.TypeError.$factory("list() takes no keyword arguments")}while(self.length>0){self.pop()}var arg=args[0];if(arg===undefined){return _b_.None}var pos=0;for(var item of $B.make_js_iterator(arg)){self[pos++]=item}return _b_.None};var list_iterator=$B.make_iterator_class("list_iterator");list_iterator.__reduce__=list_iterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([list.$factory(self)]),0])};list.__iter__=function(self){return list_iterator.$factory(self)};list.__le__=function(self,other){if(!isinstance(other,[list,_b_.tuple])){return _b_.NotImplemented}var i=0;while(i$B.max_array_size/other){throw _b_.OverflowError.$factory(`cannot fit `+`'${$B.class_name(other)}' into an index-sized integer`)}var res=[],$temp=self.slice(),len=$temp.length;for(var i=0;i=0&&pos0){if(args.length==1){for(var item of $B.make_js_iterator(args[0])){self.push(item)}}else{throw _b_.TypeError.$factory("tuple expected at most 1 "+`argument, got ${args.length}`)}}if(cls===tuple&&_b_.dict.__len__(kw)>0){throw _b_.TypeError.$factory("tuple() takes no keyword arguments")}return self};tuple.__repr__=function(self){$B.builtins_repr_check(tuple,arguments);return list_repr(self)};$B.set_func_names(tuple,"builtins");_b_.list=list;_b_.tuple=tuple;_b_.object.__bases__=tuple.$factory();_b_.type.__bases__=$B.fast_tuple([_b_.object])})(__BRYTHON__);(function($B){var _b_=$B.builtins;function to_simple(value){switch(typeof value){case"string":case"number":return value;case"boolean":return value?"true":"false";case"object":if(value===_b_.None){return"null"}else if(value instanceof Number){return value.valueOf()}else if(value instanceof String){return value.valueOf()}break;default:throw _b_.TypeError.$factory("keys must be str, int, "+"float, bool or None, not "+$B.class_name(value))}}$B.pyobj2structuredclone=function(obj,strict){strict=strict===undefined?true:strict;if(typeof obj=="boolean"||typeof obj=="number"||typeof obj=="string"||obj instanceof String){return obj}else if(obj.__class__===_b_.float){return obj.value}else if(obj===_b_.None){return null}else if(Array.isArray(obj)||obj.__class__===_b_.list||obj.__class__===_b_.tuple||obj.__class__===js_array){let res=new Array(obj.length);for(var i=0,len=obj.length;i`}var js_repr=Object.prototype.toString.call(_self);return``};$B.JSObj.bind=function(_self,evt,func){var js_func=function(ev){try{return func(jsobj2pyobj(ev))}catch(err){if(err.__class__!==undefined){$B.handle_error(err)}else{try{$B.$getattr($B.get_stderr(),"write")(err)}catch(err1){console.log(err)}}}};Object.defineProperty(_self,"$brython_events",{value:_self.$brython_events||{},writable:true});if(_self.$brython_events){_self.$brython_events[evt]=_self.$brython_events[evt]||[];_self.$brython_events[evt].push([func,js_func])}_self.addEventListener(evt,js_func);return _b_.None};$B.JSObj.bindings=function(_self){var res=$B.empty_dict();if(_self.$brython_events){for(var key in _self.$brython_events){_b_.dict.$setitem(res,key,$B.fast_tuple(_self.$brython_events[key].map((x=>x[0]))))}}return res};$B.JSObj.unbind=function(_self,evt,func){if(!_self.$brython_events){return _b_.None}if(!_self.$brython_events[evt]){return _b_.None}var events=_self.$brython_events[evt];if(func===undefined){for(var item of events){_self.removeEventListener(evt,item[1])}delete _self.$brython_events[evt]}else{for(var i=0,len=events.length;i-1){return function(){var args=new Array(arguments.length);args[0]=arguments[0];for(var i=1,len=arguments.length;i-1){return function(){var pylist=$B.$list(arguments[0].map(jsobj2pyobj));return jsobj2pyobj(_b_.list[attr].call(null,pylist,...Array.from(arguments).slice(1)))}}else if(js_array.hasOwnProperty(attr)){return js_array[attr]}else if(["__repr__","__str__"].includes(attr)){return function(js_array){var t=jsobj2pyobj(js_array);return _b_.list[attr]($B.$list(t))}}return function(js_array){var t=jsobj2pyobj(js_array);return _b_.list[attr](t)}};$B.set_func_names(js_list_meta,"builtins");$B.SizedJSObj=$B.make_class("SizedJavascriptObject");$B.SizedJSObj.__bases__=[$B.JSObj];$B.SizedJSObj.__mro__=[$B.JSObj,_b_.object];$B.SizedJSObj.__len__=function(_self){return _self.length};$B.set_func_names($B.SizedJSObj,"builtins");$B.IterableJSObj=$B.make_class("IterableJavascriptObject");$B.IterableJSObj.__bases__=[$B.JSObj];$B.IterableJSObj.__mro__=[$B.JSObj,_b_.object];$B.IterableJSObj.__contains__=function(self,key){if(self.contains!==undefined&&typeof self.contains=="function"){return self.contains(key)}else{for(var item of $B.IterableJSObj.__iter__(self).it){if($B.is_or_equals(item,key)){return true}}return false}};$B.IterableJSObj.__iter__=function(_self){return{__class__:$B.IterableJSObj,it:_self[Symbol.iterator]()}};$B.IterableJSObj.__len__=function(_self){return _self.length};$B.IterableJSObj.__next__=function(_self){var value=_self.it.next();if(!value.done){return jsobj2pyobj(value.value)}throw _b_.StopIteration.$factory("")};$B.set_func_names($B.IterableJSObj,"builtins");var js_array=$B.js_array=$B.make_class("Array");js_array.__class__=js_list_meta;js_array.__mro__=[$B.JSObj,_b_.object];js_array.__add__=function(_self,other){var res=_self.slice();if($B.$isinstance(other,js_array)){return _self.slice().concat(other)}for(var item of $B.make_js_iterator(other)){res.push(pyobj2jsobj(item))}return res};js_array.__getattribute__=function(_self,attr){if(_b_.list[attr]===undefined){var proto=Object.getPrototypeOf(_self),res=proto[attr];if(res!==undefined){return jsobj2pyobj(res,_self)}if(_self.hasOwnProperty(attr)){return jsobj2pyobj(_self[attr])}if(js_array.hasOwnProperty(attr)){return js_array[attr]}throw $B.attr_error(attr,_self)}if(js_array.hasOwnProperty(attr)){return function(){return js_array[attr](_self,...arguments)}}return function(){var args=pyobj2jsobj(Array.from(arguments));return _b_.list[attr].call(null,_self,...args)}};js_array.__getitem__=function(_self,i){i=$B.PyNumber_Index(i);return jsobj2pyobj(_self[i])};js_array.__iadd__=function(_self,other){if($B.$isinstance(other,js_array)){for(var item of other){_self.push(item)}}else{for(var item of $B.make_js_iterator(other)){_self.push($B.pyobj2jsobj(item))}}return _self};js_array.__iter__=function(_self){return js_array_iterator.$factory(_self)};js_array.__mul__=function(_self,nb){var res=_self.slice();for(var i=1;i-1){return $B.SizedJSObj}return $B.JSObj};$B.JSMeta=$B.make_class("JSMeta");$B.JSMeta.__call__=function(cls){var extra_args=new Array(arguments.length-1),klass=arguments[0];for(var i=1,len=arguments.length;i`};$B.generator.close=function(self){var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}try{$B.generator.throw(self,_b_.GeneratorExit.$factory())}catch(err){if(!$B.is_exc(err,[_b_.GeneratorExit,_b_.StopIteration])){$B.frame_obj=save_frame_obj;throw _b_.RuntimeError.$factory("generator ignored GeneratorExit")}}$B.frame_obj=save_frame_obj};$B.generator.send=function(self,value){var gen=self.js_gen;gen.$has_run=true;if(gen.$finished){throw _b_.StopIteration.$factory(value)}if(gen.gi_running===true){throw _b_.ValueError.$factory("generator already executing")}gen.gi_running=true;var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}try{var res=gen.next(value)}catch(err){gen.$finished=true;$B.frame_obj=save_frame_obj;throw err}if($B.frame_obj!==null&&$B.frame_obj.frame===self.$frame){$B.leave_frame()}$B.frame_obj=save_frame_obj;if(res.value&&res.value.__class__===$GeneratorReturn){gen.$finished=true;throw _b_.StopIteration.$factory(res.value.value)}gen.gi_running=false;if(res.done){throw _b_.StopIteration.$factory(res.value)}return res.value};$B.generator.throw=function(){var $=$B.args("throw",4,{self:null,type:null,value:null,traceback:null},["self","type","value","traceback"],arguments,{value:_b_.None,traceback:_b_.None},null,null),self=$.self,type=$.type,value=$.value,traceback=$.traceback;var gen=self.js_gen,exc=type;if(exc.$is_class){if(!_b_.issubclass(type,_b_.BaseException)){throw _b_.TypeError.$factory("exception value must be an "+"instance of BaseException")}else if(value===undefined||value===_b_.None){exc=$B.$call(exc)()}else if($B.$isinstance(value,type)){exc=value}}else{if(value===_b_.None){value=exc}else{exc=$B.$call(exc)(value)}}if(traceback!==_b_.None){exc.$traceback=traceback}var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}var res=gen.throw(exc);$B.frame_obj=save_frame_obj;if(res.done){throw _b_.StopIteration.$factory(res.value)}return res.value};$B.set_func_names($B.generator,"builtins");$B.async_generator=$B.make_class("async_generator",(function(func){var f=function(){var gen=func.apply(null,arguments);var res=Object.create(null);res.__class__=$B.async_generator;res.js_gen=gen;return res};return f}));$B.async_generator.__aiter__=function(self){return self};$B.async_generator.__anext__=function(self){return $B.async_generator.asend(self,_b_.None)};$B.async_generator.aclose=function(self){self.js_gen.$finished=true;return _b_.None};$B.async_generator.asend=async function(self,value){var gen=self.js_gen;if(gen.$finished){throw _b_.StopAsyncIteration.$factory(value)}if(gen.ag_running===true){throw _b_.ValueError.$factory("generator already executing")}gen.ag_running=true;var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}try{var res=await gen.next(value)}catch(err){gen.$finished=true;$B.frame_obj=save_frame_obj;throw err}if($B.frame_obj!==null&&$B.frame_obj.frame===self.$frame){$B.leave_frame()}$B.frame_obj=save_frame_obj;if(res.done){throw _b_.StopAsyncIteration.$factory(value)}if(res.value.__class__===$GeneratorReturn){gen.$finished=true;throw _b_.StopAsyncIteration.$factory(res.value.value)}gen.ag_running=false;return res.value};$B.async_generator.athrow=async function(self,type,value,traceback){var gen=self.js_gen,exc=type;if(exc.$is_class){if(!_b_.issubclass(type,_b_.BaseException)){throw _b_.TypeError.$factory("exception value must be an "+"instance of BaseException")}else if(value===undefined){value=$B.$call(exc)()}}else{if(value===undefined){value=exc}else{exc=$B.$call(exc)(value)}}if(traceback!==undefined){exc.$traceback=traceback}var save_frame_obj=$B.frame_obj;if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)}await gen.throw(value);$B.frame_obj=save_frame_obj};$B.set_func_names($B.async_generator,"builtins")})(__BRYTHON__);(function($B){var _b_=$B.builtins,object=_b_.object,_window=globalThis;function convertDomValue(v){if(v===null||v===undefined){return _b_.None}return $B.jsobj2pyobj(v)}var py_immutable_to_js=$B.py_immutable_to_js=function(pyobj){if($B.$isinstance(pyobj,_b_.float)){return pyobj.value}else if($B.$isinstance(pyobj,$B.long_int)){return $B.long_int.$to_js_number(pyobj)}return pyobj};function js_immutable_to_py(jsobj){if(typeof jsobj=="number"){if(Number.isSafeInteger(jsobj)){return jsobj}else if(Number.isInteger(jsobj)){return $B.fast_long_int(BigInt(jsobj+""))}else{return $B.fast_float(jsobj)}}return jsobj}function $getPosition(e){var left=0,top=0,width=e.width||e.offsetWidth,height=e.height||e.offsetHeight;while(e.offsetParent){left+=e.offsetLeft;top+=e.offsetTop;e=e.offsetParent}left+=e.offsetLeft||0;top+=e.offsetTop||0;if(e.parentElement){var parent_pos=$getPosition(e.parentElement);left+=parent_pos.left;top+=parent_pos.top}return{left:left,top:top,width:width,height:height}}var $mouseCoords=$B.$mouseCoords=function(ev){if(ev.type.startsWith("touch")){let res={};res.x=_b_.int.$factory(ev.touches[0].screenX);res.y=_b_.int.$factory(ev.touches[0].screenY);res.__getattr__=function(attr){return this[attr]};res.__class__="MouseCoords";return res}var posx=0,posy=0;if(!ev){ev=_window.event}if(ev.pageX||ev.pageY){posx=ev.pageX;posy=ev.pageY}else if(ev.clientX||ev.clientY){posx=ev.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;posy=ev.clientY+document.body.scrollTop+document.documentElement.scrollTop}let res={};res.x=_b_.int.$factory(posx);res.y=_b_.int.$factory(posy);res.__getattr__=function(attr){return this[attr]};res.__class__="MouseCoords";return res};$B.$isNode=function(o){return typeof Node==="object"?o instanceof Node:o&&typeof o==="object"&&typeof o.nodeType==="number"&&typeof o.nodeName==="string"};$B.$isNodeList=function(nodes){try{var result=Object.prototype.toString.call(nodes);var re=new RegExp("^\\[object (HTMLCollection|NodeList)\\]$");return typeof nodes==="object"&&re.exec(result)!==null&&nodes.length!==undefined&&(nodes.length==0||typeof nodes[0]==="object"&&nodes[0].nodeType>0)}catch(err){return false}};var $DOMEventAttrs_W3C=["NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","type","target","currentTarget","eventPhase","bubbles","cancelable","timeStamp","stopPropagation","preventDefault","initEvent"];var $DOMEventAttrs_IE=["altKey","altLeft","button","cancelBubble","clientX","clientY","contentOverflow","ctrlKey","ctrlLeft","data","dataFld","dataTransfer","fromElement","keyCode","nextPage","offsetX","offsetY","origin","propertyName","reason","recordset","repeat","screenX","screenY","shiftKey","shiftLeft","source","srcElement","srcFilter","srcUrn","toElement","type","url","wheelDelta","x","y"];$B.$isEvent=function(obj){var flag=true;for(let attr of $DOMEventAttrs_W3C){if(obj[attr]===undefined){flag=false;break}}if(flag){return true}for(let attr of $DOMEventAttrs_IE){if(obj[attr]===undefined){return false}}return true};var $NodeTypes={1:"ELEMENT",2:"ATTRIBUTE",3:"TEXT",4:"CDATA_SECTION",5:"ENTITY_REFERENCE",6:"ENTITY",7:"PROCESSING_INSTRUCTION",8:"COMMENT",9:"DOCUMENT",10:"DOCUMENT_TYPE",11:"DOCUMENT_FRAGMENT",12:"NOTATION"};var Attributes=$B.make_class("Attributes",(function(elt){return{__class__:Attributes,elt:elt}}));Attributes.__contains__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null);if($.self.elt instanceof SVGElement){return $.self.elt.hasAttributeNS(null,$.key)}else if(typeof $.self.elt.hasAttribute=="function"){return $.self.elt.hasAttribute($.key)}return false};Attributes.__delitem__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null);if(!Attributes.__contains__($.self,$.key)){throw _b_.KeyError.$factory($.key)}if($.self.elt instanceof SVGElement){$.self.elt.removeAttributeNS(null,$.key);return _b_.None}else if(typeof $.self.elt.hasAttribute=="function"){$.self.elt.removeAttribute($.key);return _b_.None}};Attributes.__getitem__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null);if($.self.elt instanceof SVGElement&&$.self.elt.hasAttributeNS(null,$.key)){return $.self.elt.getAttributeNS(null,$.key)}else if(typeof $.self.elt.hasAttribute=="function"&&$.self.elt.hasAttribute($.key)){return $.self.elt.getAttribute($.key)}throw _b_.KeyError.$factory($.key)};Attributes.__iter__=function(self){self.$counter=0;var attrs=self.elt.attributes,items=[];for(var i=0;i");var DOMEvent=$B.DOMEvent=$B.make_class("DOMEvent",(function(evt_name){return DOMEvent.__new__(DOMEvent,evt_name)}));DOMEvent.__new__=function(cls,evt_name){var ev=new Event(evt_name);ev.__class__=DOMEvent;if(ev.preventDefault===undefined){ev.preventDefault=function(){ev.returnValue=false}}if(ev.stopPropagation===undefined){ev.stopPropagation=function(){ev.cancelBubble=true}}return ev};DOMEvent.__setattr__=function(self,attr,value){self[attr]=value};function dom2svg(svg_elt,coords){var pt=svg_elt.createSVGPoint();pt.x=coords.x;pt.y=coords.y;return pt.matrixTransform(svg_elt.getScreenCTM().inverse())}DOMEvent.__getattribute__=function(ev,attr){switch(attr){case"__repr__":case"__str__":return function(){return""};case"x":return $mouseCoords(ev).x;case"y":return $mouseCoords(ev).y;case"data":if(ev.dataTransfer!==null&&ev.dataTransfer!==undefined){return Clipboard.$factory(ev.dataTransfer)}else if(typeof Worker!=="undefined"&&ev.target instanceof Worker){return $B.structuredclone2pyobj(ev.data)}else if(typeof DedicatedWorkerGlobalScope!=="undefined"&&ev.target instanceof DedicatedWorkerGlobalScope){return $B.structuredclone2pyobj(ev.data)}return convertDomValue(ev.data);case"target":if(ev.target!==undefined){return DOMNode.$factory(ev.target)}break;case"char":return String.fromCharCode(ev.which);case"svgX":if(ev.target instanceof SVGSVGElement){return Math.floor(dom2svg(ev.target,$mouseCoords(ev)).x)}throw _b_.AttributeError.$factory("event target is not an SVG "+"element");case"svgY":if(ev.target instanceof SVGSVGElement){return Math.floor(dom2svg(ev.target,$mouseCoords(self)).y)}throw _b_.AttributeError.$factory("event target is not an SVG "+"element")}var res=ev[attr];if(res!==undefined){if(typeof res=="function"){var func=function(){var args=[];for(var i=0;i");var dom={File:function(){},FileReader:function(){}};dom.File.__class__=_b_.type;dom.File.__str__=function(){return""};dom.FileReader.__class__=_b_.type;dom.FileReader.__str__=function(){return""};var DOMNode=$B.make_class("DOMNode",(function(elt){return elt}));DOMNode.__add__=function(self,other){var res=TagSum.$factory();res.children=[self];var pos=1;if($B.$isinstance(other,TagSum)){res.children=res.children.concat(other.children)}else if($B.$isinstance(other,[_b_.str,_b_.int,_b_.float,_b_.list,_b_.dict,_b_.set,_b_.tuple])){res.children[pos++]=DOMNode.$factory(document.createTextNode(_b_.str.$factory(other)))}else if($B.$isinstance(other,DOMNode)){res.children[pos++]=other}else{try{res.children=res.children.concat(_b_.list.$factory(other))}catch(err){throw _b_.TypeError.$factory("can't add '"+$B.class_name(other)+"' object to DOMNode instance")}}return res};DOMNode.__bool__=function(){return true};DOMNode.__contains__=function(self,key){if(self.nodeType==9&&typeof key=="string"){return document.getElementById(key)!==null}if(self.length!==undefined&&typeof self.item=="function"){for(var i=0,len=self.length;i-1){return function(selector){if(selector===undefined){self.select();return _b_.None}return DOMNode.select(self,selector)}}if(attr=="query"&&self.nodeType==9){let res={__class__:Query,_keys:$B.$list([]),_values:{}};let qs=location.search.substr(1).split("&");if(location.search!=""){for(let i=0;i-1){res._values[key].push(value)}else{res._keys.push(key);res._values[key]=[value]}}}return res}var klass=$B.get_class(self);var property=self[attr];if(property!==undefined&&self.__class__&&klass.__module__!="browser.html"&&klass.__module__!="browser.svg"&&!klass.$webcomponent){var from_class=$B.$getattr(klass,attr,null);if(from_class!==null){property=from_class;if(typeof from_class==="function"){return property.bind(self,self)}}else{var bases=self.__class__.__bases__;var show_message=true;for(var base of bases){if(base.__module__=="browser.html"){show_message=false;break}}if(show_message){from_class=$B.$getattr(self.__class__,attr,_b_.None);if(from_class!==_b_.None){var frame=$B.frame_obj.frame,line=frame.$lineno;console.info("Warning: line "+line+", "+self.tagName+" element has instance attribute '"+attr+"' set."+" Attribute of class "+$B.class_name(self)+" is ignored.")}}}}if(property===undefined){if(self.tagName){var ce=customElements.get(self.tagName.toLowerCase());if(ce!==undefined&&ce.$cls!==undefined){var save_class=self.__class__;self.__class__=ce.$cls;try{let res=_b_.object.__getattribute__(self,attr);self.__class__=save_class;return res}catch(err){self.__class__=save_class;if(!$B.is_exc(err,[_b_.AttributeError])){throw err}}}}else{return object.__getattribute__(self,attr)}}var res=property;if(res!==undefined){if(res===null){return res}if(typeof res==="function"){if(self.__class__&&self.__class__.$webcomponent){var method=$B.$getattr(self.__class__,attr,null);if(method!==null){return res.bind(self)}}if(res.$is_func){return res}var func=function(f,elt){return function(){var args=[];for(var i=0;i0){var res=TagSum.$factory();var pos=res.children.length;for(var i=0;i"}var res=""};DOMNode.__setattr__=function(self,attr,value){switch(attr){case"left":case"top":case"width":case"height":if($B.$isinstance(value,[_b_.int,_b_.float])&&self.nodeType==1){self.style[attr]=value+"px";return _b_.None}else{throw _b_.ValueError.$factory(attr+" value should be"+" an integer or float, not "+$B.class_name(value))}}if(DOMNode["set_"+attr]!==undefined){return DOMNode["set_"+attr](self,value)}function warn(msg){console.log(msg);var frame=$B.frame_obj.frame;if(!frame){return}if($B.get_option("debug")>0){var file=frame.__file__,lineno=frame.$lineno;console.log("module",frame[2],"line",lineno);if($B.file_cache.hasOwnProperty(file)){var src=$B.file_cache[file];console.log(src.split("\n")[lineno-1])}}else{console.log("module",frame[2])}}var proto=Object.getPrototypeOf(self),nb=0;while(!!proto&&proto!==Object.prototype&&nb++<10){var descriptors=Object.getOwnPropertyDescriptors(proto);if(!!descriptors&&typeof descriptors.hasOwnProperty=="function"){if(descriptors.hasOwnProperty(attr)){if(!descriptors[attr].writable&&descriptors[attr].set===undefined){warn("Warning: property '"+attr+"' is not writable. Use element.attrs['"+attr+"'] instead.")}break}}else{break}proto=Object.getPrototypeOf(proto)}if(self.style&&self.style[attr]!==undefined&&attr!="src"){warn("Warning: '"+attr+"' is a property of element.style")}self[attr]=py_immutable_to_js(value);return _b_.None};DOMNode.__setitem__=function(self,key,value){if(typeof key=="number"){self.childNodes[key]=value}else if(typeof key=="string"){if(self.attributes){if(self instanceof SVGElement){self.setAttributeNS(null,key,value)}else if(typeof self.setAttribute=="function"){self.setAttribute(key,value)}}}};DOMNode.abs_left={__get__:function(self){return $getPosition(self).left},__set__:function(){throw _b_.AttributeError.$factory("'DOMNode' objectattribute "+"'abs_left' is read-only")}};DOMNode.abs_top={__get__:function(self){return $getPosition(self).top},__set__:function(){throw _b_.AttributeError.$factory("'DOMNode' objectattribute "+"'abs_top' is read-only")}};DOMNode.attach=DOMNode.__le__;DOMNode.bind=function(){var $=$B.args("bind",4,{self:null,event:null,func:null,options:null},["self","event","func","options"],arguments,{func:_b_.None,options:_b_.None},null,null),self=$.self,event=$.event,func=$.func,options=$.options;if(func===_b_.None){return function(f){return DOMNode.bind(self,event,f)}}var callback=function(f){return function(ev){try{return $B.$call(f)($DOMEvent(ev))}catch(err){if(err.__class__!==undefined){$B.handle_error(err)}else{try{$B.$getattr($B.get_stderr(),"write")(err)}catch(err1){console.log(err)}}}}}(func);callback.$infos=func.$infos;callback.$attrs=func.$attrs||{};callback.$func=func;if(typeof options=="boolean"){self.addEventListener(event,callback,options)}else if(options.__class__===_b_.dict){self.addEventListener(event,callback,_b_.dict.$to_obj(options))}else if(options===_b_.None){self.addEventListener(event,callback,false)}self.$events=self.$events||{};self.$events[event]=self.$events[event]||[];self.$events[event].push([func,callback]);return self};DOMNode.children=function(self){var res=[];if(self.nodeType==9){self=self.body}for(var child of self.children){res.push(DOMNode.$factory(child))}return $B.$list(res)};DOMNode.child_nodes=function(self){var res=[];if(self.nodeType==9){self=self.body}for(var child of self.childNodes){res.push(DOMNode.$factory(child))}return $B.$list(res)};DOMNode.clear=function(){var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null),self=$.self;if(self.nodeType==9){self=self.body}while(self.firstChild){self.removeChild(self.firstChild)}};DOMNode.Class=function(self){if(self.className!==undefined){return self.className}return _b_.None};DOMNode.class_name=function(self){return DOMNode.Class(self)};DOMNode.clone=function(self){var res=DOMNode.$factory(self.cloneNode(true));var events=self.$events||{};for(var event in events){var evt_list=events[event];evt_list.forEach((function(evt){var func=evt[0];DOMNode.bind(res,event,func)}))}return res};DOMNode.closest=function(){var $=$B.args("closest",2,{self:null,selector:null},["self","selector"],arguments,{},null,null),self=$.self,selector=$.selector;if(self.closest===undefined){throw _b_.AttributeError.$factory(_b_.str.$factory(self)+" has no attribute 'closest'")}var res=self.closest(selector);if(res===null){throw _b_.KeyError.$factory("no parent with selector "+selector)}return DOMNode.$factory(res)};DOMNode.bindings=function(self){var res=$B.empty_dict();for(var key in self.$events){_b_.dict.$setitem(res,key,self.$events[key].map((x=>x[1])))}return res};DOMNode.events=function(self,event){self.$events=self.$events||{};var evt_list=self.$events[event]=self.$events[event]||[],callbacks=[];evt_list.forEach((function(evt){callbacks.push(evt[1])}));return $B.$list(callbacks)};function make_list(node_list){var res=[];for(var i=0;i-1};Query.__getitem__=function(self,key){var result=self._values[key];if(result===undefined){throw _b_.KeyError.$factory(key)}else if(result.length==1){return result[0]}return result};var Query_iterator=$B.make_iterator_class("query string iterator");Query.__iter__=function(self){return Query_iterator.$factory(self._keys)};Query.__setitem__=function(self,key,value){self._values[key]=[value];return _b_.None};Query.__str__=Query.__repr__=function(self){var elts=[];for(var key in self._values){for(const val of self._values[key]){elts.push(encodeURIComponent(key)+"="+encodeURIComponent(val))}}if(elts.length==0){return""}else{return"?"+elts.join("&")}};Query.getfirst=function(self,key,_default){var result=self._values[key];if(result===undefined){if(_default===undefined){return _b_.None}return _default}return result[0]};Query.getlist=function(self,key){return $B.$list(self._values[key]??[])};Query.getvalue=function(self,key,_default){try{return Query.__getitem__(self,key)}catch(err){if(_default===undefined){return _b_.None}return _default}};Query.keys=function(self){return self._keys};$B.set_func_names(Query,"");var TagSum=$B.make_class("TagSum",(function(){return{__class__:TagSum,children:[],toString:function(){return"(TagSum)"}}}));TagSum.appendChild=function(self,child){self.children.push(child)};TagSum.__add__=function(self,other){if($B.get_class(other)===TagSum){self.children=self.children.concat(other.children)}else if($B.$isinstance(other,[_b_.str,_b_.int,_b_.float,_b_.dict,_b_.set,_b_.list])){self.children=self.children.concat(DOMNode.$factory(document.createTextNode(other)))}else{self.children.push(other)}return self};TagSum.__radd__=function(self,other){var res=TagSum.$factory();res.children=self.children.slice();res.children.splice(0,0,DOMNode.$factory(document.createTextNode(other)));return res};TagSum.__repr__=function(self){var res=" ";for(var i=0;i");$B.TagSum=TagSum;$B.DOMNode=DOMNode})(__BRYTHON__);(function($B){$B.pattern_match=function(subject,pattern){var _b_=$B.builtins,frame=$B.frame_obj.frame,locals=frame[1];function bind(pattern,subject){if(pattern.alias){locals[pattern.alias]=subject}}if(pattern.sequence){if($B.$isinstance(subject,[_b_.str,_b_.bytes,_b_.bytearray])){return false}let Sequence;if($B.imported["collections.abc"]){Sequence=$B.imported["collections.abc"].Sequence}let deque;if($B.imported["collections"]){deque=$B.imported["collections"].deque}let supported=false;let klass=subject.__class__||$B.get_class(subject);for(let base of[klass].concat(klass.__bases__||[])){if(base.$match_sequence_pattern){supported=true;break}else if(base===Sequence||base==deque){supported=true;break}}if(!supported&&Sequence){supported=_b_.issubclass(klass,Sequence)}if(!supported){return false}if(pattern.sequence.length==1&&pattern.sequence[0].capture_starred=="_"){return true}let subject_length=_b_.len(subject),nb_fixed_length=0;for(let item of pattern.sequence){if(!item.capture_starred){nb_fixed_length++}}if(subject_length0){if([_b_.bool,_b_.bytearray,_b_.bytes,_b_.dict,_b_.float,_b_.frozenset,_b_.int,_b_.list,_b_.set,_b_.str,_b_.tuple].indexOf(klass)>-1){if(pattern.args.length>1){throw _b_.TypeError.$factory("for builtin type "+$B.class_name(subject)+", a single positional "+"subpattern is accepted")}return $B.pattern_match(subject,pattern.args[0])}else{let match_args=$B.$getattr(klass,"__match_args__",$B.fast_tuple([]));if(!$B.$isinstance(match_args,_b_.tuple)){throw _b_.TypeError.$factory("__match_args__() did not return a tuple")}if(pattern.args.length>match_args.length){throw _b_.TypeError.$factory("__match_args__() returns "+match_args.length+" names but "+pattern.args.length+" positional "+"arguments were passed")}for(let i=0,len=pattern.args.length;i"}else{return""}};$B.set_func_names(coroutine,"builtins");$B.make_async=func=>{if(func.$is_genfunc){return func}var f=function(){var args=arguments;var res={__class__:coroutine,$args:args,$func:func};if($B.frame_obj!==null){var frame=$B.frame_obj.frame;frame.$coroutine=res;res.$lineno=frame.$lineno}return res};f.$infos=func.$infos;f.$is_func=true;f.$is_async=true;f.$args_parser=func.$args_parser;return f};$B.promise=function(obj){if(obj.__class__===coroutine){obj.$frame_obj=$B.frame_obj;return coroutine.send(obj)}if(typeof obj=="function"){return obj()}if(obj instanceof Promise||typeof obj.then=="function"){obj.frame_obj=$B.frame_obj;return obj.then((function(x){$B.frame_obj=obj.frame_obj;return $B.jsobj2pyobj(x)})).catch((function(err){$B.frame_obj=obj.frame_obj;throw $B.exception(err)}))}var awaitable=$B.$getattr(obj,"__await__",null);if(awaitable!==null){awaitable=$B.$call(awaitable)();if($B.$getattr(awaitable,"__next__",null)===null){throw _b_.TypeError.$factory("__await__() returned non-iterator"+` of type '${$B.class_name(awaitable)}'`)}return awaitable}throw _b_.TypeError.$factory(`object ${$B.class_name(obj)} `+`can't be used in 'await' expression`)}})(__BRYTHON__);(function($B){$B.builtin_class_flags={builtins:{1073763586:["ImportError","StopIteration","ArithmeticError","PythonFinalizationError","EnvironmentError","GeneratorExit","RuntimeError","IOError","NotImplementedError","FileNotFoundError","KeyError","UnboundLocalError","WindowsError","TimeoutError","NotADirectoryError","OverflowError","IndexError","AttributeError","ResourceWarning","BaseException","ConnectionResetError","ChildProcessError","Warning","UnicodeDecodeError","UnicodeTranslateError","RuntimeWarning","FutureWarning","BytesWarning","InterruptedError","BaseExceptionGroup","TabError","AssertionError","ImportWarning","ConnectionError","OSError","ConnectionAbortedError","ConnectionRefusedError","EncodingWarning","EOFError","TypeError","UserWarning","Exception","PermissionError","UnicodeEncodeError","FloatingPointError","ModuleNotFoundError","SyntaxWarning","MemoryError","SystemExit","ReferenceError","SyntaxError","_IncompleteInputError","PendingDeprecationWarning","SystemError","DeprecationWarning","IsADirectoryError","ValueError","FileExistsError","BufferError","RecursionError","ProcessLookupError","LookupError","BlockingIOError","BrokenPipeError","IndentationError","StopAsyncIteration","NameError","UnicodeError","UnicodeWarning","KeyboardInterrupt","ZeroDivisionError"],1073763848:["ExceptionGroup"],20975874:["bool"],4199682:["float","bytearray"],138417410:["bytes"],21762:["super","enumerate","staticmethod","classmethod","property","zip","map","reversed","filter"],5378:["object","complex"],541087042:["dict"],4216066:["frozenset","set"],20976898:["int"],37770530:["list"],20770:["memoryview"],4386:["range"],20738:["slice"],272635138:["str"],71324962:["tuple"],2155896066:["type"]},types:{20866:["generator","member_descriptor","method-wrapper","classmethod_descriptor","async_generator","coroutine","frame","getset_descriptor"],22914:["builtin_function_or_method"],20738:["cell","traceback"],4354:["ellipsis","NoneType","code","NotImplementedType"],153858:["function"],20802:["mappingproxy"],153986:["method_descriptor"],22786:["method"],21762:["module"],151938:["wrapper_descriptor"]}}})(__BRYTHON__);(function($B){var _b_=$B.builtins;var update=$B.update_obj=function(mod,data){for(let attr in data){mod[attr]=data[attr]}};var modules={};var win=$B.jsobj2pyobj(globalThis);var browser={$package:true,$is_package:true,__initialized__:true,__package__:"browser",__file__:$B.brython_path.replace(new RegExp("/*$","g"),"")+"/Lib/browser/__init__.py",bind:function(){var $=$B.args("bind",3,{elt:null,evt:null,options:null},["elt","evt","options"],arguments,{options:_b_.None},null,null);var options=$.options;if(typeof options=="boolean"){}else if(options.__class__===_b_.dict){var _options={};for(var key of _b_.dict.$keys_string(options)){_options[key]=_b_.dict.$getitem_string(options,key)}options=_options}else{options==false}return function(callback){if($B.get_class($.elt)===$B.JSObj){function f(ev){try{return callback($B.jsobj2pyobj(ev))}catch(err){$B.handle_error(err)}}$.elt.addEventListener($.evt,f,options);return callback}else if($B.$isinstance($.elt,$B.DOMNode)){$B.DOMNode.bind($.elt,$.evt,callback,options);return callback}else if($B.$isinstance($.elt,_b_.str)){var items=document.querySelectorAll($.elt);for(var i=0;i1){console.log(err,err.__class__,err.args);console.log("first",first);console.log(arguments)}throw err}}}}for(var item of _b_.dict.$iter_items($ns.kw)){var arg=item.key,value=item.value;if(arg.toLowerCase().substr(0,2)=="on"){$B.DOMNode.__setattr__(self,arg,value)}else if(arg.toLowerCase()=="style"){$B.DOMNode.set_style(self,value)}else{if(value!==false){try{arg=$B.imported["browser.html"].attribute_mapper(arg);self.setAttribute(arg,$B.pyobj2jsobj(value))}catch(err){throw _b_.ValueError.$factory("can't set attribute "+arg)}}}}};dict.__mro__=[$B.DOMNode,$B.builtins.object];dict.__new__=function(cls){var res=document.createElement(tagName);if(cls!==html[tagName]){res.__class__=cls}return res};dict.__rmul__=function(self,num){return $B.DOMNode.__mul__(self,num)};$B.set_func_names(dict,"browser.html");return dict}function makeFactory(klass){return function(k){return function(){var res;if(k.__name__=="SVG"){res=$B.DOMNode.$factory(document.createElementNS("http://www.w3.org/2000/svg","svg"),true)}else{try{res=document.createElement(k.__name__)}catch(err){console.log("error "+err);console.log("creating element",k.__name__);throw err}}var init=$B.$getattr(k,"__init__",null);if(init!==null){init(res,...arguments)}return res}}(klass)}var tags=["A","ABBR","ACRONYM","ADDRESS","APPLET","AREA","B","BASE","BASEFONT","BDO","BIG","BLOCKQUOTE","BODY","BR","BUTTON","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","DD","DEL","DFN","DIR","DIV","DL","DT","EM","FIELDSET","FONT","FORM","FRAME","FRAMESET","H1","H2","H3","H4","H5","H6","HEAD","HR","HTML","I","IFRAME","IMG","INPUT","INS","ISINDEX","KBD","LABEL","LEGEND","LI","LINK","MAP","MENU","META","NOFRAMES","NOSCRIPT","OBJECT","OL","OPTGROUP","OPTION","P","PARAM","PRE","Q","S","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRIKE","STRONG","STYLE","SUB","SUP","SVG","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TITLE","TR","TT","U","UL","VAR","ARTICLE","ASIDE","AUDIO","BDI","CANVAS","COMMAND","DATA","DATALIST","EMBED","FIGCAPTION","FIGURE","FOOTER","HEADER","KEYGEN","MAIN","MARK","MATH","METER","NAV","OUTPUT","PROGRESS","RB","RP","RT","RTC","RUBY","SECTION","SOURCE","TEMPLATE","TIME","TRACK","VIDEO","WBR","DETAILS","DIALOG","MENUITEM","PICTURE","SUMMARY"];var html={};html.tags=$B.empty_dict();function maketag(tagName,ComponentClass){if(!(typeof tagName=="string")){throw _b_.TypeError.$factory("html.maketag expects a string as argument")}if(html[tagName]!==undefined){throw _b_.ValueError.$factory("cannot reset class for "+tagName)}var klass=makeTagDict(tagName);klass.$factory=makeFactory(klass,ComponentClass);html[tagName]=klass;_b_.dict.$setitem(html.tags,tagName,html[tagName]);return klass}for(var tagName of tags){maketag(tagName)}html.maketag=maketag;html.attribute_mapper=function(attr){return attr.replace(/_/g,"-")};return html}(__BRYTHON__)}modules["browser"]=browser;$B.UndefinedType=$B.make_class("UndefinedType",(function(){return $B.Undefined}));$B.UndefinedType.__mro__=[_b_.object];$B.UndefinedType.__bool__=function(){return false};$B.UndefinedType.__repr__=function(){return""};$B.UndefinedType.__str__=$B.UndefinedType.__repr__;$B.Undefined={__class__:$B.UndefinedType};$B.set_func_names($B.UndefinedType,"javascript");var super_class=$B.make_class("JavascriptSuper",(function(){var res=_b_.super.$factory();var js_constr=res.__thisclass__.__bases__[0];return function(){var obj=new js_constr.$js_func(...arguments);for(var attr in obj){res.__self_class__.__dict__[attr]=$B.jsobj2pyobj(obj[attr])}return obj}}));super_class.__getattribute__=function(self,attr){if(attr=="__init__"||attr=="__call__"){return self.__init__}return $B.$getattr(self.__self_class__,attr)};$B.set_func_names(super_class,"javascript");modules["javascript"]={this:function(){if($B.js_this===undefined){return $B.builtins.None}return $B.jsobj2pyobj($B.js_this)},Array:$B.js_array,Date:self.Date&&$B.jsobj2pyobj(self.Date),extends:function(js_constr){if(!js_constr.$js_func||!js_constr.$js_func.toString().startsWith("class ")){console.log(js_constr);throw _b_.TypeError.$factory("argument of extend must be a Javascript class")}js_constr.__class__=_b_.type;return function(obj){obj.__bases__.splice(0,0,js_constr);obj.__mro__.splice(0,0,js_constr);return obj}},import_js:function(){var $=$B.args("import_js",2,{url:null,alias:null},["url","alias"],arguments,{alias:_b_.None},null,null),url=$.url,alias=$.alias;var xhr=new XMLHttpRequest,result;xhr.open("GET",url,false);xhr.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){var js=this.responseText+"\nreturn $module",f=new Function(js);var $module=f();if(typeof $module!=="undefined"){result=$B.module.$factory(alias);for(var key in $module){result[key]=$B.jsobj2pyobj($module[key])}result.__file__=url}else{console.log(this.responseText);result=_b_.ImportError.$factory("Javascript "+`module at ${url} doesn't define $module`)}}else{result=_b_.ModuleNotFoundError.$factory(url)}}};xhr.send();if($B.$isinstance(result,_b_.BaseException)){$B.handle_error(result)}else{if(alias===_b_.None){var name=url.split(".");if(name.length>1){name.pop()}alias=name.join(".");result.__name__=alias}$B.imported[alias]=result;var frame=$B.frame_obj.frame;frame[1][alias]=result}},import_modules:function(refs,callback,loaded){if(loaded===undefined){loaded=[]}if(!Array.isArray(refs)){throw _b_.TypeError.$factory(`first argument must be a list, got ${$B.class_name(refs)}`)}if(refs.length>1){var ref=refs.shift();import(ref).then((function(module){loaded.push(module);$B.imported.javascript.import_modules(refs,callback,loaded)})).catch($B.show_error)}else{import(refs[0]).then((function(module){loaded.push(module);return $B.$call(callback).apply(null,loaded)})).catch($B.show_error)}},import_scripts:function(refs,callback,loaded){console.log("import scripts",refs);if(loaded===undefined){loaded=[]}if(!Array.isArray(refs)){throw _b_.TypeError.$factory(`first argument must be a list, got ${$B.class_name(refs)}`)}if(refs.length>0){var ref=refs.shift();var script=document.createElement("script");script.src=ref;script.addEventListener("load",(function(){loaded.push(script);$B.imported.javascript.import_scripts(refs,callback,loaded)}));document.body.appendChild(script)}else{return $B.$call(callback).apply(null,loaded)}},JSObject:$B.JSObj,JSON:{__class__:$B.make_class("JSON"),parse:function(){return $B.structuredclone2pyobj(JSON.parse.apply(this,arguments))},stringify:function(obj,replacer,space){return JSON.stringify($B.pyobj2structuredclone(obj,false),$B.jsobj2pyobj(replacer),space)}},jsobj2pyobj:function(obj){return $B.jsobj2pyobj(obj)},load:function(script_url){console.log('"javascript.load" is deprecrated. '+"Use browser.load instead.");var file_obj=$B.builtins.open(script_url);var content=$B.$getattr(file_obj,"read")();eval(content)},Math:self.Math&&$B.jsobj2pyobj(self.Math),NULL:null,NullType:$B.make_class("NullType"),Number:self.Number&&$B.jsobj2pyobj(self.Number),py2js:function(src,module_name){if(module_name===undefined){module_name="__main__"+$B.UUID()}var js=$B.py2js({src:src,filename:""},module_name,module_name,$B.builtins_scope).to_js();return $B.format_indent(js,0)},pyobj2jsobj:function(obj){return $B.pyobj2jsobj(obj)},RegExp:self.RegExp&&$B.jsobj2pyobj(self.RegExp),String:self.String&&$B.jsobj2pyobj(self.String),super:super_class,UNDEFINED:$B.Undefined,UndefinedType:$B.UndefinedType};modules.javascript.NullType.__module__="javascript";modules.javascript.NullType.__eq__=function(_self,other){return other===null||other===$B.Undefined};modules.javascript.NullType.__repr__=function(_self){return""};$B.set_func_names(modules.javascript.NullType,"javascript");modules.javascript.UndefinedType.__module__="javascript";var $io=$B.$io=$B.make_class("io",(function(out){return{__class__:$io,__dict__:$B.empty_dict(),out:out,encoding:"utf-8"}}));$io.flush=function(self){if(self.buf){var s=self.buf.join(""),chr0=String.fromCodePoint(0);s=s.replace(new RegExp(chr0,"g")," ");console[self.out](s);self.buf=[]}};$io.write=function(self,msg){if(self.buf===undefined){self.buf=[]}if(typeof msg!="string"){throw _b_.TypeError.$factory("write() argument must be str, not "+$B.class_name(msg))}self.buf.push(msg);return _b_.None};modules["_sys"]={_getframe:function(){var $=$B.args("_getframe",1,{depth:null},["depth"],arguments,{depth:0},null,null),depth=$.depth,frame_obj=$B.frame_obj;for(var i=0;i0){var lines=headers.trim().split(/[\r\n]+/);lines.forEach((function(line){var parts=line.split(": ");var header=parts.shift();var value=parts.join(": ");_b_.dict.$setitem(res,header,value)}))}return res}));var Future=$B.make_class("Future",(function(){var methods={};var promise=new Promise((function(resolve,reject){methods.resolve=resolve;methods.reject=reject}));promise._methods=methods;promise._done=false;promise.__class__=Future;return promise}));Future.done=function(){var $=$B.args("done",1,{self:null},["self"],arguments,{},null,null);return!!$.self._done};Future.set_result=function(){var $=$B.args("set_result",2,{self:null,value:null},["self","value"],arguments,{},null,null);$.self._done=true;$.self._methods.resolve($.value);return _b_.None};Future.set_exception=function(){var $=$B.args("set_exception",2,{self:null,exception:null},["self","exception"],arguments,{},null,null);$.self._done=true;$.self._methods.reject($.exception);return _b_.None};$B.set_func_names(Future,"browser.aio");modules["browser.aio"]={ajax:function(){var $=$B.args("ajax",2,{method:null,url:null},["method","url"],arguments,{},null,"kw"),method=$.method.toUpperCase(),url=$.url,kw=$.kw;var args=handle_kwargs(kw,"get");if(method=="GET"&&!args.cache){url=url+"?ts"+(new Date).getTime()+"=0"}if(args.body&&method=="GET"){url=url+(args.cache?"?":"&")+args.body}var func=function(){return new Promise((function(resolve){var xhr=new XMLHttpRequest;xhr.open(method,url,true);for(var key in args.headers){xhr.setRequestHeader(key,args.headers[key])}xhr.format=args.format;xhr.responseType=responseType[args.format];xhr.onreadystatechange=function(){if(this.readyState==4){this.__class__=HTTPRequest;resolve(this)}};if(args.body&&["POST","PUT","DELETE","PATCH"].indexOf(method)>-1){xhr.send(args.body)}else{xhr.send()}}))};func.$infos={__name__:"ajax_"+method};return{__class__:$B.coroutine,$args:[url,args],$func:func}},event:function(){var $=$B.args("event",1,{element:null},["element"],arguments,{},"names",null),element=$.element,names=$.names;return new Promise((function(resolve){var callbacks=[];names.forEach((function(name){var callback=function(evt){callbacks.forEach((function(items){$B.DOMNode.unbind(element,items[0],items[1])}));resolve($B.$DOMEvent(evt))};callbacks.push([name,callback]);$B.DOMNode.bind(element,name,callback)}))}))},get:function(){return $B.imported["browser.aio"].ajax.bind(null,"GET").apply(null,arguments)},iscoroutine:function(f){return f.__class__===$B.coroutine},iscoroutinefunction:function(f){return(f.$infos.__code__.co_flags&128)!=0},post:function(){return $B.imported["browser.aio"].ajax.bind(null,"POST").apply(null,arguments)},run:function(){var handle_success=function(){$B.leave_frame()},handle_error=$B.show_error;var $=$B.args("run",3,{coro:null,onsuccess:null,onerror:null},["coro","onsuccess","onerror"],arguments,{onsuccess:handle_success,onerror:handle_error},null,null),coro=$.coro,onsuccess=$.onsuccess,onerror=$.onerror;var save_frame_obj=$B.frame_obj;$B.coroutine.send(coro).then(onsuccess).catch(onerror);$B.frame_obj=save_frame_obj;return _b_.None},sleep:function(seconds){if(seconds.__class__===_b_.float){seconds=seconds.value}else if(typeof seconds!="number"){throw _b_.TypeError.$factory("'sleep' argument must be "+"int or float, not "+$B.class_name(seconds))}var func=function(){return new Promise((resolve=>setTimeout((function(){resolve(_b_.None)}),1e3*seconds)))};func.$infos={__name__:"sleep"};return{__class__:$B.coroutine,$args:[seconds],$func:func}},Future:Future,__getattr__:function(attr){$B.$import("_aio");return $B.$getattr($B.imported._aio,attr)}};function load(name,module_obj){module_obj.__class__=$B.module;module_obj.__name__=name;$B.imported[name]=module_obj;for(var attr in module_obj){if(typeof module_obj[attr]=="function"){module_obj[attr].$infos={__module__:name,__name__:attr,__qualname__:name+"."+attr}}}}for(let attr in modules){load(attr,modules[attr])}if(!($B.isWebWorker||$B.isNode)){modules["browser"].html=modules["browser.html"];modules["browser"].aio=modules["browser.aio"]}_b_.__builtins__=$B.module.$factory("__builtins__","Python builtins");for(let attr in _b_){_b_.__builtins__[attr]=_b_[attr];$B.builtins_scope.binding[attr]=true;if(_b_[attr].$is_class){if(_b_[attr].__bases__){_b_[attr].__bases__.__class__=_b_.tuple}else{_b_[attr].__bases__=$B.fast_tuple([_b_.object])}}}_b_.__builtins__.__setattr__=function(attr,value){_b_[attr]=value};$B.method_descriptor.__getattribute__=$B.function.__getattribute__;$B.wrapper_descriptor.__getattribute__=$B.function.__getattribute__;var tp_dict=_b_.type.__dict__=$B.empty_dict(),setitem=_b_.dict.$setitem;for(let method in _b_.type){if(method.startsWith("__")&&method.endsWith("__")){setitem(tp_dict,method,_b_.type[method])}}setitem(tp_dict,"__mro__",{__get__:function(cls){return $B.fast_tuple([cls].concat(cls.__mro__))}});for(var name in _b_){var builtin=_b_[name];if(_b_[name].__class__===_b_.type){_b_[name].__qualname__=name;_b_[name].__module__="builtins";_b_[name].__name__=name;_b_[name].$is_builtin_class=true;$B.builtin_classes.push(_b_[name]);for(var key in _b_[name]){var value=_b_[name][key];if(value===undefined||value.__class__||typeof value!="function"){continue}else if(key=="__new__"){value.__class__=$B.builtin_function_or_method}else if(key.startsWith("__")){value.__class__=$B.wrapper_descriptor}else{value.__class__=$B.method_descriptor}value.__objclass__=_b_[name]}}else if(typeof builtin=="function"){builtin.$infos={__name__:name,__qualname__:name}}}for(let attr in $B){if(Array.isArray($B[attr])){$B[attr].__class__=_b_.list}}$B.cell=$B.make_class("cell",(function(value){return{__class__:$B.cell,$cell_contents:value}}));$B.cell.cell_contents=$B.$call(_b_.property)((function(self){if(self.$cell_contents===null){throw _b_.ValueError.$factory("empty cell")}return self.$cell_contents}),(function(self,value){self.$cell_contents=value}));var $comps=Object.values($B.$comps).concat(["eq","ne"]);$comps.forEach((function(comp){var op="__"+comp+"__";$B.cell[op]=function(op){return function(self,other){if(!$B.$isinstance(other,$B.cell)){return _b_.NotImplemented}if(self.$cell_contents===null){if(other.$cell_contents===null){return op=="__eq__"}else{return["__ne__","__lt__","__le__"].indexOf(op)>-1}}else if(other.$cell_contents===null){return["__ne__","__gt__","__ge__"].indexOf(op)>-1}return $B.rich_comp(op,self.$cell_contents,other.$cell_contents)}}(op)}));$B.set_func_names($B.cell,"builtins");for(let flag in $B.builtin_class_flags.builtins){for(let key of $B.builtin_class_flags.builtins[flag]){if(_b_[key]){_b_[key].__flags__=parseInt(flag)}else{console.log("not in _b_",key)}}}for(let flag in $B.builtin_class_flags.types){for(let key of $B.builtin_class_flags.types[flag]){if($B[key]){$B[key].__flags__=parseInt(flag)}}}$B.AST={__class__:_b_.type,__mro__:[_b_.object],__name__:"AST",__qualname__:"AST",$is_class:true,$convert:function(js_node){if(js_node===undefined){return _b_.None}var constr=js_node.constructor;if(constr&&constr.$name){$B.create_python_ast_classes();return $B.python_ast_classes[constr.$name].$factory(js_node)}else if(Array.isArray(js_node)){return js_node.map($B.AST.$convert)}else if(js_node.type){switch(js_node.type){case"int":var value=js_node.value[1],base=js_node.value[0];var res=parseInt(value,base);if(!Number.isSafeInteger(res)){res=$B.long_int.$factory(value,base)}return res;case"float":return $B.fast_float(parseFloat(js_node.value));case"imaginary":return $B.make_complex(0,$B.AST.$convert(js_node.value));case"ellipsis":return _b_.Ellipsis;case"str":if(js_node.is_bytes){return _b_.bytes.$factory(js_node.value,"latin-1")}return js_node.value;case"id":if(["False","None","True"].indexOf(js_node.value)>-1){return _b_[js_node.value]}break}}else if(["string","number"].indexOf(typeof js_node)>-1){return js_node}else if(js_node.$name){return js_node.$name+"()"}else if([_b_.None,_b_.True,_b_.False].indexOf(js_node)>-1){return js_node}else if(js_node.__class__){return js_node}else{console.log("cannot handle",js_node);return js_node}}};$B.stdin={__class__:$io,__original__:true,closed:false,len:1,pos:0,read:function(){return""},readline:function(){return""}};$B.__ARGV=$B.$list([]);$B.tracefunc=_b_.None})(__BRYTHON__);(function($B){var _b_=$B.builtins;function ast_dump(tree,indent){var attr,value;indent=indent||0;if(tree===_b_.None){return"None"}else if(typeof tree=="string"){return`'${tree}'`}else if(typeof tree=="number"){return tree+""}else if(tree.imaginary){return tree.value+"j"}else if(Array.isArray(tree)){if(tree.length==0){return"[]"}res="[\n";var items=[];for(var x of tree){try{items.push(ast_dump(x,indent+1))}catch(err){console.log("error",tree);console.log("for item",x);throw err}}res+=items.join(",\n");return res+"]"}else if(tree.$name){return tree.$name+"()"}else if(tree instanceof ast.MatchSingleton){return`MatchSingleton(value=${$B.AST.$convert(tree.value)})`}else if(tree instanceof ast.Constant){value=tree.value;if(value.imaginary){return`Constant(value=${_b_.repr(value.value)}j)`}return`Constant(value=${$B.AST.$convert(value)})`}var proto=Object.getPrototypeOf(tree).constructor;var res=" ".repeat(indent)+proto.$name+"(";if($B.ast_classes[proto.$name]===undefined){console.log("no ast class",proto)}var attr_names=$B.ast_classes[proto.$name].split(","),attrs=[];attr_names=attr_names.map((x=>x.endsWith("*")||x.endsWith("?")?x.substr(0,x.length-1):x));if([ast.Name].indexOf(proto)>-1){for(attr of attr_names){if(tree[attr]!==undefined){attrs.push(`${attr}=${ast_dump(tree[attr])}`)}}return res+attrs.join(", ")+")"}for(attr of attr_names){if(tree[attr]!==undefined){value=tree[attr];attrs.push(attr+"="+ast_dump(tree[attr],indent+1).trimStart())}}if(attrs.length>0){res+="\n";res+=attrs.map((x=>" ".repeat(indent+1)+x)).join(",\n")}res+=")";return res}function string_from_ast_value(value){return value.replace(new RegExp("\\\\'","g"),"'")}function compiler_error(ast_obj,message,end){var exc=_b_.SyntaxError.$factory(message);exc.filename=state.filename;if(exc.filename!=""){var src=$B.file_cache[exc.filename],lines=src.split("\n"),line=lines[ast_obj.lineno-1];exc.text=line}else{exc.text=_b_.None}exc.lineno=ast_obj.lineno;exc.offset=ast_obj.col_offset+1;end=end||ast_obj;exc.end_lineno=end.end_lineno;exc.end_offset=end.end_col_offset+1;exc.args[1]=[exc.filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset];exc.$frame_obj=$B.frame_obj;if($B.frame_obj===null){}throw exc}var uuid=Math.floor(Math.random()*1e6);function make_id(){uuid+=1;return uuid}function fast_id(obj){if(obj.$id!==undefined){return obj.$id}return obj.$id=make_id()}function copy_position(target,origin){target.lineno=origin.lineno;target.col_offset=origin.col_offset;target.end_lineno=origin.end_lineno;target.end_col_offset=origin.end_col_offset}function encode_position(a,b,c,d){if(d===undefined){return`[${[a,b,c]}]`}else{return`[${[a,b,c,d]}]`}}$B.decode_position=function(pos){return pos};function get_source_from_position(src,ast_obj){var lines=src.split("\n"),start_line=lines[ast_obj.lineno-1];if(ast_obj.end_lineno==ast_obj.lineno){return start_line.substring(ast_obj.col_offset,ast_obj.end_col_offset)}else{var res=start_line.substr(ast_obj.col_offset),line_num=ast_obj.lineno+1;while(line_num-1){_scopes=scopes.slice(0,ix+1)}else{_scopes=scopes.concat(scope)}}var names=[];for(var _scope of _scopes){if(!_scope.parent){names.push(_scope.name)}}return names.join("_").replace(/\./g,"_")}function module_name(scopes){var _scopes=scopes.slice();var names=[];for(var _scope of _scopes){if(!_scope.parent){names.push(_scope.name)}}return names.join(".")}function make_scope_name(scopes,scope){if(scope===builtins_scope){return`_b_`}return"locals_"+qualified_scope_name(scopes,scope)}function make_search_namespaces(scopes){var namespaces=[];for(var scope of scopes.slice().reverse()){if(scope.parent||scope.type=="class"){continue}else if(scope.is_exec_scope){namespaces.push("$B.exec_scope")}namespaces.push(make_scope_name(scopes,scope))}namespaces.push("_b_");return namespaces}function mangle(scopes,scope,name){if(name.startsWith("__")&&!name.endsWith("__")){var ix=scopes.indexOf(scope);while(ix>=0){if(scopes[ix].ast instanceof $B.ast.ClassDef){var scope_name=scopes[ix].name;while(scope_name.length>0&&scope_name.startsWith("_")){scope_name=scope_name.substr(1)}if(scope_name.length==0){return name}return"_"+scope_name+name}ix--}}return name}function reference(scopes,scope,name){return make_scope_name(scopes,scope)+"."+mangle(scopes,scope,name)}function bind(name,scopes){var scope=$B.last(scopes),up_scope=last_scope(scopes);name=mangle(scopes,up_scope,name);if(up_scope.globals&&up_scope.globals.has(name)){scope=scopes[0]}else if(up_scope.nonlocals.has(name)){for(var i=scopes.indexOf(up_scope)-1;i>=0;i--){if(scopes[i].locals.has(name)){return scopes[i]}}}scope.locals.add(name);return scope}var SF=$B.SYMBOL_FLAGS;function name_reference(name,scopes,position){var scope=name_scope(name,scopes);return make_ref(name,scopes,scope,position)}function make_ref(name,scopes,scope,position){var test=false;if(test){console.log("make ref",name,scopes.slice(),scope)}if(scope.found){var res=reference(scopes,scope.found,name);if(test){console.log("res",res)}return res}else if(scope.resolve=="all"){var scope_names=make_search_namespaces(scopes);return`$B.resolve_in_scopes('${name}', [${scope_names}], [${position}])`}else if(scope.resolve=="local"){return`$B.resolve_local('${name}', [${position}])`}else if(scope.resolve=="global"){return`$B.resolve_global('${name}', _frame_obj)`}else if(Array.isArray(scope.resolve)){return`$B.resolve_in_scopes('${name}', [${scope.resolve}], [${position}])`}else if(scope.resolve=="own_class_name"){return`$B.own_class_name('${name}')`}}function local_scope(name,scope){var s=scope;while(true){if(s.locals.has(name)){return{found:true,scope:s}}if(!s.parent){return{found:false}}s=s.parent}}function name_scope(name,scopes){var test=false;if(test){console.log("name scope",name,scopes.slice());alert()}var flags,block;if(scopes.length==0){return{found:false,resolve:"all"}}var scope=$B.last(scopes),up_scope=last_scope(scopes);name=mangle(scopes,scope,name);if(up_scope.ast===undefined){console.log("no ast",scope)}block=scopes.symtable.table.blocks.get(fast_id(up_scope.ast));if(block===undefined){console.log("no block",scope,scope.ast,"id",fast_id(up_scope.ast));console.log("scopes",scopes.slice());console.log("symtable",scopes.symtable)}if(test){console.log("block symbols",block.symbols)}try{flags=_b_.dict.$getitem_string(block.symbols,name)}catch(err){console.log("name",name,"not in symbols of block",block);console.log("symtables",scopes.symtable);console.log("scopes",scopes.slice());return{found:false,resolve:"all"}}let __scope=flags>>SF.SCOPE_OFF&SF.SCOPE_MASK,is_local=[SF.LOCAL,SF.CELL].indexOf(__scope)>-1;if(test){console.log("block",block,"is local",is_local,"__scope",__scope);console.log("flags",flags,"scopeoff",SF.SCOPE_OFF,"scope mask",SF.SCOPE_MASK)}if(up_scope.ast instanceof $B.ast.ClassDef&&name==up_scope.name){return{found:false,resolve:"own_class_name"}}if(name=="__annotations__"){if(block.type==SF.TYPE_CLASS&&up_scope.has_annotation){is_local=true}else if(block.type==SF.TYPE_MODULE){is_local=true}}if(test){console.log("is local ???",is_local,"scope",scope)}if(is_local){var l_scope=local_scope(name,scope);if(!l_scope.found){if(block.type==SF.TYPE_CLASS){scope.needs_frames=true;return{found:false,resolve:"global"}}else if(block.type==SF.TYPE_MODULE){scope.needs_frames=true;return{found:false,resolve:"global"}}return{found:false,resolve:"local"}}else{return{found:l_scope.scope}}}else if(scope.globals.has(name)){var global_scope=scopes[0];if(global_scope.locals.has(name)){return{found:global_scope}}scope.needs_frames=true;return{found:false,resolve:"global"}}else if(scope.nonlocals.has(name)){for(let i=scopes.length-2;i>=0;i--){block=scopes.symtable.table.blocks.get(fast_id(scopes[i].ast));if(block&&_b_.dict.$contains_string(block.symbols,name)){var fl=_b_.dict.$getitem_string(block.symbols,name),local_to_block=[SF.LOCAL,SF.CELL].indexOf(fl>>SF.SCOPE_OFF&SF.SCOPE_MASK)>-1;if(!local_to_block){continue}return{found:scopes[i]}}}}if(scope.has_import_star){if(!is_local){scope.needs_frames=true}return{found:false,resolve:is_local?"all":"global"}}for(let i=scopes.length-2;i>=0;i--){block=undefined;if(scopes[i].ast){block=scopes.symtable.table.blocks.get(fast_id(scopes[i].ast))}if(scopes[i].globals.has(name)){scope.needs_frames=true;return{found:false,resolve:"global"}}if(scopes[i].locals.has(name)&&scopes[i].type!="class"){return{found:scopes[i]}}else if(block&&_b_.dict.$contains_string(block.symbols,name)){flags=_b_.dict.$getitem_string(block.symbols,name);let __scope=flags>>SF.SCOPE_OFF&SF.SCOPE_MASK;if([SF.LOCAL,SF.CELL].indexOf(__scope)>-1){return{found:false,resolve:"all"}}}if(scopes[i].has_import_star){return{found:false,resolve:"all"}}}if(builtins_scope.locals.has(name)){return{found:builtins_scope}}var scope_names=make_search_namespaces(scopes);return{found:false,resolve:scope_names}}function resolve_in_namespace(name,ns){if(ns.$proxy){return ns[name]===undefined?{found:false}:{found:true,value:ns[name]}}if(!ns.hasOwnProperty){if(ns[name]!==undefined){return{found:true,value:ns[name]}}}else if(ns.hasOwnProperty(name)){return{found:true,value:ns[name]}}else if(ns.$dict){try{return{found:true,value:ns.$getitem(ns.$dict,name)}}catch(err){if(ns.$missing){try{return{found:true,value:$B.$call(ns.$missing)(ns.$dict,name)}}catch(err){if(!$B.is_exc(err,[_b_.KeyError])){throw err}}}}}return{found:false}}$B.resolve=function(name){var checked=new Set,current_globals,frame_obj=$B.frame_obj,frame;while(frame_obj!==null){frame=frame_obj.frame;if(current_globals===undefined){current_globals=frame[3]}else if(frame[3]!==current_globals){let v=resolve_in_namespace(name,current_globals);if(v.found){return v.value}checked.add(current_globals);current_globals=frame[3]}let v=resolve_in_namespace(name,frame[1]);if(v.found){return v.value}frame_obj=frame_obj.prev}if(!checked.has(frame[3])){var v=resolve_in_namespace(name,frame[3]);if(v.found){return v.value}}if(builtins_scope.locals.has(name)){return _b_[name]}throw $B.name_error(name)};$B.resolve_local=function(name,position){if($B.frame_obj!==null){var frame=$B.frame_obj.frame;if(frame[1].hasOwnProperty){if(frame[1].hasOwnProperty(name)){return frame[1][name]}}else{var value=frame[1][name];if(value!==undefined){return value}}}var exc=_b_.UnboundLocalError.$factory(`cannot access local variable `+`'${name}' where it is not associated with a value`);if(position&&$B.frame_obj){$B.set_exception_offsets(exc,position)}throw exc};$B.resolve_in_scopes=function(name,namespaces,position){for(var ns of namespaces){if(ns===$B.exec_scope){var exec_top,frame_obj=$B.frame_obj,frame;while(frame_obj!==null){frame=frame_obj.frame;if(frame.is_exec_top){exec_top=frame;break}frame_obj=frame_obj.prev}if(exec_top){for(var ns1 of[exec_top[1],exec_top[3]]){let v=resolve_in_namespace(name,ns1);if(v.found){return v.value}}}}else{let v=resolve_in_namespace(name,ns);if(v.found){return v.value}}}var exc=$B.name_error(name);if(position){$B.set_exception_offsets(exc,position)}throw exc};$B.resolve_global=function(name,frame_obj){while(frame_obj!==null){var frame=frame_obj.frame,v=resolve_in_namespace(name,frame[3]);if(v.found){return v.value}if(frame.is_exec_top){break}frame_obj=frame_obj.prev}if(builtins_scope.locals.has(name)){return _b_[name]}throw $B.name_error(name)};$B.own_class_name=function(name){throw $B.name_error(name)};var $operators=$B.op2method.subset("all");var opname2opsign={};for(var key in $operators){opname2opsign[$operators[key]]=key}var opclass2dunder={};for(var op_type of $B.op_types){for(var operator in op_type){opclass2dunder[op_type[operator]]="__"+$operators[operator]+"__"}}opclass2dunder["UAdd"]="__pos__";opclass2dunder["USub"]="__neg__";opclass2dunder["Invert"]="__invert__";var builtins_scope=new Scope("__builtins__");for(var name in $B.builtins){builtins_scope.locals.add(name)}function mark_parents(node){if(node.body&&node.body instanceof Array){for(let child of node.body){child.$parent=node;mark_parents(child)}}else if(node.handlers){var p={$parent:node,type:"except_handler"};for(let child of node.handlers){child.$parent=p;mark_parents(child)}}}function add_body(body,scopes){var res="";let js;for(var item of body){js=$B.js_from_ast(item,scopes);if(js.length>0){res+=js+"\n"}}return res.trimRight()}function extract_docstring(ast_obj,scopes){var js="_b_.None";if(ast_obj.body.length&&ast_obj.body[0]instanceof $B.ast.Expr&&ast_obj.body[0].value instanceof $B.ast.Constant){var value=ast_obj.body[0].value.value;if(typeof value=="string"){js=ast_obj.body[0].value.to_js(scopes);ast_obj.body.shift()}}return js}function init_comprehension(comp,scopes){if(comp.type=="genexpr"){return init_genexpr(comp,scopes)}return`var next_func_${comp.id} = $B.make_js_iterator(expr, frame, ${comp.ast.lineno})\n`}function init_genexpr(comp,scopes){var varnames=Object.keys(comp.varnames||{}).map((x=>`'${x}'`)).join(", ");return`var ${comp.locals_name} = {},\n`+`locals = ${comp.locals_name}\n`+`locals['.0'] = expr\n`+`var frame = ["<${comp.type.toLowerCase()}>", ${comp.locals_name}, `+`"${comp.module_name}", ${comp.globals_name}]\n`+`frame.$has_generators = true\n`+`frame.__file__ = '${scopes.filename}'\n`+`frame.$lineno = ${comp.ast.lineno}\n`+`frame.f_code = {\n`+`co_argcount: 1,\n`+`co_firstlineno:${comp.ast.lineno},\n`+`co_name: "<${comp.type.toLowerCase()}>",\n`+`co_filename: "${scopes.filename}",\n`+`co_flags: ${comp.type=="genexpr"?115:83},\n`+`co_freevars: $B.fast_tuple([]),\n`+`co_kwonlyargcount: 0,\n`+`co_posonlyargount: 0,\n`+`co_qualname: "<${comp.type.toLowerCase()}>",\n`+`co_varnames: $B.fast_tuple(['.0', ${varnames}])\n`+`}\n`+`var next_func_${comp.id} = $B.make_js_iterator(expr, frame, ${comp.ast.lineno})\n`+`frame.$f_trace = _b_.None\n`+`var _frame_obj = $B.frame_obj\n`}function make_comp(scopes){var id=make_id(),type=this.constructor.$name,symtable_block=scopes.symtable.table.blocks.get(fast_id(this)),varnames=Object.keys(symtable_block.symbols.$strings).map((x=>`"${x}"`)),comp_iter,comp_scope=$B.last(scopes),upper_comp_scope=comp_scope;while(upper_comp_scope.parent){upper_comp_scope=upper_comp_scope.parent}var comp_scope_block=scopes.symtable.table.blocks.get(fast_id(upper_comp_scope.ast)),comp_scope_symbols=comp_scope_block.symbols;var initial_nb_await_in_scope=upper_comp_scope.nb_await===undefined?0:upper_comp_scope.nb_await;for(var symbol of _b_.dict.$iter_items(symtable_block.symbols)){if(symbol.value&SF.DEF_COMP_ITER){comp_iter=symbol.key}}var comp_iter_scope=name_scope(comp_iter,scopes);var first_for=this.generators[0],outmost_expr=$B.js_from_ast(first_for.iter,scopes),nb_paren=1;var comp={ast:this,id:id,type:type,varnames:varnames,module_name:scopes[0].name,locals_name:make_scope_name(scopes),globals_name:make_scope_name(scopes,scopes[0])};var js=init_comprehension(comp,scopes);if(comp_iter_scope.found){js+=`var save_comp_iter = ${name_reference(comp_iter,scopes)}\n`}if(this instanceof $B.ast.ListComp){js+=`var result_${id} = $B.$list([])\n`}else if(this instanceof $B.ast.SetComp){js+=`var result_${id} = _b_.set.$factory()\n`}else if(this instanceof $B.ast.DictComp){js+=`var result_${id} = $B.empty_dict()\n`}var first=this.generators[0];js+=`try{\n`+`for(var next_${id} of next_func_${id}){\n`;var save_target_flags;if(first.target instanceof $B.ast.Name){var target_name=first.target.id;if(comp_scope_symbols.$strings.hasOwnProperty(target_name)){save_target_flags=comp_scope_symbols.$strings[target_name];comp_scope_symbols.$strings[target_name]=SF.LOCAL<initial_nb_await_in_scope;js=`(${has_await?"async ":""}function(expr){\n`+js;js+=has_await?"var save_frame_obj = $B.frame_obj;\n":"";if(this instanceof $B.ast.ListComp){js+=`result_${id}.push(${elt})\n`}else if(this instanceof $B.ast.SetComp){js+=`_b_.set.add(result_${id}, ${elt})\n`}else if(this instanceof $B.ast.DictComp){js+=`_b_.dict.$setitem(result_${id}, ${key}, ${value})\n`}for(var i=0;i")){name="exec"}else{name=filename.replace(/\./g,"_")}var top_scope=new Scope(name,`${type}`,this),block=scopes.symtable.table.blocks.get(fast_id(this));if(block&&block.$has_import_star){top_scope.has_import_star=true}scopes.push(top_scope);var namespaces=scopes.namespaces;if(namespaces){top_scope.is_exec_scope=true;for(let key in namespaces.exec_globals){if(!key.startsWith("$")){top_scope.globals.add(key)}}if(namespaces.exec_locals!==namespaces.exec_globals){if(namespaces.exec_locals[$B.LOCALS_PROXY]){for(let item of $B.make_js_iterator(namespaces.exec_locals.$target)){top_scope.locals.add(item)}}else{for(let key in namespaces.exec_locals){if(!key.startsWith("$")){top_scope.locals.add(key)}}}}}return name}function compiler_check(obj){var check_func=Object.getPrototypeOf(obj)._check;if(check_func){obj._check()}}function check_assign_or_delete(obj,target,action){action=action??"assign to";if(target instanceof $B.ast.Attribute){if(target.attr=="__debug__"){compiler_error(obj,`cannot ${action} __debug__`,target)}}else if(target instanceof $B.ast.Name){if(target.id=="__debug__"){compiler_error(obj,`cannot ${action} __debug__`,target)}}else if(target instanceof $B.ast.Tuple){for(var elt of target.elts){check_assign_or_delete(elt,elt,action)}}else if(target instanceof $B.ast.Starred){check_assign_or_delete(obj,target.value,action)}}function check_is_arg(e){if(!(e instanceof $B.ast.Constant)){return true}var value=e.value;return value===_b_.None||value===false||value===true||value===_b_.Ellipsis}function check_compare(op_name,left,right,scopes){var test_left=check_is_arg(left),test_right=check_is_arg(right);if(!test_left||!test_right){var item=test_left?right:left,name=$B.class_name(item.value);$B.warn(_b_.SyntaxWarning,`"${op_name}" with '${name}' literal. `+`Did you mean "=="?`,scopes.filename,item)}}function check_type_params(ast_obj){var type_params=ast_obj.type_params;if(Array.isArray(type_params)){var has_defaults=false;for(var type_param of type_params){if(type_param.default_value===undefined&&has_defaults){throw compiler_error(type_param,`non-default type `+`parameter '${type_param.name}' follows default type parameter`)}else if(type_param.default_value){has_defaults=true}}}}function maybe_add_static(attr,scopes){var last=last_scope(scopes);if(last.type=="def"){var ix=scopes.indexOf(last)-1;while(scopes[ix]){last=last_scope(scopes.slice(0,ix+1));if(last.type=="class"){last.static_attributes=last.static_attributes??new Set;last.static_attributes.add(attr.attr);return}else if(last.type=="def"){ix=scopes.indexOf(last)-1}else{return}}}}$B.ast.Assert.prototype.to_js=function(scopes){var test=$B.js_from_ast(this.test,scopes),msg=this.msg?$B.js_from_ast(this.msg,scopes):"";return`if($B.set_lineno(frame, ${this.lineno}) && !$B.$bool(${test})){\n`+`throw _b_.AssertionError.$factory(${msg})}\n`};function annotation_to_str(obj,scopes){return get_source_from_position(scopes.src,obj)}$B.ast.AnnAssign.prototype.to_js=function(scopes){compiler_check(this);var postpone_annotation=scopes.symtable.table.future.features&$B.CO_FUTURE_ANNOTATIONS;var scope=last_scope(scopes);var js="";if(!scope.has_annotation){js+="locals.__annotations__ = locals.__annotations__ || $B.empty_dict()\n";scope.has_annotation=true;scope.locals.add("__annotations__")}if(this.target instanceof $B.ast.Name){var ann_value=postpone_annotation?`'${annotation_to_str(this.annotation,scopes)}'`:$B.js_from_ast(this.annotation,scopes)}if(this.value){js+=`var ann = ${$B.js_from_ast(this.value,scopes)}\n`;if(this.target instanceof $B.ast.Name&&this.simple){let scope=bind(this.target.id,scopes),mangled=mangle(scopes,scope,this.target.id);if(scope.type!="def"){js+=`$B.$setitem(locals.__annotations__, `+`'${mangled}', ${ann_value})\n`}let target_ref=name_reference(this.target.id,scopes);js+=`${target_ref} = ann`}else if(this.target instanceof $B.ast.Attribute){js+=`$B.$setattr(${$B.js_from_ast(this.target.value,scopes)}`+`, "${this.target.attr}", ann)`}else if(this.target instanceof $B.ast.Subscript){js+=`$B.$setitem(${$B.js_from_ast(this.target.value,scopes)}`+`, ${$B.js_from_ast(this.target.slice,scopes)}, ann)`}}else{if(this.target instanceof $B.ast.Name){if(this.simple&&scope.type!="def"){let mangled=mangle(scopes,scope,this.target.id);js+=`$B.$setitem(locals.__annotations__, `+`'${mangled}', ${ann_value})`}}}return`$B.set_lineno(frame, ${this.lineno})\n`+js};$B.ast.AnnAssign.prototype._check=function(){check_assign_or_delete(this,this.target)};$B.ast.Assign.prototype.to_js=function(scopes){compiler_check(this);var js=this.lineno?`$B.set_lineno(frame, ${this.lineno})\n`:"",value=$B.js_from_ast(this.value,scopes);function assign_one(target,value){if(target instanceof $B.ast.Name){return $B.js_from_ast(target,scopes)+" = "+value}else if(target instanceof $B.ast.Starred){return assign_one(target.value,value)}else if(target instanceof $B.ast.Subscript){return`$B.$setitem(${$B.js_from_ast(target.value,scopes)}`+`, ${$B.js_from_ast(target.slice,scopes)}, ${value})`}else if(target instanceof $B.ast.Attribute){if(target.value.id=="self"){maybe_add_static(target,scopes)}var attr=mangle(scopes,last_scope(scopes),target.attr);return`$B.$setattr(${$B.js_from_ast(target.value,scopes)}`+`, "${attr}", ${value})`}}function assign_many(target,value){var js="";var nb_targets=target.elts.length,has_starred=false,nb_after_starred;for(var i=0,len=nb_targets;ithis.lineno){end_col_offset=this.col_offset+1}var position=encode_position(this.col_offset,this.col_offset,end_col_offset);js+=`, ${position}`;js+=")";var args=make_args.bind(this)(scopes);return js+(args.has_starred?`.apply(null, ${args.js})`:`(${args.js})`)};$B.ast.Call.prototype._check=function(){for(var kw of this.keywords){if(kw.arg=="__debug__"){compiler_error(this,"cannot assign to __debug__",kw)}}};function make_args(scopes){var js="",named_args=[],named_kwargs=[],starred_kwargs=[],has_starred=false;for(let arg of this.args){if(arg instanceof $B.ast.Starred){arg.$handled=true;has_starred=true}else{named_args.push($B.js_from_ast(arg,scopes))}}var kwds=new Set;for(var keyword of this.keywords){if(keyword.arg){if(kwds.has(keyword.arg)){compiler_error(keyword,`keyword argument repeated: ${keyword.arg}`)}kwds.add(keyword.arg);named_kwargs.push(`${keyword.arg}: ${$B.js_from_ast(keyword.value,scopes)}`)}else{starred_kwargs.push($B.js_from_ast(keyword.value,scopes))}}var args="";named_args=named_args.join(", ");if(!has_starred){args+=`${named_args}`}else{var start=true,not_starred=[];for(let arg of this.args){if(arg instanceof $B.ast.Starred){if(not_starred.length>0){let arg_list=not_starred.map((x=>$B.js_from_ast(x,scopes)));if(start){args+=`[${arg_list.join(", ")}]`}else{args+=`.concat([${arg_list.join(", ")}])`}not_starred=[]}else if(args==""){args="[]"}var starred_arg=$B.js_from_ast(arg.value,scopes);args+=`.concat(_b_.list.$factory(${starred_arg}))`;start=false}else{not_starred.push(arg)}}if(not_starred.length>0){let arg_list=not_starred.map((x=>$B.js_from_ast(x,scopes)));if(start){args+=`[${arg_list.join(", ")}]`;start=false}else{args+=`.concat([${arg_list.join(", ")}])`}}if(args[0]=="."){console.log("bizarre",args)}}if(named_kwargs.length+starred_kwargs.length==0){return{has_starred:has_starred,js:js+`${args}`}}else{var kw=`{${named_kwargs.join(", ")}}`;for(var starred_kwarg of starred_kwargs){kw+=`, ${starred_kwarg}`}kw=`{$kw:[${kw}]}`;if(args.length>0){if(has_starred){kw=`.concat([${kw}])`}else{kw=", "+kw}}return{has_starred:has_starred,js:js+`${args}${kw}`}}}$B.ast.ClassDef.prototype.to_js=function(scopes){var enclosing_scope=bind(this.name,scopes);var class_scope=new Scope(this.name,"class",this);var js="",locals_name=make_scope_name(scopes,class_scope),ref=this.name+make_id(),glob=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]),decorators=[],decorated=false;for(let dec of this.decorator_list){decorated=true;var dec_id="decorator"+make_id();decorators.push(dec_id);js+=`$B.set_lineno(frame, ${dec.lineno})\n`+`var ${dec_id} = ${$B.js_from_ast(dec,scopes)}\n`}js+=`$B.set_lineno(frame, ${this.lineno})\n`;var qualname=this.name;var ix=scopes.length-1;while(ix>=0){if(scopes[ix].parent){ix--}else if(scopes[ix].ast instanceof $B.ast.ClassDef){qualname=scopes[ix].name+"."+qualname;ix--}else{break}}var bases=this.bases.map((x=>$B.js_from_ast(x,scopes)));var has_type_params=this.type_params.length>0;if(has_type_params){check_type_params(this);js+=`$B.$import('_typing')\n`+`var _typing = $B.imported._typing\n`;var params=[];for(let item of this.type_params){if(item instanceof $B.ast.TypeVar){params.push(`$B.$call(_typing.TypeVar)('${item.name}')`)}else if(item instanceof $B.ast.TypeVarTuple){params.push(`$B.$call($B.$getattr(_typing.Unpack, '__getitem__'))($B.$call(_typing.TypeVarTuple)('${item.name.id}'))`)}else if(item instanceof $B.ast.ParamSpec){params.push(`$B.$call(_typing.ParamSpec)('${item.name.id}')`)}}bases.push(`_typing.Generic.__class_getitem__(_typing.Generic,`+` $B.fast_tuple([${params}]))`);for(let item of this.type_params){var name,param_type=item.constructor.$name;if(param_type=="TypeVar"){name=item.name}else{name=item.name.id}js+=`locals.${name} = $B.$call(_typing.${param_type})('${name}')\n`}}var keywords=[],metaclass;for(var keyword of this.keywords){if(keyword.arg=="metaclass"){metaclass=keyword.value}keywords.push(`["${keyword.arg}", `+$B.js_from_ast(keyword.value,scopes)+"]")}var docstring=extract_docstring(this,scopes);js+=`var ${ref} = (function(name, module, bases){\n`+`var _frame_obj = $B.frame_obj,\n`+`resolved_bases = $B.resolve_mro_entries(bases),\n`+`metaclass = $B.get_metaclass(name, module, `+`resolved_bases`;if(metaclass){js+=`, ${metaclass.to_js(scopes)}`}js+=")\n";js+=`var ${locals_name} = $B.make_class_namespace(metaclass, `+`name, module ,"${qualname}", resolved_bases),\n`;js+=`locals = ${locals_name}\n`+`if(resolved_bases !== bases){\nlocals.__orig_bases__ = bases}\n`+`locals.__doc__ = ${docstring}\n`+`var frame = [name, locals, module, ${globals_name}]\n`+`$B.enter_frame(frame, __file__, ${this.lineno})\n`+`var _frame_obj = $B.frame_obj\n`+`if(frame.$f_trace !== _b_.None){\n$B.trace_line()}\n`;scopes.push(class_scope);js+=add_body(this.body,scopes);scopes.pop();var static_attrs=[];if(class_scope.static_attributes){static_attrs=Array.from(class_scope.static_attributes).map((x=>`"${x}"`))}js+="\n$B.trace_return_and_leave(frame, _b_.None)\n"+`return $B.$class_constructor('${this.name}', locals, metaclass, `+`resolved_bases, bases, [${keywords.join(", ")}], `+`[${static_attrs}], ${this.lineno})\n`+`})('${this.name}',${globals_name}.__name__ ?? '${glob}', $B.fast_tuple([${bases}]))\n`;var class_ref=reference(scopes,enclosing_scope,this.name);if(decorated){class_ref=`decorated${make_id()}`;js+="var "}js+=`${class_ref} = ${ref}\n`;if(decorated){js+=reference(scopes,enclosing_scope,this.name)+" = ";var decorate=class_ref;for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`}js+=decorate+"\n"}return js};$B.ast.Compare.prototype.to_js=function(scopes){var test_left=check_is_arg(this.left);var left=$B.js_from_ast(this.left,scopes),comps=[];var len=this.ops.length,prefix=len>1?"locals.$op = ":"";for(var i=0;i1){left="locals.$op"}}return comps.join(" && ")};$B.ast.comprehension.prototype.to_js=function(scopes){var id=make_id(),iter=$B.js_from_ast(this.iter,scopes);var js=`var next_func_${id} = $B.make_js_iterator(${iter}, frame, ${this.lineno})\n`+`for(var next_${id} of next_func_${id}){\n`;var name=new $B.ast.Name(`next_${id}`,new $B.ast.Load);copy_position(name,this.target);name.to_js=function(){return`next_${id}`};var assign=new $B.ast.Assign([this.target],name);copy_position(assign,this.target);js+=assign.to_js(scopes)+" // assign to target\n";for(var _if of this.ifs){js+=`if($B.$bool(${$B.js_from_ast(_if,scopes)})){\n`}return js};$B.ast.Constant.prototype.to_js=function(){if(this.value===true||this.value===false){return this.value+""}else if(this.value===_b_.None){return"_b_.None"}else if(typeof this.value=="string"){var s=this.value,srg=$B.surrogates(s);if(srg.length==0){return`'${s}'`}return`$B.make_String('${s}', [${srg}])`}else if(this.value.__class__===_b_.bytes){return`_b_.bytes.$factory([${this.value.source}])`}else if(typeof this.value=="number"){if(Number.isInteger(this.value)){return this.value}else{return`({__class__: _b_.float, value: ${this.value}})`}}else if(this.value.__class__===$B.long_int){return`$B.fast_long_int(${this.value.value}n)`}else if(this.value.__class__===_b_.float){return`({__class__: _b_.float, value: ${this.value.value}})`}else if(this.value.__class__===_b_.complex){return`$B.make_complex(${this.value.$real.value}, ${this.value.$imag.value})`}else if(this.value===_b_.Ellipsis){return`_b_.Ellipsis`}else{console.log("invalid value",this.value);throw SyntaxError("bad value",this.value)}};$B.ast.Continue.prototype.to_js=function(scopes){if(!in_loop(scopes)){compiler_error(this,"'continue' not properly in loop")}return"continue"};$B.ast.Delete.prototype.to_js=function(scopes){compiler_check(this);var js="";for(var target of this.targets){if(target instanceof $B.ast.Name){var scope=name_scope(target.id,scopes);if(scope.found){scope.found.locals.delete(target.id)}js+=`$B.$delete("${target.id}")\n`}else if(target instanceof $B.ast.Subscript){js+=`$B.$delitem(${$B.js_from_ast(target.value,scopes)}, `+`${$B.js_from_ast(target.slice,scopes)})\n`}else if(target instanceof $B.ast.Attribute){js+=`_b_.delattr(${$B.js_from_ast(target.value,scopes)}, `+`'${target.attr}')\n`}}return`$B.set_lineno(frame, ${this.lineno})\n`+js};$B.ast.Delete.prototype._check=function(){for(var target of this.targets){check_assign_or_delete(this,target,"delete")}};$B.ast.Dict.prototype.to_js=function(scopes){var items=[],keys=this.keys,has_packed=false;function no_key(i){return keys[i]===_b_.None||keys[i]===undefined}for(let i=0,len=this.keys.length;i0){js+=`\nif(no_break_${id}){\n`+add_body(this.orelse,scopes)+"}\n"}return js};$B.ast.FormattedValue.prototype.to_js=function(scopes){var value=$B.js_from_ast(this.value,scopes);if(this.conversion==114){value=`_b_.repr(${value})`}else if(this.conversion==115){value=`_b_.str.$factory(${value})`}else if(this.conversion==97){value=`_b_.ascii(${value})`}if(this.format_spec){value=`_b_.str.format('{0:' + `+$B.js_from_ast(this.format_spec,scopes)+` + '}', ${value})`}else if(this.conversion==-1){value=`_b_.str.$factory(${value})`}return value};function transform_args(scopes){var has_posonlyargs=this.args.posonlyargs.length>0,_defaults=[],nb_defaults=this.args.defaults.length,positional=this.args.posonlyargs.concat(this.args.args),ix=positional.length-nb_defaults,default_names=[],kw_defaults=[],annotations;for(let arg of positional.concat(this.args.kwonlyargs).concat([this.args.vararg,this.args.kwarg])){if(arg&&arg.annotation){annotations=annotations||{};annotations[arg.arg]=arg.annotation}}for(var i=ix;i ${PARAMS_POS_COUNT} ) {\n $B.args0_old(fct, args);\n throw new Error('Too much positional arguments given (args0 should have raised an error) !');\n }\n`;if(hasPosOnly||hasPos){fct+=`\n for( ; offset < ARGS_POS_COUNT ; ++offset)\n result[ PARAMS_NAMES[offset] ] = args[offset];\n`}}if(!hasPos&&!hasNamedOnly&&!hasKWargs){fct+=`\n if( HAS_KW === true ) {\n for(let argname in ARGS_NAMED[0] ) {\n $B.args0_old(fct, args);\n throw new Error('No named arguments expected !!!');\n }\n for(let id = 1; id < ARGS_NAMED.length; ++id ) {\n const kargs = ARGS_NAMED[id];\n for(let argname of $B.unpack_mapping( fct, kargs) ) { //TODO: not optimal\n $B.args0_old(fct, args);\n throw new Error('No named arguments expected !!!');\n }\n }\n }\n`}else{fct+=`\n if( HAS_KW === false ) {\n `}if(hasPos||hasPosOnly){if(posOnlyDefaults!==DEFAULTS.ALL&&posDefaults!==DEFAULTS.ALL){fct+=`\n if( offset < ${PARAMS_POS_DEFAULTS_OFFSET} ) {\n $B.args0_old(fct, args);\n throw new Error('Not enough positional arguments given (args0 should have raised an error) !');\n }\n`}if(posOnlyDefaults!==DEFAULTS.NONE||posDefaults!==DEFAULTS.NONE){fct+=`\n for(let i = offset - PARAMS_POS_DEFAULTS_OFFSET;\n i < PARAMS_POS_DEFAULTS_COUNT;\n ++i)\n result[ PARAMS_NAMES[offset++] ] = PARAMS_POS_DEFAULTS[i];`}}if(hasKWargs){fct+=`\n result[$INFOS.kwarg] = __BRYTHON__.empty_dict();`}if(hasNamedOnly&&namedOnlyDefaults!==DEFAULTS.ALL){fct+=`\n $B.args0_old(fct, args);\n throw new Error('Named argument expected (args0 should have raised an error) !');\n`}else if(namedOnlyDefaults!==DEFAULTS.NONE){fct+=`\n const kwargs_defaults_values = fct.$kwdefaults_values;\n for(let i = 0; i < kwargs_defaults_values.length; ++i )\n result[ PARAMS_NAMES[offset++] ] = kwargs_defaults_values[i];\n`}fct+=`\n return result;\n`;if(!hasPos&&!hasNamedOnly&&!hasKWargs){return fct}else{fct+=`\n }\n`}if(namedOnlyDefaults!==DEFAULTS.NONE){fct+=`\n const kwargs_defaults = fct.$kwdefaults;\n`}if(hasPosOnly){fct+=`\n const PARAMS_POSONLY_COUNT = $CODE.co_posonlyargcount;\n if( offset < PARAMS_POSONLY_COUNT ) {\n `;if(posOnlyDefaults!==DEFAULTS.SOME){fct+=`\n if( offset < ${PARAMS_POS_DEFAULTS_OFFSET} ) {\n $B.args0_old(fct, args);\n throw new Error('Not enough positional parameters given (args0 should have raised an error) !');\n }\n`}if(posOnlyDefaults===DEFAULTS.NONE){fct+=`\n $B.args0_old(fct, args);\n throw new Error('Not enough positional parameters given (args0 should have raised an error) !');\n`}fct+=`\n const max = ${PARAMS_POS_DEFAULTS_COUNT} - (${PARAMS_POS_COUNT} - PARAMS_POSONLY_COUNT);\n // default parameters\n for(let i = offset - ${PARAMS_POS_DEFAULTS_OFFSET};\n i < max;\n ++i)\n result[ PARAMS_NAMES[offset++] ] = PARAMS_POS_DEFAULTS[i];\n }\n`}if(hasKWargs){fct+=`\n const extra = {};\n let nb_extra_args = 0;\n`;if(hasPos||hasNamedOnly){fct+=`\n const HAS_PARAMS = fct.$hasParams;\n`}}fct+=`\n let nb_named_args = 0;\n const kargs = ARGS_NAMED[0];\n for(let argname in kargs) {\n `;if(!hasKWargs){fct+=`\n result[ argname ] = kargs[argname];\n ++nb_named_args;\n`}if(hasKWargs){if(!hasNamedOnly&&!hasPos){fct+=`\n extra[ argname ] = kargs[argname];\n ++nb_extra_args;\n`}else{fct+=`\n if( HAS_PARAMS.has(argname) ) {\n result[ argname ] = kargs[argname];\n ++nb_named_args;\n } else {\n extra[ argname ] = kargs[argname];\n ++nb_extra_args;\n }\n`}}fct+=`\n }\n for(let id = 1; id < ARGS_NAMED.length; ++id ) {\n const kargs = ARGS_NAMED[id];\n for(let item of $B.unpack_mapping(fct, kargs) ) {\n let argname = item.key\n if( typeof argname !== "string") {\n $B.args0_old(fct, args);\n throw new Error('Non string key passed in **kargs');\n }\n `;if(!hasKWargs){fct+=`\n result[ argname ] = item.value;\n ++nb_named_args;\n`}if(hasKWargs){if(!hasNamedOnly&&!hasPos){fct+=`\n extra[ argname ] = $B.$getitem(kargs, argname);\n ++nb_extra_args;\n`}else{fct+=`\n if( HAS_PARAMS.has(argname) ) {\n result[ argname ] = $B.$getitem(kargs, argname);\n ++nb_named_args;\n } else {\n extra[ argname ] = $B.$getitem(kargs, argname);\n ++nb_extra_args;\n }\n`}}fct+=`\n }\n }\n`;fct+=`\n let found = 0;\n let ioffset = offset;\n`;if((hasPosOnly||hasPos)&&(!hasPosOnly||posOnlyDefaults!==DEFAULTS.ALL)&&(!hasPos||posDefaults!==DEFAULTS.ALL)){fct+=`\n for( ; ioffset < ${PARAMS_POS_DEFAULTS_OFFSET}; ++ioffset) {\n const key = PARAMS_NAMES[ioffset];\n if( key in result ) // maybe could be speed up using "!(key in result)"\n continue;\n $B.args0_old(fct, args);\n throw new Error('Missing a named arguments (args0 should have raised an error) !');\n }\n`}if(hasPosOnly&&posOnlyDefaults!==DEFAULTS.NONE||hasPos&&posDefaults!==DEFAULTS.NONE){fct+=`\n for( ; ioffset < PARAMS_POS_COUNT; ++ioffset) {\n const key = PARAMS_NAMES[ioffset];\n if( key in result )\n continue;\n result[key] = PARAMS_POS_DEFAULTS[ioffset - ${PARAMS_POS_DEFAULTS_OFFSET}];\n ++found;\n }\n`}if(hasNamedOnly){fct+=`\n for( ; ioffset < PARAMS_NAMES.length; ++ioffset) {\n const key = PARAMS_NAMES[ioffset];\n if( key in result )\n continue;\n`;if(namedOnlyDefaults===DEFAULTS.SOME){fct+=`\n if( ! kwargs_defaults.has(key) ) {\n $B.args0_old(fct, args);\n throw new Error('Missing a named arguments (args0 should have raised an error) !');\n }\n`}if(namedOnlyDefaults===DEFAULTS.NONE){fct+=`\n $B.args0_old(fct, args);\n throw new Error('Missing a named arguments (args0 should have raised an error) !');\n`}if(namedOnlyDefaults!==DEFAULTS.NONE){fct+=`\n result[key] = kwargs_defaults.get(key);\n ++found;\n`}fct+=`\n }\n`}if(hasNamedOnly||hasPos)fct+=`\n if( found + nb_named_args !== PARAMS_NAMES.length - offset) {\n $B.args0_old(fct, args);\n throw new Error('Inexistant or duplicate named arguments (args0 should have raised an error) !');\n }\n`;if(hasKWargs){fct+=`\n if( Object.keys(extra).length !== nb_extra_args ) {\n $B.args0_old(fct, args);\n throw new Error('Duplicate name given to **kargs parameter (args0 should have raised an error) !');\n }\n result[$INFOS.kwarg] = __BRYTHON__.builtins.dict.$from_js(extra);\n`}fct+=`\n return result\n `;return fct}function type_param_in_def(tp,ref,scopes){var gname=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]);var js="";var name,param_type=tp.constructor.$name;if(param_type=="TypeVar"){name=tp.name}else{name=tp.name.id}bind(name,scopes);if(tp.bound){var typevarscope=new Scope(name,"typevarbound",tp);scopes.push(typevarscope);js+=`function BOUND_OF_${name}(){\n`+`var current_frame = $B.frame_obj.frame,\n`+`frame = ['BOUND_OF_${name}', {}, '${gname}', ${globals_name}]\n`+`$B.enter_frame(frame, __file__, ${tp.bound.lineno})\n`+`try{\n`+`var res = ${tp.bound.to_js(scopes)}\n`+`$B.leave_frame()\nreturn res\n`+`}catch(err){\n`+`$B.leave_frame()\n`+`throw err\n}\n}\n`;scopes.pop()}js+=`locals_${ref}.${name} = `+`$B.$call(_typing.${param_type})('${name}', {$kw: [{infer_variance: true}]})\n`+`type_params.push(locals_${ref}.${name})\n`;if(tp.bound){if(!tp.bound.elts){js+=`_typing.${param_type}._set_lazy_eval(locals_${ref}.${name}, `+`'__bound__', BOUND_OF_${name})\n`}else{js+=`_typing.${param_type}._set_lazy_eval(locals_${ref}.${name}, `+`'__constraints__', BOUND_OF_${name})\n`}}return js}$B.make_args_parser_and_parse=function make_args_parser_and_parse(fct,args){return $B.make_args_parser(fct)(fct,args)};$B.ast.FunctionDef.prototype.to_js=function(scopes){compiler_check(this);var symtable_block=scopes.symtable.table.blocks.get(fast_id(this));var in_class=last_scope(scopes).ast instanceof $B.ast.ClassDef,is_async=this instanceof $B.ast.AsyncFunctionDef,mangle_arg=x=>x;if(in_class){var class_scope=last_scope(scopes);mangle_arg=x=>mangle(scopes,class_scope,x)}var func_name_scope=bind(this.name,scopes);var gname=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]);var decorators=[],decorated=false,decs_declare=this.decorator_list.length>0?"// declare decorators\n":"";for(let dec of this.decorator_list){decorated=true;var dec_id="decorator"+make_id();decorators.push(dec_id);decs_declare+=`$B.set_lineno(frame, ${dec.lineno})\n`;decs_declare+=`var ${dec_id} = ${$B.js_from_ast(dec,scopes)}\n`}var docstring=extract_docstring(this,scopes);var parsed_args=transform_args.bind(this)(scopes),positional=parsed_args.positional,kw_defaults=parsed_args.kw_defaults,kw_default_names=parsed_args.kw_default_names;var defaults=`$B.fast_tuple([${this.args.defaults.map((x=>x.to_js(scopes)))}])`;kw_defaults=kw_default_names.length==0?"_b_.None":`_b_.dict.$from_js({${kw_defaults.join(", ")}})`;var id=make_id(),name2=this.name+id;var has_type_params=this.type_params.length>0,type_params="";if(has_type_params){check_type_params(this);var tp_name=`type_params_${name2}`;var type_params_scope=new Scope(tp_name,"type_params",this.type_params);scopes.push(type_params_scope);var type_params_ref=qualified_scope_name(scopes,type_params_scope);var type_params_func=`function TYPE_PARAMS_OF_${name2}(){\n`;type_params=`$B.$import('_typing')\n`+`var _typing = $B.imported._typing\n`+`var locals_${type_params_ref} = {\n},\n`+`locals = locals_${type_params_ref},\n`+`frame = ['${type_params_ref}', locals, '${gname}', ${globals_name}],\n`+`type_params = []\n`+`$B.enter_frame(frame, '${scopes.filename}', ${this.lineno})\n`;for(var item of this.type_params){type_params+=type_param_in_def(item,type_params_ref,scopes)}type_params_func+=type_params}var func_scope=new Scope(this.name,"def",this);scopes.push(func_scope);var args=positional.concat(this.args.kwonlyargs),slots=[],arg_names=[];for(let arg of args){slots.push(arg.arg+": null");bind(arg.arg,scopes)}for(let arg of this.args.posonlyargs){arg_names.push(`'${mangle_arg(arg.arg)}'`)}for(let arg of this.args.args.concat(this.args.kwonlyargs)){arg_names.push(`'${mangle_arg(arg.arg)}'`)}if(this.args.vararg){bind(mangle_arg(this.args.vararg.arg),scopes)}if(this.args.kwarg){bind(mangle_arg(this.args.kwarg.arg),scopes)}var function_body;if(this.$is_lambda){var _return=new $B.ast.Return(this.body);copy_position(_return,this.body);var body=[_return];function_body=add_body(body,scopes)}else{function_body=add_body(this.body,scopes)}var is_generator=symtable_block.generator;var parse_args=[name2];var js=`$B.set_lineno(frame, ${this.lineno})\n`;if(is_async&&!is_generator){js+="async "}js+=`function ${name2}(){\n`;var locals_name=make_scope_name(scopes,func_scope);js+=`var locals\n`;parse_args.push("arguments");var args_vararg=this.args.vararg===undefined?"null":"'"+mangle_arg(this.args.vararg.arg)+"'",args_kwarg=this.args.kwarg===undefined?"null":"'"+mangle_arg(this.args.kwarg.arg)+"'";if(positional.length==0&&slots.length==0&&this.args.vararg===undefined&&this.args.kwarg===undefined){js+=`var ${locals_name} = locals = {};\n`;js+=`if(arguments.length !== 0){\n`+`${name2}.$args_parser(${parse_args.join(", ")})\n`+`}\n`}else{js+=`var ${locals_name} = locals = ${name2}.$args_parser(${parse_args.join(", ")})\n`}js+=`var frame = ["${this.$is_lambda?"":this.name}", `+`locals, "${gname}", ${globals_name}, ${name2}]\n $B.enter_frame(frame, __file__, ${this.lineno})\n`;if(func_scope.needs_stack_length){js+=`var stack_length = $B.count_frames()\n`}if(func_scope.needs_frames||is_async){js+=`var _frame_obj = $B.frame_obj,\n`+`_linenums = $B.make_linenums()\n`}if(is_async){js+="frame.$async = true\n"}if(is_generator){js+=`locals.$is_generator = true\n`;if(is_async){js+=`var gen_${id} = $B.async_generator.$factory(async function*(){\n`}else{js+=`var gen_${id} = $B.generator.$factory(function*(){\n`}}js+=`try{\n$B.js_this = this\n`;if(in_class){var ix=scopes.indexOf(class_scope),parent=scopes[ix-1];var scope_ref=make_scope_name(scopes,parent),class_ref=class_scope.name,refs=class_ref.split(".").map((x=>`'${x}'`));bind("__class__",scopes);js+=`locals.__class__ = `+`$B.get_method_class(${name2}, ${scope_ref}, "${class_ref}", [${refs}])\n`}js+=function_body+"\n";if(!this.$is_lambda&&!($B.last(this.body)instanceof $B.ast.Return)){js+="var result = _b_.None\n"+"$B.trace_return_and_leave(frame, result)\n"+"return result\n"}js+=`}catch(err){\n`;if(func_scope.needs_frames){js+=`$B.set_exc_and_trace(frame, err)\n`+`err.$frame_obj = _frame_obj\n`+`_linenums[_linenums.length - 1] = frame.$lineno\n`+`err.$linenums = _linenums\n`+`$B.leave_frame()\n`}else{js+=`$B.set_exc_and_leave(frame, err)\n`}js+=`throw err\n }\n }\n`;if(is_generator){js+=`, '${this.name}')\n`+`var _gen_${id} = gen_${id}()\n`+`_gen_${id}.$frame = frame\n`+`$B.leave_frame()\n`+`return _gen_${id}}\n`}scopes.pop();var qualname=in_class?`${func_name_scope.name}.${this.name}`:this.name;var flags=$B.COMPILER_FLAGS.OPTIMIZED|$B.COMPILER_FLAGS.NEWLOCALS;if(this.args.vararg){flags|=$B.COMPILER_FLAGS.VARARGS}if(this.args.kwarg){flags|=$B.COMPILER_FLAGS.VARKEYWORDS}if(is_generator){flags|=$B.COMPILER_FLAGS.GENERATOR}if(is_async){flags|=$B.COMPILER_FLAGS.COROUTINE}var parameters=[],locals=[],identifiers=_b_.dict.$keys_string(symtable_block.symbols);var free_vars=[];for(var ident of identifiers){var flag=_b_.dict.$getitem_string(symtable_block.symbols,ident),_scope=flag>>SF.SCOPE_OFF&SF.SCOPE_MASK;if(_scope==SF.FREE){free_vars.push(`'${ident}'`)}if(flag&SF.DEF_PARAM){parameters.push(`'${ident}'`)}else if(flag&SF.DEF_LOCAL){locals.push(`'${ident}'`)}}var varnames=parameters.concat(locals);if(in_class){js+=`${name2}.$is_method = true\n`}js+=`$B.make_function_infos(${name2}, `+`'${gname}', `+`${defaults}, `+`${kw_defaults}, `+`${docstring}, `+`[${arg_names}], `+`${args_vararg}, `+`${args_kwarg},\n`+`${positional.length}, `+`__file__, `+`${this.lineno}, `+`${flags}, `+`[${free_vars}], `+`${this.args.kwonlyargs.length}, `+`'${this.$is_lambda?"":this.name}', `+`${this.args.posonlyargs.length}, `+`'${this.$is_lambda?"":qualname}', `+`[${varnames}])\n`;if(is_async&&!is_generator){js+=`${name2} = $B.make_async(${name2})\n`}var mangled=mangle(scopes,func_name_scope,this.name),func_ref=`${make_scope_name(scopes,func_name_scope)}.${mangled}`;if(decorated){func_ref=`decorated${make_id()}`;js+="var "}js+=`${func_ref} = ${name2}\n`;if(this.returns||parsed_args.annotations){var features=scopes.symtable.table.future.features,postponed=features&$B.CO_FUTURE_ANNOTATIONS;if(postponed){var src=scopes.src;if(src===undefined){console.log("no src, filename",scopes)}}var ann_items=[];if(parsed_args.annotations){for(var arg_ann in parsed_args.annotations){var ann_ast=parsed_args.annotations[arg_ann];if(in_class){arg_ann=mangle(scopes,class_scope,arg_ann)}if(postponed){var ann_str=annotation_to_str(ann_ast,scopes);ann_items.push(`['${arg_ann}', '${ann_str}']`)}else{var value=ann_ast.to_js(scopes);ann_items.push(`['${arg_ann}', ${value}]`)}}}if(this.returns){if(postponed){var ann_str=annotation_to_str(this.returns,scopes);ann_items.push(`['return', '${ann_str}']`)}else{ann_items.push(`['return', ${this.returns.to_js(scopes)}]`)}}js+=`${func_ref}.__annotations__ = _b_.dict.$from_array([${ann_items.join(", ")}])\n`}else{js+=`${func_ref}.__annotations__ = $B.empty_dict()\n`}if(has_type_params){scopes.pop()}if(decorated&&!has_type_params){js+=`${make_scope_name(scopes,func_name_scope)}.${mangled} = `;let decorate=func_ref;for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`}js+=decorate}if(has_type_params){type_params_func+="\n"+js+"\n"+`${name2}.__type_params__ = $B.fast_tuple(type_params)\n`+`$B.leave_frame()\n`+`return ${name2}\n}\n`;js=type_params_func;if(decorated){js+=`var ${func_ref} = TYPE_PARAMS_OF_${name2}()\n`+`${make_scope_name(scopes,func_name_scope)}.${mangled} = `;let decorate=func_ref;for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`}js+=decorate}else{js+=`var locals_${type_params_ref} = TYPE_PARAMS_OF_${name2}()\n`}}js=decs_declare+js;return js};$B.ast.FunctionDef.prototype._check=function(){for(var arg of this.args.args){if(arg instanceof $B.ast.arg){if(arg.arg=="__debug__"){compiler_error(arg,"cannot assign to __debug__")}}}for(var arg of this.args.kwonlyargs){if(arg instanceof $B.ast.arg){if(arg.arg=="__debug__"){compiler_error(arg,"cannot assign to __debug__")}}}if(this.args.kwarg&&this.args.kwarg.arg=="__debug__"){compiler_error(this.args.kwarg,"cannot assign to __debug__")}};$B.ast.GeneratorExp.prototype.to_js=function(scopes){var id=make_id(),symtable_block=scopes.symtable.table.blocks.get(fast_id(this)),varnames=symtable_block.varnames.map((x=>`"${x}"`));var first_for=this.generators[0],outmost_expr=$B.js_from_ast(first_for.iter,scopes),nb_paren=1;var comp_scope=new Scope(`genexpr_${id}`,"comprehension",this);scopes.push(comp_scope);var comp={ast:this,id:id,type:"genexpr",varnames:varnames,module_name:scopes[0].name,locals_name:make_scope_name(scopes),globals_name:make_scope_name(scopes,scopes[0])};var head=init_comprehension(comp,scopes);var first=this.generators[0];var js=`$B.enter_frame(frame, __file__, ${this.lineno})\n`+`var next_func_${id} = $B.make_js_iterator(expr, frame, ${this.lineno})\n`+`for(var next_${id} of next_func_${id}){\n`+`$B.enter_frame(frame, __file__, ${this.lineno})\n`;var name=new $B.ast.Name(`next_${id}`,new $B.ast.Load);copy_position(name,first_for.iter);name.to_js=function(){return`next_${id}`};var assign=new $B.ast.Assign([first.target],name);assign.lineno=this.lineno;js+=assign.to_js(scopes)+"\n";for(let _if of first.ifs){nb_paren++;js+=`if($B.$bool(${$B.js_from_ast(_if,scopes)})){\n`}for(var comprehension of this.generators.slice(1)){js+=comprehension.to_js(scopes);nb_paren++;for(let _if of comprehension.ifs){nb_paren++}}var elt=$B.js_from_ast(this.elt,scopes),has_await=comp_scope.has_await;js=`var gen${id} = $B.generator.$factory(${has_await?"async ":""}function*(expr){\n`+js;js+=has_await?"var save_frame_obj = $B.frame_obj;\n":"";js+=`try{\n`+` yield ${elt}\n`+`}catch(err){\n`+(has_await?"$B.restore_frame_obj(save_frame_obj, locals)\n":"")+`$B.leave_frame()\nthrow err\n}\n`+(has_await?"\n$B.restore_frame_obj(save_frame_obj, locals);":"");for(var i=0;i")(expr)\n';scopes.pop();var func=`${head}\n${js}\nreturn gen${id}`;return`(function(expr){\n${func}\n})(${outmost_expr})\n`};$B.ast.Global.prototype.to_js=function(scopes){var scope=last_scope(scopes);for(var name of this.names){scope.globals.add(name)}return""};$B.ast.If.prototype.to_js=function(scopes){var scope=$B.last(scopes),new_scope=copy_scope(scope,this);var js=`if($B.set_lineno(frame, ${this.lineno}) && `;if(this.test instanceof $B.ast.BoolOp){this.test.$dont_evaluate=true;js+=`${$B.js_from_ast(this.test,scopes)}){\n`}else{js+=`$B.$bool(${$B.js_from_ast(this.test,scopes)})){\n`}scopes.push(new_scope);js+=add_body(this.body,scopes)+"\n}";scopes.pop();if(this.orelse.length>0){if(this.orelse[0]instanceof $B.ast.If&&this.orelse.length==1){js+="else "+$B.js_from_ast(this.orelse[0],scopes)+add_body(this.orelse.slice(1),scopes)}else{js+="\nelse{\n"+add_body(this.orelse,scopes)+"\n}"}}return js};$B.ast.IfExp.prototype.to_js=function(scopes){return"($B.$bool("+$B.js_from_ast(this.test,scopes)+") ? "+$B.js_from_ast(this.body,scopes)+": "+$B.js_from_ast(this.orelse,scopes)+")"};$B.ast.Import.prototype.to_js=function(scopes){var js=`$B.set_lineno(frame, ${this.lineno})\n`;for(var alias of this.names){js+=`$B.$import("${alias.name}", [], `;if(alias.asname){js+=`{'${alias.name}' : '${alias.asname}'}, `;bind(alias.asname,scopes)}else{js+="{}, ";bind(alias.name,scopes)}var parts=alias.name.split(".");for(var i=0;i`"${x.name}"`)).join(", "),aliases=[];for(var name of this.names){if(name.asname){aliases.push(`${name.name}: '${name.asname}'`)}}js+=`[${names}], {${aliases.join(", ")}}, ${this.level}, locals);`;for(var alias of this.names){if(alias.asname){bind(alias.asname,scopes)}else if(alias.name=="*"){last_scope(scopes).blurred=true;js+=`\n$B.import_all(locals, module)`}else{bind(alias.name,scopes)}}return js};$B.ast.Interactive.prototype.to_js=function(scopes){mark_parents(this);var name=init_scopes.bind(this)("module",scopes);var module_id=name,global_name=make_scope_name(scopes),mod_name=module_name(scopes);var js=`// Javascript code generated from ast\n`+`var $B = __BRYTHON__,\n_b_ = $B.builtins,\n`;js+=`${global_name} = {}, // $B.imported["${mod_name}"],\n`+`locals = ${global_name},\n`+`frame = ["${module_id}", locals, "${module_id}", locals]`;js+=`\nvar __file__ = '${scopes.filename??""}'\n`+`locals.__name__ = '${name}'\n`+`locals.__doc__ = ${extract_docstring(this,scopes)}\n`;if(!scopes.imported){js+=`locals.__annotations__ = locals.__annotations__ || $B.empty_dict()\n`}js+=`$B.enter_frame(frame, __file__, 1)\n`;js+="\nvar _frame_obj = $B.frame_obj\n";js+="var stack_length = $B.count_frames()\n";js+=`try{\n`+add_body(this.body,scopes)+"\n"+`$B.leave_frame({locals, value: _b_.None})\n`+`}catch(err){\n`+`$B.set_exc_and_trace(frame, err)\n`+`$B.leave_frame({locals, value: _b_.None})\n`+"throw err\n"+`}`;scopes.pop();console.log("Interactive",js);return js};$B.ast.JoinedStr.prototype.to_js=function(scopes){var items=this.values.map((s=>$B.js_from_ast(s,scopes)));if(items.length==0){return"''"}return items.join(" + ")};$B.ast.Lambda.prototype.to_js=function(scopes){var id=make_id(),name="lambda_"+$B.lambda_magic+"_"+id;var f=new $B.ast.FunctionDef(name,this.args,this.body,[]);f.lineno=this.lineno;f.$id=fast_id(this);f.$is_lambda=true;var js=f.to_js(scopes),lambda_ref=reference(scopes,last_scope(scopes),name);return`(function(){ ${js}\n`+`return ${lambda_ref}\n})()`};function list_or_tuple_to_js(func,scopes){if(this.elts.filter((x=>x instanceof $B.ast.Starred)).length>0){var parts=[],simple=[];for(var elt of this.elts){if(elt instanceof $B.ast.Starred){elt.$handled=true;parts.push(`[${simple.join(", ")}]`);simple=[];parts.push(`_b_.list.$factory(${$B.js_from_ast(elt,scopes)})`)}else{simple.push($B.js_from_ast(elt,scopes))}}if(simple.length>0){parts.push(`[${simple.join(", ")}]`)}var js=parts[0];for(var part of parts.slice(1)){js+=`.concat(${part})`}return`${func}(${js})`}var elts=this.elts.map((x=>$B.js_from_ast(x,scopes)));return`${func}([${elts.join(", ")}])`}$B.ast.List.prototype.to_js=function(scopes){return list_or_tuple_to_js.bind(this)("$B.$list",scopes)};$B.ast.ListComp.prototype.to_js=function(scopes){compiler_check(this);return make_comp.bind(this)(scopes)};$B.ast.match_case.prototype.to_js=function(scopes){var js=`($B.set_lineno(frame, ${this.lineno}) && `+`$B.pattern_match(subject, {`+`${$B.js_from_ast(this.pattern,scopes)}})`;if(this.guard){js+=` && $B.$bool(${$B.js_from_ast(this.guard,scopes)})`}js+=`){\n`;js+=add_body(this.body,scopes)+"\n}";return js};function is_irrefutable(pattern){switch(pattern.constructor){case $B.ast.MatchAs:if(pattern.pattern===undefined){return pattern}else{return is_irrefutable(pattern.pattern)}case $B.ast.MatchOr:for(var i=0;i-1){compiler_error(this,`multiple assignment to name '${name}' in pattern`)}scope.bindings.push(name)}return params};$B.ast.MatchClass.prototype.to_js=function(scopes){var names=[];for(let pattern of this.patterns.concat(this.kwd_patterns)){let name=pattern.name;if(name){if(names.indexOf(name)>-1){compiler_error(pattern,`multiple assignment to name '${name}' in pattern`)}names.push(name)}}names=[];for(let i=0;i-1){compiler_error(this.kwd_patterns[i],`attribute name repeated in class pattern: ${kwd_attr}`)}names.push(kwd_attr)}var cls=$B.js_from_ast(this.cls,scopes),patterns=this.patterns.map((x=>`{${$B.js_from_ast(x,scopes)}}`));var kw=[];for(let i=0,len=this.kwd_patterns.length;i-1){compiler_error(pattern,`multiple assignments to name '${pattern.name}' in pattern`)}names.push(pattern.name)}}var items=[];for(let i=0,len=this.keys.length;i-1){compiler_error(pattern,`multiple assignments to name '${pattern.name}' in pattern`)}names.push(pattern.name)}items.push("{"+$B.js_from_ast(pattern,scopes)+"}")}return`sequence: [${items.join(", ")}]`};$B.ast.MatchSingleton.prototype.to_js=function(){var value=this.value===true?"_b_.True":this.value===false?"_b_.False":"_b_.None";return`literal: ${value}`};$B.ast.MatchStar.prototype.to_js=function(){var name=this.name===undefined?"_":this.name;return`capture_starred: '${name}'`};$B.ast.MatchValue.prototype.to_js=function(scopes){if(this.value instanceof $B.ast.Constant){return`literal: ${$B.js_from_ast(this.value,scopes)}`}else if(this.value instanceof $B.ast.Constant||this.value instanceof $B.ast.UnaryOp||this.value instanceof $B.ast.BinOp||this.value instanceof $B.ast.Attribute){return`value: ${$B.js_from_ast(this.value,scopes)}`}else{compiler_error(this,"patterns may only match literals and attribute lookups")}};$B.ast.Module.prototype.to_js=function(scopes){mark_parents(this);var name=init_scopes.bind(this)("module",scopes),namespaces=scopes.namespaces;var module_id=name,global_name=make_scope_name(scopes),mod_name=module_name(scopes);var js=`var $B = __BRYTHON__,\n_b_ = $B.builtins,\n`;if(!namespaces){js+=`${global_name} = $B.imported["${mod_name}"],\n`+`locals = ${global_name},\n`+`frame = ["${module_id}", locals, "${module_id}", locals]`}else{js+=`locals = ${namespaces.local_name},\n`+`globals = ${namespaces.global_name}`;if(name){let local_name=("locals_"+name).replace(/\./g,"_");js+=`,\n${local_name} = locals`}}js+=`\nvar __file__ = '${scopes.filename??""}'\n`+`locals.__name__ = '${name}'\n`+`locals.__doc__ = ${extract_docstring(this,scopes)}\n`;if(!scopes.imported){js+=`locals.__annotations__ = locals.__annotations__ || $B.empty_dict()\n`}if(!namespaces){js+=`$B.enter_frame(frame, __file__, 1)\n`;js+="\nvar _frame_obj = $B.frame_obj\n"}js+="var stack_length = $B.count_frames()\n";js+=`try{\n`+add_body(this.body,scopes)+"\n"+`$B.leave_frame({locals, value: _b_.None})\n`+`}catch(err){\n`+`$B.set_exc_and_trace(frame, err)\n`+`$B.leave_frame({locals, value: _b_.None})\n`+"throw err\n"+`}`;scopes.pop();return js};$B.ast.Name.prototype.to_js=function(scopes){if(this.ctx instanceof $B.ast.Store){var scope=bind(this.id,scopes);if(scope===$B.last(scopes)&&scope.freevars.has(this.id)){scope.freevars.delete(this.id)}return reference(scopes,scope,this.id)}else if(this.ctx instanceof $B.ast.Load){var res=name_reference(this.id,scopes,[this.col_offset,this.col_offset,this.end_col_offset]);if(this.id=="__debugger__"&&res.startsWith("$B.resolve_in_scopes")){return"debugger"}return res}};$B.ast.NamedExpr.prototype.to_js=function(scopes){compiler_check(this);var i=scopes.length-1;while(scopes[i].type=="comprehension"){i--}var enclosing_scopes=scopes.slice(0,i+1);enclosing_scopes.symtable=scopes.symtable;bind(this.target.id,enclosing_scopes);return"("+$B.js_from_ast(this.target,enclosing_scopes)+" = "+$B.js_from_ast(this.value,scopes)+")"};$B.ast.NamedExpr.prototype._check=function(){check_assign_or_delete(this,this.target)};$B.ast.Nonlocal.prototype.to_js=function(scopes){var scope=$B.last(scopes);for(var name of this.names){scope.nonlocals.add(name)}return""};$B.ast.Pass.prototype.to_js=function(){return`$B.set_lineno(frame, ${this.lineno})\n`+"void(0)"};$B.ast.Raise.prototype.to_js=function(scopes){var js=`$B.set_lineno(frame, ${this.lineno})\n`+"$B.$raise(";if(this.exc){js+=$B.js_from_ast(this.exc,scopes)}if(this.cause){js+=", "+$B.js_from_ast(this.cause,scopes)}return js+")"};$B.ast.Return.prototype.to_js=function(scopes){if(last_scope(scopes).type!="def"){compiler_error(this,"'return' outside function")}compiler_check(this);var js=`$B.set_lineno(frame, ${this.lineno})\n`+"var result = "+(this.value?$B.js_from_ast(this.value,scopes):" _b_.None")+"\n"+`$B.trace_return_and_leave(frame, result)\nreturn result\n`;return js};function remove_escapes(value){for(var key in $B.escape2cp){value=value.replace(new RegExp("\\\\"+key,"g"),$B.escape2cp[key])}return value}$B.ast.Set.prototype.to_js=function(scopes){var elts=[];for(var elt of this.elts){var js;if(elt instanceof $B.ast.Constant){var v=elt.value;if(typeof v=="string"){v=remove_escapes(v)}js=`{constant: [${$B.js_from_ast(elt,scopes)}, `+`${$B.$hash(v)}]}`}else if(elt instanceof $B.ast.Starred){js=`{starred: ${$B.js_from_ast(elt.value,scopes)}}`}else{js=`{item: ${$B.js_from_ast(elt,scopes)}}`}elts.push(js)}return`_b_.set.$literal([${elts.join(", ")}])`};$B.ast.SetComp.prototype.to_js=function(scopes){return make_comp.bind(this)(scopes)};$B.ast.Slice.prototype.to_js=function(scopes){var lower=this.lower?$B.js_from_ast(this.lower,scopes):"_b_.None",upper=this.upper?$B.js_from_ast(this.upper,scopes):"_b_.None",step=this.step?$B.js_from_ast(this.step,scopes):"_b_.None";return`_b_.slice.$fast_slice(${lower}, ${upper}, ${step})`};$B.ast.Starred.prototype.to_js=function(scopes){if(this.$handled){return`_b_.list.$unpack(${$B.js_from_ast(this.value,scopes)})`}if(this.ctx instanceof $B.ast.Store){compiler_error(this,"starred assignment target must be in a list or tuple")}else{compiler_error(this,"can't use starred expression here")}};$B.ast.Subscript.prototype.to_js=function(scopes){var value=$B.js_from_ast(this.value,scopes),slice=$B.js_from_ast(this.slice,scopes);if(this.slice instanceof $B.ast.Slice){return`$B.getitem_slice(${value}, ${slice})`}else{var position=encode_position(this.value.col_offset,this.slice.col_offset,this.slice.end_col_offset);return`$B.$getitem(${value}, ${slice},${position})`}};$B.ast.Try.prototype.to_js=function(scopes){compiler_check(this);var id=make_id(),has_except_handlers=this.handlers.length>0,has_else=this.orelse.length>0,has_finally=this.finalbody.length>0;var js=`$B.set_lineno(frame, ${this.lineno})\ntry{\n`;js+=`var stack_length_${id} = $B.count_frames()\n`;if(has_finally){js+=`var save_frame_obj_${id} = $B.frames_obj\n`}if(has_else){js+=`var failed${id} = false\n`}var try_scope=copy_scope($B.last(scopes));scopes.push(try_scope);js+=add_body(this.body,scopes)+"\n";if(has_except_handlers){var err="err"+id;js+="}\n";js+=`catch(${err}){\n`+`$B.set_exc_and_trace(frame, ${err})\n`;if(has_else){js+=`failed${id} = true\n`}var first=true,has_untyped_except=false;for(var handler of this.handlers){if(first){js+="if";first=false}else{js+="}else if"}js+=`($B.set_lineno(frame, ${handler.lineno})`;if(handler.type){js+=` && $B.is_exc(${err}, `;if(handler.type instanceof $B.ast.Tuple){js+=`${$B.js_from_ast(handler.type,scopes)}`}else{js+=`[${$B.js_from_ast(handler.type,scopes)}]`}js+=`)){\n`}else{has_untyped_except=true;js+="){\n"}if(handler.name){bind(handler.name,scopes);var mangled=mangle(scopes,try_scope,handler.name);js+=`locals.${mangled} = ${err}\n`}js+=add_body(handler.body,scopes)+"\n";if(!($B.last(handler.body)instanceof $B.ast.Return)){js+="$B.del_exc(frame)\n"}}if(!has_untyped_except){js+=`}else{\nthrow ${err}\n`}js+="}\n"}if(has_else||has_finally){js+="}\n";js+="finally{\n";var finalbody=`var exit = false\n`+`if($B.count_frames() < stack_length_${id}){\n`+`exit = true\n`+`$B.frame_obj = $B.push_frame(frame)\n`+`}\n`+add_body(this.finalbody,scopes);if(this.finalbody.length>0&&!($B.last(this.finalbody)instanceof $B.ast.Return)){finalbody+=`\nif(exit){\n`+`$B.leave_frame()\n`+`}`}var elsebody=`if($B.count_frames() == stack_length_${id} `+`&& ! failed${id}){\n`+add_body(this.orelse,scopes)+"\n}";if(has_else&&has_finally){js+=`try{\n`+elsebody+"\n}\n"+`finally{\n`+finalbody+"}\n"}else if(has_else&&!has_finally){js+=elsebody}else{js+=finalbody}js+="\n}\n"}else{js+="}\n"}scopes.pop();return js};$B.ast.TryStar.prototype.to_js=function(scopes){var id=make_id(),has_except_handlers=this.handlers.length>0,has_else=this.orelse.length>0,has_finally=this.finalbody.length>0;var js=`$B.set_lineno(frame, ${this.lineno})\ntry{\n`;js+=`var stack_length_${id} = $B.count_frames()\n`;if(has_finally){js+=`var save_frame_obj_${id} = $B.frame_obj\n`}if(has_else){js+=`var failed${id} = false\n`}var try_scope=copy_scope($B.last(scopes));scopes.push(try_scope);js+=add_body(this.body,scopes)+"\n";if(has_except_handlers){var err="err"+id;js+="}\n";js+=`catch(${err}){\n`+`$B.set_exc_and_trace(frame, ${err})\n`+`if(! $B.$isinstance(${err}, _b_.BaseExceptionGroup)){\n`+`${err} = _b_.BaseExceptionGroup.$factory(_b_.None, [${err}])\n`+"}\n"+`function fake_split(exc, condition){\n`+`return condition(exc) ? `+`$B.fast_tuple([exc, _b_.None]) : $B.fast_tuple([_b_.None, exc])\n`+"}\n";if(has_else){js+=`failed${id} = true\n`}for(var handler of this.handlers){js+=`$B.set_lineno(frame, ${handler.lineno})\n`;if(handler.type){js+="var condition = function(exc){\n"+" return $B.$isinstance(exc, "+`${$B.js_from_ast(handler.type,scopes)})\n`+"}\n"+`var klass = $B.get_class(${err}),\n`+`split_method = $B.$getattr(klass, 'split'),\n`+`split = $B.$call(split_method)(${err}, condition),\n`+" matching = split[0],\n"+" rest = split[1]\n"+"if(matching.exceptions !== _b_.None){\n"+" for(var err of matching.exceptions){\n";if(handler.name){bind(handler.name,scopes);var mangled=mangle(scopes,try_scope,handler.name);js+=`locals.${mangled} = ${err}\n`}js+=add_body(handler.body,scopes)+"\n";if(!($B.last(handler.body)instanceof $B.ast.Return)){js+="$B.del_exc(frame)\n"}js+="}\n";js+="}\n";js+=`${err} = rest\n`}}js+=`if(${err}.exceptions !== _b_.None){\n`+`throw ${err}\n`+"}\n"}if(has_else||has_finally){js+="}\n";js+="finally{\n";var finalbody=`var exit = false\n`+`if($B.count_frames() < stack_length_${id}){\n`+`exit = true\n`+`$B.frame_obj = $B.push_frame(frame)\n`+`}\n`+add_body(this.finalbody,scopes);if(this.finalbody.length>0&&!($B.last(this.finalbody)instanceof $B.ast.Return)){finalbody+=`\nif(exit){\n`+`$B.leave_frame(locals)\n`+`}`}var elsebody=`if($B.count_frames() == stack_length_${id} `+`&& ! failed${id}){\n`+add_body(this.orelse,scopes)+"\n}";if(has_else&&has_finally){js+=`try{\n`+elsebody+"\n}\n"+`finally{\n`+finalbody+"}\n"}else if(has_else&&!has_finally){js+=elsebody}else{js+=finalbody}js+="\n}\n"}else{js+="}\n"}scopes.pop();return js};$B.ast.Tuple.prototype.to_js=function(scopes){return list_or_tuple_to_js.bind(this)("$B.fast_tuple",scopes)};$B.ast.TypeAlias.prototype.to_js=function(scopes){var type_param_scope=new Scope("type_params","type_params",this.type_params);scopes.push(type_param_scope);var type_alias_scope=new Scope("type_alias","type_alias",this);scopes.push(type_alias_scope);var type_params_names=[];check_type_params(this);for(var type_param of this.type_params){if(type_param instanceof $B.ast.TypeVar){type_params_names.push(type_param.name)}else if(type_param instanceof $B.ast.TypeVarTuple||type_param instanceof $B.ast.ParamSpec){type_params_names.push(type_param.name.id)}}for(var name of type_params_names){bind(name,scopes)}var qualified_name=qualified_scope_name(scopes,type_alias_scope);var value=this.value.to_js(scopes);scopes.pop();scopes.pop();var js=`$B.$import('_typing')\n`;js+=`var locals_${qualified_scope_name(scopes,type_param_scope)} = {}\n`;js+=`function TYPE_PARAMS_OF_${this.name.id}(){\n`+`var locals_${qualified_name} = {},\n`+` locals = locals_${qualified_name}, \n`+` type_params = $B.fast_tuple([])\n`;for(var i=0,len=this.type_params.length;i0){js+=`\nif(no_break_${id}){\n`+add_body(this.orelse,scopes)+"}\n"}return js};$B.ast.With.prototype.to_js=function(scopes){function add_item(item,js){var id=make_id();var s=`var mgr_${id} = `+$B.js_from_ast(item.context_expr,scopes)+",\n"+`klass = $B.get_class(mgr_${id})\n`+`try{\n`+`var exit_${id} = $B.$getattr(klass, '__exit__'),\n`+`enter_${id} = $B.$getattr(klass, '__enter__')\n`+`}catch(err){\n`+`var klass_name = $B.class_name(mgr_${id})\n`+`throw _b_.TypeError.$factory("'" + klass_name + `+`"' object does not support the con`+`text manager protocol")\n`+`}\n`+`var value_${id} = $B.$call(enter_${id})(mgr_${id}),\n`+`exc_${id} = true\n`;if(in_generator){s+=`locals.$context_managers = locals.$context_managers || []\n`+`locals.$context_managers.push(mgr_${id})\n`}s+="try{\ntry{\n";if(item.optional_vars){var value={to_js:function(){return`value_${id}`}};copy_position(value,_with);var assign=new $B.ast.Assign([item.optional_vars],value);copy_position(assign,_with);s+=assign.to_js(scopes)+"\n"}s+=js;s+=`}catch(err_${id}){\n`+`frame.$lineno = ${lineno}\n`+`exc_${id} = false\n`+`err_${id} = $B.exception(err_${id}, frame)\n`+`var $b = exit_${id}(mgr_${id}, err_${id}.__class__, `+`err_${id}, $B.$getattr(err_${id}, '__traceback__'))\n`+`if(! $B.$bool($b)){\n`+`throw err_${id}\n`+`}\n`+`}\n`;s+=`}\nfinally{\n`+`frame.$lineno = ${lineno}\n`+(in_generator?`locals.$context_managers.pop()\n`:"")+`if(exc_${id}){\n`+`try{\n`+`exit_${id}(mgr_${id}, _b_.None, _b_.None, _b_.None)\n`+`}catch(err){\n`+`if($B.count_frames() < stack_length){\n`+`$B.frame_obj = $B.push_frame(frame)\n`+`}\n`+`throw err\n`+`}\n`+`}\n`+`}\n`;return s}var _with=this,scope=last_scope(scopes),lineno=this.lineno;scope.needs_stack_length=true;var js=add_body(this.body,scopes)+"\n";var in_generator=scopes.symtable.table.blocks.get(fast_id(scope.ast)).generator;for(var item of this.items.slice().reverse()){js=add_item(item,js)}return`$B.set_lineno(frame, ${this.lineno})\n`+js};$B.ast.Yield.prototype.to_js=function(scopes){var scope=last_scope(scopes);if(scope.type!="def"){compiler_error(this,"'yield' outside function")}last_scope(scopes).is_generator=true;var value=this.value?$B.js_from_ast(this.value,scopes):"_b_.None";return`yield ${value}`};$B.ast.YieldFrom.prototype.to_js=function(scopes){var scope=last_scope(scopes);if(scope.type!="def"){compiler_error(this,"'yield' outside function")}scope.is_generator=true;var value=$B.js_from_ast(this.value,scopes);var n=make_id();return`yield* (function* f(){\n var _i${n} = _b_.iter(${value}),\n _r${n}\n var failed${n} = false\n try{\n var _y${n} = _b_.next(_i${n})\n }catch(_e){\n $B.set_exc(_e, frame)\n failed${n} = true\n $B.pmframe = $B.frame_obj.frame\n _e = $B.exception(_e)\n if(_e.__class__ === _b_.StopIteration){\n var _r${n} = $B.$getattr(_e, "value")\n }else{\n throw _e\n }\n }\n if(! failed${n}){\n while(true){\n var failed1${n} = false\n try{\n $B.leave_frame()\n var _s${n} = yield _y${n}\n $B.frame_obj = $B.push_frame(frame)\n }catch(_e){\n $B.set_exc(_e, frame)\n if(_e.__class__ === _b_.GeneratorExit){\n var failed2${n} = false\n try{\n var _m${n} = $B.$getattr(_i${n}, "close")\n }catch(_e1){\n failed2${n} = true\n if(_e1.__class__ !== _b_.AttributeError){\n throw _e1\n }\n }\n if(! failed2${n}){\n $B.$call(_m${n})()\n }\n throw _e\n }else if($B.is_exc(_e, [_b_.BaseException])){\n var sys_module = $B.imported._sys,\n _x${n} = sys_module.exc_info()\n var failed3${n} = false\n try{\n var _m${n} = $B.$getattr(_i${n}, "throw")\n }catch(err){\n failed3${n} = true\n if($B.is_exc(err, [_b_.AttributeError])){\n throw err\n }\n }\n if(! failed3${n}){\n try{\n _y${n} = $B.$call(_m${n}).apply(null,\n _b_.list.$factory(_x${n}))\n }catch(err){\n if($B.is_exc(err, [_b_.StopIteration])){\n _r${n} = $B.$getattr(err, "value")\n break\n }\n throw err\n }\n }\n }\n }\n if(! failed1${n}){\n try{\n if(_s${n} === _b_.None){\n _y${n} = _b_.next(_i${n})\n }else{\n _y${n} = $B.$call($B.$getattr(_i${n}, "send"))(_s${n})\n }\n }catch(err){\n if($B.is_exc(err, [_b_.StopIteration])){\n _r${n} = $B.$getattr(err, "value")\n break\n }\n throw err\n }\n }\n }\n }\n return _r${n}\n })()`};var state={};$B.js_from_root=function(arg){var ast_root=arg.ast,symtable=arg.symtable,filename=arg.filename,src=arg.src,namespaces=arg.namespaces,imported=arg.imported;if($B.show_ast_dump){console.log($B.ast_dump(ast_root))}if($B.compiler_check){$B.compiler_check(ast_root,symtable)}var scopes=[];state.filename=filename;scopes.symtable=symtable;scopes.filename=filename;scopes.src=src;scopes.namespaces=namespaces;scopes.imported=imported;scopes.imports={};var js=ast_root.to_js(scopes);return{js:js,imports:scopes.imports}};$B.js_from_ast=function(ast,scopes){if(!scopes.symtable){throw Error("perdu symtable")}scopes=scopes||[];if(ast.to_js!==undefined){if(ast.col_offset===undefined){var klass=ast.constructor.$name;if(["match_case"].indexOf(klass)==-1){console.log("no col_offset for",klass);console.log(ast);throw Error("no col offset")}}return ast.to_js(scopes)}console.log("unhandled",ast.constructor.$name,ast,typeof ast);return"// unhandled class ast."+ast.constructor.$name}})(__BRYTHON__);(function($B){var _b_=$B.builtins;var GLOBAL_PARAM="name '%s' is parameter and global",NONLOCAL_PARAM="name '%s' is parameter and nonlocal",GLOBAL_AFTER_ASSIGN="name '%s' is assigned to before global declaration",NONLOCAL_AFTER_ASSIGN="name '%s' is assigned to before nonlocal declaration",GLOBAL_AFTER_USE="name '%s' is used prior to global declaration",NONLOCAL_AFTER_USE="name '%s' is used prior to nonlocal declaration",GLOBAL_ANNOT="annotated name '%s' can't be global",NONLOCAL_ANNOT="annotated name '%s' can't be nonlocal",IMPORT_STAR_WARNING="import * only allowed at module level",NAMED_EXPR_COMP_IN_CLASS="assignment expression within a comprehension cannot be used in a class body",NAMED_EXPR_COMP_CONFLICT="assignment expression cannot rebind comprehension iteration variable '%s'",NAMED_EXPR_COMP_INNER_LOOP_CONFLICT="comprehension inner loop cannot rebind assignment expression target '%s'",NAMED_EXPR_COMP_ITER_EXPR="assignment expression cannot be used in a comprehension iterable expression",ANNOTATION_NOT_ALLOWED="'%s' can not be used within an annotation",DUPLICATE_ARGUMENT="duplicate argument '%s' in function definition",TYPEVAR_BOUND_NOT_ALLOWED="%s cannot be used within a TypeVar bound",TYPEALIAS_NOT_ALLOWED="%s cannot be used within a type alias",TYPEPARAM_NOT_ALLOWED="%s cannot be used within the definition of a generic",DUPLICATE_TYPE_PARAM="duplicate type parameter '%s'";var SF=$B.SYMBOL_FLAGS;var NULL=undefined;var ModuleBlock=2,ClassBlock=1,FunctionBlock=0,AnnotationBlock=4,TypeVarBoundBlock=5,TypeAliasBlock=6,TypeParamBlock=7;var PyExc_SyntaxError=_b_.SyntaxError;function assert(test){if(!$B.$bool(test)){console.log("test fails",test);throw Error("test fails")}}function LOCATION(x){return[x.lineno,x.col_offset,x.end_lineno,x.end_col_offset]}function ST_LOCATION(x){return[x.lineno,x.col_offset,x.end_lineno,x.end_col_offset]}function _Py_Mangle(privateobj,ident){var plen,ipriv;if(privateobj==NULL||!ident.startsWith("__")){return ident}plen=privateobj.length;if(ident.endsWith("__")||ident.search(/\./)!=-1){return ident}ipriv=0;while(privateobj[ipriv]=="_"){ipriv++}if(ipriv==plen){return ident}var prefix=privateobj.substr(ipriv);return"_"+prefix+ident}var lambda=NULL;var NoComprehension=0,ListComprehension=1,DictComprehension=2,SetComprehension=3,GeneratorExpression=4;function GET_IDENTIFIER(VAR){return VAR}function Symtable(){this.filename=NULL;this.stack=[];this.blocks=new Map;this.cur=NULL;this.private=NULL}function id(obj){if(obj.$id!==undefined){return obj.$id}return obj.$id=$B.UUID()}function ste_new(st,name,block,key,lineno,col_offset,end_lineno,end_col_offset){var ste;ste={table:st,id:id(key),name:name,directives:NULL,type:block,nested:0,free:0,varargs:0,varkeywords:0,opt_lineno:0,opt_col_offset:0,lineno:lineno,col_offset:col_offset,end_lineno:end_lineno,end_col_offset:end_col_offset};if(st.cur!=NULL&&(st.cur.nested||st.cur.type==FunctionBlock)){ste.nested=1}ste.child_free=0;ste.generator=0;ste.coroutine=0;ste.comprehension=NoComprehension;ste.returns_value=0;ste.needs_class_closure=0;ste.comp_inlined=0;ste.comp_iter_target=0;ste.comp_iter_expr=0;ste.symbols=$B.empty_dict();ste.varnames=[];ste.children=[];st.blocks.set(ste.id,ste);return ste}$B._PySymtable_Build=function(mod,filename,future){var st=new Symtable,seq;st.filename=filename;st.future=future||{};st.type=SF.TYPE_MODULE;if(!symtable_enter_block(st,"top",ModuleBlock,mod,0,0,0,0)){return NULL}st.top=st.cur;switch(mod.constructor){case $B.ast.Module:seq=mod.body;for(let item of seq){visitor.stmt(st,item)}break;case $B.ast.Expression:visitor.expr(st,mod.body);break;case $B.ast.Interactive:seq=mod.body;for(let item of seq){visitor.stmt(st,item)}break}symtable_analyze(st);return st.top};function _PyST_GetSymbol(ste,name){if(!_b_.dict.$contains_string(ste.symbols,name)){return 0}return _b_.dict.$getitem_string(ste.symbols,name)}function _PyST_GetScope(ste,name){var symbol=_PyST_GetSymbol(ste,name);return symbol>>SF.SCOPE_OFFSET&SF.SCOPE_MASK}function _PyST_IsFunctionLike(ste){return ste.type==FunctionBlock||ste.type==TypeVarBoundBlock||ste.type==TypeAliasBlock||ste.type==TypeParamBlock}function PyErr_Format(exc_type,message,arg){if(arg){message=_b_.str.__mod__(message,arg)}return exc_type.$factory(message)}function PyErr_SetString(exc_type,message){return exc_type.$factory(message)}function set_exc_info(exc,filename,lineno,offset,end_lineno,end_offset){exc.filename=filename;exc.lineno=lineno;exc.offset=offset+1;exc.end_lineno=end_lineno;exc.end_offset=end_offset+1;var src=$B.file_cache[filename];if(src!==undefined){var lines=src.split("\n");exc.text=lines[lineno-1]}else{exc.text=""}exc.args[1]=[filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]}function error_at_directive(exc,ste,name){assert(ste.directives);for(var data of ste.directives){if(data[0]==name){set_exc_info(exc,ste.table.filename,data[1],data[2],data[3],data[4]);return 0}}throw _b_.RuntimeError.$factory("BUG: internal directive bookkeeping broken")}function SET_SCOPE(DICT,NAME,I){DICT[NAME]=I}function is_free_in_any_child(entry,key){for(var child_ste of entry.ste_children){var scope=_PyST_GetScope(child_ste,key);if(scope==SF.FREE){return 1}}return 0}function inline_comprehension(ste,comp,scopes,comp_free,inlined_cells){for(var item of _b_.dict.$iter_items(comp.symbols)){var k=item.key,comp_flags=item.value;if(comp_flags&SF.DEF_PARAM){continue}var scope=comp_flags>>SF.SCOPE_OFFSET&SF.SCOPE_MASK;var only_flags=comp_flags&(1<=0;i--){let entry=ste.children[i];if(entry.comp_inlined){ste.children.splice(i,0,...entry.children)}}if(_PyST_IsFunctionLike(ste)&&!analyze_cells(scopes,newfree,inlined_cells)){return 0}else if(ste.type===ClassBlock&&!drop_class_free(ste,newfree)){return 0}if(!update_symbols(ste.symbols,scopes,bound,newfree,inlined_cells,ste.type===ClassBlock||ste.can_see_class_scope)){return 0}Set_Union(free,newfree);success=1;return success}function PySet_New(arg){if(arg===NULL){return new Set}return new Set(arg)}function Set_Union(setA,setB){for(let elem of setB){setA.add(elem)}}function analyze_child_block(entry,bound,free,global,typeparams,class_entry,child_free){var temp_bound=PySet_New(bound),temp_free=PySet_New(free),temp_global=PySet_New(global),temp_typeparams=PySet_New(typeparams);if(!analyze_block(entry,temp_bound,temp_free,temp_global,temp_typeparams,class_entry)){return 0}Set_Union(child_free,temp_free);return 1}function symtable_analyze(st){var free=new Set,global=new Set,typeparams=new Set;return analyze_block(st.top,NULL,free,global,typeparams,NULL)}function symtable_exit_block(st){var size=st.stack.length;st.cur=NULL;if(size){st.stack.pop();if(--size){st.cur=st.stack[size-1]}}return 1}function symtable_enter_block(st,name,block,ast,lineno,col_offset,end_lineno,end_col_offset){var prev;if(ast===undefined){console.log("call ste new, key undef",st,name)}var ste=ste_new(st,name,block,ast,lineno,col_offset,end_lineno,end_col_offset);st.stack.push(ste);prev=st.cur;if(prev){ste.comp_iter_expr=prev.comp_iter_expr}st.cur=ste;if(block===AnnotationBlock){return 1}if(block===ModuleBlock){st.global=st.cur.symbols}if(prev){prev.children.push(ste)}return 1}function symtable_lookup(st,name){var mangled=_Py_Mangle(st.private,name);if(!mangled){return 0}var ret=_PyST_GetSymbol(st.cur,mangled);return ret}function symtable_add_def_helper(st,name,flag,ste,_location){var o,dict,val,mangled=_Py_Mangle(st.private,name);if(!mangled){return 0}dict=ste.symbols;if(_b_.dict.$contains_string(dict,mangled)){o=_b_.dict.$getitem_string(dict,mangled);val=o;if(flag&SF.DEF_PARAM&&val&SF.DEF_PARAM){let exc=PyErr_Format(_b_.SyntaxError,DUPLICATE_ARGUMENT,name);set_exc_info(exc,st.filename,..._location);throw exc}if(flag&SF.DEF_TYPE_PARAM&&val&SF.DEF_TYPE_PARAM){let exc=PyErr_Format(_b_.SyntaxError,DUPLICATE_TYPE_PARAM,name);set_exc_info(exc,st.filename,...location);throw exc}val|=flag}else{val=flag}if(ste.comp_iter_target){if(val&(SF.DEF_GLOBAL|SF.DEF_NONLOCAL)){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_INNER_LOOP_CONFLICT,name);set_exc_info(exc,st.filename,..._location);throw exc}val|=SF.DEF_COMP_ITER}o=val;if(o==NULL){return 0}_b_.dict.$setitem(dict,mangled,o);if(flag&SF.DEF_PARAM){ste.varnames.push(mangled)}else if(flag&SF.DEF_GLOBAL){val=flag;if(st.global.hasOwnProperty(mangled)){val|=st.global[mangled]}o=val;if(o==NULL){return 0}st.global[mangled]=o}return 1}function symtable_add_def(st,name,flag,_location){return symtable_add_def_helper(st,name,flag,st.cur,_location)}function symtable_enter_type_param_block(st,name,ast,has_defaults,has_kwdefaults,kind,_location){var prev=st.cur,current_type=st.cur.type;if(!symtable_enter_block(st,name,TypeParamBlock,ast,..._location)){return 0}prev.$type_param=st.cur;if(current_type===ClassBlock){st.cur.can_see_class_scope=1;if(!symtable_add_def(st,"__classdict__",SF.USE,_location)){return 0}}if(kind==$B.ast.ClassDef){if(!symtable_add_def(st,"type_params",SF.DEF_LOCAL,_location)){return 0}if(!symtable_add_def(st,"type_params",SF.USE,_location)){return 0}st.st_private=name;var generic_base=".generic_base";if(!symtable_add_def(st,generic_base,SF.DEF_LOCAL,_location)){return 0}if(!symtable_add_def(st,generic_base,SF.USE,_location)){return 0}}if(has_defaults){var defaults=".defaults";if(!symtable_add_def(st,defaults,SF.DEF_PARAM,_location)){return 0}}if(has_kwdefaults){var kwdefaults=".kwdefaults";if(!symtable_add_def(st,kwdefaults,SF.DEF_PARAM,_location)){return 0}}return 1}function VISIT_QUIT(ST,X){return X}function VISIT(ST,TYPE,V){var f=visitor[TYPE];if(!f(ST,V)){VISIT_QUIT(ST,0)}}function VISIT_SEQ(ST,TYPE,SEQ){for(var elt of SEQ){if(!visitor[TYPE](ST,elt)){VISIT_QUIT(ST,0)}}}function VISIT_SEQ_TAIL(ST,TYPE,SEQ,START){for(var i=START,len=SEQ.length;i0){if(!symtable_enter_type_param_block(st,s.name,s.type_params,s.args.defaults!=NULL,has_kwonlydefaults(s.args.kwonlyargs,s.args.kw_defaults),s.constructor,LOCATION(s))){VISIT_QUIT(st,0)}VISIT_SEQ(st,type_param,s.type_params)}if(!visitor.annotations(st,s,s.args,s.returns))VISIT_QUIT(st,0);if(s.decorator_list){VISIT_SEQ(st,expr,s.decorator_list)}if(!symtable_enter_block(st,s.name,FunctionBlock,s,...LOCATION(s))){VISIT_QUIT(st,0)}VISIT(st,"arguments",s.args);VISIT_SEQ(st,stmt,s.body);if(!symtable_exit_block(st)){VISIT_QUIT(st,0)}if(s.type_params.length>0){if(!symtable_exit_block(st)){VISIT_QUIT(st,0)}}break;case $B.ast.ClassDef:var tmp;if(!symtable_add_def(st,s.name,SF.DEF_LOCAL,LOCATION(s)))VISIT_QUIT(st,0);VISIT_SEQ(st,expr,s.bases);VISIT_SEQ(st,keyword,s.keywords);if(s.decorator_list)VISIT_SEQ(st,expr,s.decorator_list);if(s.type_params.length>0){if(!symtable_enter_type_param_block(st,s.name,s.type_params,false,false,s.constructor,LOCATION(s))){VISIT_QUIT(st,0)}VISIT_SEQ(st,type_param,s.type_params)}VISIT_SEQ(st,expr,s.bases);VISIT_SEQ(st,keyword,s.keywords);if(!symtable_enter_block(st,s.name,ClassBlock,s,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset))VISIT_QUIT(st,0);tmp=st.private;st.private=s.name;if(s.type_params.length>0){if(!symtable_add_def(st,"__type_params__",SF.DEF_LOCAL,LOCATION(s))){VISIT_QUIT(st,0)}if(!symtable_add_def(st,"type_params",SF.USE,LOCATION(s))){VISIT_QUIT(st,0)}}VISIT_SEQ(st,stmt,s.body);st.private=tmp;if(!symtable_exit_block(st))VISIT_QUIT(st,0);if(s.type_params.length>0){if(!symtable_exit_block(st))VISIT_QUIT(st,0)}break;case $B.ast.TypeAlias:VISIT(st,expr,s.name);assert(s.name instanceof $B.ast.Name);var name=s.name.id,is_in_class=st.cur.type===ClassBlock,is_generic=s.type_params.length>0;if(is_generic){if(!symtable_enter_type_param_block(st,name,s.type_params,false,false,s.kind,LOCATION(s))){VISIT_QUIT(st,0)}VISIT_SEQ(st,type_param,s.type_params)}if(!symtable_enter_block(st,name,TypeAliasBlock,s,LOCATION(s))){VISIT_QUIT(st,0)}st.cur.can_see_class_scope=is_in_class;if(is_in_class&&!symtable_add_def(st,"__classdict__",SF.USE,LOCATION(s.value))){VISIT_QUIT(st,0)}VISIT(st,expr,s.value);if(!symtable_exit_block(st)){VISIT_QUIT(st,0)}if(is_generic){if(!symtable_exit_block(st))VISIT_QUIT(st,0)}break;case $B.ast.Return:if(s.value){VISIT(st,expr,s.value);st.cur.returns_value=1}break;case $B.ast.Delete:VISIT_SEQ(st,expr,s.targets);break;case $B.ast.Assign:VISIT_SEQ(st,expr,s.targets);VISIT(st,expr,s.value);break;case $B.ast.AnnAssign:if(s.target instanceof $B.ast.Name){var e_name=s.target;var cur=symtable_lookup(st,e_name.id);if(cur<0){VISIT_QUIT(st,0)}if(cur&(SF.DEF_GLOBAL|SF.DEF_NONLOCAL)&&st.cur.symbols!=st.global&&s.simple){var exc=PyErr_Format(_b_.SyntaxError,cur&SF.DEF_GLOBAL?GLOBAL_ANNOT:NONLOCAL_ANNOT,e_name.id);exc.args[1]=[st.filename,s.lineno,s.col_offset+1,s.end_lineno,s.end_col_offset+1];throw exc}if(s.simple&&!symtable_add_def(st,e_name.id,SF.DEF_ANNOT|SF.DEF_LOCAL,LOCATION(e_name))){VISIT_QUIT(st,0)}else{if(s.value&&!symtable_add_def(st,e_name.id,SF.DEF_LOCAL,LOCATION(e_name))){VISIT_QUIT(st,0)}}}else{VISIT(st,expr,s.target)}if(!visitor.annotation(st,s.annotation)){VISIT_QUIT(st,0)}if(s.value){VISIT(st,expr,s.value)}break;case $B.ast.AugAssign:VISIT(st,expr,s.target);VISIT(st,expr,s.value);break;case $B.ast.For:VISIT(st,expr,s.target);VISIT(st,expr,s.iter);VISIT_SEQ(st,stmt,s.body);if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)}break;case $B.ast.While:VISIT(st,expr,s.test);VISIT_SEQ(st,stmt,s.body);if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)}break;case $B.ast.If:VISIT(st,expr,s.test);VISIT_SEQ(st,stmt,s.body);if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)}break;case $B.ast.Match:VISIT(st,expr,s.subject);VISIT_SEQ(st,match_case,s.cases);break;case $B.ast.Raise:if(s.exc){VISIT(st,expr,s.exc);if(s.cause){VISIT(st,expr,s.cause)}}break;case $B.ast.Try:VISIT_SEQ(st,stmt,s.body);VISIT_SEQ(st,excepthandler,s.handlers);VISIT_SEQ(st,stmt,s.orelse);VISIT_SEQ(st,stmt,s.finalbody);break;case $B.ast.TryStar:VISIT_SEQ(st,stmt,s.body);VISIT_SEQ(st,stmt,s.orelse);VISIT_SEQ(st,excepthandler,s.handlers);VISIT_SEQ(st,stmt,s.finalbody);break;case $B.ast.Assert:VISIT(st,expr,s.test);if(s.msg){VISIT(st,expr,s.msg)}break;case $B.ast.Import:VISIT_SEQ(st,alias,s.names);break;case $B.ast.ImportFrom:VISIT_SEQ(st,alias,s.names);break;case $B.ast.Global:var seq=s.names;for(var name of seq){var cur=symtable_lookup(st,name);if(cur<0){VISIT_QUIT(st,0)}if(cur&(SF.DEF_PARAM|SF.DEF_LOCAL|SF.USE|SF.DEF_ANNOT)){var msg;if(cur&SF.DEF_PARAM){msg=GLOBAL_PARAM}else if(cur&SF.USE){msg=GLOBAL_AFTER_USE}else if(cur&SF.DEF_ANNOT){msg=GLOBAL_ANNOT}else{msg=GLOBAL_AFTER_ASSIGN}var exc=PyErr_Format(_b_.SyntaxError,msg,name);set_exc_info(exc,st.filename,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset);throw exc}if(!symtable_add_def(st,name,SF.DEF_GLOBAL,LOCATION(s)))VISIT_QUIT(st,0);if(!symtable_record_directive(st,name,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset))VISIT_QUIT(st,0)}break;case $B.ast.Nonlocal:var seq=s.names;for(var name of seq){var cur=symtable_lookup(st,name);if(cur<0){VISIT_QUIT(st,0)}if(cur&(SF.DEF_PARAM|SF.DEF_LOCAL|SF.USE|SF.DEF_ANNOT)){var msg;if(cur&SF.DEF_PARAM){msg=NONLOCAL_PARAM}else if(cur&SF.USE){msg=NONLOCAL_AFTER_USE}else if(cur&SF.DEF_ANNOT){msg=NONLOCAL_ANNOT}else{msg=NONLOCAL_AFTER_ASSIGN}var exc=PyErr_Format(_b_.SyntaxError,msg,name);set_exc_info(exc,st.filename,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset);throw exc}if(!symtable_add_def(st,name,SF.DEF_NONLOCAL,LOCATION(s)))VISIT_QUIT(st,0);if(!symtable_record_directive(st,name,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset))VISIT_QUIT(st,0)}break;case $B.ast.Expr:VISIT(st,expr,s.value);break;case $B.ast.Pass:case $B.ast.Break:case $B.ast.Continue:break;case $B.ast.With:VISIT_SEQ(st,"withitem",s.items);VISIT_SEQ(st,stmt,s.body);break;case $B.ast.AsyncFunctionDef:if(!symtable_add_def(st,s.name,SF.DEF_LOCAL,LOCATION(s)))VISIT_QUIT(st,0);if(s.args.defaults)VISIT_SEQ(st,expr,s.args.defaults);if(s.args.kw_defaults)VISIT_SEQ_WITH_NULL(st,expr,s.args.kw_defaults);if(!visitor.annotations(st,s,s.args,s.returns))VISIT_QUIT(st,0);if(s.decorator_list)VISIT_SEQ(st,expr,s.decorator_list);if(s.type_params.length>0){if(!symtable_enter_type_param_block(st,s.name,s.type_params,s.args.defaults!=NULL,has_kwonlydefaults(s.args.kwonlyargs,s.args.kw_defaults),s.constructor,LOCATION(s))){VISIT_QUIT(st,0)}VISIT_SEQ(st,type_param,s.type_params)}if(!visitor.annotations(st,s,s.args,s.returns))VISIT_QUIT(st,0);if(!symtable_enter_block(st,s.name,FunctionBlock,s,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset))VISIT_QUIT(st,0);st.cur.coroutine=1;VISIT(st,"arguments",s.args);VISIT_SEQ(st,stmt,s.body);if(!symtable_exit_block(st))VISIT_QUIT(st,0);if(s.type_params.length>0){if(!symtable_exit_block(st))VISIT_QUIT(st,0)}break;case $B.ast.AsyncWith:VISIT_SEQ(st,withitem,s.items);VISIT_SEQ(st,stmt,s.body);break;case $B.ast.AsyncFor:VISIT(st,expr,s.target);VISIT(st,expr,s.iter);VISIT_SEQ(st,stmt,s.body);if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)}break;default:console.log("unhandled",s);break}VISIT_QUIT(st,1)};function symtable_extend_namedexpr_scope(st,e){assert(st.stack);assert(e instanceof $B.ast.Name);var target_name=e.id;var i,size,ste;size=st.stack.length;assert(size);for(i=size-1;i>=0;i--){ste=st.stack[i];if(ste.comprehension){let target_in_scope=_PyST_GetSymbol(ste,target_name);if(target_in_scope&SF.DEF_COMP_ITER){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_CONFLICT,target_name);set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.ed_lineno,e.end_col_offset);throw exc}continue}if(_PyST_IsFunctionLike(ste)){let target_in_scope=_PyST_GetSymbol(ste,target_name);if(target_in_scope&SF.DEF_GLOBAL){if(!symtable_add_def(st,target_name,SF.DEF_GLOBAL,LOCATION(e)))VISIT_QUIT(st,0)}else{if(!symtable_add_def(st,target_name,SF.DEF_NONLOCAL,LOCATION(e)))VISIT_QUIT(st,0)}if(!symtable_record_directive(st,target_name,LOCATION(e)))VISIT_QUIT(st,0);return symtable_add_def_helper(st,target_name,SF.DEF_LOCAL,ste,LOCATION(e))}if(ste.type==ModuleBlock){if(!symtable_add_def(st,target_name,SF.DEF_GLOBAL,LOCATION(e)))VISIT_QUIT(st,0);if(!symtable_record_directive(st,target_name,LOCATION(e)))VISIT_QUIT(st,0);return symtable_add_def_helper(st,target_name,SF.DEF_GLOBAL,ste,LOCATION(e))}if(ste.type==ClassBlock){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_IN_CLASS);set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset);throw exc}}assert(0);return 0}function symtable_handle_namedexpr(st,e){if(st.cur.comp_iter_expr>0){var exc=PyErr_Format(PyExc_SyntaxError,NAMED_EXPR_COMP_ITER_EXPR);set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset);throw exc}if(st.cur.comprehension){if(!symtable_extend_namedexpr_scope(st,e.target))return 0}VISIT(st,expr,e.value);VISIT(st,expr,e.target);return 1}const alias="alias",comprehension="comprehension",excepthandler="excepthandler",expr="expr",keyword="keyword",match_case="match_case",pattern="pattern",stmt="stmt",type_param="type_param",withitem="withitem";visitor.expr=function(st,e){switch(e.constructor){case $B.ast.NamedExpr:if(!symtable_raise_if_annotation_block(st,"named expression",e)){VISIT_QUIT(st,0)}if(!symtable_handle_namedexpr(st,e))VISIT_QUIT(st,0);break;case $B.ast.BoolOp:VISIT_SEQ(st,"expr",e.values);break;case $B.ast.BinOp:VISIT(st,"expr",e.left);VISIT(st,"expr",e.right);break;case $B.ast.UnaryOp:VISIT(st,"expr",e.operand);break;case $B.ast.Lambda:{if(!GET_IDENTIFIER("lambda"))VISIT_QUIT(st,0);if(e.args.defaults)VISIT_SEQ(st,"expr",e.args.defaults);if(e.args.kw_defaults)VISIT_SEQ_WITH_NULL(st,"expr",e.args.kw_defaults);if(!symtable_enter_block(st,lambda,FunctionBlock,e,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset))VISIT_QUIT(st,0);VISIT(st,"arguments",e.args);VISIT(st,"expr",e.body);if(!symtable_exit_block(st))VISIT_QUIT(st,0);break}case $B.ast.IfExp:VISIT(st,"expr",e.test);VISIT(st,"expr",e.body);VISIT(st,"expr",e.orelse);break;case $B.ast.Dict:VISIT_SEQ_WITH_NULL(st,"expr",e.keys);VISIT_SEQ(st,"expr",e.values);break;case $B.ast.Set:VISIT_SEQ(st,"expr",e.elts);break;case $B.ast.GeneratorExp:if(!visitor.genexp(st,e))VISIT_QUIT(st,0);break;case $B.ast.ListComp:if(!visitor.listcomp(st,e))VISIT_QUIT(st,0);break;case $B.ast.SetComp:if(!visitor.setcomp(st,e))VISIT_QUIT(st,0);break;case $B.ast.DictComp:if(!visitor.dictcomp(st,e))VISIT_QUIT(st,0);break;case $B.ast.Yield:if(!symtable_raise_if_annotation_block(st,"yield expression",e)){VISIT_QUIT(st,0)}if(e.value)VISIT(st,"expr",e.value);st.cur.generator=1;if(st.cur.comprehension){return symtable_raise_if_comprehension_block(st,e)}break;case $B.ast.YieldFrom:if(!symtable_raise_if_annotation_block(st,"yield expression",e)){VISIT_QUIT(st,0)}VISIT(st,"expr",e.value);st.cur.generator=1;if(st.cur.comprehension){return symtable_raise_if_comprehension_block(st,e)}break;case $B.ast.Await:if(!symtable_raise_if_annotation_block(st,"await expression",e)){VISIT_QUIT(st,0)}VISIT(st,"expr",e.value);st.cur.coroutine=1;break;case $B.ast.Compare:VISIT(st,"expr",e.left);VISIT_SEQ(st,"expr",e.comparators);break;case $B.ast.Call:VISIT(st,"expr",e.func);VISIT_SEQ(st,"expr",e.args);VISIT_SEQ_WITH_NULL(st,"keyword",e.keywords);break;case $B.ast.FormattedValue:VISIT(st,"expr",e.value);if(e.format_spec)VISIT(st,"expr",e.format_spec);break;case $B.ast.JoinedStr:VISIT_SEQ(st,"expr",e.values);break;case $B.ast.Constant:break;case $B.ast.Attribute:VISIT(st,"expr",e.value);break;case $B.ast.Subscript:VISIT(st,"expr",e.value);VISIT(st,"expr",e.slice);break;case $B.ast.Starred:VISIT(st,"expr",e.value);break;case $B.ast.Slice:if(e.lower)VISIT(st,expr,e.lower);if(e.upper)VISIT(st,expr,e.upper);if(e.step)VISIT(st,expr,e.step);break;case $B.ast.Name:var flag=e.ctx instanceof $B.ast.Load?SF.USE:SF.DEF_LOCAL;if(!symtable_add_def(st,e.id,flag,LOCATION(e)))VISIT_QUIT(st,0);if(e.ctx instanceof $B.ast.Load&&_PyST_IsFunctionLike(st.cur)&&e.id=="super"){if(!GET_IDENTIFIER("__class__")||!symtable_add_def(st,"__class__",SF.USE,LOCATION(e)))VISIT_QUIT(st,0)}break;case $B.ast.List:VISIT_SEQ(st,expr,e.elts);break;case $B.ast.Tuple:VISIT_SEQ(st,expr,e.elts);break}VISIT_QUIT(st,1)};visitor.type_param_bound_or_default=function(st,e,name,key){if(e){var is_in_class=st.cur.can_see_class_scope;if(!symtable_enter_block(st,name,TypeVarBoundBlock,key,LOCATION(e))){return 0}st.cur.can_see_class_scope=is_in_class;if(is_in_class&&!symtable_add_def(st,"__classdict__",SF.USE,LOCATION(e))){VISIT_QUIT(st,0)}VISIT(st,expr,e);if(!symtable_exit_block(st)){return 0}}return 1};visitor.type_param=function(st,tp){switch(tp.constructor){case $B.ast.TypeVar:if(!symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM|SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0)}if(!visitor.type_param_bound_or_default(st,tp.bound,tp.name,tp)){VISIT_QUIT(st,0)}if(!visitor.type_param_bound_or_default(st,tp.default_value,tp.name,{$id:$B.UUID()})){VISIT_QUIT(st,0)}break;case $B.ast.TypeVarTuple:if(!symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM|SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0)}if(!visitor.type_param_bound_or_default(st,tp.default_value,tp.name,tp)){VISIT_QUIT(st,0)}break;case $B.ast.ParamSpec:if(!symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM|SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0)}if(!visitor.type_param_bound_or_default(st,tp.default_value,tp.name,tp)){VISIT_QUIT(st,0)}break}VISIT_QUIT(st,1)};visitor.pattern=function(st,p){switch(p.constructor){case $B.ast.MatchValue:VISIT(st,expr,p.value);break;case $B.ast.MatchSingleton:break;case $B.ast.MatchSequence:VISIT_SEQ(st,pattern,p.patterns);break;case $B.ast.MatchStar:if(p.name){symtable_add_def(st,p.name,SF.DEF_LOCAL,LOCATION(p))}break;case $B.ast.MatchMapping:VISIT_SEQ(st,expr,p.keys);VISIT_SEQ(st,pattern,p.patterns);if(p.rest){symtable_add_def(st,p.rest,SF.DEF_LOCAL,LOCATION(p))}break;case $B.ast.MatchClass:VISIT(st,expr,p.cls);VISIT_SEQ(st,pattern,p.patterns);VISIT_SEQ(st,pattern,p.kwd_patterns);break;case $B.ast.MatchAs:if(p.pattern){VISIT(st,pattern,p.pattern)}if(p.name){symtable_add_def(st,p.name,SF.DEF_LOCAL,LOCATION(p))}break;case $B.ast.MatchOr:VISIT_SEQ(st,pattern,p.patterns);break}VISIT_QUIT(st,1)};function symtable_implicit_arg(st,pos){var id="."+pos;if(!symtable_add_def(st,id,SF.DEF_PARAM,ST_LOCATION(st.cur))){return 0}return 1}visitor.params=function(st,args){if(!args){return-1}for(var arg of args){if(!symtable_add_def(st,arg.arg,SF.DEF_PARAM,LOCATION(arg)))return 0}return 1};visitor.annotation=function(st,annotation){var future_annotations=st.future.features&$B.CO_FUTURE_ANNOTATIONS;if(future_annotations&&!symtable_enter_block(st,"_annotation",AnnotationBlock,annotation,annotation.lineno,annotation.col_offset,annotation.end_lineno,annotation.end_col_offset)){VISIT_QUIT(st,0)}VISIT(st,expr,annotation);if(future_annotations&&!symtable_exit_block(st)){VISIT_QUIT(st,0)}return 1};visitor.argannotations=function(st,args){if(!args){return-1}for(var arg of args){if(arg.annotation){VISIT(st,expr,arg.annotation)}}return 1};visitor.annotations=function(st,o,a,returns){var future_annotations=st.future.ff_features&$B.CO_FUTURE_ANNOTATIONS;if(future_annotations&&!symtable_enter_block(st,"_annotation",AnnotationBlock,o,o.lineno,o.col_offset,o.end_lineno,o.end_col_offset)){VISIT_QUIT(st,0)}if(a.posonlyargs&&!visitor.argannotations(st,a.posonlyargs))return 0;if(a.args&&!visitor.argannotations(st,a.args))return 0;if(a.vararg&&a.vararg.annotation)VISIT(st,expr,a.vararg.annotation);if(a.kwarg&&a.kwarg.annotation)VISIT(st,expr,a.kwarg.annotation);if(a.kwonlyargs&&!visitor.argannotations(st,a.kwonlyargs))return 0;if(future_annotations&&!symtable_exit_block(st)){VISIT_QUIT(st,0)}if(returns&&!visitor.annotation(st,returns)){VISIT_QUIT(st,0)}return 1};visitor.arguments=function(st,a){if(a.posonlyargs&&!visitor.params(st,a.posonlyargs))return 0;if(a.args&&!visitor.params(st,a.args))return 0;if(a.kwonlyargs&&!visitor.params(st,a.kwonlyargs))return 0;if(a.vararg){if(!symtable_add_def(st,a.vararg.arg,SF.DEF_PARAM,LOCATION(a.vararg)))return 0;st.cur.varargs=1}if(a.kwarg){if(!symtable_add_def(st,a.kwarg.arg,SF.DEF_PARAM,LOCATION(a.kwarg)))return 0;st.cur.varkeywords=1}return 1};visitor.excepthandler=function(st,eh){if(eh.type)VISIT(st,expr,eh.type);if(eh.name)if(!symtable_add_def(st,eh.name,SF.DEF_LOCAL,LOCATION(eh)))return 0;VISIT_SEQ(st,stmt,eh.body);return 1};visitor.withitem=function(st,item){VISIT(st,"expr",item.context_expr);if(item.optional_vars){VISIT(st,"expr",item.optional_vars)}return 1};visitor.match_case=function(st,m){VISIT(st,pattern,m.pattern);if(m.guard){VISIT(st,expr,m.guard)}VISIT_SEQ(st,stmt,m.body);return 1};visitor.alias=function(st,a){var store_name,name=a.asname==NULL?a.name:a.asname;var dot=name.search("\\.");if(dot!=-1){store_name=name.substring(0,dot);if(!store_name)return 0}else{store_name=name}if(name!="*"){var r=symtable_add_def(st,store_name,SF.DEF_IMPORT,LOCATION(a));return r}else{if(st.cur.type!=ModuleBlock){var lineno=a.lineno,col_offset=a.col_offset,end_lineno=a.end_lineno,end_col_offset=a.end_col_offset;var exc=PyErr_SetString(PyExc_SyntaxError,IMPORT_STAR_WARNING);set_exc_info(exc,st.filename,lineno,col_offset,end_lineno,end_col_offset);throw exc}st.cur.$has_import_star=true;return 1}};visitor.comprehension=function(st,lc){st.cur.comp_iter_target=1;VISIT(st,expr,lc.target);st.cur.comp_iter_target=0;st.cur.comp_iter_expr++;VISIT(st,expr,lc.iter);st.cur.comp_iter_expr--;VISIT_SEQ(st,expr,lc.ifs);if(lc.is_async){st.cur.coroutine=1}return 1};visitor.keyword=function(st,k){VISIT(st,expr,k.value);return 1};function symtable_handle_comprehension(st,e,scope_name,generators,elt,value){var is_generator=e.constructor===$B.ast.GeneratorExp;var outermost=generators[0];st.cur.comp_iter_expr++;VISIT(st,expr,outermost.iter);st.cur.comp_iter_expr--;if(!scope_name||!symtable_enter_block(st,scope_name,FunctionBlock,e,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset)){return 0}switch(e.constructor){case $B.ast.ListComp:st.cur.comprehension=ListComprehension;break;case $B.ast.SetComp:st.cur.comprehension=SetComprehension;break;case $B.ast.DictComp:st.cur.comprehension=DictComprehension;break;default:st.cur.comprehension=GeneratorExpression;break}if(outermost.is_async){st.cur.coroutine=1}if(!symtable_implicit_arg(st,0)){symtable_exit_block(st);return 0}st.cur.comp_iter_target=1;VISIT(st,expr,outermost.target);st.cur.comp_iter_target=0;VISIT_SEQ(st,expr,outermost.ifs);VISIT_SEQ_TAIL(st,comprehension,generators,1);if(value)VISIT(st,expr,value);VISIT(st,expr,elt);st.cur.generator=is_generator;var is_async=st.cur.coroutine&&!is_generator;if(!symtable_exit_block(st)){return 0}if(is_async){st.cur.coroutine=1}return 1}visitor.genexp=function(st,e){return symtable_handle_comprehension(st,e,"genexpr",e.generators,e.elt,NULL)};visitor.listcomp=function(st,e){return symtable_handle_comprehension(st,e,"listcomp",e.generators,e.elt,NULL)};visitor.setcomp=function(st,e){return symtable_handle_comprehension(st,e,"setcomp",e.generators,e.elt,NULL)};visitor.dictcomp=function(st,e){return symtable_handle_comprehension(st,e,"dictcomp",e.generators,e.key,e.value)};function symtable_raise_if_annotation_block(st,name,e){var type=st.cur.type,exc;if(type==AnnotationBlock)exc=PyErr_Format(PyExc_SyntaxError,ANNOTATION_NOT_ALLOWED,name);else if(type==TypeVarBoundBlock)exc=PyErr_Format(PyExc_SyntaxError,TYPEVAR_BOUND_NOT_ALLOWED,name);else if(type==TypeAliasBlock)exc=PyErr_Format(PyExc_SyntaxError,TYPEALIAS_NOT_ALLOWED,name);else if(type==TypeParamBlock)exc=PyErr_Format(PyExc_SyntaxError,TYPEPARAM_NOT_ALLOWED,name);else return 1;set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset);throw exc}function symtable_raise_if_comprehension_block(st,e){var type=st.cur.comprehension;var exc=PyErr_SetString(PyExc_SyntaxError,type==ListComprehension?"'yield' inside list comprehension":type==SetComprehension?"'yield' inside set comprehension":type==DictComprehension?"'yield' inside dict comprehension":"'yield' inside generator expression");exc.$frame_obj=$B.frame_obj;set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset);throw exc}})(__BRYTHON__);(function($B){var _b_=$B.builtins,NULL=undefined,DOT=".",ELLIPSIS="...";const STAR_TARGETS=1,DEL_TARGETS=2,FOR_TARGETS=3;function make_string_for_ast_value(value){value=value.replace(/\n/g,"\\n\\\n");value=value.replace(/\r/g,"\\r\\\r");if(value[0]=="'"){var unquoted=value.substr(1,value.length-2);return unquoted}if(value.indexOf("'")>-1){var s="",escaped=false;for(var char of value){if(char=="\\"){if(escaped){s+="\\\\"}escaped=!escaped}else{if(char=="'"&&!escaped){s+="\\"}else if(escaped){s+="\\"}s+=char;escaped=false}}value=s}return value.substr(1,value.length-2)}function encode_bytestring(s){s=s.replace(/\\t/g,"\t").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\f/g,"\f").replace(/\\v/g,"\v").replace(/\\\\/g,"\\");var t=[];for(var i=0,len=s.length;i255){throw Error()}t.push(cp)}return t}function EXTRA_EXPR(head,tail){return{lineno:head.lineno,col_offset:head.col_offset,end_lineno:tail.end_lineno,end_col_offset:tail.end_col_offset}}function set_list(list,other){for(var item of other){list.push(item)}}var positions=["lineno","col_offset","end_lineno","end_col_offset"];function set_position_from_list(ast_obj,EXTRA){for(var i=0;i<4;i++){ast_obj[positions[i]]=EXTRA[i]}}function set_position_from_token(ast_obj,token){ast_obj.lineno=token.lineno;ast_obj.col_offset=token.col_offset;ast_obj.end_lineno=token.end_lineno;ast_obj.end_col_offset=token.end_col_offset}function set_position_from_obj(ast_obj,obj){for(var position of positions){ast_obj[position]=obj[position]}}function _get_names(p,names_with_defaults){var seq=[];for(var pair of names_with_defaults){seq.push(pair.arg)}return seq}function _get_defaults(p,names_with_defaults){var seq=[];for(var pair of names_with_defaults){seq.push(pair.value)}return seq}function _make_posonlyargs(p,slash_without_default,slash_with_default,posonlyargs){if(slash_without_default!=NULL){set_list(posonlyargs,slash_without_default)}else if(slash_with_default!=NULL){var slash_with_default_names=_get_names(p,slash_with_default.names_with_defaults);if(!slash_with_default_names){return-1}set_list(posonlyargs,$B._PyPegen.join_sequences(p,slash_with_default.plain_names,slash_with_default_names))}return posonlyargs==NULL?-1:0}function _make_posargs(p,plain_names,names_with_default,posargs){if(plain_names!=NULL&&names_with_default!=NULL){var names_with_default_names=_get_names(p,names_with_default);if(!names_with_default_names){return-1}var seqs=$B._PyPegen.join_sequences(p,plain_names,names_with_default_names);set_list(posargs,seqs)}else if(plain_names==NULL&&names_with_default!=NULL){set_list(posargs,_get_names(p,names_with_default))}else if(plain_names!=NULL&&names_with_default==NULL){set_list(posargs,plain_names)}return posargs==NULL?-1:0}function _make_posdefaults(p,slash_with_default,names_with_default,posdefaults){if(slash_with_default!=NULL&&names_with_default!=NULL){var slash_with_default_values=_get_defaults(p,slash_with_default.names_with_defaults);if(!slash_with_default_values){return-1}var names_with_default_values=_get_defaults(p,names_with_default);if(!names_with_default_values){return-1}set_list(posdefaults,$B._PyPegen.join_sequences(p,slash_with_default_values,names_with_default_values))}else if(slash_with_default==NULL&&names_with_default!=NULL){set_list(posdefaults,_get_defaults(p,names_with_default))}else if(slash_with_default!=NULL&&names_with_default==NULL){set_list(posdefaults,_get_defaults(p,slash_with_default.names_with_defaults))}return posdefaults==NULL?-1:0}function _make_kwargs(p,star_etc,kwonlyargs,kwdefaults){if(star_etc!=NULL&&star_etc.kwonlyargs!=NULL){set_list(kwonlyargs,_get_names(p,star_etc.kwonlyargs))}else{set_list(kwonlyargs,[])}if(kwonlyargs==NULL){return-1}if(star_etc!=NULL&&star_etc.kwonlyargs!=NULL){set_list(kwdefaults,_get_defaults(p,star_etc.kwonlyargs))}else{set_list(kwdefaults,[])}if(kwdefaults==NULL){return-1}return 0}function _seq_number_of_starred_exprs(seq){var n=0;for(var k of seq){if(!k.is_keyword){n++}}return n}$B._PyPegen={};$B._PyPegen.constant_from_string=function(p,token){var prepared=$B.prepare_string(p,token);var is_bytes=prepared.value.startsWith("b");if(!is_bytes){var value=make_string_for_ast_value(prepared.value)}else{value=prepared.value.substr(2,prepared.value.length-3);try{value=_b_.bytes.$factory(encode_bytestring(value))}catch(err){$B._PyPegen.raise_error_known_location(p,_b_.SyntaxError,token.lineno,token.col_offset,token.end_lineno,token.end_col_offset,"bytes can only contain ASCII literal characters")}}var ast_obj=new $B.ast.Constant(value);set_position_from_token(ast_obj,token);return ast_obj};$B._PyPegen.constant_from_token=function(p,t){var ast_obj=new $B.ast.Constant(t.string);set_position_from_token(ast_obj,t);return ast_obj};$B._PyPegen.decoded_constant_from_token=function(p,t){var ast_obj=new $B.ast.Constant(t.string);set_position_from_token(ast_obj,t);return ast_obj};$B._PyPegen.formatted_value=function(p,expression,debug,conversion,format,closing_brace,arena){var conversion_val=-1;if(conversion){var conversion_expr=conversion.result,first=conversion_expr.id;if(first.length>1||!"sra".includes(first)){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conversion_expr,`f-string: invalid conversion character {first}: `+"expected 's', 'r', or 'a'")}var conversion_val=first.charCodeAt(0)}var formatted_value=new $B.ast.FormattedValue(expression,conversion_val,format===undefined?format:format.result);set_position_from_obj(formatted_value,arena);if(debug){var debug_end_line,debug_end_offset,debug_metadata;if(conversion){debug_end_line=conversion.result.lineno;debug_end_offset=conversion.result.col_offset;debug_metadata=conversion.metadata}else if(format){debug_end_line=format.result.lineno;debug_end_offset=format.result.col_offset+1;debug_metadata=format.metadata}else{debug_end_line=p.end_lineno;debug_end_offset=p.end_col_offset;debug_metadata=closing_brace.metadata}var debug=new $B.ast.Constant(debug_metadata);debug.lineno=p.lineno;debug.col_offset=p.col_offset+1;debug.end_lineno=debug_end_line;debug.end_col_offset=debug_end_offset;var joined_str=new $B.ast.JoinedStr([debug,formatted_value]);set_position_from_obj(joined_str,arena);return joined_str}return formatted_value};$B._PyPegen.joined_str=function(p,a,items,c){var ast_obj=new $B.ast.JoinedStr(items);ast_obj.lineno=a.lineno;ast_obj.col_offset=a.col_offset;ast_obj.end_lineno=c.end_lineno;ast_obj.end_col_offset=c.end_col_offset;return ast_obj};$B._PyPegen.setup_full_format_spec=function(p,colon,spec,arena){var ast_obj=new $B.ast.JoinedStr(spec);set_position_from_obj(ast_obj,arena);return result_token_with_metadata(p,ast_obj,colon.metadata)};function result_token_with_metadata(p,result,metadata){return{result:result,metadata:metadata}}$B._PyPegen.check_fstring_conversion=function(p,conv_token,conv){if(conv_token.lineno!=conv.lineno||conv_token.end_col_offset!=conv.col_offset){$B._PyPegen.raise_error_known_location(p,_b_.SyntaxError,conv.lineno,conv.col_offset,conv.end_lineno,conv.end_col_offset,"f-string: conversion type must come right after the exclamanation mark")}return result_token_with_metadata(p,conv,conv_token.metadata)};$B._PyPegen.seq_count_dots=function(seq){if(seq===undefined){return 0}var number_of_dots=0;for(var token of seq){if(token.num_type==$B.py_tokens.DOT){number_of_dots+=token.string.length}else if(token.num_type==$B.py_tokens.ELLIPSIS){number_of_dots+=3}}return number_of_dots};$B._PyPegen.map_names_to_ids=function(p,seq){return seq.map((e=>e.id))};$B._PyPegen.alias_for_star=function(p,lineno,col_offset,end_lineno,end_col_offset,arena){var str="*";return $B._PyAST.alias(str,NULL,lineno,col_offset,end_lineno,end_col_offset,arena)};$B._PyPegen.cmpop_expr_pair=function(p,cmpop,expr){return{cmpop:cmpop,expr:expr}};$B._PyPegen.get_cmpops=function(p,seq){var new_seq=[];for(var pair of seq){new_seq.push(pair.cmpop)}return new_seq};$B._PyPegen.get_exprs=function(p,seq){var new_seq=[];for(var pair of seq){new_seq.push(pair.expr)}return new_seq};function _set_seq_context(p,seq,ctx){var new_seq=[];for(var e of seq){new_seq.push($B._PyPegen.set_expr_context(p,e,ctx))}return new_seq}function _set_name_context(p,e,ctx){return $B._PyAST.Name(e.id,ctx,EXTRA_EXPR(e,e))}function _set_tuple_context(p,e,ctx){return $B._PyAST.Tuple(_set_seq_context(p,e.elts,ctx),ctx,EXTRA_EXPR(e,e))}function _set_list_context(p,e,ctx){return $B._PyAST.List(_set_seq_context(p,e.elts,ctx),ctx,EXTRA_EXPR(e,e))}function _set_subscript_context(p,e,ctx){console.log("set subscritp cntext",p,e);return $B._PyAST.Subscript(e.value,e.slice,ctx,EXTRA_EXPR(e,e))}function _set_attribute_context(p,e,ctx){return $B._PyAST.Attribute(e.value,e.attr,ctx,EXTRA_EXPR(e,e))}function _set_starred_context(p,e,ctx){return $B._PyAST.Starred($B._PyPegen.set_expr_context(p,e.value,ctx),ctx,EXTRA_EXPR(e,e))}$B._PyPegen.set_expr_context=function(p,expr,ctx){var _new=NULL;switch(expr.constructor){case $B.ast.Name:_new=_set_name_context(p,expr,ctx);break;case $B.ast.Tuple:_new=_set_tuple_context(p,expr,ctx);break;case $B.ast.List:_new=_set_list_context(p,expr,ctx);break;case $B.ast.Subscript:_new=_set_subscript_context(p,expr,ctx);break;case $B.ast.Attribute:_new=_set_attribute_context(p,expr,ctx);break;case $B.ast.Starred:_new=_set_starred_context(p,expr,ctx);break;default:_new=expr}return _new};$B._PyPegen.key_value_pair=function(p,key,value){return{key:key,value:value}};$B._PyPegen.get_expr_name=function(e){switch(e.constructor.$name){case"Attribute":case"Subscript":case"Starred":case"Name":case"List":case"Tuple":case"Lambda":return e.constructor.$name.toLowerCase();case"Call":return"function call";case"BoolOp":case"BinOp":case"UnaryOp":return"expression";case"GeneratorExp":return"generator expression";case"Yield":case"YieldFrom":return"yield expression";case"Await":return"await expression";case"ListComp":return"list comprehension";case"SetComp":return"set comprehension";case"DictComp":return"dict comprehension";case"Dict":return"dict literal";case"Set":return"set display";case"JoinedStr":case"FormattedValue":return"f-string expression";case"Constant":var value=e.value;if(value===_b_.None){return"None"}if(value===false){return"False"}if(value===true){return"True"}if(value===_b_.Ellipsis){return"ellipsis"}return"literal";case"Compare":return"comparison";case"IfExp":return"conditional expression";case"NamedExpr":return"named expression";default:return NULL}};$B._PyPegen.get_keys=function(p,seq){return seq===undefined?[]:seq.map((pair=>pair.key))};$B._PyPegen.get_values=function(p,seq){return seq===undefined?[]:seq.map((pair=>pair.value))};$B._PyPegen.key_pattern_pair=function(p,key,pattern){return{key:key,pattern:pattern}};$B._PyPegen.get_pattern_keys=function(p,seq){return seq===undefined?[]:seq.map((x=>x.key))};$B._PyPegen.get_patterns=function(p,seq){return seq===undefined?[]:seq.map((x=>x.pattern))};$B._PyPegen.check_legacy_stmt=function(p,name){return["print","exec"].includes(name)};$B._PyPegen.dummy_name=function(p){var cache=NULL;if(cache!=NULL){return cache}var id="dummy"+Math.random().toString(36).substr(2),ast_obj=new $B.ast.Name(id,new $B.ast.Load);set_position_from_list(ast_obj,[1,0,1,0]);return ast_obj};$B._PyPegen.add_type_comment_to_arg=function(p,a,tc){if(tc==NULL){return a}var bytes=_b_.bytes.$factory(tc),tco=$B._PyPegen.new_type_comment(p,bytes);var ast_obj=$B._PyAST.arg(a.arg,a.annotation,tco,a.lineno,a.col_offset,a.end_lineno,a.end_col_offset,p.arena);console.log("arg with type comment",ast_obj);return ast_obj};$B._PyPegen.check_barry_as_flufl=function(p,t){return false};$B._PyPegen.empty_arguments=function(p){return $B._PyAST.arguments([],[],NULL,[],[],NULL,[],p.arena)};$B._PyPegen.augoperator=function(p,kind){return{kind:kind}};$B._PyPegen.function_def_decorators=function(p,decorators,function_def){var constr=function_def instanceof $B.ast.AsyncFunctionDef?$B.ast.AsyncFunctionDef:$B.ast.FunctionDef;var ast_obj=new constr(function_def.name,function_def.args,function_def.body,decorators,function_def.returns,function_def.type_comment,function_def.type_params);for(var position of positions){ast_obj[position]=function_def[position]}return ast_obj};$B._PyPegen.class_def_decorators=function(p,decorators,class_def){var ast_obj=$B._PyAST.ClassDef(class_def.name,class_def.bases,class_def.keywords,class_def.body,decorators,class_def.type_params);set_position_from_obj(ast_obj,class_def);return ast_obj};$B._PyPegen.keyword_or_starred=function(p,element,is_keyword){return{element:element,is_keyword:is_keyword}};$B._PyPegen.make_arguments=function(p,slash_without_default,slash_with_default,plain_names,names_with_default,star_etc){var posonlyargs=[];if(_make_posonlyargs(p,slash_without_default,slash_with_default,posonlyargs)==-1){return NULL}var posargs=[];if(_make_posargs(p,plain_names,names_with_default,posargs)==-1){return NULL}var posdefaults=[];if(_make_posdefaults(p,slash_with_default,names_with_default,posdefaults)==-1){return NULL}var vararg=NULL;if(star_etc!=NULL&&star_etc.vararg!=NULL){vararg=star_etc.vararg}var kwonlyargs=[],kwdefaults=[];if(_make_kwargs(p,star_etc,kwonlyargs,kwdefaults)==-1){return NULL}var kwarg=NULL;if(star_etc!=NULL&&star_etc.kwarg!=NULL){kwarg=star_etc.kwarg}var ast_obj=$B._PyAST.arguments(posonlyargs,posargs,vararg,kwonlyargs,kwdefaults,kwarg,posdefaults,p.arena);if(ast_obj.posonlyargs===undefined){console.log("pas de posonlyargs",ast_bj);alert()}return ast_obj};$B._PyPegen.name_default_pair=function(p,arg,value,tc){return{arg:$B._PyPegen.add_type_comment_to_arg(p,arg,tc),value:value}};$B._PyPegen.raise_error=function(p,errtype,errmsg){if(p.fill==0){var va=[errmsg];$B._PyPegen.raise_error_known_location(p,errtype,0,0,0,-1,errmsg,va);return NULL}var t=p.known_err_token!=NULL?p.known_err_token:p.tokens[p.fill-1];var va=errmsg;$B._PyPegen.raise_error_known_location(p,errtype,t.lineno,t.col_offset,t.end_lineno,t.end_col_offset,errmsg,va)};$B._PyPegen.raise_error_known_location=function(p,errtype,lineno,col_offset,end_lineno,end_col_offset,errmsg,va){var exc=errtype.$factory(errmsg);exc.filename=p.filename;if(p.known_err_token){var token=p.known_err_token;exc.lineno=token.lineno;exc.offset=token.col_offset+1;exc.end_lineno=token.end_lineno;exc.end_offset=token.end_col_offset;exc.text=token.line}else{exc.lineno=lineno;exc.offset=col_offset+1;exc.end_lineno=end_lineno;exc.end_offset=end_col_offset+1;var src=$B.file_cache[p.filename];if(src!==undefined){var lines=src.split("\n"),line=lines[exc.lineno-1];exc.text=line+"\n"}else{exc.text=_b_.None}}exc.args[1]=$B.fast_tuple([p.filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]);throw exc};$B._PyPegen.seq_delete_starred_exprs=function(p,kwargs){var len=kwargs.length,new_len=len-_seq_number_of_starred_exprs(kwargs);if(new_len==0){return NULL}var new_seq=[];for(var k of kwargs){if(k.is_keyword){new_seq.push(k.element)}}return new_seq};$B._PyPegen.seq_extract_starred_exprs=function(p,kwargs){var new_len=_seq_number_of_starred_exprs(kwargs);if(new_len==0){return NULL}var new_seq=[];var idx=0;for(var k of kwargs){if(!k.is_keyword){new_seq[idx++]=k.element}}return new_seq};$B._PyPegen.slash_with_default=function(p,plain_names,names_with_defaults){return{plain_names:plain_names,names_with_defaults:names_with_defaults}};$B._PyPegen.star_etc=function(p,vararg,kwonlyargs,kwarg){return{vararg:vararg,kwonlyargs:kwonlyargs,kwarg:kwarg}};$B._PyPegen.collect_call_seqs=function(p,a,b,lineno,col_offset,end_lineno,end_col_offset,arena){var args_len=a.length,total_len=args_len;if(b==NULL){return $B._PyAST.Call($B._PyPegen.dummy_name(p),a,[],lineno,col_offset,end_lineno,end_col_offset,arena)}var starreds=$B._PyPegen.seq_extract_starred_exprs(p,b),keywords=$B._PyPegen.seq_delete_starred_exprs(p,b);if(starreds){total_len+=starreds.length}var args=[];for(var i=0;ix.replace(new RegExp("'","g"),"\\'")));fs_item.value=parts.join("\\'");fs_item.value=fs_item.value.replace(/\n/g,"\\n").replace(/\r/g,"\\r")}items.push(fs_item)}state="string"}else{items.push(token);var is_bytes=token.value.__class__===_b_.bytes;if(is_bytes&&state=="string"||state=="bytestring"&&!is_bytes){error("cannot mix bytes and nonbytes literals")}state=is_bytes?"bytestring":"string"}}if(state=="bytestring"){var bytes=[];for(var item of items){bytes=bytes.concat(item.value.source)}value=_b_.bytes.$factory(bytes);var ast_obj=new $B.ast.Constant(value);set_position_from_list(ast_obj,items);return ast_obj}function group_consec_strings(items){if(items.length==1){return items[0]}var values=items.map((x=>x.value));let ast_obj=new $B.ast.Constant(values.join(""));set_position_from_list(ast_obj,items);return ast_obj}var items1=[],consec_strs=[],item_type=null;for(var i=0,len=items.length;i0){items1.push(group_consec_strings(consec_strs))}consec_strs=[];items1.push(item)}}if(consec_strs.length>0){items1.push(group_consec_strings(consec_strs))}if(!has_fstring){return items1[0]}var jstr_values=items1;var ast_obj=new $B.ast.JoinedStr(jstr_values);set_position_from_list(ast_obj,strings);return ast_obj};$B._PyPegen.ensure_imaginary=function(p,exp){if(!(exp instanceof $B.ast.Constant)||exp.value.__class__!=_b_.complex){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp,"imaginary number required in complex literal");return NULL}return exp};$B._PyPegen.ensure_real=function(p,exp){if(!(exp instanceof $B.ast.Constant)||exp.value.type=="imaginary"){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp,"real number required in complex literal");return NULL}return exp};$B._PyPegen.set_expr_context=function(p,a,ctx){a.ctx=ctx;return a};$B._PyPegen.singleton_seq=function(p,a){return[a]};$B._PyPegen.seq_insert_in_front=function(p,a,seq){return seq?[a].concat(seq):[a]};$B._PyPegen.seq_flatten=function(p,seqs){var res=[];for(var seq of seqs){for(var item of seq){res.push(item)}}return res};$B._PyPegen.join_names_with_dot=function(p,first_name,second_name){var str=first_name.id+"."+second_name.id;return $B._PyAST.Name(str,new $B.ast.Load,EXTRA_EXPR(first_name,second_name))};$B._PyPegen.make_module=function(p,a){return new $B.ast.Module(a)};$B._PyPegen.new_type_comment=function(p,s){if(s.length===0){return NULL}return s};$B._PyPegen.get_last_comprehension_item=function(comprehension){if(comprehension.ifs==NULL||comprehension.ifs.length==0){return comprehension.iter}return $B.last(comprehension.ifs)};$B._PyPegen.arguments_parsing_error=function(p,e){var kwarg_unpacking=0;for(let keyword of e.keywords){if(!keyword.arg){kwarg_unpacking=1}}var msg=NULL;if(kwarg_unpacking){msg="positional argument follows keyword argument unpacking"}else{msg="positional argument follows keyword argument"}return $B.helper_functions.RAISE_SYNTAX_ERROR(p,msg)};$B._PyPegen.nonparen_genexp_in_call=function(p,args,comprehensions){var len=args.args.length;if(len<=1){return NULL}var last_comprehension=$B.last(comprehensions);return $B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,args.args[len-1],$B._PyPegen.get_last_comprehension_item(last_comprehension),"Generator expression must be parenthesized")};$B._PyPegen.get_invalid_target=function(e,targets_type){if(e==NULL){return NULL}function VISIT_CONTAINER(CONTAINER,TYPE){for(var elt of CONTAINER.elts){var child=$B._PyPegen.get_invalid_target(elt,targets_type);if(child!=NULL){return child}}}switch(e.constructor){case $B.ast.List:case $B.ast.Tuple:return VISIT_CONTAINER(e,e.constructor);case $B.ast.Starred:if(targets_type==DEL_TARGETS){return e}return $B._PyPegen.get_invalid_target(e.value,targets_type);case $B.ast.Compare:if(targets_type==FOR_TARGETS){var cmpop=e.ops[0];if(cmpop instanceof $B.ast.In){return $B._PyPegen.get_invalid_target(e.left,targets_type)}return NULL}return e;case $B.ast.Name:case $B.ast.Subscript:case $B.ast.Attribute:return NULL;default:return e}}})(__BRYTHON__);(function($B){var _b_=$B.builtins;var s_escaped='abfnrtvxuU"0123456789'+"'"+"\\",is_escaped={};for(var i=0;i="4"){$B.warn(_b_.SyntaxWarning,`invalid octal escape sequence '\\${mo[0]}'`,p.filename,token)}return[String.fromCharCode(parseInt(mo[0],8)),1+mo[0].length]}switch(text[antislash_pos+1]){case"x":var mo=/^[0-9A-F]{0,2}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=2){seq_end=antislash_pos+mo[0].length+1;string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\xXX escape"])}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]}case"u":var mo=/^[0-9A-F]{0,4}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=4){seq_end=antislash_pos+mo[0].length+1;string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\uXXXX escape"])}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]}case"U":var mo=/^[0-9A-F]{0,8}/i.exec(text.substr(antislash_pos+2));if(mo[0].length!=8){seq_end=antislash_pos+mo[0].length+1;string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+`bytes in position ${antislash_pos}-${seq_end}: truncated `+"\\UXXXXXXXX escape"])}else{var value=parseInt(mo[0],16);if(value>1114111){string_error(p,token,"invalid unicode escape "+mo[0])}else if(value>=65536){return[new SurrogatePair(value),2+mo[0].length]}else{return[String.fromCharCode(value),2+mo[0].length]}}}}$B.prepare_string=function(p,token){var s=token.string,len=s.length,pos=0,string_modifier,_type="string",quote,C={type:"str"};while(pos-1){elt.value+=char;pos++}else{return check(elt)}}else if(char.match(/j/i)){if(elt&&(!elt.subtype||elt.subtype=="float")){elt.imaginary=true;check(elt);elt.length++;return elt}else{error("invalid syntax")}}else{break}}return check(elt)}$B.prepare_number=function(n){n=n.replace(/_/g,"");if(n.startsWith(".")){if(n.endsWith("j")){return{type:"imaginary",value:$B.prepare_number(n.substr(0,n.length-1))}}else{return{type:"float",value:n+""}}pos=j}else if(n.startsWith("0")&&n!="0"){var num=test_num(n),base;if(num.imaginary){return{type:"imaginary",value:$B.prepare_number(num.value)}}if(num.subtype=="float"){return{type:num.subtype,value:num.value+""}}if(num.subtype===undefined){base=10}else{base={b:2,o:8,x:16}[num.subtype]}if(base!==undefined){return{type:"int",value:[base,num.value]}}}else{var num=test_num(n);if(num.subtype=="float"){if(num.imaginary){return{type:"imaginary",value:$B.prepare_number(num.value)}}else{return{type:"float",value:num.value+""}}}else{if(num.imaginary){return{type:"imaginary",value:$B.prepare_number(num.value)}}else{return{type:"int",value:[10,num.value]}}}}}})(__BRYTHON__);(function($B){var _b_=$B.builtins,debug=0;var p={feature_version:$B.version_info[1]};$B.parser_constants={Store:new $B.ast.Store,Load:new $B.ast.Load,Del:new $B.ast.Del,NULL:undefined,alias_ty:$B.ast.alias,keyword_ty:$B.ast.keyword,arguments_ty:$B.ast.arguments,expr_ty:$B.ast.expr,asdl_stmt_seq:Array,asdl_int_seq:Array,asdl_expr_seq:Array,asdl_keyword_seq:Array,asdl_identifier_seq:Array,asdl_pattern_seq:Array,asdl_type_param_seq:Array,AugOperator:$B.ast.AugAssign,IsNot:$B.ast.IsNot,Py_Ellipsis:_b_.Ellipsis,Py_False:false,Py_True:true,Py_None:_b_.None,PyExc_SyntaxError:_b_.SyntaxError,STAR_TARGETS:1,DEL_TARGETS:2,FOR_TARGETS:3,PyBytes_AS_STRING:b=>b};for(var op_type of $B.op_types){for(var key in op_type){var klass_name=op_type[key];$B.parser_constants[klass_name]=new $B.ast[klass_name]}}var NULL=$B.parser_constants.NULL;$B._PyAST={};for(var ast_class in $B.ast_classes){var args=$B.ast_classes[ast_class];if(Array.isArray(args)){continue}args=args.replace(/\*/g,"").replace(/\?/g,"");var arg_names=args.split(",");$B._PyAST[ast_class]=function(ast_name,ast_args){return function(){var _args=Array.from(arguments).slice(0,ast_args.length+1);var EXTRA=_args.pop();var ast_obj=new $B.ast[ast_name](..._args);set_position_from_EXTRA(ast_obj,EXTRA);return ast_obj}}(ast_class,arg_names)}function get_last_token(p){var last_token=$B.last(p.tokens);if(last_token.type=="ENDMARKER"){var src=$B.file_cache[p.filename];if(src){for(var token of $B.tokenizer(src)){if(token.type=="ENDMARKER"){break}if(token.type!="DEDENT"){last_token=token}}}else{last_token=undefined}}p.known_err_token=last_token}var helper_functions={CHECK:function(type,obj){if(Array.isArray(type)){var check;for(var t of type){check=helper_functions.CHECK(t,obj);if(check){return check}}return undefined}if(obj instanceof type){return obj}return undefined},CHECK_VERSION:function(type,version,msg,node){return helper_functions.INVALID_VERSION_CHECK(p,version,msg,node)},CHECK_NULL_ALLOWED:function(type,obj){if(obj!==NULL){if(type instanceof Array){for(var t of type){if(obj instanceof t){return obj}}return}else{return obj instanceof type?obj:undefined}}return obj},INVALID_VERSION_CHECK:function(p,version,msg,node){if(node==NULL){p.error_indicator=1;return NULL}if(p.feature_versiont.length,asdl_seq_GET:(t,i)=>t[i]};$B.helper_functions=helper_functions;function raise_error_known_location(type,filename,lineno,col_offset,end_lineno,end_col_offset,line,message){var exc=type.$factory(message);exc.filename=filename;exc.lineno=lineno;exc.offset=col_offset+1;exc.end_lineno=end_lineno;exc.end_offset=end_col_offset+1;exc.text=line;exc.args[1]=$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]);exc.$frame_obj=$B.frame_obj;throw exc}$B.raise_error_known_location=raise_error_known_location;function raise_error_known_token(type,filename,token,message){var exc=type.$factory(message);exc.filename=filename;exc.lineno=token.lineno;exc.offset=token.col_offset+1;exc.end_lineno=token.end_lineno;exc.end_offset=token.end_col_offset+1;exc.text=token.line;exc.args[1]=$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]);exc.$frame_obj=$B.frame_obj;throw exc}$B.raise_error_known_token=raise_error_known_token;function set_position_from_EXTRA(ast_obj,EXTRA){for(var key in EXTRA){ast_obj[key]=EXTRA[key]}}var Parser=$B.Parser=function(src,filename,mode){src=src.replace(/\r\n/gm,"\n");var tokenizer=$B.tokenizer(src,filename,mode,this);this.tokenizer=tokenizer;this.tok=tokenizer;this.mark=0;this.fill=0;this.level=0;this.size=1;this.starting_lineno=0;this.starting_col_offset=0;this.tokens=[];this.src=src;this.filename=filename;this.mode=mode;this.memo={};this.arena={a_objects:[]};if(filename){p.filename=filename}};var ignored=[$B.py_tokens.ENCODING,$B.py_tokens.NL,$B.py_tokens.COMMENT];Parser.prototype.read_token=function(){while(true){var next=this.tokenizer.next();if(!next.done){var value=next.value;if(!ignored.includes(value.num_type)){this.tokens.push(value);return value}}else{throw Error("tokenizer exhausted")}}}})(__BRYTHON__);(function($B){var _b_=__BRYTHON__.builtins;const Load=new $B.ast.Load;const NULL=undefined;const ENDMARKER=0,NAME=1,NUMBER=2,STRING=3;function strchr(s,char){return s.includes(char)}function strlen(s){return s.length}function strncmp(a,b){return ab?1:0}function PyOS_strtol(s,end,base){return parseFloat(s)}function PyOS_strtoul(s,end,base){return parseFloat(s)}function PyOS_string_to_double(s,x,y){return parseFloat(s)}function PyFloat_FromDouble(x){return x}const NSTATISTICS=2e3,memo_statistics={},TYPE_IGNORE="TYPE_IGNORE",ERRORTOKEN="ERRORTOKEN",NEWLINE=$B.py_tokens.NEWLINE,DEDENT=$B.py_tokens.DEDENT,Py_single_input="py_single_input",PyPARSE_ALLOW_INCOMPLETE_INPUT=256;function PyUnicode_IS_ASCII(char){return char.codePointAt(0)<128}function set_position_from_token(ast_obj,token){for(var attr of["lineno","col_offset","end_lineno","end_col_offset"]){ast_obj[attr]=token[attr]}}$B._PyPegen.interactive_exit=function(p){if(p.errcode){p.errcode=E_EOF}return NULL};$B._PyPegen.byte_offset_to_character_offset_raw=function(str,col_offset){var len=str.length;if(col_offset>len+1){col_offset=len+1}var text=PyUnicode_DecodeUTF8(str,col_offset,"replace");if(!text){return-1}return text.length};$B._PyPegen.calculate_display_width=function(line,character_offset){var segment=line.substring(0,character_offset);if(!segment){return-1}if(PyUnicode_IS_ASCII(segment)){return character_offset}var width_fn=_PyImport_GetModuleAttrString("unicodedata","east_asian_width");if(!width_fn){return-1}var width=0;var len=segment.length;for(let i=0;i=0;m--){token=p.tokens[m];if(token.num_type!=ENDMARKER&&(token.num_typeDEDENT)){break}}return token};$B._PyPegen.new_identifier=function(p,n){var id=n;if(!PyUnicode_IS_ASCII(id)){var id2;if(!init_normalization(p)){return error()}var form=PyUnicode_InternFromString("NFKC");if(form==NULL){return error()}var args={form:form,id:id};id2=_PyObject_FastCall(p.normalize,args,2);if(!id2){return error()}if(!PyUnicode_Check(id2)){PyErr_Format(PyExc_TypeError,"unicodedata.normalize() must return a string, not "+"%.200s",_PyType_Name(Py_TYPE(id2)));return error()}id=id2}PyUnicode_InternInPlace(id);return id;function error(){p.error_indicator=1;return NULL}};$B._PyPegen.name_from_token=function(p,t){if(t==NULL){return NULL}var s=t.string;if(!s){p.error_indicator=1;return NULL}var res=new $B.ast.Name(s,Load);set_position_from_token(res,t);return res};$B._PyPegen.name_token=function(p){var t=$B._PyPegen.expect_token(p,NAME);return $B._PyPegen.name_from_token(p,t)};$B._PyPegen.string_token=function(p){return $B._PyPegen.expect_token(p,STRING)};$B._PyPegen.soft_keyword_token=function(p){var t=$B._PyPegen.expect_token(p,NAME);if(t==NULL){return NULL}var the_token;var size;the_token=t.string;for(let keyword=p.soft_keywords;keyword!=NULL;keyword++){if(strncmp(keyword,the_token,size)==0){return $B._PyPegen.name_from_token(p,t)}}return NULL};function prepared_number_value(prepared){switch(prepared.type){case"float":return $B.fast_float(prepared.value);case"imaginary":return $B.make_complex(0,prepared_number_value(prepared.value));case"int":var res=parseInt(prepared.value[1],prepared.value[0]);if(!Number.isSafeInteger(res)){var base=prepared.value[0],num_str=prepared.value[1];switch(base){case 8:return $B.fast_long_int(BigInt("0x"+num_str));case 10:return $B.fast_long_int(BigInt(num_str));case 16:return $B.fast_long_int(BigInt("0x"+num_str))}}return res}}function parsenumber_raw(s){var prepared=$B.prepare_number(s);return prepared_number_value(prepared)}function parsenumber(s){var dup;var end;var res=NULL;if(strchr(s,"_")==NULL){return parsenumber_raw(s)}dup=s.replace(/_/g,"");res=parsenumber_raw(dup);return res}$B._PyPegen.number_token=function(p){var t=$B._PyPegen.expect_token(p,NUMBER);if(t==NULL){return NULL}var num_raw=t.string;if(num_raw==NULL){p.error_indicator=1;return NULL}if(p.feature_version<6&&strchr(num_raw,"_")!=NULL){p.error_indicator=1;return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "+"in Python 3.6 and greater")}var c=parsenumber(num_raw);if(c==NULL){p.error_indicator=1;var tstate=_PyThreadState_GET();if(tstate.current_exception!=NULL&&Py_TYPE(tstate.current_exception)==PyExc_ValueError){var exc=PyErr_GetRaisedException();RAISE_ERROR_KNOWN_LOCATION(p,PyExc_SyntaxError,t.lineno,-1,t.end_lineno,-1,"%S - Consider hexadecimal for huge integer literals "+"to avoid decimal conversion limits.",exc)}return NULL}var res=new $B.ast.Constant(c,NULL);set_position_from_token(res,t);return res};function bad_single_statement(p){var cur=p.tok.cur;var c=cur;var pos=0;for(;;){while(c==" "||c=="\t"||c=="\n"||c=="\f"){c=cur[pos++]}if(!c){return 0}if(c!="#"){return 1}while(c&&c!="\n"){c=cur[pos++]}}}function compute_parser_flags(flags){var parser_flags=0;if(!flags){return 0}if(flags.cf_flags&PyCF_DONT_IMPLY_DEDENT){parser_flags|=PyPARSE_DONT_IMPLY_DEDENT}if(flags.cf_flags&PyCF_IGNORE_COOKIE){parser_flags|=PyPARSE_IGNORE_COOKIE}if(flags.cf_flags&CO_FUTURE_BARRY_AS_BDFL){parser_flags|=PyPARSE_BARRY_AS_BDFL}if(flags.cf_flags&PyCF_TYPE_COMMENTS){parser_flags|=PyPARSE_TYPE_COMMENTS}if(flags.cf_flags&PyCF_ONLY_AST&&flags.cf_feature_version<7){parser_flags|=PyPARSE_ASYNC_HACKS}if(flags.cf_flags&PyCF_ALLOW_INCOMPLETE_INPUT){parser_flags|=PyPARSE_ALLOW_INCOMPLETE_INPUT}return parser_flags}$B._PyPegen.Parser_New=function(tok,start_rule,flags,feature_version,errcode,arena){var p={};if(p==NULL){return PyErr_NoMemory()}tok.type_comments=(flags&PyPARSE_TYPE_COMMENTS)>0;tok.async_hacks=(flags&PyPARSE_ASYNC_HACKS)>0;p.tok=tok;p.keywords=NULL;p.n_keyword_lists=-1;p.soft_keywords=NULL;p.tokens=[];if(!p.tokens){PyMem_Free(p);return PyErr_NoMemory()}p.tokens[0]=PyMem_Calloc(1,sizeof(Token));p.mark=0;p.fill=0;p.size=1;p.errcode=errcode;p.arena=arena;p.start_rule=start_rule;p.parsing_started=0;p.normalize=NULL;p.error_indicator=0;p.starting_lineno=0;p.starting_col_offset=0;p.flags=flags;p.feature_version=feature_version;p.known_err_token=NULL;p.level=0;p.call_invalid_rules=0;p.debug=_Py_GetConfig().parser_debug;return p};$B._PyPegen.Parser_Free=function(p){};function reset_parser_state_for_error_pass(p){for(let i=0;i0){var brace=$B.last(p.braces),err_lineno,msg;if("([{".includes(brace.char)){err_lineno=brace.line_num}else{if(p.braces.length>1){err_lineno=p.braces[p.braces.length-2].line_num}else{err_lineno=brace.line_num}}if(p.tokens.length==0||$B.last(p.tokens).lineno>=err_lineno){if("([{".includes(brace.char)){msg=`'${brace.char}' was never closed`}else if(p.braces.length>1){var closing=brace.char,opening=p.braces[p.braces.length-2].char;msg=`closing parenthesis '${closing}' does not match `+`opening parenthesis '${opening}'`}else{msg=`unmatched '${brace.char}'`}$B.raise_error_known_location(_b_.SyntaxError,p.filename,brace.line_num,brace.pos-brace.line_start,brace.line_num,brace.pos-brace.line_start+1,brace.line,msg)}}};$B._PyPegen.set_syntax_error=function(p,last_token){if(p.fill==0){$B.helper_functions.RAISE_SYNTAX_ERROR(p,"error at start before reading any input")}$B._PyPegen.tokenize_full_source_to_check_for_errors(p);if(last_token.num_type==ERRORTOKEN&&p.tok.done==E_EOF){if(p.tok.level){raise_unclosed_parentheses_error(p)}else{$B.helper_functions.RAISE_SYNTAX_ERROR(p,"unexpected EOF while parsing")}return}if(last_token.num_type==INDENT||last_token.num_type==DEDENT){$B.helper_functions.RAISE_INDENTATION_ERROR(p,last_token.num_type==INDENT?"unexpected indent":"unexpected unindent");return}$B._PyPegen.tokenize_full_source_to_check_for_errors(p);$B.raise_error_known_token(_b_.SyntaxError,p.filename,last_token,"invalid syntax")};$B._PyPegen.run_parser=function(p){var res=$B._PyPegen.parse(p);if(res==NULL){if(p.flags&$B.PyCF_ALLOW_INCOMPLETE_INPUT&&_is_end_of_source(p)){return $B.helper_functions.RAISE_ERROR(p,_b_._IncompleteInputError,"incomplete input")}var last_token=p.tokens[p.fill-1];reset_parser_state_for_error_pass(p);try{$B._PyPegen.parse(p)}catch(err){last_token=p.tokens[p.fill-1];$B._PyPegen.tokenize_full_source_to_check_for_errors(p);throw err}$B._PyPegen.set_syntax_error(p,last_token)}if(p.start_rule==Py_single_input&&bad_single_statement(p)){p.tok.done=E_BADSINGLE;return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement")}return res};$B._PyPegen.run_parser_from_file_pointer=function(fp,start_rule,filename_ob,enc,ps1,ps2,flags,errcode,arena){var tok=_PyTokenizer_FromFile(fp,enc,ps1,ps2);if(tok==NULL){if(PyErr_Occurred()){_PyPegen_raise_tokenizer_init_error(filename_ob);return NULL}return NULL}if(!tok.fp||ps1!=NULL||ps2!=NULL||PyUnicode_CompareWithASCIIString(filename_ob,"")==0){tok.fp_interactive=1}tok.filename=Py_NewRef(filename_ob);var result=NULL;var parser_flags=compute_parser_flags(flags);var p=$B._PyPegen.Parser_New(tok,start_rule,parser_flags,PY_MINOR_VERSION,errcode,arena);if(p==NULL){return error()}result=_PyPegen_run_parser(p);_PyPegen_Parser_Free(p);function error(){_PyTokenizer_Free(tok);return result}};$B._PyPegen.run_parser_from_string=function(str,start_rule,filename_ob,flags,arena){var exec_input=start_rule==Py_file_input;var tok;if(flags!=NULL&&flags.cf_flags&PyCF_IGNORE_COOKIE){tok=_PyTokenizer_FromUTF8(str,exec_input,0)}else{tok=_PyTokenizer_FromString(str,exec_input,0)}if(tok==NULL){if(PyErr_Occurred()){_PyPegen_raise_tokenizer_init_error(filename_ob)}return NULL}tok.filename=Py_NewRef(filename_ob);var result=NULL;var parser_flags=compute_parser_flags(flags);var feature_version=flags&&flags.cf_flags&PyCF_ONLY_AST?flags.cf_feature_version:PY_MINOR_VERSION;var p=$B._PyPegen.Parser_New(tok,start_rule,parser_flags,feature_version,NULL,arena);if(p==NULL){return error()}result=_PyPegen_run_parser(p);_PyPegen_Parser_Free(p);function error(){return result}};$B.PyPegen={first_item:function(a,type){return a[0]},last_item:function(a,ptype){return a[a.length-1]}}})(__BRYTHON__);function fprintf(dest,format){var args=Array.from(arguments).slice(2);for(var arg of args){format=format.replace(/%\*?[a-z]/,arg)}return format}const stderr=null;function D(x){console.log(x)}function UNUSED(){}function strcmp(x,y){return x==y?0:x self.obj.length - 1){\n i = self.obj.length\n }\n return i\n}\n\narray.append = function(self, value){\n $B.args(\"append\", 2, {self: null, value: null},\n [\"self\", \"value\"], arguments, {}, null, null)\n var pos = self.obj === null ? 0 : self.obj.length\n return array.insert(self, pos, value)\n}\n\narray.count = function(self, x){\n $B.args(\"count\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n if(self.obj === null){\n return 0\n }\n return self.obj.filter(function(item){return item == x}).length\n}\n\narray.extend = function(self, iterable){\n $B.args(\"extend\", 2, {self: null, iterable: null},\n [\"self\", \"iterable\"], arguments, {}, null, null)\n if(iterable.__class__ === array){\n if(iterable.typecode !== self.typecode){\n throw _b_.TypeError.$factory(\"can only extend with array \" +\n \"of same kind\")\n }\n if(iterable.obj === null){return _b_.None}\n // create new object with length = sum of lengths\n var newobj = new typecodes[self.typecode](self.obj.length +\n iterable.obj.length)\n // copy self.obj\n newobj.set(self.obj)\n // copy iterable.obj\n newobj.set(iterable.obj, self.obj.length)\n self.obj = newobj\n }else{\n var it = _b_.iter(iterable)\n while(true){\n try{\n var item = _b_.next(it)\n array.append(self, item)\n }catch(err){\n if(err.__class__ !== _b_.StopIteration){\n throw err\n }\n break\n }\n }\n }\n return _b_.None\n}\n\narray.frombytes = function(self, s){\n $B.args(\"frombytes\", 2, {self: null, s: null},\n [\"self\", \"s\"], arguments, {}, null, null)\n if(! $B.$isinstance(s, _b_.bytes)){\n throw _b_.TypeError.$factory(\"a bytes-like object is required, \" +\n \"not '\" + $B.class_name(s) + \"'\")\n }\n self.obj = new typecodes[self.typecode](s.source)\n return _b_.None\n}\n\narray.fromlist = function(self, list){\n $B.args(\"fromlist\", 2, {self: null, list: null},\n [\"self\", \"list\"], arguments, {}, null, null)\n var it = _b_.iter(list)\n while(true){\n try{\n var item = _b_.next(it)\n try{\n array.append(self, item)\n }catch(err){\n console.log(err)\n return _b_.None\n }\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n return _b_.None\n }\n throw err\n }\n }\n}\n\narray.fromstring = array.frombytes\n\narray.index = function(self, x){\n $B.args(\"index\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n var res = self.obj.findIndex(function(item){return x == item})\n if(res == -1){\n throw _b_.ValueError.$factory(\"array.index(x): x not in array\")\n }\n return res\n}\n\narray.insert = function(self, i, value){\n $B.args(\"insert\", 3, {self: null, i: null, value: null},\n [\"self\", \"i\", \"value\"], arguments, {}, null, null)\n if(self.obj === null){\n self.obj = [value]\n }else{\n self.obj.splice(i, 0, value)\n }\n return _b_.None\n}\n\narray.itemsize = function(self){\n return typecodes[self.typecode].BYTES_PER_ELEMENT\n}\n\narray.pop = function(self, i){\n var $ = $B.args(\"count\", 2, {self: null, i: null},\n [\"self\", \"i\"], arguments, {i: -1}, null, null)\n i = $.i\n if(self.obj === null){\n throw _b_.IndexError.$factory(\"pop from empty array\")\n }else if(self.obj.length == 1){\n var res = self.obj[0]\n self.obj = null\n return res\n }\n i = normalize_index(self, i)\n // store value to return\n var res = self.obj[i]\n // create new array, size = previous size - 1\n var newobj = new typecodes[self.typecode](self.obj.length - 1)\n // fill new array with values until i excluded\n newobj.set(self.obj.slice(0, i))\n // fill with values after i\n newobj.set(self.obj.slice(i + 1), i)\n // set self.obj to new array\n self.obj = newobj\n // return stored value\n return res\n}\n\narray.remove = function(self, x){\n $B.args(\"remove\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n var res = self.obj.findIndex(function(item){return x == item})\n if(res == -1){\n throw _b_.ValueError.$factory(\"array.remove(x): x not in array\")\n }\n array.pop(self, res)\n return _b_.None\n}\n\narray.reverse = function(self){\n $B.args(\"reverse\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n if(self.obj === null){return _b_.None}\n self.obj.reverse()\n return _b_.None\n}\n\narray.tobytes = function(self){\n $B.args(\"tobytes\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n var items = Array.prototype.slice.call(self.obj),\n res = []\n items.forEach(function(item){\n while(item > 256){\n res.push(item % 256)\n item = Math.floor(item / 256)\n }\n res.push(item)\n })\n return _b_.bytes.$factory(res)\n}\n\narray.tolist = function(self){\n $B.args(\"tolist\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n if(self.obj === null){\n return $B.$list([])\n }\n return $B.$list(Array.prototype.slice.call(self.obj))\n}\n\narray.tostring = array.tobytes\n\narray.typecode = function(self){\n return self.typecode\n}\n\n$B.set_func_names(array, \"array\")\n\nvar module = {\n array: array,\n typecodes: Object.keys(typecodes).join('')\n}\n\n$B.addToImported('array', module)\n\n})(__BRYTHON__)\n"], "builtins": [".js", "(function(){\n var obj = {},\n builtin_names = ['ArithmeticError', 'AssertionError',\n 'AttributeError', 'BaseException', 'BaseExceptionGroup',\n 'BlockingIOError', 'BrokenPipeError', 'BufferError',\n 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError',\n 'ConnectionError', 'ConnectionRefusedError',\n 'ConnectionResetError', 'DeprecationWarning', 'EOFError',\n 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception',\n 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError',\n 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError',\n 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError',\n 'InterruptedError', 'IsADirectoryError', 'KeyError',\n 'KeyboardInterrupt', 'LookupError', 'MemoryError',\n 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError',\n 'NotImplemented', 'NotImplementedError', 'OSError',\n 'OverflowError', 'PendingDeprecationWarning', 'PermissionError',\n 'ProcessLookupError', 'RecursionError', 'ReferenceError',\n 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',\n 'StopAsyncIteration', 'StopIteration', 'SyntaxError',\n 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',\n 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError',\n 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',\n 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',\n 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError',\n '_', '__build_class__', '__debug__', '__import__',\n 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool',\n 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr',\n 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir',\n 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float',\n 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash',\n 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',\n 'iter', 'len', 'list', 'locals', 'map', 'max', 'memoryview',\n 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',\n 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set',\n 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum',\n 'super', 'tuple', 'type', 'vars', 'zip']\n for(var key of builtin_names){\n if(__BRYTHON__.builtins[key] !== undefined){\n obj[key] = __BRYTHON__.builtins[key]\n }\n }\n obj.__doc__ = 'builtins module'\n obj.copyright = 'CPython copyright'\n obj.credits = 'CPython builtins credits'\n obj.license = 'CPython license'\n \n $B.addToImported('builtins', obj)\n})()\n"], "dis": [".js", "(function($B){\n\nvar _b_ = $B.builtins,\n dict = $B.builtins.dict\n\nvar mod = {\n dis:function(src){\n $B.$py_module_path['__main__'] = $B.brython_path\n return __BRYTHON__.py2js(src,'__main__','__main__',\n $B.builtins_scope).to_js()\n },\n COMPILER_FLAG_NAMES: $B.builtins.dict.$factory(),\n Positions: function(){\n return _b_.None\n }\n}\n\n// COMPILER_FLAGS is defined in brython_builtins.js\nfor(var key in $B.COMPILER_FLAGS){\n mod[key] = $B.COMPILER_FLAGS[key]\n _b_.dict.$setitem(mod.COMPILER_FLAG_NAMES, mod[key], key)\n}\n\n$B.addToImported('dis', mod)\n\n})(__BRYTHON__)"], "encoding_cp932": [".js", "const cps = {\"0\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 65377, 65378, 65379, 65380, 65381, 65382, 65383, 65384, 65385, 65386, 65387, 65388, 65389, 65390, 65391, 65392, 65393, 65394, 65395, 65396, 65397, 65398, 65399, 65400, 65401, 65402, 65403, 65404, 65405, 65406, 65407, 65408, 65409, 65410, 65411, 65412, 65413, 65414, 65415, 65416, 65417, 65418, 65419, 65420, 65421, 65422, 65423, 65424, 65425, 65426, 65427, 65428, 65429, 65430, 65431, 65432, 65433, 65434, 65435, 65436, 65437, 65438, 65439, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null], \"33088\": [12288, 12289, 12290, 65292, 65294, 12539, 65306, 65307, 65311, 65281, 12443, 12444, 180, 65344, 168, 65342, 65507, 65343, 12541, 12542, 12445, 12446, 12291, 20189, 12293, 12294, 12295, 12540, 8213, 8208, 65295, 65340, 65374, 8741, 65372, 8230, 8229, 8216, 8217, 8220, 8221, 65288, 65289, 12308, 12309, 65339, 65341, 65371, 65373, 12296, 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 65291, 65293, 177, 215], \"33152\": [247, 65309, 8800, 65308, 65310, 8806, 8807, 8734, 8756, 9794, 9792, 176, 8242, 8243, 8451, 65509, 65284, 65504, 65505, 65285, 65283, 65286, 65290, 65312, 167, 9734, 9733, 9675, 9679, 9678, 9671, 9670, 9633, 9632, 9651, 9650, 9661, 9660, 8251, 12306, 8594, 8592, 8593, 8595, 12307], \"33208\": [8712, 8715, 8838, 8839, 8834, 8835, 8746, 8745], \"33224\": [8743, 8744, 65506, 8658, 8660, 8704, 8707], \"33242\": [8736, 8869, 8978, 8706, 8711, 8801, 8786, 8810, 8811, 8730, 8765, 8733, 8757, 8747, 8748], \"33264\": [8491, 8240, 9839, 9837, 9834, 8224, 8225, 182], \"33276\": [9711], \"33359\": [65296, 65297, 65298, 65299, 65300, 65301, 65302, 65303, 65304, 65305], \"33376\": [65313, 65314, 65315, 65316, 65317, 65318, 65319, 65320, 65321, 65322, 65323, 65324, 65325, 65326, 65327, 65328, 65329, 65330, 65331, 65332, 65333, 65334, 65335, 65336, 65337, 65338], \"33409\": [65345, 65346, 65347, 65348, 65349, 65350, 65351, 65352, 65353, 65354, 65355, 65356, 65357, 65358, 65359, 65360, 65361, 65362, 65363, 65364, 65365, 65366, 65367, 65368, 65369, 65370], \"33439\": [12353, 12354, 12355, 12356, 12357, 12358, 12359, 12360, 12361, 12362, 12363, 12364, 12365, 12366, 12367, 12368, 12369, 12370, 12371, 12372, 12373, 12374, 12375, 12376, 12377, 12378, 12379, 12380, 12381, 12382, 12383, 12384, 12385, 12386, 12387, 12388, 12389, 12390, 12391, 12392, 12393, 12394, 12395, 12396, 12397, 12398, 12399, 12400, 12401, 12402, 12403, 12404, 12405, 12406, 12407, 12408, 12409, 12410, 12411, 12412, 12413, 12414, 12415, 12416, 12417, 12418, 12419, 12420, 12421, 12422, 12423, 12424, 12425, 12426, 12427, 12428, 12429, 12430, 12431, 12432, 12433, 12434, 12435], \"33600\": [12449, 12450, 12451, 12452, 12453, 12454, 12455, 12456, 12457, 12458, 12459, 12460, 12461, 12462, 12463, 12464, 12465, 12466, 12467, 12468, 12469, 12470, 12471, 12472, 12473, 12474, 12475, 12476, 12477, 12478, 12479, 12480, 12481, 12482, 12483, 12484, 12485, 12486, 12487, 12488, 12489, 12490, 12491, 12492, 12493, 12494, 12495, 12496, 12497, 12498, 12499, 12500, 12501, 12502, 12503, 12504, 12505, 12506, 12507, 12508, 12509, 12510, 12511], \"33664\": [12512, 12513, 12514, 12515, 12516, 12517, 12518, 12519, 12520, 12521, 12522, 12523, 12524, 12525, 12526, 12527, 12528, 12529, 12530, 12531, 12532, 12533, 12534], \"33695\": [913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937], \"33727\": [945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 963, 964, 965, 966, 967, 968, 969], \"33856\": [1040, 1041, 1042, 1043, 1044, 1045, 1025, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071], \"33904\": [1072, 1073, 1074, 1075, 1076, 1077, 1105, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085], \"33920\": [1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103], \"33951\": [9472, 9474, 9484, 9488, 9496, 9492, 9500, 9516, 9508, 9524, 9532, 9473, 9475, 9487, 9491, 9499, 9495, 9507, 9523, 9515, 9531, 9547, 9504, 9519, 9512, 9527, 9535, 9501, 9520, 9509, 9528, 9538], \"34624\": [9312, 9313, 9314, 9315, 9316, 9317, 9318, 9319, 9320, 9321, 9322, 9323, 9324, 9325, 9326, 9327, 9328, 9329, 9330, 9331, 8544, 8545, 8546, 8547, 8548, 8549, 8550, 8551, 8552, 8553], \"34655\": [13129, 13076, 13090, 13133, 13080, 13095, 13059, 13110, 13137, 13143, 13069, 13094, 13091, 13099, 13130, 13115, 13212, 13213, 13214, 13198, 13199, 13252, 13217], \"34686\": [13179], \"34688\": [12317, 12319, 8470, 13261, 8481, 12964, 12965, 12966, 12967, 12968, 12849, 12850, 12857, 13182, 13181, 13180, 8786, 8801, 8747, 8750, 8721, 8730, 8869, 8736, 8735, 8895, 8757, 8745, 8746], \"34975\": [20124, 21782, 23043, 38463, 21696, 24859, 25384, 23030, 36898, 33909, 33564, 31312, 24746, 25569, 28197, 26093, 33894, 33446, 39925, 26771, 22311, 26017, 25201, 23451, 22992, 34427, 39156, 32098, 32190, 39822, 25110, 31903, 34999, 23433, 24245, 25353, 26263, 26696, 38343, 38797, 26447, 20197, 20234, 20301, 20381, 20553, 22258, 22839, 22996, 23041, 23561, 24799, 24847, 24944, 26131, 26885, 28858, 30031, 30064, 31227, 32173, 32239, 32963, 33806, 34915, 35586, 36949, 36986, 21307, 20117, 20133, 22495, 32946, 37057, 30959, 19968, 22769, 28322, 36920, 31282, 33576, 33419, 39983, 20801, 21360, 21693, 21729, 22240, 23035, 24341, 39154, 28139, 32996, 34093], \"35136\": [38498, 38512, 38560, 38907, 21515, 21491, 23431, 28879, 32701, 36802, 38632, 21359, 40284, 31418, 19985, 30867, 33276, 28198, 22040, 21764, 27421, 34074, 39995, 23013, 21417, 28006, 29916, 38287, 22082, 20113, 36939, 38642, 33615, 39180, 21473, 21942, 23344, 24433, 26144, 26355, 26628, 27704, 27891, 27945, 29787, 30408, 31310, 38964, 33521, 34907, 35424, 37613, 28082, 30123, 30410, 39365, 24742, 35585, 36234, 38322, 27022, 21421, 20870], \"35200\": [22290, 22576, 22852, 23476, 24310, 24616, 25513, 25588, 27839, 28436, 28814, 28948, 29017, 29141, 29503, 32257, 33398, 33489, 34199, 36960, 37467, 40219, 22633, 26044, 27738, 29989, 20985, 22830, 22885, 24448, 24540, 25276, 26106, 27178, 27431, 27572, 29579, 32705, 35158, 40236, 40206, 40644, 23713, 27798, 33659, 20740, 23627, 25014, 33222, 26742, 29281, 20057, 20474, 21368, 24681, 28201, 31311, 38899, 19979, 21270, 20206, 20309, 20285, 20385, 20339, 21152, 21487, 22025, 22799, 23233, 23478, 23521, 31185, 26247, 26524, 26550, 27468, 27827, 28779, 29634, 31117, 31166, 31292, 31623, 33457, 33499, 33540, 33655, 33775, 33747, 34662, 35506, 22057, 36008, 36838, 36942, 38686, 34442, 20420, 23784, 25105, 29273, 30011, 33253, 33469, 34558, 36032, 38597, 39187, 39381, 20171, 20250, 35299, 22238, 22602, 22730, 24315, 24555, 24618, 24724, 24674, 25040, 25106, 25296, 25913], \"35392\": [39745, 26214, 26800, 28023, 28784, 30028, 30342, 32117, 33445, 34809, 38283, 38542, 35997, 20977, 21182, 22806, 21683, 23475, 23830, 24936, 27010, 28079, 30861, 33995, 34903, 35442, 37799, 39608, 28012, 39336, 34521, 22435, 26623, 34510, 37390, 21123, 22151, 21508, 24275, 25313, 25785, 26684, 26680, 27579, 29554, 30906, 31339, 35226, 35282, 36203, 36611, 37101, 38307, 38548, 38761, 23398, 23731, 27005, 38989, 38990, 25499, 31520, 27179], \"35456\": [27263, 26806, 39949, 28511, 21106, 21917, 24688, 25324, 27963, 28167, 28369, 33883, 35088, 36676, 19988, 39993, 21494, 26907, 27194, 38788, 26666, 20828, 31427, 33970, 37340, 37772, 22107, 40232, 26658, 33541, 33841, 31909, 21000, 33477, 29926, 20094, 20355, 20896, 23506, 21002, 21208, 21223, 24059, 21914, 22570, 23014, 23436, 23448, 23515, 24178, 24185, 24739, 24863, 24931, 25022, 25563, 25954, 26577, 26707, 26874, 27454, 27475, 27735, 28450, 28567, 28485, 29872, 29976, 30435, 30475, 31487, 31649, 31777, 32233, 32566, 32752, 32925, 33382, 33694, 35251, 35532, 36011, 36996, 37969, 38291, 38289, 38306, 38501, 38867, 39208, 33304, 20024, 21547, 23736, 24012, 29609, 30284, 30524, 23721, 32747, 36107, 38593, 38929, 38996, 39000, 20225, 20238, 21361, 21916, 22120, 22522, 22855, 23305, 23492, 23696, 24076, 24190, 24524, 25582, 26426, 26071, 26082, 26399, 26827, 26820], \"35648\": [27231, 24112, 27589, 27671, 27773, 30079, 31048, 23395, 31232, 32000, 24509, 35215, 35352, 36020, 36215, 36556, 36637, 39138, 39438, 39740, 20096, 20605, 20736, 22931, 23452, 25135, 25216, 25836, 27450, 29344, 30097, 31047, 32681, 34811, 35516, 35696, 25516, 33738, 38816, 21513, 21507, 21931, 26708, 27224, 35440, 30759, 26485, 40653, 21364, 23458, 33050, 34384, 36870, 19992, 20037, 20167, 20241, 21450, 21560, 23470, 24339, 24613, 25937], \"35712\": [26429, 27714, 27762, 27875, 28792, 29699, 31350, 31406, 31496, 32026, 31998, 32102, 26087, 29275, 21435, 23621, 24040, 25298, 25312, 25369, 28192, 34394, 35377, 36317, 37624, 28417, 31142, 39770, 20136, 20139, 20140, 20379, 20384, 20689, 20807, 31478, 20849, 20982, 21332, 21281, 21375, 21483, 21932, 22659, 23777, 24375, 24394, 24623, 24656, 24685, 25375, 25945, 27211, 27841, 29378, 29421, 30703, 33016, 33029, 33288, 34126, 37111, 37857, 38911, 39255, 39514, 20208, 20957, 23597, 26241, 26989, 23616, 26354, 26997, 29577, 26704, 31873, 20677, 21220, 22343, 24062, 37670, 26020, 27427, 27453, 29748, 31105, 31165, 31563, 32202, 33465, 33740, 34943, 35167, 35641, 36817, 37329, 21535, 37504, 20061, 20534, 21477, 21306, 29399, 29590, 30697, 33510, 36527, 39366, 39368, 39378, 20855, 24858, 34398, 21936, 31354, 20598, 23507, 36935, 38533, 20018, 27355, 37351, 23633, 23624], \"35904\": [25496, 31391, 27795, 38772, 36705, 31402, 29066, 38536, 31874, 26647, 32368, 26705, 37740, 21234, 21531, 34219, 35347, 32676, 36557, 37089, 21350, 34952, 31041, 20418, 20670, 21009, 20804, 21843, 22317, 29674, 22411, 22865, 24418, 24452, 24693, 24950, 24935, 25001, 25522, 25658, 25964, 26223, 26690, 28179, 30054, 31293, 31995, 32076, 32153, 32331, 32619, 33550, 33610, 34509, 35336, 35427, 35686, 36605, 38938, 40335, 33464, 36814, 39912], \"35968\": [21127, 25119, 25731, 28608, 38553, 26689, 20625, 27424, 27770, 28500, 31348, 32080, 34880, 35363, 26376, 20214, 20537, 20518, 20581, 20860, 21048, 21091, 21927, 22287, 22533, 23244, 24314, 25010, 25080, 25331, 25458, 26908, 27177, 29309, 29356, 29486, 30740, 30831, 32121, 30476, 32937, 35211, 35609, 36066, 36562, 36963, 37749, 38522, 38997, 39443, 40568, 20803, 21407, 21427, 24187, 24358, 28187, 28304, 29572, 29694, 32067, 33335, 35328, 35578, 38480, 20046, 20491, 21476, 21628, 22266, 22993, 23396, 24049, 24235, 24359, 25144, 25925, 26543, 28246, 29392, 31946, 34996, 32929, 32993, 33776, 34382, 35463, 36328, 37431, 38599, 39015, 40723, 20116, 20114, 20237, 21320, 21577, 21566, 23087, 24460, 24481, 24735, 26791, 27278, 29786, 30849, 35486, 35492, 35703, 37264, 20062, 39881, 20132, 20348, 20399, 20505, 20502, 20809, 20844, 21151, 21177, 21246, 21402, 21475, 21521], \"36160\": [21518, 21897, 22353, 22434, 22909, 23380, 23389, 23439, 24037, 24039, 24055, 24184, 24195, 24218, 24247, 24344, 24658, 24908, 25239, 25304, 25511, 25915, 26114, 26179, 26356, 26477, 26657, 26775, 27083, 27743, 27946, 28009, 28207, 28317, 30002, 30343, 30828, 31295, 31968, 32005, 32024, 32094, 32177, 32789, 32771, 32943, 32945, 33108, 33167, 33322, 33618, 34892, 34913, 35611, 36002, 36092, 37066, 37237, 37489, 30783, 37628, 38308, 38477], \"36224\": [38917, 39321, 39640, 40251, 21083, 21163, 21495, 21512, 22741, 25335, 28640, 35946, 36703, 40633, 20811, 21051, 21578, 22269, 31296, 37239, 40288, 40658, 29508, 28425, 33136, 29969, 24573, 24794, 39592, 29403, 36796, 27492, 38915, 20170, 22256, 22372, 22718, 23130, 24680, 25031, 26127, 26118, 26681, 26801, 28151, 30165, 32058, 33390, 39746, 20123, 20304, 21449, 21766, 23919, 24038, 24046, 26619, 27801, 29811, 30722, 35408, 37782, 35039, 22352, 24231, 25387, 20661, 20652, 20877, 26368, 21705, 22622, 22971, 23472, 24425, 25165, 25505, 26685, 27507, 28168, 28797, 37319, 29312, 30741, 30758, 31085, 25998, 32048, 33756, 35009, 36617, 38555, 21092, 22312, 26448, 32618, 36001, 20916, 22338, 38442, 22586, 27018, 32948, 21682, 23822, 22524, 30869, 40442, 20316, 21066, 21643, 25662, 26152, 26388, 26613, 31364, 31574, 32034, 37679, 26716, 39853, 31545, 21273, 20874, 21047], \"36416\": [23519, 25334, 25774, 25830, 26413, 27578, 34217, 38609, 30352, 39894, 25420, 37638, 39851, 30399, 26194, 19977, 20632, 21442, 23665, 24808, 25746, 25955, 26719, 29158, 29642, 29987, 31639, 32386, 34453, 35715, 36059, 37240, 39184, 26028, 26283, 27531, 20181, 20180, 20282, 20351, 21050, 21496, 21490, 21987, 22235, 22763, 22987, 22985, 23039, 23376, 23629, 24066, 24107, 24535, 24605, 25351, 25903, 23388, 26031, 26045, 26088, 26525, 27490], \"36480\": [27515, 27663, 29509, 31049, 31169, 31992, 32025, 32043, 32930, 33026, 33267, 35222, 35422, 35433, 35430, 35468, 35566, 36039, 36060, 38604, 39164, 27503, 20107, 20284, 20365, 20816, 23383, 23546, 24904, 25345, 26178, 27425, 28363, 27835, 29246, 29885, 30164, 30913, 31034, 32780, 32819, 33258, 33940, 36766, 27728, 40575, 24335, 35672, 40235, 31482, 36600, 23437, 38635, 19971, 21489, 22519, 22833, 23241, 23460, 24713, 28287, 28422, 30142, 36074, 23455, 34048, 31712, 20594, 26612, 33437, 23649, 34122, 32286, 33294, 20889, 23556, 25448, 36198, 26012, 29038, 31038, 32023, 32773, 35613, 36554, 36974, 34503, 37034, 20511, 21242, 23610, 26451, 28796, 29237, 37196, 37320, 37675, 33509, 23490, 24369, 24825, 20027, 21462, 23432, 25163, 26417, 27530, 29417, 29664, 31278, 33131, 36259, 37202, 39318, 20754, 21463, 21610, 23551, 25480, 27193, 32172, 38656, 22234, 21454, 21608], \"36672\": [23447, 23601, 24030, 20462, 24833, 25342, 27954, 31168, 31179, 32066, 32333, 32722, 33261, 33311, 33936, 34886, 35186, 35728, 36468, 36655, 36913, 37195, 37228, 38598, 37276, 20160, 20303, 20805, 21313, 24467, 25102, 26580, 27713, 28171, 29539, 32294, 37325, 37507, 21460, 22809, 23487, 28113, 31069, 32302, 31899, 22654, 29087, 20986, 34899, 36848, 20426, 23803, 26149, 30636, 31459, 33308, 39423, 20934, 24490, 26092, 26991, 27529, 28147], \"36736\": [28310, 28516, 30462, 32020, 24033, 36981, 37255, 38918, 20966, 21021, 25152, 26257, 26329, 28186, 24246, 32210, 32626, 26360, 34223, 34295, 35576, 21161, 21465, 22899, 24207, 24464, 24661, 37604, 38500, 20663, 20767, 21213, 21280, 21319, 21484, 21736, 21830, 21809, 22039, 22888, 22974, 23100, 23477, 23558, 23567, 23569, 23578, 24196, 24202, 24288, 24432, 25215, 25220, 25307, 25484, 25463, 26119, 26124, 26157, 26230, 26494, 26786, 27167, 27189, 27836, 28040, 28169, 28248, 28988, 28966, 29031, 30151, 30465, 30813, 30977, 31077, 31216, 31456, 31505, 31911, 32057, 32918, 33750, 33931, 34121, 34909, 35059, 35359, 35388, 35412, 35443, 35937, 36062, 37284, 37478, 37758, 37912, 38556, 38808, 19978, 19976, 19998, 20055, 20887, 21104, 22478, 22580, 22732, 23330, 24120, 24773, 25854, 26465, 26454, 27972, 29366, 30067, 31331, 33976, 35698, 37304, 37664, 22065, 22516, 39166], \"36928\": [25325, 26893, 27542, 29165, 32340, 32887, 33394, 35302, 39135, 34645, 36785, 23611, 20280, 20449, 20405, 21767, 23072, 23517, 23529, 24515, 24910, 25391, 26032, 26187, 26862, 27035, 28024, 28145, 30003, 30137, 30495, 31070, 31206, 32051, 33251, 33455, 34218, 35242, 35386, 36523, 36763, 36914, 37341, 38663, 20154, 20161, 20995, 22645, 22764, 23563, 29978, 23613, 33102, 35338, 36805, 38499, 38765, 31525, 35535, 38920, 37218, 22259, 21416], \"36992\": [36887, 21561, 22402, 24101, 25512, 27700, 28810, 30561, 31883, 32736, 34928, 36930, 37204, 37648, 37656, 38543, 29790, 39620, 23815, 23913, 25968, 26530, 36264, 38619, 25454, 26441, 26905, 33733, 38935, 38592, 35070, 28548, 25722, 23544, 19990, 28716, 30045, 26159, 20932, 21046, 21218, 22995, 24449, 24615, 25104, 25919, 25972, 26143, 26228, 26866, 26646, 27491, 28165, 29298, 29983, 30427, 31934, 32854, 22768, 35069, 35199, 35488, 35475, 35531, 36893, 37266, 38738, 38745, 25993, 31246, 33030, 38587, 24109, 24796, 25114, 26021, 26132, 26512, 30707, 31309, 31821, 32318, 33034, 36012, 36196, 36321, 36447, 30889, 20999, 25305, 25509, 25666, 25240, 35373, 31363, 31680, 35500, 38634, 32118, 33292, 34633, 20185, 20808, 21315, 21344, 23459, 23554, 23574, 24029, 25126, 25159, 25776, 26643, 26676, 27849, 27973, 27927, 26579, 28508, 29006, 29053, 26059, 31359, 31661, 32218], \"37184\": [32330, 32680, 33146, 33307, 33337, 34214, 35438, 36046, 36341, 36984, 36983, 37549, 37521, 38275, 39854, 21069, 21892, 28472, 28982, 20840, 31109, 32341, 33203, 31950, 22092, 22609, 23720, 25514, 26366, 26365, 26970, 29401, 30095, 30094, 30990, 31062, 31199, 31895, 32032, 32068, 34311, 35380, 38459, 36961, 40736, 20711, 21109, 21452, 21474, 20489, 21930, 22766, 22863, 29245, 23435, 23652, 21277, 24803, 24819, 25436, 25475, 25407, 25531], \"37248\": [25805, 26089, 26361, 24035, 27085, 27133, 28437, 29157, 20105, 30185, 30456, 31379, 31967, 32207, 32156, 32865, 33609, 33624, 33900, 33980, 34299, 35013, 36208, 36865, 36973, 37783, 38684, 39442, 20687, 22679, 24974, 33235, 34101, 36104, 36896, 20419, 20596, 21063, 21363, 24687, 25417, 26463, 28204, 36275, 36895, 20439, 23646, 36042, 26063, 32154, 21330, 34966, 20854, 25539, 23384, 23403, 23562, 25613, 26449, 36956, 20182, 22810, 22826, 27760, 35409, 21822, 22549, 22949, 24816, 25171, 26561, 33333, 26965, 38464, 39364, 39464, 20307, 22534, 23550, 32784, 23729, 24111, 24453, 24608, 24907, 25140, 26367, 27888, 28382, 32974, 33151, 33492, 34955, 36024, 36864, 36910, 38538, 40667, 39899, 20195, 21488, 22823, 31532, 37261, 38988, 40441, 28381, 28711, 21331, 21828, 23429, 25176, 25246, 25299, 27810, 28655, 29730, 35351, 37944, 28609, 35582, 33592, 20967, 34552, 21482], \"37440\": [21481, 20294, 36948, 36784, 22890, 33073, 24061, 31466, 36799, 26842, 35895, 29432, 40008, 27197, 35504, 20025, 21336, 22022, 22374, 25285, 25506, 26086, 27470, 28129, 28251, 28845, 30701, 31471, 31658, 32187, 32829, 32966, 34507, 35477, 37723, 22243, 22727, 24382, 26029, 26262, 27264, 27573, 30007, 35527, 20516, 30693, 22320, 24347, 24677, 26234, 27744, 30196, 31258, 32622, 33268, 34584, 36933, 39347, 31689, 30044, 31481, 31569, 33988], \"37504\": [36880, 31209, 31378, 33590, 23265, 30528, 20013, 20210, 23449, 24544, 25277, 26172, 26609, 27880, 34411, 34935, 35387, 37198, 37619, 39376, 27159, 28710, 29482, 33511, 33879, 36015, 19969, 20806, 20939, 21899, 23541, 24086, 24115, 24193, 24340, 24373, 24427, 24500, 25074, 25361, 26274, 26397, 28526, 29266, 30010, 30522, 32884, 33081, 33144, 34678, 35519, 35548, 36229, 36339, 37530, 38263, 38914, 40165, 21189, 25431, 30452, 26389, 27784, 29645, 36035, 37806, 38515, 27941, 22684, 26894, 27084, 36861, 37786, 30171, 36890, 22618, 26626, 25524, 27131, 20291, 28460, 26584, 36795, 34086, 32180, 37716, 26943, 28528, 22378, 22775, 23340, 32044, 29226, 21514, 37347, 40372, 20141, 20302, 20572, 20597, 21059, 35998, 21576, 22564, 23450, 24093, 24213, 24237, 24311, 24351, 24716, 25269, 25402, 25552, 26799, 27712, 30855, 31118, 31243, 32224, 33351, 35330, 35558, 36420, 36883], \"37696\": [37048, 37165, 37336, 40718, 27877, 25688, 25826, 25973, 28404, 30340, 31515, 36969, 37841, 28346, 21746, 24505, 25764, 36685, 36845, 37444, 20856, 22635, 22825, 23637, 24215, 28155, 32399, 29980, 36028, 36578, 39003, 28857, 20253, 27583, 28593, 30000, 38651, 20814, 21520, 22581, 22615, 22956, 23648, 24466, 26007, 26460, 28193, 30331, 33759, 36077, 36884, 37117, 37709, 30757, 30778, 21162, 24230, 22303, 22900, 24594, 20498, 20826, 20908], \"37760\": [20941, 20992, 21776, 22612, 22616, 22871, 23445, 23798, 23947, 24764, 25237, 25645, 26481, 26691, 26812, 26847, 30423, 28120, 28271, 28059, 28783, 29128, 24403, 30168, 31095, 31561, 31572, 31570, 31958, 32113, 21040, 33891, 34153, 34276, 35342, 35588, 35910, 36367, 36867, 36879, 37913, 38518, 38957, 39472, 38360, 20685, 21205, 21516, 22530, 23566, 24999, 25758, 27934, 30643, 31461, 33012, 33796, 36947, 37509, 23776, 40199, 21311, 24471, 24499, 28060, 29305, 30563, 31167, 31716, 27602, 29420, 35501, 26627, 27233, 20984, 31361, 26932, 23626, 40182, 33515, 23493, 37193, 28702, 22136, 23663, 24775, 25958, 27788, 35930, 36929, 38931, 21585, 26311, 37389, 22856, 37027, 20869, 20045, 20970, 34201, 35598, 28760, 25466, 37707, 26978, 39348, 32260, 30071, 21335, 26976, 36575, 38627, 27741, 20108, 23612, 24336, 36841, 21250, 36049, 32905, 34425, 24319, 26085, 20083, 20837], \"37952\": [22914, 23615, 38894, 20219, 22922, 24525, 35469, 28641, 31152, 31074, 23527, 33905, 29483, 29105, 24180, 24565, 25467, 25754, 29123, 31896, 20035, 24316, 20043, 22492, 22178, 24745, 28611, 32013, 33021, 33075, 33215, 36786, 35223, 34468, 24052, 25226, 25773, 35207, 26487, 27874, 27966, 29750, 30772, 23110, 32629, 33453, 39340, 20467, 24259, 25309, 25490, 25943, 26479, 30403, 29260, 32972, 32954, 36649, 37197, 20493, 22521, 23186, 26757], \"38016\": [26995, 29028, 29437, 36023, 22770, 36064, 38506, 36889, 34687, 31204, 30695, 33833, 20271, 21093, 21338, 25293, 26575, 27850, 30333, 31636, 31893, 33334, 34180, 36843, 26333, 28448, 29190, 32283, 33707, 39361, 40614, 20989, 31665, 30834, 31672, 32903, 31560, 27368, 24161, 32908, 30033, 30048, 20843, 37474, 28300, 30330, 37271, 39658, 20240, 32624, 25244, 31567, 38309, 40169, 22138, 22617, 34532, 38588, 20276, 21028, 21322, 21453, 21467, 24070, 25644, 26001, 26495, 27710, 27726, 29256, 29359, 29677, 30036, 32321, 33324, 34281, 36009, 31684, 37318, 29033, 38930, 39151, 25405, 26217, 30058, 30436, 30928, 34115, 34542, 21290, 21329, 21542, 22915, 24199, 24444, 24754, 25161, 25209, 25259, 26000, 27604, 27852, 30130, 30382, 30865, 31192, 32203, 32631, 32933, 34987, 35513, 36027, 36991, 38750, 39131, 27147, 31800, 20633, 23614, 24494, 26503, 27608, 29749, 30473, 32654], \"38208\": [40763, 26570, 31255, 21305, 30091, 39661, 24422, 33181, 33777, 32920, 24380, 24517, 30050, 31558, 36924, 26727, 23019, 23195, 32016, 30334, 35628, 20469, 24426, 27161, 27703, 28418, 29922, 31080, 34920, 35413, 35961, 24287, 25551, 30149, 31186, 33495, 37672, 37618, 33948, 34541, 39981, 21697, 24428, 25996, 27996, 28693, 36007, 36051, 38971, 25935, 29942, 19981, 20184, 22496, 22827, 23142, 23500, 20904, 24067, 24220, 24598, 25206, 25975], \"38272\": [26023, 26222, 28014, 29238, 31526, 33104, 33178, 33433, 35676, 36000, 36070, 36212, 38428, 38468, 20398, 25771, 27494, 33310, 33889, 34154, 37096, 23553, 26963, 39080, 33914, 34135, 20239, 21103, 24489, 24133, 26381, 31119, 33145, 35079, 35206, 28149, 24343, 25173, 27832, 20175, 29289, 39826, 20998, 21563, 22132, 22707, 24996, 25198, 28954, 22894, 31881, 31966, 32027, 38640, 25991, 32862, 19993, 20341, 20853, 22592, 24163, 24179, 24330, 26564, 20006, 34109, 38281, 38491, 31859, 38913, 20731, 22721, 30294, 30887, 21029, 30629, 34065, 31622, 20559, 22793, 29255, 31687, 32232, 36794, 36820, 36941, 20415, 21193, 23081, 24321, 38829, 20445, 33303, 37610, 22275, 25429, 27497, 29995, 35036, 36628, 31298, 21215, 22675, 24917, 25098, 26286, 27597, 31807, 33769, 20515, 20472, 21253, 21574, 22577, 22857, 23453, 23792, 23791, 23849, 24214, 25265, 25447, 25918, 26041, 26379], \"38464\": [27861, 27873, 28921, 30770, 32299, 32990, 33459, 33804, 34028, 34562, 35090, 35370, 35914, 37030, 37586, 39165, 40179, 40300, 20047, 20129, 20621, 21078, 22346, 22952, 24125, 24536, 24537, 25151, 26292, 26395, 26576, 26834, 20882, 32033, 32938, 33192, 35584, 35980, 36031, 37502, 38450, 21536, 38956, 21271, 20693, 21340, 22696, 25778, 26420, 29287, 30566, 31302, 37350, 21187, 27809, 27526, 22528, 24140, 22868, 26412, 32763, 20961, 30406], \"38528\": [25705, 30952, 39764, 40635, 22475, 22969, 26151, 26522, 27598, 21737, 27097, 24149, 33180, 26517, 39850, 26622, 40018, 26717, 20134, 20451, 21448, 25273, 26411, 27819, 36804, 20397, 32365, 40639, 19975, 24930, 28288, 28459, 34067, 21619, 26410, 39749, 24051, 31637, 23724, 23494, 34588, 28234, 34001, 31252, 33032, 22937, 31885, 27665, 30496, 21209, 22818, 28961, 29279, 30683, 38695, 40289, 26891, 23167, 23064, 20901, 21517, 21629, 26126, 30431, 36855, 37528, 40180, 23018, 29277, 28357, 20813, 26825, 32191, 32236, 38754, 40634, 25720, 27169, 33538, 22916, 23391, 27611, 29467, 30450, 32178, 32791, 33945, 20786, 26408, 40665, 30446, 26466, 21247, 39173, 23588, 25147, 31870, 36016, 21839, 24758, 32011, 38272, 21249, 20063, 20918, 22812, 29242, 32822, 37326, 24357, 30690, 21380, 24441, 32004, 34220, 35379, 36493, 38742, 26611, 34222, 37971, 24841, 24840, 27833, 30290], \"38720\": [35565, 36664, 21807, 20305, 20778, 21191, 21451, 23461, 24189, 24736, 24962, 25558, 26377, 26586, 28263, 28044, 29494, 29495, 30001, 31056, 35029, 35480, 36938, 37009, 37109, 38596, 34701, 22805, 20104, 20313, 19982, 35465, 36671, 38928, 20653, 24188, 22934, 23481, 24248, 25562, 25594, 25793, 26332, 26954, 27096, 27915, 28342, 29076, 29992, 31407, 32650, 32768, 33865, 33993, 35201, 35617, 36362, 36965, 38525, 39178, 24958, 25233, 27442], \"38784\": [27779, 28020, 32716, 32764, 28096, 32645, 34746, 35064, 26469, 33713, 38972, 38647, 27931, 32097, 33853, 37226, 20081, 21365, 23888, 27396, 28651, 34253, 34349, 35239, 21033, 21519, 23653, 26446, 26792, 29702, 29827, 30178, 35023, 35041, 37324, 38626, 38520, 24459, 29575, 31435, 33870, 25504, 30053, 21129, 27969, 28316, 29705, 30041, 30827, 31890, 38534, 31452, 40845, 20406, 24942, 26053, 34396, 20102, 20142, 20698, 20001, 20940, 23534, 26009, 26753, 28092, 29471, 30274, 30637, 31260, 31975, 33391, 35538, 36988, 37327, 38517, 38936, 21147, 32209, 20523, 21400, 26519, 28107, 29136, 29747, 33256, 36650, 38563, 40023, 40607, 29792, 22593, 28057, 32047, 39006, 20196, 20278, 20363, 20919, 21169, 23994, 24604, 29618, 31036, 33491, 37428, 38583, 38646, 38666, 40599, 40802, 26278, 27508, 21015, 21155, 28872, 35010, 24265, 24651, 24976, 28451, 29001, 31806, 32244, 32879], \"38976\": [34030, 36899, 37676, 21570, 39791, 27347, 28809, 36034, 36335, 38706, 21172, 23105, 24266, 24324, 26391, 27004, 27028, 28010, 28431, 29282, 29436, 31725, 32769, 32894, 34635, 37070, 20845, 40595, 31108, 32907, 37682, 35542, 20525, 21644, 35441, 27498, 36036, 33031, 24785, 26528, 40434, 20121, 20120, 39952, 35435, 34241, 34152, 26880, 28286, 30871, 33109], \"39071\": [24332, 19984, 19989, 20010, 20017, 20022, 20028, 20031, 20034, 20054, 20056, 20098, 20101, 35947, 20106, 33298, 24333, 20110, 20126, 20127, 20128, 20130, 20144, 20147, 20150, 20174, 20173, 20164, 20166, 20162, 20183, 20190, 20205, 20191, 20215, 20233, 20314, 20272, 20315, 20317, 20311, 20295, 20342, 20360, 20367, 20376, 20347, 20329, 20336, 20369, 20335, 20358, 20374, 20760, 20436, 20447, 20430, 20440, 20443, 20433, 20442, 20432, 20452, 20453, 20506, 20520, 20500, 20522, 20517, 20485, 20252, 20470, 20513, 20521, 20524, 20478, 20463, 20497, 20486, 20547, 20551, 26371, 20565, 20560, 20552, 20570, 20566, 20588, 20600, 20608, 20634, 20613, 20660, 20658], \"39232\": [20681, 20682, 20659, 20674, 20694, 20702, 20709, 20717, 20707, 20718, 20729, 20725, 20745, 20737, 20738, 20758, 20757, 20756, 20762, 20769, 20794, 20791, 20796, 20795, 20799, 20800, 20818, 20812, 20820, 20834, 31480, 20841, 20842, 20846, 20864, 20866, 22232, 20876, 20873, 20879, 20881, 20883, 20885, 20886, 20900, 20902, 20898, 20905, 20906, 20907, 20915, 20913, 20914, 20912, 20917, 20925, 20933, 20937, 20955, 20960, 34389, 20969, 20973], \"39296\": [20976, 20981, 20990, 20996, 21003, 21012, 21006, 21031, 21034, 21038, 21043, 21049, 21071, 21060, 21067, 21068, 21086, 21076, 21098, 21108, 21097, 21107, 21119, 21117, 21133, 21140, 21138, 21105, 21128, 21137, 36776, 36775, 21164, 21165, 21180, 21173, 21185, 21197, 21207, 21214, 21219, 21222, 39149, 21216, 21235, 21237, 21240, 21241, 21254, 21256, 30008, 21261, 21264, 21263, 21269, 21274, 21283, 21295, 21297, 21299, 21304, 21312, 21318, 21317, 19991, 21321, 21325, 20950, 21342, 21353, 21358, 22808, 21371, 21367, 21378, 21398, 21408, 21414, 21413, 21422, 21424, 21430, 21443, 31762, 38617, 21471, 26364, 29166, 21486, 21480, 21485, 21498, 21505, 21565, 21568, 21548, 21549, 21564, 21550, 21558, 21545, 21533, 21582, 21647, 21621, 21646, 21599, 21617, 21623, 21616, 21650, 21627, 21632, 21622, 21636, 21648, 21638, 21703, 21666, 21688, 21669, 21676, 21700, 21704, 21672], \"39488\": [21675, 21698, 21668, 21694, 21692, 21720, 21733, 21734, 21775, 21780, 21757, 21742, 21741, 21754, 21730, 21817, 21824, 21859, 21836, 21806, 21852, 21829, 21846, 21847, 21816, 21811, 21853, 21913, 21888, 21679, 21898, 21919, 21883, 21886, 21912, 21918, 21934, 21884, 21891, 21929, 21895, 21928, 21978, 21957, 21983, 21956, 21980, 21988, 21972, 22036, 22007, 22038, 22014, 22013, 22043, 22009, 22094, 22096, 29151, 22068, 22070, 22066, 22072], \"39552\": [22123, 22116, 22063, 22124, 22122, 22150, 22144, 22154, 22176, 22164, 22159, 22181, 22190, 22198, 22196, 22210, 22204, 22209, 22211, 22208, 22216, 22222, 22225, 22227, 22231, 22254, 22265, 22272, 22271, 22276, 22281, 22280, 22283, 22285, 22291, 22296, 22294, 21959, 22300, 22310, 22327, 22328, 22350, 22331, 22336, 22351, 22377, 22464, 22408, 22369, 22399, 22409, 22419, 22432, 22451, 22436, 22442, 22448, 22467, 22470, 22484, 22482, 22483, 22538, 22486, 22499, 22539, 22553, 22557, 22642, 22561, 22626, 22603, 22640, 27584, 22610, 22589, 22649, 22661, 22713, 22687, 22699, 22714, 22750, 22715, 22712, 22702, 22725, 22739, 22737, 22743, 22745, 22744, 22757, 22748, 22756, 22751, 22767, 22778, 22777, 22779, 22780, 22781, 22786, 22794, 22800, 22811, 26790, 22821, 22828, 22829, 22834, 22840, 22846, 31442, 22869, 22864, 22862, 22874, 22872, 22882, 22880, 22887, 22892, 22889], \"39744\": [22904, 22913, 22941, 20318, 20395, 22947, 22962, 22982, 23016, 23004, 22925, 23001, 23002, 23077, 23071, 23057, 23068, 23049, 23066, 23104, 23148, 23113, 23093, 23094, 23138, 23146, 23194, 23228, 23230, 23243, 23234, 23229, 23267, 23255, 23270, 23273, 23254, 23290, 23291, 23308, 23307, 23318, 23346, 23248, 23338, 23350, 23358, 23363, 23365, 23360, 23377, 23381, 23386, 23387, 23397, 23401, 23408, 23411, 23413, 23416, 25992, 23418, 23424], \"39808\": [23427, 23462, 23480, 23491, 23495, 23497, 23508, 23504, 23524, 23526, 23522, 23518, 23525, 23531, 23536, 23542, 23539, 23557, 23559, 23560, 23565, 23571, 23584, 23586, 23592, 23608, 23609, 23617, 23622, 23630, 23635, 23632, 23631, 23409, 23660, 23662, 20066, 23670, 23673, 23692, 23697, 23700, 22939, 23723, 23739, 23734, 23740, 23735, 23749, 23742, 23751, 23769, 23785, 23805, 23802, 23789, 23948, 23786, 23819, 23829, 23831, 23900, 23839, 23835, 23825, 23828, 23842, 23834, 23833, 23832, 23884, 23890, 23886, 23883, 23916, 23923, 23926, 23943, 23940, 23938, 23970, 23965, 23980, 23982, 23997, 23952, 23991, 23996, 24009, 24013, 24019, 24018, 24022, 24027, 24043, 24050, 24053, 24075, 24090, 24089, 24081, 24091, 24118, 24119, 24132, 24131, 24128, 24142, 24151, 24148, 24159, 24162, 24164, 24135, 24181, 24182, 24186, 40636, 24191, 24224, 24257, 24258, 24264, 24272, 24271], \"40000\": [24278, 24291, 24285, 24282, 24283, 24290, 24289, 24296, 24297, 24300, 24305, 24307, 24304, 24308, 24312, 24318, 24323, 24329, 24413, 24412, 24331, 24337, 24342, 24361, 24365, 24376, 24385, 24392, 24396, 24398, 24367, 24401, 24406, 24407, 24409, 24417, 24429, 24435, 24439, 24451, 24450, 24447, 24458, 24456, 24465, 24455, 24478, 24473, 24472, 24480, 24488, 24493, 24508, 24534, 24571, 24548, 24568, 24561, 24541, 24755, 24575, 24609, 24672], \"40064\": [24601, 24592, 24617, 24590, 24625, 24603, 24597, 24619, 24614, 24591, 24634, 24666, 24641, 24682, 24695, 24671, 24650, 24646, 24653, 24675, 24643, 24676, 24642, 24684, 24683, 24665, 24705, 24717, 24807, 24707, 24730, 24708, 24731, 24726, 24727, 24722, 24743, 24715, 24801, 24760, 24800, 24787, 24756, 24560, 24765, 24774, 24757, 24792, 24909, 24853, 24838, 24822, 24823, 24832, 24820, 24826, 24835, 24865, 24827, 24817, 24845, 24846, 24903, 24894, 24872, 24871, 24906, 24895, 24892, 24876, 24884, 24893, 24898, 24900, 24947, 24951, 24920, 24921, 24922, 24939, 24948, 24943, 24933, 24945, 24927, 24925, 24915, 24949, 24985, 24982, 24967, 25004, 24980, 24986, 24970, 24977, 25003, 25006, 25036, 25034, 25033, 25079, 25032, 25027, 25030, 25018, 25035, 32633, 25037, 25062, 25059, 25078, 25082, 25076, 25087, 25085, 25084, 25086, 25088, 25096, 25097, 25101, 25100, 25108, 25115], \"40256\": [25118, 25121, 25130, 25134, 25136, 25138, 25139, 25153, 25166, 25182, 25187, 25179, 25184, 25192, 25212, 25218, 25225, 25214, 25234, 25235, 25238, 25300, 25219, 25236, 25303, 25297, 25275, 25295, 25343, 25286, 25812, 25288, 25308, 25292, 25290, 25282, 25287, 25243, 25289, 25356, 25326, 25329, 25383, 25346, 25352, 25327, 25333, 25424, 25406, 25421, 25628, 25423, 25494, 25486, 25472, 25515, 25462, 25507, 25487, 25481, 25503, 25525, 25451], \"40320\": [25449, 25534, 25577, 25536, 25542, 25571, 25545, 25554, 25590, 25540, 25622, 25652, 25606, 25619, 25638, 25654, 25885, 25623, 25640, 25615, 25703, 25711, 25718, 25678, 25898, 25749, 25747, 25765, 25769, 25736, 25788, 25818, 25810, 25797, 25799, 25787, 25816, 25794, 25841, 25831, 33289, 25824, 25825, 25260, 25827, 25839, 25900, 25846, 25844, 25842, 25850, 25856, 25853, 25880, 25884, 25861, 25892, 25891, 25899, 25908, 25909, 25911, 25910, 25912, 30027, 25928, 25942, 25941, 25933, 25944, 25950, 25949, 25970, 25976, 25986, 25987, 35722, 26011, 26015, 26027, 26039, 26051, 26054, 26049, 26052, 26060, 26066, 26075, 26073, 26080, 26081, 26097, 26482, 26122, 26115, 26107, 26483, 26165, 26166, 26164, 26140, 26191, 26180, 26185, 26177, 26206, 26205, 26212, 26215, 26216, 26207, 26210, 26224, 26243, 26248, 26254, 26249, 26244, 26264, 26269, 26305, 26297, 26313, 26302, 26300], \"40512\": [26308, 26296, 26326, 26330, 26336, 26175, 26342, 26345, 26352, 26357, 26359, 26383, 26390, 26398, 26406, 26407, 38712, 26414, 26431, 26422, 26433, 26424, 26423, 26438, 26462, 26464, 26457, 26467, 26468, 26505, 26480, 26537, 26492, 26474, 26508, 26507, 26534, 26529, 26501, 26551, 26607, 26548, 26604, 26547, 26601, 26552, 26596, 26590, 26589, 26594, 26606, 26553, 26574, 26566, 26599, 27292, 26654, 26694, 26665, 26688, 26701, 26674, 26702], \"40576\": [26803, 26667, 26713, 26723, 26743, 26751, 26783, 26767, 26797, 26772, 26781, 26779, 26755, 27310, 26809, 26740, 26805, 26784, 26810, 26895, 26765, 26750, 26881, 26826, 26888, 26840, 26914, 26918, 26849, 26892, 26829, 26836, 26855, 26837, 26934, 26898, 26884, 26839, 26851, 26917, 26873, 26848, 26863, 26920, 26922, 26906, 26915, 26913, 26822, 27001, 26999, 26972, 27000, 26987, 26964, 27006, 26990, 26937, 26996, 26941, 26969, 26928, 26977, 26974, 26973, 27009, 26986, 27058, 27054, 27088, 27071, 27073, 27091, 27070, 27086, 23528, 27082, 27101, 27067, 27075, 27047, 27182, 27025, 27040, 27036, 27029, 27060, 27102, 27112, 27138, 27163, 27135, 27402, 27129, 27122, 27111, 27141, 27057, 27166, 27117, 27156, 27115, 27146, 27154, 27329, 27171, 27155, 27204, 27148, 27250, 27190, 27256, 27207, 27234, 27225, 27238, 27208, 27192, 27170, 27280, 27277, 27296, 27268, 27298, 27299], \"40768\": [27287, 34327, 27323, 27331, 27330, 27320, 27315, 27308, 27358, 27345, 27359, 27306, 27354, 27370, 27387, 27397, 34326, 27386, 27410, 27414, 39729, 27423, 27448, 27447, 30428, 27449, 39150, 27463, 27459, 27465, 27472, 27481, 27476, 27483, 27487, 27489, 27512, 27513, 27519, 27520, 27524, 27523, 27533, 27544, 27541, 27550, 27556, 27562, 27563, 27567, 27570, 27569, 27571, 27575, 27580, 27590, 27595, 27603, 27615, 27628, 27627, 27635, 27631], \"40832\": [40638, 27656, 27667, 27668, 27675, 27684, 27683, 27742, 27733, 27746, 27754, 27778, 27789, 27802, 27777, 27803, 27774, 27752, 27763, 27794, 27792, 27844, 27889, 27859, 27837, 27863, 27845, 27869, 27822, 27825, 27838, 27834, 27867, 27887, 27865, 27882, 27935, 34893, 27958, 27947, 27965, 27960, 27929, 27957, 27955, 27922, 27916, 28003, 28051, 28004, 27994, 28025, 27993, 28046, 28053, 28644, 28037, 28153, 28181, 28170, 28085, 28103, 28134, 28088, 28102, 28140, 28126, 28108, 28136, 28114, 28101, 28154, 28121, 28132, 28117, 28138, 28142, 28205, 28270, 28206, 28185, 28274, 28255, 28222, 28195, 28267, 28203, 28278, 28237, 28191, 28227, 28218, 28238, 28196, 28415, 28189, 28216, 28290, 28330, 28312, 28361, 28343, 28371, 28349, 28335, 28356, 28338, 28372, 28373, 28303, 28325, 28354, 28319, 28481, 28433, 28748, 28396, 28408, 28414, 28479, 28402, 28465, 28399, 28466, 28364], \"57408\": [28478, 28435, 28407, 28550, 28538, 28536, 28545, 28544, 28527, 28507, 28659, 28525, 28546, 28540, 28504, 28558, 28561, 28610, 28518, 28595, 28579, 28577, 28580, 28601, 28614, 28586, 28639, 28629, 28652, 28628, 28632, 28657, 28654, 28635, 28681, 28683, 28666, 28689, 28673, 28687, 28670, 28699, 28698, 28532, 28701, 28696, 28703, 28720, 28734, 28722, 28753, 28771, 28825, 28818, 28847, 28913, 28844, 28856, 28851, 28846, 28895, 28875, 28893], \"57472\": [28889, 28937, 28925, 28956, 28953, 29029, 29013, 29064, 29030, 29026, 29004, 29014, 29036, 29071, 29179, 29060, 29077, 29096, 29100, 29143, 29113, 29118, 29138, 29129, 29140, 29134, 29152, 29164, 29159, 29173, 29180, 29177, 29183, 29197, 29200, 29211, 29224, 29229, 29228, 29232, 29234, 29243, 29244, 29247, 29248, 29254, 29259, 29272, 29300, 29310, 29314, 29313, 29319, 29330, 29334, 29346, 29351, 29369, 29362, 29379, 29382, 29380, 29390, 29394, 29410, 29408, 29409, 29433, 29431, 20495, 29463, 29450, 29468, 29462, 29469, 29492, 29487, 29481, 29477, 29502, 29518, 29519, 40664, 29527, 29546, 29544, 29552, 29560, 29557, 29563, 29562, 29640, 29619, 29646, 29627, 29632, 29669, 29678, 29662, 29858, 29701, 29807, 29733, 29688, 29746, 29754, 29781, 29759, 29791, 29785, 29761, 29788, 29801, 29808, 29795, 29802, 29814, 29822, 29835, 29854, 29863, 29898, 29903, 29908, 29681], \"57664\": [29920, 29923, 29927, 29929, 29934, 29938, 29936, 29937, 29944, 29943, 29956, 29955, 29957, 29964, 29966, 29965, 29973, 29971, 29982, 29990, 29996, 30012, 30020, 30029, 30026, 30025, 30043, 30022, 30042, 30057, 30052, 30055, 30059, 30061, 30072, 30070, 30086, 30087, 30068, 30090, 30089, 30082, 30100, 30106, 30109, 30117, 30115, 30146, 30131, 30147, 30133, 30141, 30136, 30140, 30129, 30157, 30154, 30162, 30169, 30179, 30174, 30206, 30207], \"57728\": [30204, 30209, 30192, 30202, 30194, 30195, 30219, 30221, 30217, 30239, 30247, 30240, 30241, 30242, 30244, 30260, 30256, 30267, 30279, 30280, 30278, 30300, 30296, 30305, 30306, 30312, 30313, 30314, 30311, 30316, 30320, 30322, 30326, 30328, 30332, 30336, 30339, 30344, 30347, 30350, 30358, 30355, 30361, 30362, 30384, 30388, 30392, 30393, 30394, 30402, 30413, 30422, 30418, 30430, 30433, 30437, 30439, 30442, 34351, 30459, 30472, 30471, 30468, 30505, 30500, 30494, 30501, 30502, 30491, 30519, 30520, 30535, 30554, 30568, 30571, 30555, 30565, 30591, 30590, 30585, 30606, 30603, 30609, 30624, 30622, 30640, 30646, 30649, 30655, 30652, 30653, 30651, 30663, 30669, 30679, 30682, 30684, 30691, 30702, 30716, 30732, 30738, 31014, 30752, 31018, 30789, 30862, 30836, 30854, 30844, 30874, 30860, 30883, 30901, 30890, 30895, 30929, 30918, 30923, 30932, 30910, 30908, 30917, 30922, 30956], \"57920\": [30951, 30938, 30973, 30964, 30983, 30994, 30993, 31001, 31020, 31019, 31040, 31072, 31063, 31071, 31066, 31061, 31059, 31098, 31103, 31114, 31133, 31143, 40779, 31146, 31150, 31155, 31161, 31162, 31177, 31189, 31207, 31212, 31201, 31203, 31240, 31245, 31256, 31257, 31264, 31263, 31104, 31281, 31291, 31294, 31287, 31299, 31319, 31305, 31329, 31330, 31337, 40861, 31344, 31353, 31357, 31368, 31383, 31381, 31384, 31382, 31401, 31432, 31408], \"57984\": [31414, 31429, 31428, 31423, 36995, 31431, 31434, 31437, 31439, 31445, 31443, 31449, 31450, 31453, 31457, 31458, 31462, 31469, 31472, 31490, 31503, 31498, 31494, 31539, 31512, 31513, 31518, 31541, 31528, 31542, 31568, 31610, 31492, 31565, 31499, 31564, 31557, 31605, 31589, 31604, 31591, 31600, 31601, 31596, 31598, 31645, 31640, 31647, 31629, 31644, 31642, 31627, 31634, 31631, 31581, 31641, 31691, 31681, 31692, 31695, 31668, 31686, 31709, 31721, 31761, 31764, 31718, 31717, 31840, 31744, 31751, 31763, 31731, 31735, 31767, 31757, 31734, 31779, 31783, 31786, 31775, 31799, 31787, 31805, 31820, 31811, 31828, 31823, 31808, 31824, 31832, 31839, 31844, 31830, 31845, 31852, 31861, 31875, 31888, 31908, 31917, 31906, 31915, 31905, 31912, 31923, 31922, 31921, 31918, 31929, 31933, 31936, 31941, 31938, 31960, 31954, 31964, 31970, 39739, 31983, 31986, 31988, 31990, 31994, 32006], \"58176\": [32002, 32028, 32021, 32010, 32069, 32075, 32046, 32050, 32063, 32053, 32070, 32115, 32086, 32078, 32114, 32104, 32110, 32079, 32099, 32147, 32137, 32091, 32143, 32125, 32155, 32186, 32174, 32163, 32181, 32199, 32189, 32171, 32317, 32162, 32175, 32220, 32184, 32159, 32176, 32216, 32221, 32228, 32222, 32251, 32242, 32225, 32261, 32266, 32291, 32289, 32274, 32305, 32287, 32265, 32267, 32290, 32326, 32358, 32315, 32309, 32313, 32323, 32311], \"58240\": [32306, 32314, 32359, 32349, 32342, 32350, 32345, 32346, 32377, 32362, 32361, 32380, 32379, 32387, 32213, 32381, 36782, 32383, 32392, 32393, 32396, 32402, 32400, 32403, 32404, 32406, 32398, 32411, 32412, 32568, 32570, 32581, 32588, 32589, 32590, 32592, 32593, 32597, 32596, 32600, 32607, 32608, 32616, 32617, 32615, 32632, 32642, 32646, 32643, 32648, 32647, 32652, 32660, 32670, 32669, 32666, 32675, 32687, 32690, 32697, 32686, 32694, 32696, 35697, 32709, 32710, 32714, 32725, 32724, 32737, 32742, 32745, 32755, 32761, 39132, 32774, 32772, 32779, 32786, 32792, 32793, 32796, 32801, 32808, 32831, 32827, 32842, 32838, 32850, 32856, 32858, 32863, 32866, 32872, 32883, 32882, 32880, 32886, 32889, 32893, 32895, 32900, 32902, 32901, 32923, 32915, 32922, 32941, 20880, 32940, 32987, 32997, 32985, 32989, 32964, 32986, 32982, 33033, 33007, 33009, 33051, 33065, 33059, 33071, 33099], \"58432\": [38539, 33094, 33086, 33107, 33105, 33020, 33137, 33134, 33125, 33126, 33140, 33155, 33160, 33162, 33152, 33154, 33184, 33173, 33188, 33187, 33119, 33171, 33193, 33200, 33205, 33214, 33208, 33213, 33216, 33218, 33210, 33225, 33229, 33233, 33241, 33240, 33224, 33242, 33247, 33248, 33255, 33274, 33275, 33278, 33281, 33282, 33285, 33287, 33290, 33293, 33296, 33302, 33321, 33323, 33336, 33331, 33344, 33369, 33368, 33373, 33370, 33375, 33380], \"58496\": [33378, 33384, 33386, 33387, 33326, 33393, 33399, 33400, 33406, 33421, 33426, 33451, 33439, 33467, 33452, 33505, 33507, 33503, 33490, 33524, 33523, 33530, 33683, 33539, 33531, 33529, 33502, 33542, 33500, 33545, 33497, 33589, 33588, 33558, 33586, 33585, 33600, 33593, 33616, 33605, 33583, 33579, 33559, 33560, 33669, 33690, 33706, 33695, 33698, 33686, 33571, 33678, 33671, 33674, 33660, 33717, 33651, 33653, 33696, 33673, 33704, 33780, 33811, 33771, 33742, 33789, 33795, 33752, 33803, 33729, 33783, 33799, 33760, 33778, 33805, 33826, 33824, 33725, 33848, 34054, 33787, 33901, 33834, 33852, 34138, 33924, 33911, 33899, 33965, 33902, 33922, 33897, 33862, 33836, 33903, 33913, 33845, 33994, 33890, 33977, 33983, 33951, 34009, 33997, 33979, 34010, 34000, 33985, 33990, 34006, 33953, 34081, 34047, 34036, 34071, 34072, 34092, 34079, 34069, 34068, 34044, 34112, 34147, 34136, 34120], \"58688\": [34113, 34306, 34123, 34133, 34176, 34212, 34184, 34193, 34186, 34216, 34157, 34196, 34203, 34282, 34183, 34204, 34167, 34174, 34192, 34249, 34234, 34255, 34233, 34256, 34261, 34269, 34277, 34268, 34297, 34314, 34323, 34315, 34302, 34298, 34310, 34338, 34330, 34352, 34367, 34381, 20053, 34388, 34399, 34407, 34417, 34451, 34467, 34473, 34474, 34443, 34444, 34486, 34479, 34500, 34502, 34480, 34505, 34851, 34475, 34516, 34526, 34537, 34540], \"58752\": [34527, 34523, 34543, 34578, 34566, 34568, 34560, 34563, 34555, 34577, 34569, 34573, 34553, 34570, 34612, 34623, 34615, 34619, 34597, 34601, 34586, 34656, 34655, 34680, 34636, 34638, 34676, 34647, 34664, 34670, 34649, 34643, 34659, 34666, 34821, 34722, 34719, 34690, 34735, 34763, 34749, 34752, 34768, 38614, 34731, 34756, 34739, 34759, 34758, 34747, 34799, 34802, 34784, 34831, 34829, 34814, 34806, 34807, 34830, 34770, 34833, 34838, 34837, 34850, 34849, 34865, 34870, 34873, 34855, 34875, 34884, 34882, 34898, 34905, 34910, 34914, 34923, 34945, 34942, 34974, 34933, 34941, 34997, 34930, 34946, 34967, 34962, 34990, 34969, 34978, 34957, 34980, 34992, 35007, 34993, 35011, 35012, 35028, 35032, 35033, 35037, 35065, 35074, 35068, 35060, 35048, 35058, 35076, 35084, 35082, 35091, 35139, 35102, 35109, 35114, 35115, 35137, 35140, 35131, 35126, 35128, 35148, 35101, 35168, 35166], \"58944\": [35174, 35172, 35181, 35178, 35183, 35188, 35191, 35198, 35203, 35208, 35210, 35219, 35224, 35233, 35241, 35238, 35244, 35247, 35250, 35258, 35261, 35263, 35264, 35290, 35292, 35293, 35303, 35316, 35320, 35331, 35350, 35344, 35340, 35355, 35357, 35365, 35382, 35393, 35419, 35410, 35398, 35400, 35452, 35437, 35436, 35426, 35461, 35458, 35460, 35496, 35489, 35473, 35493, 35494, 35482, 35491, 35524, 35533, 35522, 35546, 35563, 35571, 35559], \"59008\": [35556, 35569, 35604, 35552, 35554, 35575, 35550, 35547, 35596, 35591, 35610, 35553, 35606, 35600, 35607, 35616, 35635, 38827, 35622, 35627, 35646, 35624, 35649, 35660, 35663, 35662, 35657, 35670, 35675, 35674, 35691, 35679, 35692, 35695, 35700, 35709, 35712, 35724, 35726, 35730, 35731, 35734, 35737, 35738, 35898, 35905, 35903, 35912, 35916, 35918, 35920, 35925, 35938, 35948, 35960, 35962, 35970, 35977, 35973, 35978, 35981, 35982, 35988, 35964, 35992, 25117, 36013, 36010, 36029, 36018, 36019, 36014, 36022, 36040, 36033, 36068, 36067, 36058, 36093, 36090, 36091, 36100, 36101, 36106, 36103, 36111, 36109, 36112, 40782, 36115, 36045, 36116, 36118, 36199, 36205, 36209, 36211, 36225, 36249, 36290, 36286, 36282, 36303, 36314, 36310, 36300, 36315, 36299, 36330, 36331, 36319, 36323, 36348, 36360, 36361, 36351, 36381, 36382, 36368, 36383, 36418, 36405, 36400, 36404, 36426], \"59200\": [36423, 36425, 36428, 36432, 36424, 36441, 36452, 36448, 36394, 36451, 36437, 36470, 36466, 36476, 36481, 36487, 36485, 36484, 36491, 36490, 36499, 36497, 36500, 36505, 36522, 36513, 36524, 36528, 36550, 36529, 36542, 36549, 36552, 36555, 36571, 36579, 36604, 36603, 36587, 36606, 36618, 36613, 36629, 36626, 36633, 36627, 36636, 36639, 36635, 36620, 36646, 36659, 36667, 36665, 36677, 36674, 36670, 36684, 36681, 36678, 36686, 36695, 36700], \"59264\": [36706, 36707, 36708, 36764, 36767, 36771, 36781, 36783, 36791, 36826, 36837, 36834, 36842, 36847, 36999, 36852, 36869, 36857, 36858, 36881, 36885, 36897, 36877, 36894, 36886, 36875, 36903, 36918, 36917, 36921, 36856, 36943, 36944, 36945, 36946, 36878, 36937, 36926, 36950, 36952, 36958, 36968, 36975, 36982, 38568, 36978, 36994, 36989, 36993, 36992, 37002, 37001, 37007, 37032, 37039, 37041, 37045, 37090, 37092, 25160, 37083, 37122, 37138, 37145, 37170, 37168, 37194, 37206, 37208, 37219, 37221, 37225, 37235, 37234, 37259, 37257, 37250, 37282, 37291, 37295, 37290, 37301, 37300, 37306, 37312, 37313, 37321, 37323, 37328, 37334, 37343, 37345, 37339, 37372, 37365, 37366, 37406, 37375, 37396, 37420, 37397, 37393, 37470, 37463, 37445, 37449, 37476, 37448, 37525, 37439, 37451, 37456, 37532, 37526, 37523, 37531, 37466, 37583, 37561, 37559, 37609, 37647, 37626, 37700, 37678], \"59456\": [37657, 37666, 37658, 37667, 37690, 37685, 37691, 37724, 37728, 37756, 37742, 37718, 37808, 37804, 37805, 37780, 37817, 37846, 37847, 37864, 37861, 37848, 37827, 37853, 37840, 37832, 37860, 37914, 37908, 37907, 37891, 37895, 37904, 37942, 37931, 37941, 37921, 37946, 37953, 37970, 37956, 37979, 37984, 37986, 37982, 37994, 37417, 38000, 38005, 38007, 38013, 37978, 38012, 38014, 38017, 38015, 38274, 38279, 38282, 38292, 38294, 38296, 38297], \"59520\": [38304, 38312, 38311, 38317, 38332, 38331, 38329, 38334, 38346, 28662, 38339, 38349, 38348, 38357, 38356, 38358, 38364, 38369, 38373, 38370, 38433, 38440, 38446, 38447, 38466, 38476, 38479, 38475, 38519, 38492, 38494, 38493, 38495, 38502, 38514, 38508, 38541, 38552, 38549, 38551, 38570, 38567, 38577, 38578, 38576, 38580, 38582, 38584, 38585, 38606, 38603, 38601, 38605, 35149, 38620, 38669, 38613, 38649, 38660, 38662, 38664, 38675, 38670, 38673, 38671, 38678, 38681, 38692, 38698, 38704, 38713, 38717, 38718, 38724, 38726, 38728, 38722, 38729, 38748, 38752, 38756, 38758, 38760, 21202, 38763, 38769, 38777, 38789, 38780, 38785, 38778, 38790, 38795, 38799, 38800, 38812, 38824, 38822, 38819, 38835, 38836, 38851, 38854, 38856, 38859, 38876, 38893, 40783, 38898, 31455, 38902, 38901, 38927, 38924, 38968, 38948, 38945, 38967, 38973, 38982, 38991, 38987, 39019, 39023, 39024], \"59712\": [39025, 39028, 39027, 39082, 39087, 39089, 39094, 39108, 39107, 39110, 39145, 39147, 39171, 39177, 39186, 39188, 39192, 39201, 39197, 39198, 39204, 39200, 39212, 39214, 39229, 39230, 39234, 39241, 39237, 39248, 39243, 39249, 39250, 39244, 39253, 39319, 39320, 39333, 39341, 39342, 39356, 39391, 39387, 39389, 39384, 39377, 39405, 39406, 39409, 39410, 39419, 39416, 39425, 39439, 39429, 39394, 39449, 39467, 39479, 39493, 39490, 39488, 39491], \"59776\": [39486, 39509, 39501, 39515, 39511, 39519, 39522, 39525, 39524, 39529, 39531, 39530, 39597, 39600, 39612, 39616, 39631, 39633, 39635, 39636, 39646, 39647, 39650, 39651, 39654, 39663, 39659, 39662, 39668, 39665, 39671, 39675, 39686, 39704, 39706, 39711, 39714, 39715, 39717, 39719, 39720, 39721, 39722, 39726, 39727, 39730, 39748, 39747, 39759, 39757, 39758, 39761, 39768, 39796, 39827, 39811, 39825, 39830, 39831, 39839, 39840, 39848, 39860, 39872, 39882, 39865, 39878, 39887, 39889, 39890, 39907, 39906, 39908, 39892, 39905, 39994, 39922, 39921, 39920, 39957, 39956, 39945, 39955, 39948, 39942, 39944, 39954, 39946, 39940, 39982, 39963, 39973, 39972, 39969, 39984, 40007, 39986, 40006, 39998, 40026, 40032, 40039, 40054, 40056, 40167, 40172, 40176, 40201, 40200, 40171, 40195, 40198, 40234, 40230, 40367, 40227, 40223, 40260, 40213, 40210, 40257, 40255, 40254, 40262, 40264], \"59968\": [40285, 40286, 40292, 40273, 40272, 40281, 40306, 40329, 40327, 40363, 40303, 40314, 40346, 40356, 40361, 40370, 40388, 40385, 40379, 40376, 40378, 40390, 40399, 40386, 40409, 40403, 40440, 40422, 40429, 40431, 40445, 40474, 40475, 40478, 40565, 40569, 40573, 40577, 40584, 40587, 40588, 40594, 40597, 40593, 40605, 40613, 40617, 40632, 40618, 40621, 38753, 40652, 40654, 40655, 40656, 40660, 40668, 40670, 40669, 40672, 40677, 40680, 40687], \"60032\": [40692, 40694, 40695, 40697, 40699, 40700, 40701, 40711, 40712, 30391, 40725, 40737, 40748, 40766, 40778, 40786, 40788, 40803, 40799, 40800, 40801, 40806, 40807, 40812, 40810, 40823, 40818, 40822, 40853, 40860, 40864, 22575, 27079, 36953, 29796, 20956, 29081], \"60736\": [32394, 35100, 37704, 37512, 34012, 20425, 28859, 26161, 26824, 37625, 26363, 24389, 20008, 20193, 20220, 20224, 20227, 20281, 20310, 20370, 20362, 20378, 20372, 20429, 20544, 20514, 20479, 20510, 20550, 20592, 20546, 20628, 20724, 20696, 20810, 20836, 20893, 20926, 20972, 21013, 21148, 21158, 21184, 21211, 21248, 21255, 21284, 21362, 21395, 21426, 21469, 64014, 21660, 21642, 21673, 21759, 21894, 22361, 22373, 22444, 22472, 22471, 64015], \"60800\": [64016, 22686, 22706, 22795, 22867, 22875, 22877, 22883, 22948, 22970, 23382, 23488, 29999, 23512, 23532, 23582, 23718, 23738, 23797, 23847, 23891, 64017, 23874, 23917, 23992, 23993, 24016, 24353, 24372, 24423, 24503, 24542, 24669, 24709, 24714, 24798, 24789, 24864, 24818, 24849, 24887, 24880, 24984, 25107, 25254, 25589, 25696, 25757, 25806, 25934, 26112, 26133, 26171, 26121, 26158, 26142, 26148, 26213, 26199, 26201, 64018, 26227, 26265, 26272, 26290, 26303, 26362, 26382, 63785, 26470, 26555, 26706, 26560, 26625, 26692, 26831, 64019, 26984, 64020, 27032, 27106, 27184, 27243, 27206, 27251, 27262, 27362, 27364, 27606, 27711, 27740, 27782, 27759, 27866, 27908, 28039, 28015, 28054, 28076, 28111, 28152, 28146, 28156, 28217, 28252, 28199, 28220, 28351, 28552, 28597, 28661, 28677, 28679, 28712, 28805, 28843, 28943, 28932, 29020, 28998, 28999, 64021, 29121, 29182, 29361], \"60992\": [29374, 29476, 64022, 29559, 29629, 29641, 29654, 29667, 29650, 29703, 29685, 29734, 29738, 29737, 29742, 29794, 29833, 29855, 29953, 30063, 30338, 30364, 30366, 30363, 30374, 64023, 30534, 21167, 30753, 30798, 30820, 30842, 31024, 64024, 64025, 64026, 31124, 64027, 31131, 31441, 31463, 64028, 31467, 31646, 64029, 32072, 32092, 32183, 32160, 32214, 32338, 32583, 32673, 64030, 33537, 33634, 33663, 33735, 33782, 33864, 33972, 34131, 34137], \"61056\": [34155, 64031, 34224, 64032, 64033, 34823, 35061, 35346, 35383, 35449, 35495, 35518, 35551, 64034, 35574, 35667, 35711, 36080, 36084, 36114, 36214, 64035, 36559, 64036, 64037, 36967, 37086, 64038, 37141, 37159, 37338, 37335, 37342, 37357, 37358, 37348, 37349, 37382, 37392, 37386, 37434, 37440, 37436, 37454, 37465, 37457, 37433, 37479, 37543, 37495, 37496, 37607, 37591, 37593, 37584, 64039, 37589, 37600, 37587, 37669, 37665, 37627, 64040, 37662, 37631, 37661, 37634, 37744, 37719, 37796, 37830, 37854, 37880, 37937, 37957, 37960, 38290, 63964, 64041, 38557, 38575, 38707, 38715, 38723, 38733, 38735, 38737, 38741, 38999, 39013, 64042, 64043, 39207, 64044, 39326, 39502, 39641, 39644, 39797, 39794, 39823, 39857, 39867, 39936, 40304, 40299, 64045, 40473, 40657], \"61167\": [8560, 8561, 8562, 8563, 8564, 8565, 8566, 8567, 8568, 8569, 65506, 65508, 65287, 65282], \"64064\": [8560, 8561, 8562, 8563, 8564, 8565, 8566, 8567, 8568, 8569, 8544, 8545, 8546, 8547, 8548, 8549, 8550, 8551, 8552, 8553, 65506, 65508, 65287, 65282, 12849, 8470, 8481, 8757, 32394, 35100, 37704, 37512, 34012, 20425, 28859, 26161, 26824, 37625, 26363, 24389, 20008, 20193, 20220, 20224, 20227, 20281, 20310, 20370, 20362, 20378, 20372, 20429, 20544, 20514, 20479, 20510, 20550, 20592, 20546, 20628, 20724, 20696, 20810], \"64128\": [20836, 20893, 20926, 20972, 21013, 21148, 21158, 21184, 21211, 21248, 21255, 21284, 21362, 21395, 21426, 21469, 64014, 21660, 21642, 21673, 21759, 21894, 22361, 22373, 22444, 22472, 22471, 64015, 64016, 22686, 22706, 22795, 22867, 22875, 22877, 22883, 22948, 22970, 23382, 23488, 29999, 23512, 23532, 23582, 23718, 23738, 23797, 23847, 23891, 64017, 23874, 23917, 23992, 23993, 24016, 24353, 24372, 24423, 24503, 24542, 24669, 24709, 24714, 24798, 24789, 24864, 24818, 24849, 24887, 24880, 24984, 25107, 25254, 25589, 25696, 25757, 25806, 25934, 26112, 26133, 26171, 26121, 26158, 26142, 26148, 26213, 26199, 26201, 64018, 26227, 26265, 26272, 26290, 26303, 26362, 26382, 63785, 26470, 26555, 26706, 26560, 26625, 26692, 26831, 64019, 26984, 64020, 27032, 27106, 27184, 27243, 27206, 27251, 27262, 27362, 27364, 27606, 27711, 27740, 27782, 27759, 27866, 27908, 28039, 28015], \"64320\": [28054, 28076, 28111, 28152, 28146, 28156, 28217, 28252, 28199, 28220, 28351, 28552, 28597, 28661, 28677, 28679, 28712, 28805, 28843, 28943, 28932, 29020, 28998, 28999, 64021, 29121, 29182, 29361, 29374, 29476, 64022, 29559, 29629, 29641, 29654, 29667, 29650, 29703, 29685, 29734, 29738, 29737, 29742, 29794, 29833, 29855, 29953, 30063, 30338, 30364, 30366, 30363, 30374, 64023, 30534, 21167, 30753, 30798, 30820, 30842, 31024, 64024, 64025], \"64384\": [64026, 31124, 64027, 31131, 31441, 31463, 64028, 31467, 31646, 64029, 32072, 32092, 32183, 32160, 32214, 32338, 32583, 32673, 64030, 33537, 33634, 33663, 33735, 33782, 33864, 33972, 34131, 34137, 34155, 64031, 34224, 64032, 64033, 34823, 35061, 35346, 35383, 35449, 35495, 35518, 35551, 64034, 35574, 35667, 35711, 36080, 36084, 36114, 36214, 64035, 36559, 64036, 64037, 36967, 37086, 64038, 37141, 37159, 37338, 37335, 37342, 37357, 37358, 37348, 37349, 37382, 37392, 37386, 37434, 37440, 37436, 37454, 37465, 37457, 37433, 37479, 37543, 37495, 37496, 37607, 37591, 37593, 37584, 64039, 37589, 37600, 37587, 37669, 37665, 37627, 64040, 37662, 37631, 37661, 37634, 37744, 37719, 37796, 37830, 37854, 37880, 37937, 37957, 37960, 38290, 63964, 64041, 38557, 38575, 38707, 38715, 38723, 38733, 38735, 38737, 38741, 38999, 39013, 64042, 64043, 39207, 64044, 39326, 39502, 39641], \"64576\": [39644, 39797, 39794, 39823, 39857, 39867, 39936, 40304, 40299, 64045, 40473, 40657]}\nvar decoding_table = [],\n encoding_table = []\nfor(let cp in cps){\n cp = parseInt(cp)\n for(let i = 0, len = cps[cp].length; i < len; i++){\n let key = cp + i,\n value = cps[cp][i]\n decoding_table[key] = value\n encoding_table[value] = key\n }\n}\nvar module = {encoding_table, decoding_table}\n__BRYTHON__.addToImported(\"encoding_cp932\", module)\n"], "hashlib": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nvar block_size = {\n md5: 64,\n sha1: 64,\n sha224: 64,\n sha256: 64,\n sha384: 128,\n sha512: 128\n}\n\nvar $mod = {\n\n __getattr__ : function(attr){\n if(attr == 'new'){\n return hash.$factory\n }\n throw $B.attr_error(attr, $mod)\n },\n md5: function(obj){return hash.$factory('md5', obj)},\n sha1: function(obj){return hash.$factory('sha1', obj)},\n sha224: function(obj){return hash.$factory('sha224', obj)},\n sha256: function(obj){return hash.$factory('sha256', obj)},\n sha384: function(obj){return hash.$factory('sha384', obj)},\n sha512: function(obj){return hash.$factory('sha512', obj)},\n\n algorithms_guaranteed: ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],\n algorithms_available: ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']\n}\n\n//todo: eventually move this function to a \"utility\" file or use ajax module?\nfunction $get_CryptoJS_lib(alg){\n if($B.VFS !== undefined && $B.VFS.hashlib){\n // use file in brython_stdlib.js\n var lib = $B.VFS[\"crypto_js.rollups.\" + alg]\n if (lib === undefined){\n throw _b_.ImportError.$factory(\"can't import hashlib.\" + alg)\n }\n var res = lib[1]\n try{\n eval(res + \"; $B.CryptoJS = CryptoJS;\")\n return\n }catch(err){\n throw Error(\"JS Eval Error\",\n \"Cannot eval CryptoJS algorithm '\" + alg + \"' : error:\" + err)\n }\n }\n\n var module = {__name__: 'CryptoJS', $is_package: false}\n var res = $B.$download_module(module, $B.brython_path + 'libs/crypto_js/rollups/' + alg + '.js');\n\n try{\n eval(res + \"; $B.CryptoJS = CryptoJS;\")\n }catch(err){\n throw Error(\"JS Eval Error\",\n \"Cannot eval CryptoJS algorithm '\" + alg + \"' : error:\" + err)\n }\n}\n\nfunction bytes2WordArray(obj){\n // Transform a bytes object into an instance of class WordArray\n // defined in CryptoJS\n if(!$B.$isinstance(obj, _b_.bytes)){\n throw _b_.TypeError(\"expected bytes, got \" + $B.class_name(obj))\n }\n\n var words = []\n for(var i = 0; i < obj.source.length; i += 4){\n var word = obj.source.slice(i, i + 4)\n while(word.length < 4){word.push(0)}\n var w = word[3] + (word[2] << 8) + (word[1] << 16) + (word[0] << 24)\n words.push(w)\n }\n return {words: words, sigBytes: obj.source.length}\n}\n\nvar hash = {\n __class__: _b_.type,\n __mro__: [_b_.object],\n __qualname__: 'hash',\n __name__: 'hash'\n}\n\nhash.update = function(self, msg){\n self.hash.update(bytes2WordArray(msg))\n}\n\nhash.copy = function(self){\n return self.hash.clone()\n}\n\nhash.digest = function(self){\n var obj = self.hash.clone().finalize().toString(),\n res = []\n for(var i = 0; i < obj.length; i += 2){\n res.push(parseInt(obj.substr(i, 2), 16))\n }\n return _b_.bytes.$factory(res)\n}\n\nhash.hexdigest = function(self) {\n return self.hash.clone().finalize().toString()\n}\n\nhash.$factory = function(alg, obj) {\n var res = {\n __class__: hash\n }\n\n switch(alg) {\n case 'md5':\n case 'sha1':\n case 'sha224':\n case 'sha256':\n case 'sha384':\n case 'sha512':\n var ALG = alg.toUpperCase()\n if($B.Crypto === undefined ||\n $B.CryptoJS.algo[ALG] === undefined){$get_CryptoJS_lib(alg)}\n\n res.hash = $B.CryptoJS.algo[ALG].create()\n if(obj !== undefined){\n res.hash.update(bytes2WordArray(obj))\n }\n break\n default:\n throw $B.builtins.AttributeError.$factory('Invalid hash algorithm: ' + alg)\n }\n res.digest_size = res.hash._hash.sigBytes\n res.block_size = block_size[alg]\n return res\n}\n\n$B.addToImported('hashlib', $mod)\n\n})(__BRYTHON__)\n"], "html_parser": [".js", "(function($B){\n\n_b_ = $B.builtins\n\nvar ELEMENT_NODE = 1,\n TEXT_NODE = 3,\n COMMENT_NODE = 8,\n DOCUMENT_TYPE_NODE = 10\n\nvar HTMLNode = $B.make_class(\"HTMLNode\",\n function(){\n return {\n __class__: HTMLNode,\n nodeType: TEXT_NODE,\n text: \"\"\n }\n }\n)\n\nHTMLNode.__str__ = function(self){\n return self.text\n}\n\n$B.set_func_names(HTMLNode, \"_html_parser\")\n\nfunction* tokenize(src){\n var node = HTMLNode.$factory(),\n pos = 0,\n tag = \"\",\n type = \"text\"\n while(pos < src.length){\n var char = src[pos]\n switch(type){\n case \"text\":\n if(char == \"<\"){\n // starts a tag if immediately followed by a letter or by /\n var tag_mo = /^(\\/?)[a-zA-Z]+/.exec(src.substr(pos + 1))\n if(tag_mo){\n yield node\n node = HTMLNode.$factory()\n type = \"tag\"\n node.tagName = \"\"\n node.nodeType = ELEMENT_NODE\n node.closing = tag_mo[1] != \"\"\n node.attrs = []\n }else{\n // doctype declaration\n var decl_mo = /^/i.exec(src.substr(pos))\n if(decl_mo){\n yield node\n node = HTMLNode.$factory()\n node.text = decl_mo[0]\n node.doctype = decl_mo[1]\n node.nodeType = DOCUMENT_TYPE_NODE\n yield node\n node = HTMLNode.$factory()\n type = \"text\"\n pos += decl_mo[0].length\n break\n }else{\n // comment\n var comment_mo = /^\\/.exec(src.substr(pos))\n if(comment_mo){\n yield node\n node = HTMLNode.$factory()\n node.text = comment_mo[0]\n node.comment = comment_mo[1]\n node.nodeType = COMMENT_NODE\n yield node\n node = HTMLNode.$factory()\n type = \"text\"\n pos += comment_mo[0].length\n break\n }\n }\n }\n }\n pos++\n node.text += char\n break\n case \"tag\":\n if(char.search(/[_a-zA-Z]/) > -1){\n var mo = /\\w+/.exec(src.substr(pos))\n if(mo !== null){\n pos += mo[0].length\n if(node.tagName == \"\"){\n node.tagName = mo[0].toUpperCase()\n }\n node.text += mo[0]\n }else{\n pos++\n }\n }else if(char == \">\"){\n node.text += char\n yield node\n node = HTMLNode.$factory()\n type = \"text\"\n pos++\n }else if(char == \"=\"){\n node.text += char\n pos++\n }else if(char == \"'\" || char == '\"'){\n var i = pos + 1,\n found_string_end = false\n while(i < src.length){\n if(src[i] == char){\n var nb_escape = 0\n while(src[i - 1 - nb_escape] == '/'){\n nb_escape++\n }\n if(nb_escape % 2 == 0){\n node.text += src.substr(pos, i + 1 - pos)\n pos = i + 1\n found_string_end = true\n break\n }else{\n i++\n }\n }else if(src[i] == '>'){\n break\n }else{\n i++\n }\n }\n if(! found_string_end){\n // unterminated string: ignore\n pos++\n }\n }else{\n node.text += char\n pos++\n }\n break\n default:\n pos++\n }\n }\n yield node\n}\nvar module = {\n ELEMENT_NODE: 1,\n TEXT_NODE: 3,\n COMMENT_NODE: 8,\n DOCUMENT_TYPE_NODE: 10,\n tokenize: tokenize\n}\n\n$B.addToImported('html_parser', module)\n\n})(__BRYTHON__)\n"], "marshal": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nvar module = {\n loads: function(){\n var $ = $B.args('loads', 1, {obj:null}, ['obj'], arguments, {},\n null, null)\n return $B.structuredclone2pyobj(JSON.parse($.obj))\n },\n load: function(){\n var $ = $B.args('load', 1, {file:null}, ['file'], arguments, {},\n null, null)\n var content = $B.$call($B.$getattr($.file, \"read\"))()\n return $module.loads(_b_.bytes.decode(content, \"latin-1\"));\n },\n dump: function(){\n var $ = $B.args('dump', 2, {value:null, file: null},\n ['value', 'file'], arguments, {}, null, null)\n var s = JSON.stringify($B.pyobj2structuredclone($.value))\n $B.$getattr($.file, \"write\")(_b_.str.encode(s, 'latin-1'))\n var flush = $B.$getattr($.file, \"flush\", null)\n if(flush !== null){\n $B.$call(flush)()\n }\n return _b_.None\n },\n dumps: function(){\n var $ = $B.args('dumps', 1, {obj:null}, ['obj'], arguments, {},\n null, null)\n return JSON.stringify($B.pyobj2structuredclone($.obj))\n }\n}\n\n$B.addToImported('marshal', module)\n\n})(__BRYTHON__)\n"], "math": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nconst INF = $B.fast_float(Number.POSITIVE_INFINITY),\n NINF = $B.fast_float(Number.NEGATIVE_INFINITY),\n ZERO = $B.fast_float(0),\n NAN = $B.fast_float(Number.NaN)\n\nvar float_check = function(x) {\n // Returns a Javascript number\n if(x.__class__ === $B.long_int){\n var res = parseInt(x.value)\n if(! isFinite(res)){\n throw _b_.OverflowError.$factory('int too big for float')\n }\n return res\n }else if(x.__class__ === _b_.float){\n return x.value\n }\n try{\n return _b_.float.$factory(x).value\n }catch(err){\n throw _b_.TypeError.$factory('must be real number, not ' +\n $B.class_name(x))\n }\n}\n\nfunction check_int(x){\n if(! $B.$isinstance(x, _b_.int)){\n throw _b_.TypeError.$factory(\"'\" + $B.class_name(x) +\n \"' object cannot be interpreted as an integer\")\n }\n}\n\nfunction check_int_or_round_float(x){\n return ($B.$isinstance(x, _b_.float) && Number.isInteger(x.value)) ||\n $B.$isinstance(x, _b_.int)\n}\n\nvar isWholeNumber = function(x){return (x * 10) % 10 == 0}\n\nvar isOdd = function(x) {return isWholeNumber(x) && 2 * Math.floor(x / 2) != x}\n\nvar isNegZero = function(x) {return x === 0 && Math.atan2(x,x) < 0}\n\nfunction overflow(){\n throw _b_.OverflowError.$factory(\"math range error\")\n}\n\nfunction value_error(){\n throw _b_.ValueError.$factory(\"math range error\")\n}\n\nvar EPSILON = Math.pow(2, -52),\n MAX_VALUE = (2 - EPSILON) * Math.pow(2, 1023),\n MIN_VALUE = Math.pow(2, -1022),\n Py_HUGE_VAL = Number.POSITIVE_INFINITY,\n logpi = 1.144729885849400174143427351353058711647,\n sqrtpi = 1.772453850905516027298167483341145182798\n\nfunction nextUp(x){\n if(x !== x){ // NaN\n return x\n }\n if(_b_.float.$funcs.isinf(x)){\n if(_b_.float.$funcs.isninf(x)){\n return -MAX_VALUE\n }\n return _mod.inf\n }\n if($B.$isinstance(x, $B.long_int)){\n x = Number(x.value)\n }else if($B.$isinstance(x, _b_.float)){\n x = x.value\n }\n\n if(x == +MAX_VALUE){\n return +1 / 0\n }\n if(typeof x == \"number\"){\n var y = x * (x < 0 ? 1 - EPSILON / 2 : 1 + EPSILON)\n if(y == x){\n y = MIN_VALUE * EPSILON > 0 ? x + MIN_VALUE * EPSILON : x + MIN_VALUE\n }\n if(y === +1 / 0){\n y = +MAX_VALUE\n }\n var b = x + (y - x) / 2\n if(x < b && b < y){\n y = b;\n }\n var c = (y + x) / 2\n if(x < c && c < y){\n y = c;\n }\n return y === 0 ? -0 : y\n }else{\n var factor = $B.rich_comp('__lt__', x, 0) ? 1 - EPSILON / 2 :\n 1 + EPSILON\n var y = $B.rich_op(\"__mul__\", x , factor)\n if(y == x){\n y = MIN_VALUE * EPSILON > 0 ?\n $B.rich_op('__add__', x, MIN_VALUE * EPSILON) :\n $B.rich_op('__add__', x, MIN_VALUE)\n }\n if(y === +1 / 0){\n y = +MAX_VALUE\n }\n var y_minus_x = $B.rich_op('__sub__', y, x)\n var z = $B.rich_op('__truediv__', y_minus_x, 2) // (y - x) / 2\n\n var b = $B.rich_op('__add__', x, z)\n if($B.rich_comp('__lt__', x, b) && $B.rich_comp('__lt__', b, y)){\n y = b;\n }\n var c = $B.rich_op('__truediv__', $B.rich_op('__add__', y, x), 2)\n if($B.rich_comp('__lt__', x, c) && $B.rich_comp('__lt__', c, y)){\n y = c;\n }\n return y === 0 ? -0 : y\n }\n}\n\nfunction gcd2(a, b){\n // GCD of 2 factors\n if($B.rich_comp(\"__gt__\", b, a)){\n var temp = a\n a = b\n b = temp\n }\n while(true){\n if(b == 0){\n return a\n }\n a = $B.rich_op(\"__mod__\", a, b)\n if(a == 0){\n return b\n }\n b = $B.rich_op(\"__mod__\", b, a)\n }\n}\n\nconst LANCZOS_N = 13,\n lanczos_g = 6.024680040776729583740234375,\n lanczos_g_minus_half = 5.524680040776729583740234375,\n lanczos_num_coeffs = [\n 23531376880.410759688572007674451636754734846804940,\n 42919803642.649098768957899047001988850926355848959,\n 35711959237.355668049440185451547166705960488635843,\n 17921034426.037209699919755754458931112671403265390,\n 6039542586.3520280050642916443072979210699388420708,\n 1439720407.3117216736632230727949123939715485786772,\n 248874557.86205415651146038641322942321632125127801,\n 31426415.585400194380614231628318205362874684987640,\n 2876370.6289353724412254090516208496135991145378768,\n 186056.26539522349504029498971604569928220784236328,\n 8071.6720023658162106380029022722506138218516325024,\n 210.82427775157934587250973392071336271166969580291,\n 2.5066282746310002701649081771338373386264310793408\n ],\n /* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */\n lanczos_den_coeffs = [\n 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,\n 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0],\n /* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */\n NGAMMA_INTEGRAL = 23,\n gamma_integral = [\n 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,\n 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,\n 1307674368000.0, 20922789888000.0, 355687428096000.0,\n 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,\n 51090942171709440000.0, 1124000727777607680000.0]\n\n/* Lanczos' sum L_g(x), for positive x */\nfunction lanczos_sum(x){\n var num = 0.0,\n den = 0.0,\n i\n /* evaluate the rational function lanczos_sum(x). For large\n x, the obvious algorithm risks overflow, so we instead\n rescale the denominator and numerator of the rational\n function by x**(1-LANCZOS_N) and treat this as a\n rational function in 1/x. This also reduces the error for\n larger x values. The choice of cutoff point (5.0 below) is\n somewhat arbitrary; in tests, smaller cutoff values than\n this resulted in lower accuracy. */\n if (x < 5.0) {\n for (i = LANCZOS_N; --i >= 0; ) {\n num = num * x + lanczos_num_coeffs[i];\n den = den * x + lanczos_den_coeffs[i];\n }\n }else{\n for (i = 0; i < LANCZOS_N; i++) {\n num = num / x + lanczos_num_coeffs[i];\n den = den / x + lanczos_den_coeffs[i];\n }\n }\n return num/den;\n}\n\nfunction m_sinpi(x){\n // x is float\n // returns a float\n var r,\n y = fmod(fabs(x), 2.0), // float\n n = _b_.round($B.fast_float(2.0 * y.value)) // int\n switch(n){\n case 0:\n r = sin(pi.value * y.value);\n break;\n case 1:\n r = cos(pi.value * (y.value - 0.5));\n break;\n case 2:\n /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give\n -0.0 instead of 0.0 when y == 1.0. */\n r = sin(pi.value * (1.0 - y.value));\n break;\n case 3:\n r = _b_.float.__neg__(cos(pi.value *(y.value - 1.5)))\n break;\n case 4:\n r = sin(pi.value * (y.value - 2.0));\n break;\n }\n return $B.fast_float(copysign(1.0, x).value * r.value);\n}\n\n/*\n lgamma: natural log of the absolute value of the Gamma function.\n For large arguments, Lanczos' formula works extremely well here.\n*/\nfunction m_lgamma(x){\n var r,\n absx\n\n /* special cases */\n if(! isfinite(x)){\n if(isnan(x)){\n return x; /* lgamma(nan) = nan */\n }else{\n return $B.fast_float(Number.POSITIVE_INFINITY); /* lgamma(+-inf) = +inf */\n }\n }\n\n /* integer arguments */\n var x1 = float_check(x)\n if(Number.isInteger(x1) && x1 <= 2.0){\n if(x1 <= 0.0){\n value_error()\n }else{\n return $B.fast_float(0.0); /* lgamma(1) = lgamma(2) = 0.0 */\n }\n }\n\n absx = fabs(x)\n /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */\n if (absx.value < 1e-20){\n return $B.fast_float(-log(absx).value);\n }\n /* Lanczos' formula. We could save a fraction of a ulp in accuracy by\n having a second set of numerator coefficients for lanczos_sum that\n absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g\n subtraction below; it's probably not worth it. */\n var lsum = $B.fast_float(lanczos_sum(absx.value))\n r = log(lsum).value - lanczos_g;\n r += (absx.value - 0.5) *\n (log($B.fast_float(absx.value + lanczos_g - 0.5)).value - 1)\n if (x1 < 0.0){\n /* Use reflection formula to get value for negative x. */\n r = logpi - log(fabs(m_sinpi(absx))).value - log(absx).value - r\n }\n r = $B.fast_float(r)\n if(isinf(r)){\n overflow()\n }\n return r;\n}\n\nfunction acos(x){\n $B.check_nb_args('acos', 1, arguments)\n $B.check_no_kw('acos', x)\n if(_mod.isinf(x)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }else if(_mod.isnan(x)){\n return _mod.nan\n }else{\n x = float_check(x)\n if(x > 1 || x < -1){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return _b_.float.$factory(Math.acos(x))\n }\n}\n\nfunction acosh(x){\n $B.check_nb_args('acosh', 1, arguments)\n $B.check_no_kw('acosh', x)\n\n if(_b_.float.$funcs.isinf(x)){\n if(_b_.float.$funcs.isninf(x)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return _mod.inf\n }else if(_mod.isnan(x)){\n return _mod.nan\n }\n var y = float_check(x)\n if(y <= 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if(y > Math.pow(2, 28)){ // issue 1590\n return _b_.float.$factory(_mod.log(y).value + _mod.log(2).value)\n }\n return _b_.float.$factory(Math.log(y + Math.sqrt(y * y - 1)))\n}\n\nfunction asin(x){\n $B.check_nb_args('asin', 1, arguments)\n $B.check_no_kw('asin', x)\n if(_mod.isinf(x)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }else if(_mod.isnan(x)){\n return _mod.nan\n }else{\n x = float_check(x)\n if(x > 1 || x < -1){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return _b_.float.$factory(Math.asin(x))\n }\n}\n\nfunction asinh(x){\n $B.check_nb_args('asinh', 1, arguments)\n $B.check_no_kw('asinh', x)\n\n var y = float_check(x)\n if(_b_.float.$funcs.isninf(x)){\n return NINF\n }else if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n if(y == 0 && 1 / y === -Infinity){\n return $B.fast_float(-0.0)\n }\n return _b_.float.$factory(Math.asinh(y))\n}\n\nfunction atan(x){\n $B.check_nb_args('atan', 1, arguments)\n $B.check_no_kw('atan', x)\n\n if(_b_.float.$funcs.isninf(x)){return _b_.float.$factory(-Math.PI / 2)}\n if(_b_.float.$funcs.isinf(x)){return _b_.float.$factory(Math.PI / 2)}\n return _b_.float.$factory(Math.atan(float_check(x)))\n}\n\nfunction atan2(x, y){\n $B.check_nb_args('atan2', 2, arguments)\n $B.check_no_kw('atan2', x, y)\n\n return _b_.float.$factory(Math.atan2(float_check(x), float_check(y)))\n}\n\nfunction atanh(x){\n $B.check_nb_args('atanh', 1, arguments)\n $B.check_no_kw('atanh', x)\n if(_b_.float.$funcs.isinf(x)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n var y = float_check(x)\n if(y == 0){\n return 0\n }else if(y <= -1 || y >= 1){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return _b_.float.$factory(0.5 * Math.log((1 / y + 1)/(1 / y - 1)));\n}\n\nfunction cbrt(x){\n // Cubic root\n $B.check_nb_args('cbrt ', 1, arguments)\n $B.check_no_kw('cbrt ', x)\n\n var y = float_check(x)\n if(_b_.float.$funcs.isninf(x)){\n return NINF\n }else if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n var _r = $B.fast_float(Math.cbrt(y))\n if(_b_.float.$funcs.isinf(_r)){\n throw _b_.OverflowError.$factory(\"math range error\")\n }\n return _r\n}\n\nfunction ceil(x){\n $B.check_nb_args('ceil', 1, arguments)\n $B.check_no_kw('ceil', x)\n\n var res\n\n if($B.$isinstance(x, _b_.float)){\n if(_b_.float.$funcs.isinf(x)){\n throw _b_.OverflowError.$factory(\n \"cannot convert float infinity to integer\")\n }else if(_mod.isnan(x)){\n throw _b_.OverflowError.$factory(\n \"cannot convert float NaN to integer\")\n }\n }\n\n var klass = x.__class__ || $B.get_class(x)\n\n try{\n // Use attribute of the object's class, not of the object\n // itself (special method)\n return $B.$call($B.$getattr(klass, '__ceil__'))(x)\n }catch(err){\n if(! $B.is_exc(err, [_b_.AttributeError])){\n throw err\n }\n }\n\n try{\n x = $B.$call($B.$getattr(klass, '__float__'))(x)\n }catch(err){\n if(! $B.is_exc(err, [_b_.AttributeError])){\n throw err\n }else{\n throw _b_.TypeError.$factory(\"must be real number, not \" +\n $B.class_name(x))\n }\n }\n return _mod.ceil(x)\n}\n\nconst ULLONG_MAX = 2n ** 64n - 1n,\n LONG_MAX = 2147483647,\n LONG_MIN = -2147483647,\n LLONG_MAX = 9223372036854775807n,\n LLONG_MIN = -9223372036854775807n,\n p2_64 = 2n ** 64n\n\nconst reduced_factorial_odd_part = [\n 0x0000000000000001n, 0x0000000000000001n, 0x0000000000000001n, 0x0000000000000003n,\n 0x0000000000000003n, 0x000000000000000fn, 0x000000000000002dn, 0x000000000000013bn,\n 0x000000000000013bn, 0x0000000000000b13n, 0x000000000000375fn, 0x0000000000026115n,\n 0x000000000007233fn, 0x00000000005cca33n, 0x0000000002898765n, 0x00000000260eeeebn,\n 0x00000000260eeeebn, 0x0000000286fddd9bn, 0x00000016beecca73n, 0x000001b02b930689n,\n 0x00000870d9df20adn, 0x0000b141df4dae31n, 0x00079dd498567c1bn, 0x00af2e19afc5266dn,\n 0x020d8a4d0f4f7347n, 0x335281867ec241efn, 0x9b3093d46fdd5923n, 0x5e1f9767cc5866b1n,\n 0x92dd23d6966aced7n, 0xa30d0f4f0a196e5bn, 0x8dc3e5a1977d7755n, 0x2ab8ce915831734bn,\n 0x2ab8ce915831734bn, 0x81d2a0bc5e5fdcabn, 0x9efcac82445da75bn, 0xbc8b95cf58cde171n,\n 0xa0e8444a1f3cecf9n, 0x4191deb683ce3ffdn, 0xddd3878bc84ebfc7n, 0xcb39a64b83ff3751n,\n 0xf8203f7993fc1495n, 0xbd2a2a78b35f4bddn, 0x84757be6b6d13921n, 0x3fbbcfc0b524988bn,\n 0xbd11ed47c8928df9n, 0x3c26b59e41c2f4c5n, 0x677a5137e883fdb3n, 0xff74e943b03b93ddn,\n 0xfe5ebbcb10b2bb97n, 0xb021f1de3235e7e7n, 0x33509eb2e743a58fn, 0x390f9da41279fb7dn,\n 0xe5cb0154f031c559n, 0x93074695ba4ddb6dn, 0x81c471caa636247fn, 0xe1347289b5a1d749n,\n 0x286f21c3f76ce2ffn, 0x00be84a2173e8ac7n, 0x1595065ca215b88bn, 0xf95877595b018809n,\n 0x9c2efe3c5516f887n, 0x373294604679382bn, 0xaf1ff7a888adcd35n, 0x18ddf279a2c5800bn,\n 0x18ddf279a2c5800bn, 0x505a90e2542582cbn, 0x5bacad2cd8d5dc2bn, 0xfe3152bcbff89f41n,\n 0xe1467e88bf829351n, 0xb8001adb9e31b4d5n, 0x2803ac06a0cbb91fn, 0x1904b5d698805799n,\n 0xe12a648b5c831461n, 0x3516abbd6160cfa9n, 0xac46d25f12fe036dn, 0x78bfa1da906b00efn,\n 0xf6390338b7f111bdn, 0x0f25f80f538255d9n, 0x4ec8ca55b8db140fn, 0x4ff670740b9b30a1n,\n 0x8fd032443a07f325n, 0x80dfe7965c83eeb5n, 0xa3dc1714d1213afdn, 0x205b7bbfcdc62007n,\n 0xa78126bbe140a093n, 0x9de1dc61ca7550cfn, 0x84f0046d01b492c5n, 0x2d91810b945de0f3n,\n 0xf5408b7f6008aa71n, 0x43707f4863034149n, 0xdac65fb9679279d5n, 0xc48406e7d1114eb7n,\n 0xa7dc9ed3c88e1271n, 0xfb25b2efdb9cb30dn, 0x1bebda0951c4df63n, 0x5c85e975580ee5bdn,\n 0x1591bc60082cb137n, 0x2c38606318ef25d7n, 0x76ca72f7c5c63e27n, 0xf04a75d17baa0915n,\n 0x77458175139ae30dn, 0x0e6c1330bc1b9421n, 0xdf87d2b5797e8293n, 0xefa5c703e1e68925n,\n 0x2b6b1b3278b4f6e1n, 0xceee27b382394249n, 0xd74e3829f5dab91dn, 0xfdb17989c26b5f1fn,\n 0xc1b7d18781530845n, 0x7b4436b2105a8561n, 0x7ba7c0418372a7d7n, 0x9dbc5c67feb6c639n,\n 0x502686d7f6ff6b8fn, 0x6101855406be7a1fn, 0x9956afb5806930e7n, 0xe1f0ee88af40f7c5n,\n 0x984b057bda5c1151n, 0x9a49819acc13ea05n, 0x8ef0dead0896ef27n, 0x71f7826efe292b21n,\n 0xad80a480e46986efn, 0x01cdc0ebf5e0c6f7n, 0x6e06f839968f68dbn, 0xdd5943ab56e76139n,\n 0xcdcf31bf8604c5e7n, 0x7e2b4a847054a1cbn, 0x0ca75697a4d3d0f5n, 0x4703f53ac514a98bn,\n];\n\nconst inverted_factorial_odd_part = [\n 0x0000000000000001n, 0x0000000000000001n, 0x0000000000000001n, 0xaaaaaaaaaaaaaaabn,\n 0xaaaaaaaaaaaaaaabn, 0xeeeeeeeeeeeeeeefn, 0x4fa4fa4fa4fa4fa5n, 0x2ff2ff2ff2ff2ff3n,\n 0x2ff2ff2ff2ff2ff3n, 0x938cc70553e3771bn, 0xb71c27cddd93e49fn, 0xb38e3229fcdee63dn,\n 0xe684bb63544a4cbfn, 0xc2f684917ca340fbn, 0xf747c9cba417526dn, 0xbb26eb51d7bd49c3n,\n 0xbb26eb51d7bd49c3n, 0xb0a7efb985294093n, 0xbe4b8c69f259eabbn, 0x6854d17ed6dc4fb9n,\n 0xe1aa904c915f4325n, 0x3b8206df131cead1n, 0x79c6009fea76fe13n, 0xd8c5d381633cd365n,\n 0x4841f12b21144677n, 0x4a91ff68200b0d0fn, 0x8f9513a58c4f9e8bn, 0x2b3e690621a42251n,\n 0x4f520f00e03c04e7n, 0x2edf84ee600211d3n, 0xadcaa2764aaacdfdn, 0x161f4f9033f4fe63n,\n 0x161f4f9033f4fe63n, 0xbada2932ea4d3e03n, 0xcec189f3efaa30d3n, 0xf7475bb68330bf91n,\n 0x37eb7bf7d5b01549n, 0x46b35660a4e91555n, 0xa567c12d81f151f7n, 0x4c724007bb2071b1n,\n 0x0f4a0cce58a016bdn, 0xfa21068e66106475n, 0x244ab72b5a318ae1n, 0x366ce67e080d0f23n,\n 0xd666fdae5dd2a449n, 0xd740ddd0acc06a0dn, 0xb050bbbb28e6f97bn, 0x70b003fe890a5c75n,\n 0xd03aabff83037427n, 0x13ec4ca72c783bd7n, 0x90282c06afdbd96fn, 0x4414ddb9db4a95d5n,\n 0xa2c68735ae6832e9n, 0xbf72d71455676665n, 0xa8469fab6b759b7fn, 0xc1e55b56e606caf9n,\n 0x40455630fc4a1cffn, 0x0120a7b0046d16f7n, 0xa7c3553b08faef23n, 0x9f0bfd1b08d48639n,\n 0xa433ffce9a304d37n, 0xa22ad1d53915c683n, 0xcb6cbc723ba5dd1dn, 0x547fb1b8ab9d0ba3n,\n 0x547fb1b8ab9d0ba3n, 0x8f15a826498852e3n, 0x32e1a03f38880283n, 0x3de4cce63283f0c1n,\n 0x5dfe6667e4da95b1n, 0xfda6eeeef479e47dn, 0xf14de991cc7882dfn, 0xe68db79247630ca9n,\n 0xa7d6db8207ee8fa1n, 0x255e1f0fcf034499n, 0xc9a8990e43dd7e65n, 0x3279b6f289702e0fn,\n 0xe7b5905d9b71b195n, 0x03025ba41ff0da69n, 0xb7df3d6d3be55aefn, 0xf89b212ebff2b361n,\n 0xfe856d095996f0adn, 0xd6e533e9fdf20f9dn, 0xf8c0e84a63da3255n, 0xa677876cd91b4db7n,\n 0x07ed4f97780d7d9bn, 0x90a8705f258db62fn, 0xa41bbb2be31b1c0dn, 0x6ec28690b038383bn,\n 0xdb860c3bb2edd691n, 0x0838286838a980f9n, 0x558417a74b36f77dn, 0x71779afc3646ef07n,\n 0x743cda377ccb6e91n, 0x7fdf9f3fe89153c5n, 0xdc97d25df49b9a4bn, 0x76321a778eb37d95n,\n 0x7cbb5e27da3bd487n, 0x9cff4ade1a009de7n, 0x70eb166d05c15197n, 0xdcf0460b71d5fe3dn,\n 0x5ac1ee5260b6a3c5n, 0xc922dedfdd78efe1n, 0xe5d381dc3b8eeb9bn, 0xd57e5347bafc6aadn,\n 0x86939040983acd21n, 0x395b9d69740a4ff9n, 0x1467299c8e43d135n, 0x5fe440fcad975cdfn,\n 0xcaa9a39794a6ca8dn, 0xf61dbd640868dea1n, 0xac09d98d74843be7n, 0x2b103b9e1a6b4809n,\n 0x2ab92d16960f536fn, 0x6653323d5e3681dfn, 0xefd48c1c0624e2d7n, 0xa496fefe04816f0dn,\n 0x1754a7b07bbdd7b1n, 0x23353c829a3852cdn, 0xbf831261abd59097n, 0x57a8e656df0618e1n,\n 0x16e9206c3100680fn, 0xadad4c6ee921dac7n, 0x635f2b3860265353n, 0xdd6d0059f44b3d09n,\n 0xac4dd6b894447dd7n, 0x42ea183eeaa87be3n, 0x15612d1550ee5b5dn, 0x226fa19d656cb623n,\n]\n\nconst factorial_trailing_zeros = [\n 0, 0, 1, 1, 3, 3, 4, 4, 7, 7, 8, 8, 10, 10, 11, 11, // 0-15\n 15, 15, 16, 16, 18, 18, 19, 19, 22, 22, 23, 23, 25, 25, 26, 26, // 16-31\n 31, 31, 32, 32, 34, 34, 35, 35, 38, 38, 39, 39, 41, 41, 42, 42, // 32-47\n 46, 46, 47, 47, 49, 49, 50, 50, 53, 53, 54, 54, 56, 56, 57, 57, // 48-63\n 63, 63, 64, 64, 66, 66, 67, 67, 70, 70, 71, 71, 73, 73, 74, 74, // 64-79\n 78, 78, 79, 79, 81, 81, 82, 82, 85, 85, 86, 86, 88, 88, 89, 89, // 80-95\n 94, 94, 95, 95, 97, 97, 98, 98, 101, 101, 102, 102, 104, 104, 105, 105, // 96-111\n 109, 109, 110, 110, 112, 112, 113, 113, 116, 116, 117, 117, 119, 119, 120, 120, // 112-127\n].map(BigInt)\n\nconst NULL = undefined\n\n/* Calculate C(n, k) for n in the 63-bit range. */\n\nfunction perm_comb_small(n, k, iscomb){\n if(k == 0){\n return 1n\n }\n\n /* For small enough n and k the result fits in the 64-bit range and can\n * be calculated without allocating intermediate PyLong objects. */\n if(iscomb){\n /* Maps k to the maximal n so that 2*k-1 <= n <= 127 and C(n, k)\n * fits into a uint64_t. Exclude k = 1, because the second fast\n * path is faster for this case.*/\n var fast_comb_limits1 = [\n 0, 0, 127, 127, 127, 127, 127, 127, // 0-7\n 127, 127, 127, 127, 127, 127, 127, 127, // 8-15\n 116, 105, 97, 91, 86, 82, 78, 76, // 16-23\n 74, 72, 71, 70, 69, 68, 68, 67, // 24-31\n 67, 67, 67 // 32-34\n ];\n if(k < fast_comb_limits1.length && n <= fast_comb_limits1[k]){\n /*\n comb(n, k) fits into a uint64_t. We compute it as\n comb_odd_part << shift\n where 2**shift is the largest power of two dividing comb(n, k)\n and comb_odd_part is comb(n, k) >> shift. comb_odd_part can be\n calculated efficiently via arithmetic modulo 2**64, using three\n lookups and two uint64_t multiplications.\n */\n var comb_odd_part = reduced_factorial_odd_part[n]\n * inverted_factorial_odd_part[k]\n * inverted_factorial_odd_part[n - k];\n comb_odd_part %= p2_64\n var shift = factorial_trailing_zeros[n]\n - factorial_trailing_zeros[k]\n - factorial_trailing_zeros[n - k];\n return comb_odd_part << shift;\n }\n\n /* Maps k to the maximal n so that 2*k-1 <= n <= 127 and C(n, k)*k\n * fits into a long long (which is at least 64 bit). Only contains\n * items larger than in fast_comb_limits1. */\n var fast_comb_limits2 = [\n 0, ULLONG_MAX, 4294967296, 3329022, 102570, 13467, 3612, 1449, // 0-7\n 746, 453, 308, 227, 178, 147 // 8-13\n ];\n if (k < fast_comb_limits2.length && n <= fast_comb_limits2[k]) {\n /* C(n, k) = C(n, k-1) * (n-k+1) / k */\n var result = n,\n i = 1n;\n while(i < k){\n result *= --n;\n result /= ++i;\n }\n return result;\n }\n }else{\n /* Maps k to the maximal n so that k <= n and P(n, k)\n * fits into a long long (which is at least 64 bit). */\n var fast_perm_limits = [\n 0, ULLONG_MAX, 4294967296, 2642246, 65537, 7133, 1627, 568, // 0-7\n 259, 142, 88, 61, 45, 36, 30, 26, // 8-15\n 24, 22, 21, 20, 20 // 16-20\n ];\n if (k < fast_perm_limits.length && n <= fast_perm_limits[k]) {\n if(n <= 127){\n /* P(n, k) fits into a uint64_t. */\n var perm_odd_part = reduced_factorial_odd_part[n]\n * inverted_factorial_odd_part[n - k];\n perm_odd_part %= p2_64\n var shift = factorial_trailing_zeros[n]\n - factorial_trailing_zeros[n - k];\n var res = perm_odd_part << shift\n\n return res;\n }\n\n /* P(n, k) = P(n, k-1) * (n-k+1) */\n var result = n;\n for (var i = 1; i < k; i++) {\n result *= --n;\n }\n return result\n }\n }\n\n /* For larger n use recursive formulas:\n *\n * P(n, k) = P(n, j) * P(n-j, k-j)\n * C(n, k) = C(n, j) * C(n-j, k-j) // C(k, j)\n */\n var j = k / 2n;\n var a = perm_comb_small(n, j, iscomb);\n var b = perm_comb_small(n - j, k - j, iscomb);\n a = a * b;\n if(iscomb){\n b = perm_comb_small(k, j, 1);\n a = a / b;\n }\n return a;\n}\n\n/* Calculate P(n, k) or C(n, k) using recursive formulas.\n * It is more efficient than sequential multiplication thanks to\n * Karatsuba multiplication.\n */\nfunction perm_comb(n, k, iscomb){\n if(k == 0){\n return 1;\n }\n if(k == 1){\n return n;\n }\n\n /* P(n, k) = P(n, j) * P(n-j, k-j) */\n /* C(n, k) = C(n, j) * C(n-j, k-j) // C(k, j) */\n var j = k / 2n\n var a = perm_comb(n, j, iscomb);\n //var t = j\n //n = n - t;\n var b = perm_comb(n - j, k - j, iscomb);\n a = a * b;\n if(iscomb){\n b = perm_comb_small(k, j, 1);\n a = a / b;\n }\n return a;\n}\n\nfunction comb(n, k){\n var $ = $B.args('comb', 2, {n: null, k: null}, ['n', 'k'],\n arguments, {}, null, null),\n n = $.n,\n k = $.k\n\n var result = NULL,\n temp,\n overflow, cmp;\n\n // accept integers or objects with __index__\n n = $B.PyNumber_Index(n)\n k = $B.PyNumber_Index(k)\n\n n = _b_.int.$to_bigint(n);\n k = _b_.int.$to_bigint(k);\n\n if(n < 0){\n throw _b_.ValueError.$factory(\n \"n must be a non-negative integer\");\n }\n if(k < 0){\n throw _b_.ValueError.$factory(\n \"k must be a non-negative integer\");\n }\n\n overflow = n > LLONG_MAX || n < LLONG_MIN\n if(! overflow){\n overflow = k > LLONG_MAX || k < LLONG_MIN\n if (overflow || k > n) {\n result = 0n;\n }else{\n if(n - k < k){\n k = n - k\n }\n if (k > 1) {\n result = perm_comb_small(n, k, 1);\n }\n }\n /* For k == 1 just return the original n in perm_comb(). */\n }else{\n /* k = min(k, n - k) */\n temp = n - k\n if(temp < 0) {\n result = 0n;\n }\n if (temp < k) {\n k = temp\n }\n\n overflow = k > LLONG_MAX || k < LLONG_MIN\n if (overflow) {\n throw _b_.OverflowError.$factory(\n \"min(n - k, k) must not exceed \" +\n LLONG_MAX);\n }\n }\n if(result === undefined){\n result = perm_comb(n, k, 1);\n }\n\n return _b_.int.$int_or_long(result)\n}\n\n\nfunction copysign(x, y){\n $B.check_nb_args_no_kw('copysign', 2, arguments)\n\n var x1 = Math.abs(float_check(x))\n var y1 = float_check(y)\n var sign = Math.sign(y1)\n sign = (sign == 1 || Object.is(sign, +0)) ? 1 : - 1\n return _b_.float.$factory(x1 * sign)\n}\n\nfunction cos(x){\n $B.check_nb_args('cos ', 1, arguments)\n $B.check_no_kw('cos ', x)\n return _b_.float.$factory(Math.cos(float_check(x)))\n}\n\nfunction cosh(x){\n $B.check_nb_args('cosh', 1, arguments)\n $B.check_no_kw('cosh', x)\n\n if(_b_.float.$funcs.isinf(x)){return INF}\n var y = float_check(x)\n if(Math.cosh !== undefined){return _b_.float.$factory(Math.cosh(y))}\n return _b_.float.$factory((Math.pow(Math.E, y) +\n Math.pow(Math.E, -y)) / 2)\n}\n\nfunction degrees(x){\n $B.check_nb_args('degrees', 1, arguments)\n $B.check_no_kw('degrees', x)\n return _b_.float.$factory(float_check(x) * 180 / Math.PI)\n}\n\nfunction dist(p, q){\n $B.check_nb_args_no_kw('dist', 2, arguments)\n\n function test(x){\n if(typeof x === \"number\"){\n return x\n }else if(x.__class__ === _b_.float){\n return x.value\n }\n var y = $B.$getattr(x, '__float__', null)\n if(y === null){\n throw _b_.TypeError.$factory('not a float')\n }\n return $B.$call(y)().value\n }\n\n // build list of differences (as floats) between coordinates of p and q\n var diffs = [],\n diff\n\n if(Array.isArray(p) && Array.isArray(q)){\n // simple case : p and q are lists of tuples\n if(p.length != q.length){\n throw _b_.ValueError.$factory(\"both points must have \" +\n \"the same number of dimensions\")\n }\n p = p.map(test)\n q = q.map(test)\n for(var i = 0, len = p.length; i < len; i++){\n var next_p = p[i],\n next_q = q[i]\n var diff = Math.abs(next_p - next_q)\n diffs.push(diff)\n }\n }else{\n var itp = _b_.iter(p),\n itq = _b_.iter(q),\n res = 0\n\n while(true){\n try{\n var next_p = _b_.next(itp)\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n // check that the other iterator is also exhausted\n try{\n var next_q = _b_.next(itq)\n throw _b_.ValueError.$factory(\"both points must have \" +\n \"the same number of dimensions\")\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n break\n }\n throw err\n }\n }\n throw err\n }\n next_p = test(next_p)\n try{\n var next_q = _b_.next(itq)\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n throw _b_.ValueError.$factory(\"both points must have \" +\n \"the same number of dimensions\")\n }\n throw err\n }\n next_q = test(next_q)\n diff = Math.abs(next_p - next_q)\n diffs.push(diff)\n }\n }\n for(var diff of diffs){\n if(! isFinite(diff) && ! isNaN(diff)){\n return _mod.inf\n }\n }\n for(var diff of diffs){\n if(isNaN(diff)){\n return _mod.nan\n }\n }\n\n var res = 0,\n scale = 1,\n max_diff = Math.max(...diffs),\n min_diff = Math.min(...diffs)\n max_value = Math.sqrt(Number.MAX_VALUE) / p.length,\n min_value = Math.sqrt(Number.MIN_VALUE) * p.length\n if(max_diff > max_value){\n var nb = 0\n while(max_diff > max_value){\n scale *= 2\n max_diff /= 2\n nb++\n }\n for(var diff of diffs){\n diff = diff / scale\n res += diff * diff\n }\n return $B.fast_float(scale * Math.sqrt(res))\n }else if(min_diff !== 0 && min_diff < min_value){\n while(min_diff < min_value){\n scale *= 2\n min_diff *= 2\n }\n for(var diff of diffs){\n diff = diff * scale\n res += diff * diff\n }\n return $B.fast_float(Math.sqrt(res) / scale)\n }else{\n for(var diff of diffs){\n res += Math.pow(diff, 2)\n }\n return $B.fast_float(Math.sqrt(res))\n }\n}\n\nconst e = _b_.float.$factory(Math.E)\n\nconst ERF_SERIES_CUTOFF = 1.5,\n ERF_SERIES_TERMS = 25,\n ERFC_CONTFRAC_CUTOFF = 30.0,\n ERFC_CONTFRAC_TERMS = 50\n\n/*\n Error function, via power series.\n Given a finite float x, return an approximation to erf(x).\n Converges reasonably fast for small x.\n*/\n\nfunction m_erf_series(x){\n var x2, acc, fk, result\n var i\n\n x2 = x * x\n acc = 0.0\n fk = ERF_SERIES_TERMS + 0.5\n for(i = 0; i < ERF_SERIES_TERMS; i++){\n acc = 2.0 + x2 * acc / fk\n fk -= 1.0\n }\n result = acc * x * exp(-x2).value / sqrtpi\n return result\n}\n\nfunction m_erfc_contfrac(x){\n var x2, a, da, p, p_last, q, q_last, b, result;\n var i\n\n if(x >= ERFC_CONTFRAC_CUTOFF){\n return 0.0\n }\n\n x2 = x * x\n a = 0.0\n da = 0.5\n p = 1.0\n p_last = 0.0\n q = da + x2\n q_last = 1.0\n for(i = 0; i < ERFC_CONTFRAC_TERMS; i++){\n var temp\n a += da\n da += 2.0\n b = da + x2\n temp = p; p = b * p - a * p_last; p_last = temp\n temp = q; q = b * q - a * q_last; q_last = temp\n }\n result = p / q * x * exp(-x2).value / sqrtpi\n return result\n}\n\n\nfunction erf(x){\n var absx,\n cf\n var x1 = float_check(x)\n if(isNaN(x1)){\n return x\n }\n absx = fabs(x)\n if(absx.value < ERF_SERIES_CUTOFF){\n return $B.fast_float(m_erf_series(x1))\n }else{\n cf = m_erfc_contfrac(absx.value)\n return $B.fast_float(x1 > 0.0 ? 1.0 - cf : cf - 1.0)\n }\n}\n\nfunction erfc(x){\n\n // inspired from\n // http://stackoverflow.com/questions/457408/is-there-an-easily-available-implementation-of-erf-for-python\n var y = float_check(x)\n var t = 1.0 / (1.0 + 0.5 * Math.abs(y))\n var ans = 1 - t * Math.exp( -y * y - 1.26551223 +\n t * ( 1.00002368 +\n t * ( 0.37409196 +\n t * ( 0.09678418 +\n t * (-0.18628806 +\n t * ( 0.27886807 +\n t * (-1.13520398 +\n t * ( 1.48851587 +\n t * (-0.82215223 +\n t * 0.17087277)))))))))\n if(y >= 0.0){return 1 - ans}\n return 1 + ans\n}\n\nfunction erfc(x){\n $B.check_nb_args_no_kw('erfc', 1, arguments)\n var absx, cf;\n\n var x1 = float_check(x)\n if(isNaN(x1)){\n return x\n }\n absx = fabs(x);\n if(absx.value < ERF_SERIES_CUTOFF){\n return $B.fast_float(1.0 - m_erf_series(x1))\n }else{\n cf = m_erfc_contfrac(absx.value)\n return $B.fast_float(x1 > 0.0 ? cf : 2.0 - cf)\n }\n}\n\nfunction exp(x){\n $B.check_nb_args('exp', 1, arguments)\n $B.check_no_kw('exp', x)\n\n if(_b_.float.$funcs.isninf(x)){\n return _b_.float.$factory(0)\n }\n if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n var _r = Math.exp(float_check(x))\n if(! isNaN(_r) && ! isFinite(_r)){\n throw _b_.OverflowError.$factory(\"math range error\")\n }\n return _b_.float.$factory(_r)\n}\n\nfunction exp2(x){\n return pow(2, x)\n}\n\nfunction expm1(x){\n $B.check_nb_args('expm1', 1, arguments)\n $B.check_no_kw('expm1', x)\n\n if(_b_.float.$funcs.isninf(x)){\n return $B.fast_float(-1)\n }else if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n var _r = Math.expm1(float_check(x))\n if((! isNaN(_r)) && ! isFinite(_r)){\n overflow()\n }\n return $B.fast_float(_r)\n}\n\nfunction fabs(x){\n $B.check_nb_args_no_kw('fabs', 1, arguments)\n return _b_.float.$funcs.fabs(float_check(x)) // located in py_float.js\n}\n\n// factorial implementation, adapted from CPython's mathmodule.c\n\nconst SmallFactorials = [\n 1n, 1n, 2n, 6n, 24n, 120n, 720n, 5040n, 40320n,\n 362880n, 3628800n, 39916800n, 479001600n,\n 6227020800n, 87178291200n, 1307674368000n,\n 20922789888000n, 355687428096000n, 6402373705728000n,\n 121645100408832000n, 2432902008176640000n\n ]\n\nconst SIZEOF_LONG = 4\n\nfunction _Py_bit_length(x){\n const BIT_LENGTH_TABLE = [\n 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5\n ]\n var msb = 0;\n while(x >= 32n){\n msb += 6;\n x >>= 6n;\n }\n msb += BIT_LENGTH_TABLE[parseInt(x)];\n return msb\n}\nfunction count_set_bits(n){\n var count = 0n;\n while(n != 0){\n ++count;\n n &= n - 1n; /* clear least significant bit */\n }\n return count;\n}\n\nfunction factorial_partial_product(start, stop, max_bits){\n var midpoint,\n num_operands,\n left,\n right,\n result\n\n /* If the return value will fit an unsigned long, then we can\n * multiply in a tight, fast loop where each multiply is O(1).\n * Compute an upper bound on the number of bits required to store\n * the answer.\n *\n * Storing some integer z requires floor(lg(z))+1 bits, which is\n * conveniently the value returned by bit_length(z). The\n * product x*y will require at most\n * bit_length(x) + bit_length(y) bits to store, based\n * on the idea that lg product = lg x + lg y.\n *\n * We know that stop - 2 is the largest number to be multiplied. From\n * there, we have: bit_length(answer) <= num_operands *\n * bit_length(stop - 2)\n */\n\n num_operands = (stop - start) / 2n;\n max_bits = BigInt(max_bits)\n /* The \"num_operands <= 8 * SIZEOF_LONG\" check guards against the\n * unlikely case of an overflow in num_operands * max_bits. */\n if(num_operands <= 8 * SIZEOF_LONG &&\n num_operands * max_bits <= 8 * SIZEOF_LONG) {\n var j,\n total;\n for (total = start, j = start + 2n; j < stop; j += 2n){\n total *= j;\n }\n return total\n }\n\n /* find midpoint of range(start, stop), rounded up to next odd number. */\n midpoint = (start + num_operands) | 1n;\n left = factorial_partial_product(start, midpoint,\n _Py_bit_length(midpoint - 2n));\n right = factorial_partial_product(midpoint, stop, max_bits);\n result = left * right\n return result;\n}\n\n\nfunction factorial_odd_part(n){\n var i,\n v, lower, upper,\n partial, tmp, inner, outer;\n\n inner = 1n\n outer = inner;\n upper = 3n;\n for (i = BigInt(_Py_bit_length(n)) - 2n; i >= 0; i--) {\n v = n >> i;\n if (v <= 2){\n continue\n }\n lower = upper;\n /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */\n upper = (v + 1n) | 1n;\n /* Here inner is the product of all odd integers j in the range (0,\n n/2**(i+1)]. The factorial_partial_product call below gives the\n product of all odd integers j in the range (n/2**(i+1), n/2**i]. */\n partial = factorial_partial_product(lower, upper,\n _Py_bit_length(upper-2n));\n /* inner *= partial */\n tmp = inner * partial\n inner = tmp;\n /* Now inner is the product of all odd integers j in the range (0,\n n/2**i], giving the inner product in the formula above. */\n\n /* outer *= inner; */\n tmp = outer * inner\n outer = tmp;\n }\n return outer;\n}\n\nfunction factorial(arg){\n var x,\n two_valuation,\n overflow,\n result,\n odd_part;\n // Check that arg can be converted to an integer, and transform it to\n // a bigint\n x = _b_.int.$to_bigint($B.PyNumber_Index(arg))\n overflow = x > LONG_MAX || x < LONG_MIN\n if(x > LONG_MAX) {\n throw _b_.OverflowError.$factory(\n \"factorial() argument should not exceed \" +\n LONG_MAX)\n }else if(x < 0) {\n throw _b_.ValueError.$factory(\n \"factorial() not defined for negative values\");\n }\n\n /* use lookup table if x is small */\n if (x < SmallFactorials.length){\n return _b_.int.$int_or_long(SmallFactorials[x]);\n }\n /* else express in the form odd_part * 2**two_valuation, and compute as\n odd_part << two_valuation. */\n odd_part = factorial_odd_part(x);\n two_valuation = x - count_set_bits(x);\n return _b_.int.$int_or_long(odd_part << two_valuation);\n}\n\nfunction floor(x){\n $B.check_nb_args_no_kw('floor', 1, arguments)\n\n if(typeof x == \"number\" || x.__class__ === _b_.float){\n return Math.floor(float_check(x))\n }\n var klass = $B.get_class(x)\n try{\n return $B.$call($B.$getattr(klass, \"__floor__\"))(x)\n }catch(err){\n if($B.is_exc(err, [_b_.AttributeError])){\n try{\n var float = $B.$call($B.$getattr(klass, \"__float__\"))(x)\n return floor(float)\n }catch(err){\n if($B.is_exc(err, [_b_.AttributeError])){\n throw _b_.TypeError.$factory(\"no __float__\")\n }\n throw err\n }\n }\n }\n}\n\nvar _fma = (function () {\n // copied from \n // https://gist.github.com/Yaffle/fb47de4c18b63147699e0b621f1031f7\n\n \n var SPLIT = Math.pow(2, 27) + 1;\n var MIN_VALUE = Math.pow(2, -1022);\n var EPSILON = Math.pow(2, -52);\n // (1022 + 52) / 3 < C <= (1022 - 53 - 53 + 4) / 2 - ?\n var C = 416;\n var A = Math.pow(2, +C);\n var B = Math.pow(2, -C);\n\n var multiply = function (a, b) {\n var at = SPLIT * a;\n var ahi = at - (at - a);\n var alo = a - ahi;\n var bt = SPLIT * b;\n var bhi = bt - (bt - b);\n var blo = b - bhi;\n var p = a * b;\n var e = ((ahi * bhi - p) + ahi * blo + alo * bhi) + alo * blo;\n return {\n p: p,\n e: e\n };\n };\n\n var add = function (a, b) {\n var s = a + b;\n var v = s - a;\n var e = (a - (s - v)) + (b - v);\n return {\n s: s,\n e: e\n };\n };\n\n var adjust = function (x, y) {\n return x !== 0 && y !== 0 && SPLIT * x - (SPLIT * x - x) === x ? x * (1 + (x < 0 ? -1 : +1) * (y < 0 ? -1 : +1) * EPSILON) : x;\n };\n\n var fma = function (x, y, z) {\n x = Number(x);\n y = Number(y);\n z = Number(z);\n\n if (x === 0 || x !== x || x === +1 / 0 || x === -1 / 0 ||\n y === 0 || y !== y || y === +1 / 0 || y === -1 / 0) {\n return x * y + z;\n }\n if (z === 0) {\n return x * y;\n }\n if (z !== z || z === +1 / 0 || z === -1 / 0) {\n return z;\n }\n\n var scale = 1;\n while (Math.abs(x) > A) {\n scale *= A;\n x *= B;\n }\n while (Math.abs(y) > A) {\n scale *= A;\n y *= B;\n }\n if (scale === 1 / 0) {\n return x * y * scale;\n }\n while (Math.abs(x) < B) {\n scale *= B;\n x *= A;\n }\n while (Math.abs(y) < B) {\n scale *= B;\n y *= A;\n }\n if (scale === 0) {\n return z;\n }\n\n var xs = x;\n var ys = y;\n var zs = z / scale;\n\n if (Math.abs(zs) > Math.abs(xs * ys) * 4 / EPSILON) {\n return z;\n }\n if (Math.abs(zs) < Math.abs(xs * ys) * EPSILON / 4 * EPSILON / 4) {\n zs = (z < 0 ? -1 : +1) * MIN_VALUE;\n }\n\n var xy = multiply(xs, ys);\n var s = add(xy.p, zs);\n var u = add(xy.e, s.e);\n var i = add(s.s, u.s);\n\n var f = i.s + adjust(i.e, u.e);\n if (f === 0) {\n return f;\n }\n\n var fs = f * scale;\n if (Math.abs(fs) > MIN_VALUE) {\n return fs;\n }\n\n // It is possible that there was extra rounding for a denormalized value.\n return fs + adjust(f - fs / scale, i.e) * scale;\n };\n\n return fma\n\n}());\n\nfunction fma(x, y, z){\n var $ = $B.args('fma', 3, {x: null, y: null, z: null}, ['x', 'y', 'z'],\n arguments, {}, null, null),\n x = float_check($.x),\n y = float_check($.y),\n z = float_check($.z)\n\n var res =_fma(x, y, z)\n if(isFinite(res)){\n return $B.fast_float(res)\n }\n if(isNaN(res)){\n if (!isNaN(x) && !isNaN(y) && !isNaN(z)) {\n /* NaN result from non-NaN inputs. */\n throw _b_.ValueError.$factory(\"invalid operation in fma\");\n }\n }else if(isFinite(x) && isFinite(y) && isFinite(z)) {\n /* Infinite result from finite inputs. */\n throw _b_.OverflowError.$factory(\"overflow in fma\");\n }\n\n return $B.fast_float(res)\n}\n\nfunction fmod(x, y){\n $B.check_nb_args_no_kw('fmod', 2, arguments)\n if($B.$isinstance(x, _b_.float)){\n if(_b_.float.$funcs.isinf(x)){\n throw _b_.ValueError.$factory('math domain error')\n }\n }\n y = float_check(y)\n if(y == 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n return _b_.float.$factory(float_check(x) % float_check(y))\n}\n\nfunction frexp(x){\n $B.check_nb_args_no_kw('frexp', 1, arguments)\n\n var _l = _b_.float.$funcs.frexp(x)\n return _b_.tuple.$factory([_b_.float.$factory(_l[0]), _l[1]])\n}\n\nfunction fsum(x){\n $B.check_nb_args_no_kw('fsum', 1, arguments)\n\n /* Translation into Javascript of the function msum in an Active\n State Cookbook recipe : https://code.activestate.com/recipes/393090/\n by Raymond Hettinger\n */\n var partials = [],\n res = new Number(),\n _it = _b_.iter(x)\n while(true){\n try{\n var x = _b_.next(_it),\n i = 0\n x = float_check(x)\n for(var j = 0, len = partials.length; j < len; j++){\n var y = float_check(partials[j])\n if(Math.abs(x) < Math.abs(y)){\n var z = x\n x = y\n y = z\n }\n var hi = x + y,\n lo = y - (hi - x)\n if(lo){\n partials[i] = lo\n i++\n }\n x = hi\n }\n partials = partials.slice(0, i).concat([x])\n }catch(err){\n if($B.$isinstance(err, _b_.StopIteration)){break}\n throw err\n }\n }\n var res = 0\n for(var i = 0; i < partials.length; i++){\n res += partials[i]\n }\n return $B.fast_float(res)\n}\n\nfunction gamma(x){\n $B.check_nb_args('gamma', 1, arguments)\n $B.check_no_kw('gamma', x)\n var x_as_number = x,\n r,\n y,\n z,\n sqrtpow\n\n /* special cases */\n if($B.$isinstance(x, _b_.float)){\n x_as_number = x.value\n }else if(! $B.$isinstance(x, _b_.int)){\n throw _b_.TypeError.$factory(\"must be real number, not \" +\n $B.class_name(x))\n }\n if(x_as_number === Number.POSITIVE_INFINITY || isNaN(x_as_number)){\n return x\n }else if(x_as_number === Number.NEGATIVE_INFINITY || x_as_number == 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n\n /* integer arguments */\n if(Number.isInteger(x_as_number)){\n if($B.rich_comp('__lt__', x, 0.0)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if($B.rich_comp('__le__', x, NGAMMA_INTEGRAL)){\n return $B.fast_float(gamma_integral[x_as_number - 1])\n }\n }\n var absx = fabs(x)\n\n /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */\n if(absx.value < 1e-20){\n r = 1.0 / x_as_number\n if(r === Infinity || r === -Infinity){\n overflow()\n }\n return $B.fast_float(r)\n }\n\n /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for\n x > 200, and underflows to +-0.0 for x < -200, not a negative\n integer. */\n if(absx.value > 200.0){\n if(x_as_number < 0.0){\n return $B.fast_float(0.0 / m_sinpi(x).value);\n }else{\n overflow()\n }\n }\n\n y = absx.value + lanczos_g_minus_half;\n /* compute error in sum */\n if (absx.value > lanczos_g_minus_half) {\n /* note: the correction can be foiled by an optimizing\n compiler that (incorrectly) thinks that an expression like\n a + b - a - b can be optimized to 0.0. This shouldn't\n happen in a standards-conforming compiler. */\n var q = y - absx.value;\n z = q - lanczos_g_minus_half;\n }else{\n var q = y - lanczos_g_minus_half;\n z = q - absx.value;\n }\n z = z * lanczos_g / y;\n if (x_as_number < 0.0) {\n r = -pi.value / m_sinpi(absx).value /\n absx.value * _mod.exp(y).value /\n lanczos_sum(absx.value);\n r -= z * r;\n if(absx.value < 140.0){\n r /= pow(y, absx.value - 0.5).value;\n }else{\n sqrtpow = pow(y, absx.value / 2.0 - 0.25);\n r /= sqrtpow.value;\n r /= sqrtpow.value;\n }\n }else{\n r = lanczos_sum(absx.value) / exp(y).value;\n r += z * r;\n if(absx.value < 140.0){\n r *= pow(y, absx.value - 0.5).value;\n }else{\n sqrtpow = pow(y, absx.value / 2.0 - 0.25);\n r *= sqrtpow.value;\n r *= sqrtpow.value;\n }\n }\n if(r === Number.POSITIVE_INFINITY){\n overflow()\n }\n return $B.fast_float(r);\n}\n\n\n// GCD algorithm. Javascript adaptation of Python script at\n// https://gist.github.com/cmpute/baa545f0c2b6be8b628e9ded3c19f6c1\n// by Jacob Zhong\nfunction bit_length(x){\n return x.toString(2).length\n}\n\n$B.nb_simple_gcd = 0\n\nfunction simple_gcd(a, b){\n /* a fits into a long, so b must too */\n $B.nb_simple_gcd++\n var x = a >= 0 ? a : -a,\n y = b >= 0 ? b : -b\n\n /* usual Euclidean algorithm for longs */\n while (y != 0) {\n t = y;\n y = x % y;\n x = t;\n }\n return x\n}\n\nfunction lgcd(x, y){\n var a, b, c, d\n if(x < y){\n return lgcd(y, x)\n }\n var shift = BigInt(Math.max(Math.floor(bit_length(x) / 64),\n Math.floor(bit_length(y) / 64))),\n xbar = x >> (shift * 64n),\n ybar = y >> (shift * 64n)\n while(y > p2_64){\n [a, b, c, d] = [1n, 0n, 0n, 1n]\n while(ybar + c != 0 && ybar + d != 0){\n q = (xbar + a) / (ybar + c)\n p = (xbar + b) / (ybar + d)\n if(q != p){\n break\n }\n [a, c] = [c, a - q * c]\n [b, d] = [d, b - q * d]\n [xbar, ybar] = [ybar, xbar - q * ybar]\n }\n if(b == 0){\n [x, y] = [y, x % y]\n }else{\n [x, y] = [a * x + b * y, c * x + d * y]\n }\n }\n return simple_gcd(x, y)\n}\n\nfunction xgcd(x, y){\n var xneg = x < 0 ? -1n : 1n,\n yneg = y < 0 ? -1n : 1n,\n last_r,\n last_s,\n last_t,\n q, r, s, t;\n\n [x, y] = [x >= 0 ? x : -x, y >= 0 ? y : -y];\n\n // it's maintained that r = s * x + t * y, last_r = last_s * x + last_t * y\n [last_r, r] = [x, y];\n [last_s, s] = [1n, 0n];\n [last_t, t] = [0n, 1n];\n\n while(r > 0){\n q = last_r / r;\n [last_r, r] = [r, last_r - q * r];\n [last_s, s] = [s, last_s - q * s];\n [last_t, t] = [t, last_t - q * t];\n }\n return [last_r, last_s * xneg, last_t * yneg]\n}\n\nfunction lxgcd(x, y){\n var g, cy, cx,\n s, last_s,\n t, last_t,\n a, b, c, d\n x = x >= 0 ? x : -x\n y = y >= 0 ? y : -y\n\n if(x < y){\n [g, cy, cx] = xgcd(y, x)\n return [g, cx, cy]\n }\n\n var shift = BigInt(Math.max(Math.floor(bit_length(x) / 64),\n Math.floor(bit_length(y) / 64))),\n xbar = x >> (shift * 64n),\n ybar = y >> (shift * 64n);\n\n [last_s, s] = [1n, 0n];\n [last_t, t] = [0n, 1n];\n\n while(y > p2_64){\n [a, b, c, d] = [1n, 0n, 0n, 1n]\n while(ybar + c != 0 && ybar + d != 0){\n q = (xbar + a) / (ybar + c)\n p = (xbar + b) / (ybar + d)\n if(q != p){\n break\n };\n [a, c = c], [a - q * c];\n [b, d = d], [b - q * d];\n [xbar, ybar] = [ybar, xbar - q * ybar];\n }\n if(b == 0){\n q = x / y;\n [x, y] = [y, x % y];\n [last_s, s] = [s, last_s - q * s];\n [last_t, t] = [t, last_t - q * t];\n }else{\n [x, y] = [a * x + b * y, c * x + d * y];\n [last_s, s] = [a * last_s + b * s, c * last_s + d * s];\n [last_t, t] = [a * last_t + b * t, c * last_t + d * t];\n }\n }\n // notice that here x, y could be negative\n [g, cx, cy] = xgcd(x, y)\n\n return [g, cx * last_s + cy * s, cx * last_t + cy * t]\n}\n\nfunction gcd(x, y){\n var $ = $B.args(\"gcd\", 0, {}, [], arguments, {}, 'args', null)\n var args = $.args.map($B.PyNumber_Index)\n if(args.length == 0){\n return 0\n }else if(args.length == 1){\n return _b_.abs(args[0])\n }\n x = _b_.int.$to_bigint(args[0])\n y = _b_.int.$to_bigint(args[1])\n var res = lxgcd(x, y)[0],\n i = 2\n while(i < args.length){\n res = lxgcd(res, _b_.int.$to_bigint(args[i]))[0]\n i++\n }\n return _b_.int.$int_or_long(res)\n}\n\n\nfunction hypot(x, y){\n var $ = $B.args(\"hypot\", 0, {}, [],\n arguments, {}, \"args\", null)\n var args = []\n for(var arg of $.args){\n try{\n args.push(float_check(arg))\n }catch(err){\n if($B.is_exc(err, [_b_.ValueError])){\n throw _b_.TypeError.$factory('must be real number, not ' +\n $B.class_name(arg))\n }\n throw err\n }\n }\n return $B.fast_float(Math.hypot(...args))\n}\n\nvar inf = INF\n\nfunction isclose(){\n var $ = $B.args(\"isclose\",\n 4,\n {a: null, b: null, rel_tol: null, abs_tol: null},\n ['a', 'b', 'rel_tol', 'abs_tol'],\n arguments,\n {rel_tol: $B.fast_float(1e-09),\n abs_tol: $B.fast_float(0.0)},\n '*',\n null)\n var a = float_check($.a),\n b = float_check($.b),\n rel_tol = float_check($.rel_tol),\n abs_tol = float_check($.abs_tol)\n\n if(rel_tol < 0.0 || abs_tol < 0.0){\n throw _b_.ValueError.$factory('tolerances must be non-negative')\n }\n\n if(a == b){\n return _b_.True\n }\n if(_b_.float.$funcs.isinf(a) || _b_.float.$funcs.isinf(b)){\n return a === b\n }\n // isclose(a, b, rel_tol, abs_tol) is the same as\n // abs_diff = abs(a - b)\n // max_ab = max(abs(a), abs(b))\n // abs_diff <= abs_tol or abs_diff / max_ab <= rel_tol\n // This is more correct than in Python docs:\n // \"abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)\"\n // because this fails for Decimal instances, which do not support\n // multiplication by floats\n\n var diff = b - a,\n abs_diff = Math.abs(diff)\n if(abs_diff <= abs_tol){\n return true\n }\n var abs_a = Math.abs(a),\n abs_b = Math.abs(b),\n max_ab = Math.max(abs_a, abs_b)\n return abs_diff / max_ab <= rel_tol\n}\n\nfunction isfinite(x){\n $B.check_nb_args('isfinite', 1, arguments)\n $B.check_no_kw('isfinite', x)\n return isFinite(float_check(x))\n}\n\nfunction isinf(x){\n $B.check_nb_args('isinf', 1, arguments)\n $B.check_no_kw('isinf', x)\n return _b_.float.$funcs.isinf(x)\n}\n\nfunction isnan(x){\n $B.check_nb_args('isnan', 1, arguments)\n $B.check_no_kw('isnan', x)\n return isNaN(float_check(x))\n}\n\nfunction isqrt(x){\n $B.check_nb_args_no_kw('isqrt', 1, arguments)\n\n x = $B.PyNumber_Index(x)\n if($B.rich_comp(\"__lt__\", x, 0)){\n throw _b_.ValueError.$factory(\n \"isqrt() argument must be nonnegative\")\n }\n if(typeof x == \"number\"){\n return Math.floor(Math.sqrt(x))\n }else{ // big integer\n // adapted from code in mathmodule.c\n var n = x.value,\n bit_length = n.toString(2).length,\n c = BigInt(Math.floor((bit_length - 1) / 2)),\n c_bit_length = c.toString(2).length,\n a = 1n,\n d = 0n,\n e\n\n for(var s = BigInt(c_bit_length - 1); s >= 0; s--){\n // Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2\n e = d\n d = c >> s\n a = (a << d - e - 1n) + (n >> 2n*c - e - d + 1n) / a\n }\n return _b_.int.$int_or_long(a - (a * a > n ? 1n : 0n))\n }\n}\n\nfunction lcm(){\n var $ = $B.args(\"lcm\", 0, {}, [], arguments, {}, 'args', null),\n product = 1\n\n var args = $.args.map($B.PyNumber_Index)\n if(args.length == 0){\n return 1\n }else if(args.length == 1){\n return _b_.abs(args[0])\n }\n var a = _b_.abs(args[0]),\n b,\n product, gcd\n for(var i = 0, len = args.length; i < len; i++){\n b = _b_.abs(args[i])\n if(b == 0){\n return 0\n }\n gcd = gcd2(a, b)\n product = $B.rich_op('__mul__', a, b)\n a = $B.$getattr(product, \"__floordiv__\")(gcd)\n }\n return a\n}\n\nfunction ldexp(x, i){\n $B.check_nb_args('ldexp', 2, arguments)\n $B.check_no_kw('ldexp', x, i)\n return _b_.float.$funcs.ldexp(x, i) // in py_float.js\n}\n\nfunction lgamma(x){\n $B.check_nb_args('lgamma', 1, arguments)\n $B.check_no_kw('lgamma', x)\n\n return m_lgamma(x)\n}\n\nfunction longint_mant_exp(long_int){\n // Returns mantissa and exponent of a long integer\n var value = long_int.value,\n exp = value.toString(2).length,\n exp1 = exp,\n nb = 0n\n // 2 ** exp is infinite if n > 1023\n var nb = Math.floor(exp / 1023),\n exp1 = BigInt(exp - 1023 * nb)\n nb = BigInt(nb)\n var reduced_value = long_int.value / 2n ** (nb * 1023n)\n var mant = Number(reduced_value) / Number(2n ** exp1)\n return [mant, exp]\n}\n\nvar log10_func = Math.log10 || (x => Math.log(x) / Math.log(10)),\n log2_func = Math.log2 || (x => Math.log(x) / Math.log(2))\n\nfunction log(x, base){\n var $ = $B.args(\"log\", 2, {x: null, base: null}, ['x', 'base'],\n arguments, {base: _b_.None}, null, null),\n x = $.x,\n base = $.base\n if(base == 10){\n return log10(x)\n }else if(base == 2){\n return log2(x)\n }\n var log\n if($B.$isinstance(x, $B.long_int)){\n if(x.value <= 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n var mant_exp = longint_mant_exp(x)\n log = Math.log(mant_exp[0]) + Math.log(2) * mant_exp[1]\n }else if($B.$isinstance(x, _b_.int)){\n x = _b_.int.$int_value(x)\n if(x <= 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n log = Math.log(x)\n }else{\n var x1 = float_check(x)\n if(x1 <= 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n log = Math.log(x1)\n }\n if(x1 <= 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if(base === _b_.None){\n return $B.fast_float(log)\n }\n var denom = _mod.log(base).value\n if(denom == 0){\n throw _b_.ZeroDivisionError.$factory('float division by zero')\n }\n return $B.fast_float(log / denom)\n}\n\nfunction log1p(x){\n $B.check_nb_args('log1p', 1, arguments)\n $B.check_no_kw('log1p', x)\n if($B.$isinstance(x, $B.long_int)){\n if($B.long_int.bit_length(x) > 1024){\n throw _b_.OverflowError.$factory(\n \"int too large to convert to float\")\n }\n x = $B.long_int.$log2($B.fast_long_int(x.value + 1n))\n return $B.fast_float(Number(x.value) * Math.LN2)\n }\n x = float_check(x)\n if(x + 1 <= 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return $B.fast_float(Math.log1p(x))\n}\n\nfunction log2(x){\n $B.check_nb_args('log2', 1, arguments)\n $B.check_no_kw('log2', x)\n var log2_func = Math.log2 || (x => Math.log(x) / Math.LN2)\n if($B.$isinstance(x, $B.long_int)){\n if(x.value <= 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n var mant_exp = longint_mant_exp(x)\n return $B.fast_float(log2_func(mant_exp[0]) + mant_exp[1])\n }\n if(_b_.float.$funcs.isninf(x)){\n throw _b_.ValueError.$factory('')\n }\n x = float_check(x)\n if(x == 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if(isNaN(x)){\n return _b_.float.$factory('nan')\n }\n if(x < 0.0){\n throw _b_.ValueError.$factory('math domain error')\n }\n return $B.fast_float(log2_func(x))\n}\n\nfunction log10(x){\n $B.check_nb_args('log10', 1, arguments)\n $B.check_no_kw('log10', x)\n if($B.$isinstance(x, $B.long_int)){\n return $B.fast_float($B.long_int.$log10(x).value)\n }\n x = float_check(x)\n if(x <= 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return $B.fast_float(Math.log10(x))\n}\n\nfunction modf(x){\n $B.check_nb_args('modf', 1, arguments)\n $B.check_no_kw('modf', x)\n\n if(_b_.float.$funcs.isninf(x)){\n return _b_.tuple.$factory([0.0, NINF])\n }\n if(_b_.float.$funcs.isinf(x)){\n return _b_.tuple.$factory([0.0, INF])\n }\n var x1 = float_check(x)\n\n if(isNaN(x1)){\n return _b_.tuple.$factory([_b_.float.$factory('nan'),\n _b_.float.$factory('nan')])\n }\n\n if(x1 > 0){\n var i = _b_.float.$factory(x1 - Math.floor(x1))\n return _b_.tuple.$factory([i, _b_.float.$factory(x1 - i.value)])\n }\n\n var x2 = Math.ceil(x1)\n var i = _b_.float.$factory(x1 - x2)\n return _b_.tuple.$factory([i, _b_.float.$factory(x2)])\n}\n\nvar nan = _b_.float.$factory('nan')\n\nfunction _nextafter(x, y){\n // always returns a Javascript number\n if($B.rich_comp('__lt__', y, x)){\n var nu = nextUp($B.rich_op('__mul__', -1, x))\n return -nu\n }else if($B.rich_comp('__gt__', y, x)){\n return nextUp(x)\n }else{\n var res = x !== x ? x : y\n res = typeof res == 'number' ? res : res.value\n return res\n }\n}\n\nfunction make_float(x){\n return typeof x == 'number' ? $B.fast_float(x) : x\n}\n\nfunction make_number(x){\n return typeof x == 'number' ? x : x.value\n}\n\nfunction doubleToByteArray(number) {\n // adapted from https://stackoverflow.com/questions/\n // 25942516/double-to-byte-array-conversion-in-javascript\n var buffer = new ArrayBuffer(8); // JS numbers are 8 bytes long, or 64 bits\n var longNum = new Float64Array(buffer); // so equivalent to Float64\n\n longNum[0] = number;\n\n return Array.from(new Uint8Array(buffer)).reverse(); // reverse to get little endian\n}\n\nfunction byteArrayToDouble(bytearray) {\n // adapted from https://stackoverflow.com/questions/\n // 42699162/javascript-convert-array-of-4-bytes-into-a-float-value-from-modbustcp-read\n // Create a buffer\n var buf = new ArrayBuffer(8);\n // Create a data view of it\n var view = new DataView(buf);\n\n // set bytes\n bytearray.forEach(function (b, i) {\n view.setUint8(i, b);\n });\n\n // Read the bits as a float\n var num = view.getFloat64(0);\n // Done\n return num\n}\n\nfunction addSteps(array, steps){\n // convert to BigInt, avoids issue when steps >= 2 ** 32\n if(steps.__class__ == $B.long_int){\n steps = steps.value\n }else{\n steps = BigInt(steps)\n }\n var positive = steps > 0n\n if(steps < 0n){\n steps = -steps\n }\n var x1 = steps >> 32n,\n x2 = steps - x1 * 2n ** 32n\n var buffer = new ArrayBuffer(8)\n var longStep = new BigInt64Array(buffer)\n longStep[0] = steps\n var stepArray = Array.from(new Uint8Array(buffer)).reverse()\n if(positive){\n var carry = 0\n for(var i = 7; i >= 0; i--){\n array[i] += stepArray[i] + carry\n if(array[i] > 255){\n carry = 1\n array[i] -= 256\n }else{\n carry = 0\n }\n }\n }else{\n var carry = 0\n for(var i = 7; i >= 0; i--){\n array[i] -= stepArray[i] - carry\n if(array[i] < 0){\n carry = -1\n array[i] += 256\n }else{\n carry = 0\n }\n }\n }\n}\n\nfunction nextafter(){\n var $ = $B.args(\"nextafter\", 3, {x: null, y: null, steps: null},\n ['x', 'y', 'steps'], arguments, {steps: _b_.None}, null, null),\n x = $.x,\n y = $.y,\n steps = $.steps\n if(! $B.$isinstance(x, [_b_.int, _b_.float])){\n throw _b_.TypeError.$factory('must be a real number, not ' +\n $B.class_name(x))\n }\n if(! $B.$isinstance(y, [_b_.int, _b_.float])){\n throw _b_.TypeError.$factory('must be a real number, not ' +\n $B.class_name(y))\n }\n if(isnan(x)){\n return make_float(x)\n }\n if(isnan(y)){\n return make_float(y)\n }\n if(steps === _b_.None){\n return $B.fast_float(_nextafter(x, y))\n }\n steps = $B.PyNumber_Index(steps);\n if(steps < 0) {\n throw _b_.ValueError.$factory(\n \"steps must be a non-negative integer\");\n }\n if(steps == 0){\n return make_float(x)\n }\n if(isnan(x)){\n return make_float(x)\n }\n if(isnan(y)){\n return make_float(y)\n }\n var x1 = make_number(x),\n y1 = make_number(y)\n\n if(y1 == x1){\n return make_float(y)\n }else if(y1 > x1){\n var x_uint64 = doubleToByteArray(x1)\n addSteps(x_uint64, steps)\n var res = byteArrayToDouble(x_uint64)\n return res >= y1 ? y : make_float(res)\n }else{\n var x_uint64 = doubleToByteArray(x1)\n addSteps(x_uint64, -steps)\n var res = byteArrayToDouble(x_uint64)\n return res <= y1 ? y : make_float(res)\n }\n}\n\nfunction perm(n, k){\n var $ = $B.args(\"perm\", 2, {n: null, k: null}, ['n', 'k'],\n arguments, {k: _b_.None}, null, null),\n n = $.n,\n k = $.k\n\n if(k === _b_.None){\n check_int(n)\n return _mod.factorial(n)\n }\n // raise TypeError if n or k is not an integer\n n = $B.PyNumber_Index(n)\n k = $B.PyNumber_Index(k)\n\n // transform to Javascript BigInt\n var n1 = _b_.int.$to_bigint(n),\n k1 = _b_.int.$to_bigint(k);\n\n if(k1 < 0){\n throw _b_.ValueError.$factory(\"k must be a non-negative integer\")\n }\n if(n1 < 0){\n throw _b_.ValueError.$factory(\"n must be a non-negative integer\")\n }\n if(k1 == 0){\n return 1\n }\n if(k1 == 1){\n return n\n }\n if(k1 == 2){\n return _b_.int.$int_or_long(n1 * (n1 - 1n))\n }\n if(k1 > n1){\n return 0\n }\n // Evaluates to n! / (n - k)!\n var fn = _mod.factorial(n),\n fn_k = _mod.factorial(n - k)\n return $B.rich_op('__floordiv__', fn, fn_k)\n}\n\nconst pi = $B.fast_float(Math.PI)\n\nfunction pow(){\n var $ = $B.args(\"pow\", 2, {base: null, exp: null}, ['base', 'exp'],\n arguments, {}, null, null),\n x = $.base,\n y = $.exp\n\n var x1 = float_check(x)\n var y1 = float_check(y)\n\n if(y1 == 0){\n return _b_.float.$factory(1)\n }\n if(x1 == 0 && y1 < 0){\n if(y1 === -Infinity){\n return INF\n }\n throw _b_.ValueError.$factory('math domain error')\n }\n if(isFinite(x1) && x1 < 0 && isFinite(y1) && ! Number.isInteger(y1)){\n throw _b_.ValueError.$factory('math domain error')\n }\n\n if(isNaN(y1)){\n if(x1 == 1){return _b_.float.$factory(1)}\n return NAN\n }\n if(x1 == 0){\n return ZERO\n }\n\n if(_b_.float.$funcs.isninf(y)){\n if(_b_.float.$funcs.isinf(x)){ // pow(INF, NINF) = 0.0\n return ZERO\n }else if(_b_.float.$funcs.isninf(x)){ // pow(NINF, NINF) = 0.0\n return ZERO\n }\n if(x1 == 1 || x1 == -1){return _b_.float.$factory(1)}\n if(x1 < 1 && x1 > -1){return INF}\n return ZERO\n }\n if(_b_.float.$funcs.isinf(y)){\n if(_b_.float.$funcs.isinf(x)){ // pow(INF, INF)\n return INF\n }\n if(_b_.float.$funcs.isninf(x)){\n return INF\n }\n if(x1 == 1 || x1 == -1){return _b_.float.$factory(1)}\n if(x1 < 1 && x1 > -1){return ZERO}\n return INF\n }\n\n if(isNaN(x1)){return _b_.float.$factory('nan')}\n if(_b_.float.$funcs.isninf(x)){\n if(y1 > 0 && isOdd(y1)){return NINF}\n if(y1 > 0){return INF} // this is even or a float\n if(y1 < 0){return ZERO}\n if(_b_.float.$float.isinf(y)){return INF}\n return _b_.float.$factory(1)\n }\n\n if(_b_.float.$funcs.isinf(x)){\n if(y1 > 0){return INF}\n if(y1 < 0){return ZERO}\n return _b_.float.$factory(1)\n }\n\n var r = Math.pow(x1, y1)\n if(isNaN(r)){\n return NAN\n }\n if(! isFinite(r)){\n overflow()\n }\n return _b_.float.$factory(r)\n}\n\nfunction prod(){\n var $ = $B.args(\"prod\", 1, {iterable:null, start:null},\n [\"iterable\", \"start\"], arguments, {start: 1}, \"*\",\n null),\n iterable = $.iterable,\n start = $.start\n var res = start,\n it = _b_.iter(iterable),\n x\n while(true){\n try{\n x = _b_.next(it)\n if(x == 0){\n return 0\n }\n res = $B.rich_op('__mul__', res, x)\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n return res\n }\n throw err\n }\n }\n}\n\nfunction radians(x){\n $B.check_nb_args('radians', 1, arguments)\n $B.check_no_kw('radians', x)\n\n return _b_.float.$factory(float_check(x) * Math.PI / 180)\n}\n\nfunction is_finite(x){\n return typeof x == \"number\" ||\n (x.__class__ === _b_.floar && isFinite(x.value)) ||\n $B.$isinstance(x, _b_.int) ||\n ($B.$isinstance(x, _b_.float) && isFinite(x.value))\n}\n\nfunction remainder(x, y){\n $B.check_nb_args_no_kw('remainder', 2, arguments)\n float_check(x) // might raise TypeError\n /* Deal with most common case first. */\n if(is_finite(x) && is_finite(y)){\n var absx,\n absy,\n c,\n m,\n r;\n\n if(float_check(y) == 0.0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n\n absx = fabs(x);\n absy = fabs(y);\n m = fmod(absx, absy);\n\n c = absy.value - m.value\n if(m.value < c){\n r = m.value\n }else if(m.value > c){\n r = -c\n }else{\n r = m.value -\n 2.0 * fmod($B.fast_float(0.5 * (absx.value - m.value)), absy).value;\n }\n return $B.fast_float(copysign(1.0, x).value * r);\n }\n\n /* Special values. */\n if(float_check(y) == 0){\n if(isnan(x)){\n return x\n }\n }\n if(isinf(x)){\n if(isnan(y)){\n return y\n }\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if(isnan(y)){\n return y;\n }\n return x;\n}\n\nfunction sin(x){\n $B.check_nb_args('sin ', 1, arguments)\n $B.check_no_kw('sin ', x)\n return _b_.float.$factory(Math.sin(float_check(x)))\n}\n\nfunction sinh(x) {\n $B.check_nb_args('sinh', 1, arguments)\n $B.check_no_kw('sinh', x)\n\n var y = float_check(x)\n if(Math.sinh !== undefined){\n return _b_.float.$factory(Math.sinh(y))\n }\n return _b_.float.$factory(\n (Math.pow(Math.E, y) - Math.pow(Math.E, -y)) / 2)\n}\n\nfunction sqrt(x){\n $B.check_nb_args('sqrt ', 1, arguments)\n $B.check_no_kw('sqrt ', x)\n\n if(_b_.float.$funcs.isninf(x)){\n value_error()\n }else if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n var y = float_check(x)\n if(y < 0){\n value_error()\n }\n var _r = $B.fast_float(Math.sqrt(y))\n if(_b_.float.$funcs.isinf(_r)){\n overflow()\n }\n return _r\n}\n\n/*[clinic input]\nmath.sumprod\n\n p: object\n q: object\n /\n\nReturn the sum of products of values from two iterables p and q.\n\nRoughly equivalent to:\n\n sum(itertools.starmap(operator.mul, zip(p, q, strict=True)))\n\nFor float and mixed int/float inputs, the intermediate products\nand sums are computed with extended precision.\n[clinic start generated code]*/\n\nconst tl_zero = {hi: 0, lo: 0, tiny: 0}\n\nfunction _check_long_mult_overflow(a, b) {\n\n /* From Python2's int_mul code:\n\n Integer overflow checking for * is painful: Python tried a couple ways, but\n they didn't work on all platforms, or failed in endcases (a product of\n -sys.maxint-1 has been a particular pain).\n\n Here's another way:\n\n The native long product x*y is either exactly right or *way* off, being\n just the last n bits of the true product, where n is the number of bits\n in a long (the delivered product is the true product plus i*2**n for\n some integer i).\n\n The native double product (double)x * (double)y is subject to three\n rounding errors: on a sizeof(long)==8 box, each cast to double can lose\n info, and even on a sizeof(long)==4 box, the multiplication can lose info.\n But, unlike the native long product, it's not in *range* trouble: even\n if sizeof(long)==32 (256-bit longs), the product easily fits in the\n dynamic range of a double. So the leading 50 (or so) bits of the double\n product are correct.\n\n We check these two ways against each other, and declare victory if they're\n approximately the same. Else, because the native long product is the only\n one that can lose catastrophic amounts of information, it's the native long\n product that must have overflowed.\n\n */\n\n /*\n\n var longprod = (long)((unsigned long)a * b);\n double doubleprod = (double)a * (double)b;\n double doubled_longprod = (double)longprod;\n\n if (doubled_longprod == doubleprod) {\n return 0;\n }\n\n const double diff = doubled_longprod - doubleprod;\n const double absdiff = diff >= 0.0 ? diff : -diff;\n const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;\n\n if (32.0 * absdiff <= absprod) {\n return 0;\n }\n\n return 1;\n */\n return 0\n}\n\nfunction long_add_would_overflow(a, b){\n return (a > 0n) ? (b > BigInt(LONG_MAX) - a) : (b < BigInt(LONG_MIN) - a);\n}\n\nfunction PyLong_CheckExact(n){\n return typeof n == 'number' || n.__class__ === $B.long_int\n}\n\n/*\n The default implementation of dl_mul() depends on the C math library\n having an accurate fma() function as required by \u00a7 7.12.13.1 of the\n C99 standard.\n\n The UNRELIABLE_FMA option is provided as a slower but accurate\n alternative for builds where the fma() function is found wanting.\n The speed penalty may be modest (17% slower on an Apple M1 Max),\n so don't hesitate to enable this build option.\n\n The algorithms are from the T. J. Dekker paper:\n A Floating-Point Technique for Extending the Available Precision\n https://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf\n*/\n\nfunction dl_split(x) {\n // Dekker (5.5) and (5.6).\n var t = x * 134217729.0; // Veltkamp constant = 2.0 ** 27 + 1\n var hi = t - (t - x);\n var lo = x - hi;\n return {hi, lo};\n}\n\nfunction dl_mul(x, y){\n // Dekker (5.12) and mul12()\n var xx = dl_split(x);\n var yy = dl_split(y);\n var p = xx.hi * yy.hi;\n var q = xx.hi * yy.lo + xx.lo * yy.hi;\n var z = p + q;\n var zz = p - z + q + xx.lo * yy.lo;\n return {hi: z, lo: zz};\n}\n\nfunction dl_sum(a, b){\n /* Algorithm 3.1 Error-free transformation of the sum */\n var x = a + b;\n var z = x - a;\n var y = (a - (x - z)) + (b - z);\n return {hi: x, lo: y};\n}\n\nfunction tl_fma(x, y, total){\n /* Algorithm 5.10 with SumKVert for K=3 */\n var pr = dl_mul(x, y);\n var sm = dl_sum(total.hi, pr.hi);\n var r1 = dl_sum(total.lo, pr.lo);\n var r2 = dl_sum(r1.hi, sm.lo);\n return {hi: sm.hi, lo: r2.hi, tiny: total.tiny + r1.lo + r2.lo}\n}\n\nfunction tl_to_d(total){\n var last = dl_sum(total.lo, total.hi);\n return total.tiny + last.lo + last.hi;\n}\n\nfunction sumprod(p, q){\n var $ = $B.args('sumprod', 2, {p: null, q: null}, ['p', 'q'],\n arguments, {}, null, null)\n var p_i = NULL,\n q_i = NULL,\n term_i = NULL,\n new_total = NULL;\n var p_it, q_it, total;\n var p_next, q_next;\n var p_stopped = false, q_stopped = false;\n var int_path_enabled = true,\n int_total_in_use = false;\n var flt_path_enabled = true,\n flt_total_in_use = false;\n var int_total = 0n;\n var flt_total = tl_zero;\n\n p_it = $B.make_js_iterator(p);\n q_it = $B.make_js_iterator(q);\n total = 0\n p_next = p_it.next\n q_next = q_it.next\n while (1) {\n var finished;\n p_i = p_it.next()\n if (p_i.done) {\n p_stopped = true;\n }else{\n p_i = p_i.value\n }\n q_i = q_it.next()\n if (q_i.done) {\n q_stopped = true;\n }else{\n q_i = q_i.value\n }\n if (p_stopped != q_stopped) {\n throw _b_.ValueError.$factory(\"Inputs are not the same length\");\n }\n\n finished = p_stopped & q_stopped;\n\n if (int_path_enabled) {\n\n if (! finished && PyLong_CheckExact(p_i) & PyLong_CheckExact(q_i)) {\n var overflow;\n var int_p, int_q, int_prod;\n\n int_p = _b_.int.$to_bigint($B.PyNumber_Index(p_i))\n overflow = int_p > LONG_MAX || int_p < LONG_MIN\n\n if (overflow) {\n finalize_int_path()\n }\n int_q = _b_.int.$to_bigint($B.PyNumber_Index(q_i));\n overflow = int_q > LONG_MAX || int_q < LONG_MIN\n if (overflow) {\n finalize_int_path()\n }\n if (_check_long_mult_overflow(int_p, int_q)) {\n finalize_int_path()\n }\n int_prod = int_p * int_q;\n if (long_add_would_overflow(int_total, int_prod)) {\n finalize_int_path()\n }\n if(int_path_enabled){\n int_total = int_total + int_prod;\n int_total_in_use = true;\n continue;\n }\n }\n\n if(finished){\n finalize_int_path()\n }\n\n function finalize_int_path(){\n // We're finished, overflowed, or have a non-int\n int_path_enabled = false;\n if (int_total_in_use) {\n term_i = _b_.int.$int_or_long(int_total);\n new_total = $B.rich_op('__add__', total, term_i);\n total = new_total\n new_total = NULL;\n int_total = 0; // An ounce of prevention, ...\n int_total_in_use = false;\n }\n }\n }\n\n if (flt_path_enabled) {\n\n if (!finished) {\n var flt_p, flt_q;\n var p_type_float = p_i.__class__ === _b_.float;\n var q_type_float = q_i.__class__ === _b_.float\n if(p_type_float && q_type_float) {\n flt_p = p_i;\n flt_q = q_i;\n }else if (p_type_float && (PyLong_CheckExact(q_i) ||\n typeof q_i == 'boolean')){\n /* We care about float/int pairs and int/float pairs because\n they arise naturally in several use cases such as price\n times quantity, measurements with integer weights, or\n data selected by a vector of bools. */\n flt_p = p_i\n flt_q = _b_.int.$int_value(q_i)\n }else if(q_type_float && (PyLong_CheckExact(p_i) ||\n typeof p_i == 'boolean')) {\n flt_q = q_i\n flt_p = _b_.int.$int_value(p_i)\n }else{\n finalize_flt_path()\n }\n if(flt_path_enabled){\n var new_flt_total = tl_fma(flt_p.value, flt_q.value, flt_total);\n if (isfinite(new_flt_total.hi)) {\n flt_total = new_flt_total;\n flt_total_in_use = true;\n continue;\n }\n }\n }\n if(finished){\n finalize_flt_path()\n }\n\n function finalize_flt_path(){\n // We're finished, overflowed, have a non-float, or got a non-finite value\n flt_path_enabled = false;\n if(flt_total_in_use){\n term_i = $B.fast_float(tl_to_d(flt_total));\n if (term_i == NULL) {\n err_exit()\n }\n new_total = $B.rich_op('__add__', total, term_i);\n total = new_total\n new_total = NULL\n flt_total = tl_zero;\n flt_total_in_use = false;\n }\n }\n }\n\n if (finished) {\n return total\n }\n term_i = $B.rich_op('__mul__', p_i, q_i);\n new_total = $B.rich_op('__add__', total, term_i);\n total = new_total\n new_total = NULL;\n }\n\n}\n\n\n\nfunction tan(x) {\n $B.check_nb_args('tan', 1, arguments)\n $B.check_no_kw('tan', x)\n\n var y = float_check(x)\n return _b_.float.$factory(Math.tan(y))\n}\n\nfunction tanh(x) {\n $B.check_nb_args('tanh', 1, arguments)\n $B.check_no_kw('tanh', x)\n\n var y = float_check(x)\n if(Math.tanh !== undefined){return _b_.float.$factory(Math.tanh(y))}\n return _b_.float.$factory((Math.pow(Math.E, y) - Math.pow(Math.E, -y))/\n (Math.pow(Math.E, y) + Math.pow(Math.E, -y)))\n}\n\nconst tau = $B.fast_float(2 * Math.PI)\n\nfunction trunc(x) {\n $B.check_nb_args('trunc', 1, arguments)\n $B.check_no_kw('trunc', x)\n\n try{\n return $B.$getattr(x, '__trunc__')()\n }catch(err){\n }\n var x1 = float_check(x)\n if(!isNaN(parseFloat(x1)) && isFinite(x1)){\n if(Math.trunc !== undefined){\n return _b_.int.$factory(Math.trunc(x1))\n }\n if(x1 > 0){\n return _b_.int.$factory(Math.floor(x1))\n }\n return _b_.int.$factory(Math.ceil(x1)) // x1 < 0\n }\n throw _b_.ValueError.$factory(\n 'object is not a number and does not contain __trunc__')\n}\n\nfunction ulp(){\n var $ = $B.args(\"ulp\", 1, {x: null}, ['x'], arguments, {}, null, null),\n x = $.x\n if($B.$isinstance(x, _b_.float)){\n if(_b_.float.$funcs.isinf(x)){\n return _mod.inf\n }else if(_b_.float.$funcs.isnan(x)){\n return _mod.nan\n }\n }\n if(typeof x == \"number\"){\n return x >= 0 ? $B.fast_float(nextUp(x) - x) :\n $B.fast_float(x - (-nextUp(-x)))\n }else if($B.$isinstance(x, $B.long_int)){\n x = Number(_b_.int.$to_bigint(x))\n return x > 0 ? $B.fast_float(nextUp(x) - x) :\n $B.fast_float(x - (-nextUp(-x)))\n }else{\n if($B.rich_comp('__ge__', x, 0)){\n return $B.rich_op('__sub__', $B.fast_float(nextUp(x.value)), x)\n }else{\n var neg_x = $B.$call($B.$getattr(x, \"__neg__\"))()\n return $B.rich_op('__sub__', x,\n $B.$call($B.$getattr($B.fast_float(nextUp(neg_x.value)), '__neg__'))())\n }\n }\n}\n\nvar _mod = {\n acos,\n acosh,\n asin,\n asinh,\n atan,\n atan2,\n atanh,\n cbrt,\n ceil,\n comb,\n copysign,\n cos,\n cosh,\n degrees,\n dist,\n e,\n erf,\n erfc,\n exp,\n exp2,\n expm1,\n fabs,\n factorial,\n floor,\n fma,\n fmod,\n frexp,\n fsum,\n gamma,\n gcd,\n hypot,\n inf,\n isclose,\n isfinite,\n isinf,\n isnan,\n isqrt,\n lcm,\n ldexp,\n lgamma,\n log,\n log1p,\n log2,\n log10,\n modf,\n nan,\n nextafter,\n perm,\n pi,\n pow,\n prod,\n radians,\n remainder,\n sin,\n sinh,\n sqrt,\n sumprod,\n tan,\n tanh,\n tau,\n trunc,\n ulp\n}\n\nfor(var $attr in _mod){\n if(typeof _mod[$attr] === 'function'){\n _mod[$attr].__class__ = $B.builtin_function_or_method\n }\n}\n\n$B.addToImported('math', _mod)\n\n})(__BRYTHON__)\n"], "modulefinder": [".js", "(function($B){\n\nvar _b_=$B.builtins\nvar _mod = {}\n\n$ModuleFinderDict = {__class__:_b_.type,__name__:'ModuleFinder'}\n$ModuleFinderDict.__mro__ = [_b_.object]\n\n$ModuleFinderDict.run_script = function(self, pathname){\n // pathname is the url of a Python script\n var py_src = _b_.$open(pathname).read()\n // transform into internal Brython tree structure\n var root = $B.py2js(py_src)\n // walk the tree to find occurences of imports\n function walk(node){\n var modules = []\n var ctx = node.context\n if(ctx && ctx.type=='node'){ctx = ctx.tree[0]}\n\n if(ctx && ctx.type==\"import\"){\n for(var i=0, _len_i = ctx.tree.length; i < _len_i;i++){\n if(modules.indexOf(ctx.tree[i].name)==-1){\n modules.push(ctx.tree[i].name)\n }\n }\n }else if(ctx && ctx.type==\"from\"){\n if(modules.indexOf(ctx.module)==-1){\n modules.push(ctx.module)\n }\n }\n\n for(var i=0, _len_i = node.children.length; i < _len_i;i++){\n mods = walk(node.children[i])\n for(var j=0, _len_j = mods.length; j < _len_j;j++){\n if(modules.indexOf(mods[j])==-1){modules.push(mods[j])}\n }\n }\n return modules\n }\n self.modules = walk(root)\n}\n\n_mod.ModuleFinder = function(){return {__class__:$ModuleFinderDict}\n}\n_mod.ModuleFinder.$dict = $ModuleFinderDict\n_mod.ModuleFinder.__class__ = $B.$factory\n$ModuleFinderDict.$factory = _mod.ModuleFinder\n\n$B.addToImported('modulefinder', _mod)\n\n})(__BRYTHON__)\n"], "posix": [".js", "/*\nThis module provides access to operating system functionality that is\nstandardized by the C Standard and the POSIX standard (a thinly\ndisguised Unix interface). Refer to the library manual and\ncorresponding Unix manual entries for more information on calls.\n*/\nvar $B = __BRYTHON__,\n _b_ = $B.builtins\n\nfunction _randint(a, b){\n return parseInt(Math.random() * (b - a + 1) + a)\n}\n\nvar stat_result = $B.make_class(\"stat_result\",\n function(filename){\n filename = _b_.str.$factory(filename)\n if($B.file_cache && $B.file_cache.hasOwnProperty(filename)){\n var f = $B.file_cache[filename],\n res = {\n __class__: stat_result,\n st_atime: __BRYTHON__.timestamp,\n st_ctime: f.ctime,\n st_mtime: f.mtime,\n st_uid: -1,\n st_gid: -1,\n st_ino: -1,\n st_mode: 0,\n st_size: f.length\n };\n [\"mtime\", \"ctime\", \"atime_ns\", \"mtime_ns\", \"ctime_ns\"].\n forEach(function(item){\n res[\"st_\" + item] = res.st_atime\n });\n return res\n }else if($B.files && $B.files.hasOwnProperty(filename)){\n var f = $B.files[filename],\n res = {\n __class__: stat_result,\n st_atime: __BRYTHON__.timestamp,\n st_ctime: f.ctime,\n st_mtime: f.mtime,\n st_uid: -1,\n st_gid: -1,\n st_ino: -1,\n st_mode: 0,\n st_size: f.content.length\n };\n for(var item of [\"mtime\", \"ctime\", \"atime_ns\", \"mtime_ns\", \"ctime_ns\"]){\n res[\"st_\" + item] = res.st_atime\n }\n return res\n\n }else{\n var res = {\n __class__: stat_result,\n st_atime: __BRYTHON__.timestamp,\n st_uid: -1,\n st_gid: -1,\n st_ino: -1,\n st_mode: filename.endsWith('/') ? 16895 : 33206,\n st_size: 1 // fake\n };\n [\"mtime\", \"ctime\", \"atime_ns\", \"mtime_ns\", \"ctime_ns\"].\n forEach(function(item){\n res[\"st_\" + item] = res.st_atime\n });\n return res\n }\n }\n)\n$B.set_func_names(stat_result, \"posix\")\n\nvar module = {\n F_OK: 0,\n O_APPEND: 8,\n O_BINARY: 32768,\n O_CREAT: 256,\n O_EXCL: 1024,\n O_NOINHERIT: 128,\n O_RANDOM: 16,\n O_RDONLY: 0,\n O_RDWR: 2,\n O_SEQUENTIAL: 32,\n O_SHORT_LIVED: 4096,\n O_TEMPORARY: 64,\n O_TEXT: 16384,\n O_TRUNC: 512,\n O_WRONLY: 1,\n P_DETACH: 4,\n P_NOWAIT: 1,\n P_NOWAITO: 3,\n P_OVERLAY: 2,\n P_WAIT: 0,\n R_OK: 4,\n TMP_MAX: 32767,\n W_OK: 2,\n X_OK: 1,\n _have_functions: $B.$list(['MS_WINDOWS']),\n environ: _b_.dict.$from_array(\n [['PYTHONPATH', $B.brython_path],\n ['PYTHONUSERBASE', ' ']]),\n error: _b_.OSError,\n fspath: function(path){\n return path\n },\n getcwd: function(){\n return $B.brython_path\n },\n getpid: function(){\n return 0\n },\n lstat: function(filename){\n return stat_result.$factory(filename)\n },\n open: function(path, flags){\n return _b_.open(path, flags)\n },\n remove: function(path) {\n var $ = $B.args(\"remove\", 1, { path: null }, [\"path\"], arguments, {}, null, null)\n console.log($)\n\n var path = $.path\n var found_file = false\n\n if ($B.file_cache && $B.file_cache.hasOwnProperty(path)){\n delete $B.file_cache[path]\n found_file = true\n }\n if ($B.files && $B.files.hasOwnProperty(path)){\n delete $B.files[path]\n found_file = true\n }\n\n if(!found_file) {\n throw _b_.FileNotFoundError.$factory(`No such file or directory: '${path}'`)\n }\n\n return _b_.None\n },\n stat: function(filename){\n return stat_result.$factory(filename)\n },\n stat_result: function(filename){\n return stat_result.$factory(filename)\n },\n urandom: function(n){\n const randbytes = new Uint8Array(n);\n crypto.getRandomValues(randbytes);\n return _b_.bytes.$factory(Array.from(randbytes));\n },\n WTERMSIG: function(){\n return 0\n },\n WNOHANG: function(){\n return _b_.tuple.$factory([0, 0])\n }\n};\n\n[\"WCOREDUMP\", \"WIFCONTINUED\", \"WIFSTOPPED\", \"WIFSIGNALED\", \"WIFEXITED\"].forEach(function(funcname){\n module[funcname] = function(){return false}\n });\n\n[\"WEXITSTATUS\", \"WSTOPSIG\", \"WTERMSIG\"].\n forEach(function(funcname){\n module[funcname] = function(){return _b_.None}\n });\n\n[\"_exit\", \"_getdiskusage\", \"_getfileinformation\", \"_getfinalpathname\",\n \"_getfullpathname\", \"_isdir\", \"abort\", \"access\", \"chdir\", \"chmod\",\n \"close\", \"closerange\", \"device_encoding\", \"dup\", \"dup2\",\n \"execv\", \"execve\", \"fsat\", \"fsync\", \"get_terminal_size\", \"getcwdb\",\n \"getlogin\", \"getppid\", \"isatty\", \"kill\", \"link\", \"listdir\", \"lseek\",\n \"mkdir\", \"pipe\", \"putenv\", \"read\", \"readlink\", \"rename\",\n \"replace\", \"rmdir\", \"spawnv\", \"spawnve\", \"startfile\", \"stat_float_times\",\n \"statvfs_result\", \"strerror\", \"symlink\", \"system\", \"terminal_size\",\n \"times\", \"times_result\", \"umask\", \"uname_result\", \"unlink\", \"utime\",\n \"waitpid\", \"write\"].forEach(function(funcname){\n module[funcname] = function(){\n throw _b_.NotImplementedError.$factory(\"posix.\" + funcname +\n \" is not implemented\")\n }\n });\n\n$B.addToImported('posix', module)"], "pyexpat": [".js", "(function($B){\n\n$B.$import('xml_parser')\n\nvar model = $B.imported.xml_parser.models\nconsole.log('model', model)\n\nvar _b_ = $B.builtins\n\nconst XML_PARAM_ENTITY_PARSING_NEVER = 0,\n XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE = 1,\n XML_PARAM_ENTITY_PARSING_ALWAYS = 2\n\nconst FAIL = {}\n\nconst xml_entities = {\n '>': '>',\n '<': '<',\n '"': '\"',\n ''': \"'\",\n '&': '&'\n }\n\nvar xmlparser = $B.make_class('xmlparser',\n function(encoding, namespace_separator, intern){\n return {\n __class__: xmlparser,\n __dict__: $B.empty_dict(),\n encoding,\n namespace_separator,\n intern,\n buffer_text: false,\n _buffer: '',\n _state: 'data',\n _data_buffer: '',\n _initialized: false,\n _maybe_entity: null,\n _element_stack: [],\n _chunk_size: 2 << 14\n }\n }\n)\n\nxmlparser._handle_stack = function(self){\n if(! (self._element instanceof ELEMENT)){\n return\n }\n if(self._element.name === undefined){\n console.log('name undefined', self._element)\n alert()\n }\n if(self._element.is_end){\n if(self._element_stack.length == 0){\n raise_error(self, 'no opening tag for closing ' + self._element.name)\n }else{\n var expected = $B.last(self._element_stack)\n if(expected !== self._element.name){\n console.log('error handle stack, stack', self._element_stack, self._element)\n raise_error(self, `tag mismatch, ` +\n `expected closing tag ${expected}, ` +\n `got: ${self._element.name}`)\n }\n self._element_stack.pop()\n if(self._element_stack.length == 0){\n flush_char_data(self)\n }\n }\n }else if(! self._element.self_closing){\n self._element_stack.push(self._element.name)\n }\n}\n\nxmlparser.CharacterDataHandler = _b_.None\n\nxmlparser.CommentHandler = _b_.None\n\nxmlparser.EndElementHandler = _b_.None\n\nfunction check_entity(parser, pos){\n var entity = parser._maybe_entity\n var decimal = /&#(\\d+);$/.exec(entity)\n if(decimal){\n return _b_.chr(parseInt(decimal[1]))\n }\n var hexa = /&#x(\\d+);$/.exec(entity)\n if(hexa){\n return _b_.chr(parseInt(hexa[1], 16))\n }\n var xml_entity = xml_entities[entity]\n if(xml_entity){\n return xml_entity\n }\n raise_error_known_position(parser, `unknown entity: \"${entity}\"`, pos)\n}\n\nfunction flush_char_data(parser){\n var buf = parser._data_buffer\n if(buf.length > 0){\n let handler = parser._handlers.CharacterDataHandler\n if(handler !== _b_.None){\n handler(buf)\n }\n }\n parser._data_buffer = ''\n}\n\nfunction flush_final_char_data(parser){\n var buf = parser._data_buffer\n for(var i = 0; i < buf.length; i++){\n if(! buf[i].match(/\\s/)){\n var pos = parser._pos - buf.length + i - 1\n console.log('rest', buf)\n var msg = `junk after document element: line 1, column ${pos}`\n raise_error(parser, msg)\n }\n }\n}\n\nconst encoding_re = /<\\?xml .*encoding\\s*=\\s*\"(.*?)\"/\n\nconst handler_names = [\n 'CharacterDataHandler',\n 'CommentHandler',\n 'StartElementHandler',\n 'EndElementHandler',\n 'XmlDeclHandler'\n ]\n\nxmlparser.Parse = function(){\n var $ = $B.args('Parse', 3,\n {self: null, data: null, isfinal: null},\n ['self', 'data', 'isfinal'], arguments,\n {}, null, null),\n self = $.self,\n data = $.data,\n isfinal = $.isfinal,\n decoder,\n array\n if(self.finished){\n throw Error('parsing finished')\n }\n if(_b_.isinstance(data, _b_.bytes)){\n if(self.encoding === _b_.None){\n // try getting encoding from prolog\n decoder = new TextDecoder('iso-8859-1')\n array = new Uint8Array(data.source.slice(0, 200))\n var head = decoder.decode(array)\n var mo = encoding_re.exec(head)\n if(mo){\n self.encoding = mo[1]\n }else{\n self.encoding = 'utf-8' // default\n }\n }\n // decode bytes\n decoder = new TextDecoder(self.encoding)\n array = new Uint8Array(data.source)\n data = decoder.decode(array)\n }\n if(! self._initialized){\n if(data[0] != '<'){\n throw Error(\"XML or text declaration not at start of entity\")\n }\n self._initialized = true\n }\n self._buffer = data\n self._buffer_length = _b_.len(data)\n self._pos = 0\n\n var handlers = self._handlers = {}\n for(var handler_name of handler_names){\n let handler = $B.$getattr(self, handler_name)\n if(handler !== _b_.None){\n handlers[handler_name] = $B.$call(handler)\n }else{\n handlers[handler_name] = _b_.None\n }\n }\n\n for(var token of xmlparser.xml_tokenizer(self)){\n if(token instanceof ELEMENT){\n if(! token.is_declaration && ! token.is_end){\n if(handlers.StartElementHandler !== _b_.None){\n flush_char_data(self)\n handlers.StartElementHandler(token.name, token.attrs)\n }\n if(token.self_closing &&\n handlers.EndElementHandler !== _b_.None){\n handlers.EndElementHandler(token.name)\n }\n }else if(token.is_end &&\n handlers.EndElementHandler !== _b_.None){\n flush_char_data(self)\n handlers.EndElementHandler(token.name)\n }\n }else if(token instanceof DATA &&\n handlers.CharacterDataHandler !== _b_.None){\n handlers.CharacterDataHandler(token.value)\n }else if(token instanceof COMMENT &&\n handlers.CommentHandler !== _b_.None){\n flush_char_data(self)\n handlers.CommentHandler(token.value)\n }\n }\n flush_final_char_data(self)\n if(isfinal){\n self.finished = true\n }\n}\n\nxmlparser.ParseFile = function(){\n var $ = $B.args('ParseFile', 2,\n {self: null, file: null},\n ['self', 'file'], arguments,\n {}, null, null),\n self = $.self,\n file = $.file\n var reader = $B.$call($B.$getattr(file, 'read'))\n while(true){\n var data = reader(self._chunk_size)\n console.log('ParseFile, data', data)\n if(_b_.len(data) == 0){\n return xmlparser.Parse(self, data, true)\n }else{\n xmlparser.Parse(self, data, false)\n }\n }\n}\n\nxmlparser.SetBase = function(self, base){\n self._base = base\n return _b_.None\n}\n\nxmlparser.SetParamEntityParsing = function(self, peParsing){\n self._peParsing = peParsing\n return peParsing\n}\n\nxmlparser.StartElementHandler = _b_.None\n\nxmlparser.xml_tokenizer = function*(self){\n // convert bytes to string\n self._element = new $B.imported.xml_parser.DOCUMENT(self)\n while(self._pos < self._buffer_length){\n var char = self._buffer[self._pos]\n self._element = self._element.feed(char)\n if(self._element.closed){\n yield self._element\n }\n self._pos++\n }\n console.log('element', self._element)\n console.log('fini')\n alert()\n}\n\n$B.set_func_names(xmlparser, 'expat')\n\nfunction raise_error_known_position(parser, message, pos){\n message += ' at position ' + pos\n var ix = pos\n while(ix >= 0 && parser._buffer[ix] !== '\\n'){\n ix--\n }\n message += '\\n' + parser._buffer.substring(ix, pos + 1)\n message += '\\n' + ' '.repeat(pos - ix - 1) + '^'\n throw error.$factory(message)\n}\n\nfunction raise_error(parser, message){\n throw error.$factory(message)\n}\n\nfunction raise_error1(element, char){\n var head = element\n while(head.origin){\n head = head.origin\n }\n console.log(head)\n var cls = element.constructor.name,\n message = cls + ' expected ' + element.expect +\n ', got: ' + char\n var pos = head.parser._pos\n raise_error_known_position(head.parser, message, pos)\n}\n\nvar error = $B.make_class(\"error\",\n function(message){\n return {\n __class__: error,\n msg: message,\n args: $B.fast_tuple([message]),\n __cause__: _b_.None,\n __context__: _b_.None,\n __suppress_context__: false\n }\n })\nerror.__bases__ = [_b_.Exception, _b_.object]\nerror.__mro__ = [_b_.Exception, _b_.BaseException, _b_.object]\n\n$B.set_func_names(error, \"expat\")\n\nfunction expect_chars(element, char, stop){\n var res\n if(! element.hasOwnProperty('expected_chars')){\n element.expected_chars = ''\n }\n if(is_char(char)){\n element.expected_chars += char\n if(stop){\n var end_pos = element.expected_chars.length - stop.length\n var tail = element.expected_chars.substr(end_pos)\n if(tail == stop){\n res = {value: element.expected_chars.substr(0, end_pos)}\n delete element.expected_chars\n return res\n }\n }\n }else{\n res = {value: element.expected_chars}\n if(element.expected_pos == literal.length){\n delete element.expected_pos\n return {value: literal}\n }\n }\n return {value: null}\n}\n\n\nfunction expect_name(element, char){\n if(! element.hasOwnProperty('expected_name')){\n if(is_id_start(char)){\n element.expected_name = char\n }else if(! is_whitespace(char)){\n raise_error(element.parser, 'expected name start, got: ' + char)\n }\n }else if(is_id_continue(char)){\n element.expected_name += char\n }else if(is_whitespace(char)){\n var res = {value: element.expected_name}\n delete element.expected_name\n return res\n }else{\n raise_error(element.parser, 'name expected id, got: ' + char)\n }\n return {}\n}\n\nfunction expect_literal(element, literal, char){\n if(! element.hasOwnProperty('expected_pos')){\n element.expected_pos = 0\n }\n if(literal[element.expected_pos] == char){\n element.expected_pos++\n if(element.expected_pos == literal.length){\n delete element.expected_pos\n return {value: literal}\n }else{\n return {value: null}\n }\n }\n return FAIL\n}\n\nfunction get_parser(element){\n while(element.origin){\n element = element.origin\n }\n return element.parser\n}\n\nfunction get_pos(element){\n while(element.origin){\n element = element.origin\n }\n return element.parser._pos\n}\n\n/*\ndocument ::= prolog element Misc*\n\nprolog ::= XMLDecl? Misc* (doctypedecl Misc*)?\nXMLDecl ::= ''\nMisc ::= Comment | PI | S\nComment ::= ''\nPI ::= '' Char*)))? '?>'\ndoctypedecl ::= ''\n*/\nfunction DOCUMENT(parser){\n this.parser = parser\n this.expect = 'prolog'\n this.names = []\n}\n\nDOCUMENT.prototype.feed = function(char){\n if(this.expect == 'prolog'){\n this.expect = 'element'\n return (new prolog(this)).feed(char)\n if(char !== '<'){\n raise_error(this.parser, 'expected <')\n }\n this.expect = 'name_start_or_special'\n }else if(this.expect == 'name_start_or_special'){\n if(char == '!'){\n this.expect = 'comment_or_doctype'\n }else if(char == '?'){\n this.expect = 'xmldecl_or_pi'\n }else if(is_id_start(char)){\n this.expect = 'prolog'\n return new ELEMENT(this).feed(char)\n }else{\n raise_error1(this, char)\n }\n }else if(this.expect == 'comment_or_doctype'){\n if(char == '-'){\n this.expect = 'comment'\n }else if(char == 'D'){\n this.expect = 'DOCTYPE'\n return this.feed(char)\n }else{\n raise_error('expected comment or DOCTYPE, got: ' + char)\n }\n }else if(this.expect == 'DOCTYPE'){\n var res = expect_literal(this, 'DOCTYPE', char)\n if(res.value){\n return new DOCTYPE(this.parser, this)\n }\n }else if(this.expect == 'xmldecl_or_pi'){\n var res = expect_name(this, char)\n if(res.value){\n if(res.value == 'xml'){\n this.expect = 'prolog'\n return new XMLDECL(this.parser, this)\n }else{\n this.expect = 'prolog'\n var pi = new PI(this.parser, this)\n pi.name = res.value\n pi.expect = 'content'\n return pi\n }\n }\n return this\n }else if(this.expect == 'comment'){\n if(char == '-'){\n this.expect = 'prolog'\n return new COMMENT(this.parser, this)\n }else{\n raise_error(this.parser, 'DOCUMENT, expected -, got: ' + char)\n }\n }else{\n raise_error(this.parser, 'DOCUMENT, unhandled expect: ' + this.expect)\n }\n return this\n}\n\n/*\nprolog ::= XMLDecl? Misc* (doctypedecl Misc*)?\n*/\nfunction prolog(origin){\n this.origin = origin\n this.expect = 'XMLDecl?'\n}\n\nprolog.prototype.feed = function(char){\n if(this.expect == 'XMLDecl?'){\n return (new XMLDecl(this)).feed(char)\n }\n return this\n}\n\n/*\nXMLDecl ::= ''\n*/\nfunction XMLDecl(origin){\n this.origin = origin\n this.expect = ''\nintSubset ::= (markupdecl | DeclSep)*\nmarkupdecl ::= elementdecl | AttlistDecl | EntityDecl | NotationDecl\n | PI | Comment\nDeclSep ::= PEReference | S\n*/\n\nfunction DOCTYPE(parser, origin){\n this.parser = parser\n this.origin = origin\n this.expect = 'element_start'\n}\n\nDOCTYPE.prototype.feed = function(char){\n console.log('DOCTYPE feed', this.expect, 'char', char)\n if(this.expect == 'element_start'){\n var res = expect_name(this, char)\n if(res.value){\n this.name = res.value\n this.expect = 'external_id_or_[_or_>'\n }\n }else if(this.expect == 'external_id_or_[_or_>'){\n if(char == '['){\n this.expect = '>'\n return new intSubset(this)\n }else if(char == '>'){\n this.expect == 'no_whitespace'\n }else if(char == 'S' || char == 'P'){\n this.expect = '[_or_>'\n var res = new ExternalID(this)\n return res.feed(char)\n }else{\n raise_error(this.parser, 'DOCTYPE expected SYSTEM, PUBLIC, [ or >, got: ' + char)\n }\n }else if(this.expect == '[_or_>'){\n if(char == '['){\n this.expect = '>'\n return new intSubset(this)\n }else if(char == '>'){\n this.expect = 'no_whitespace'\n }else if(! is_whitespace(char)){\n raise_error(this.parser, 'DOCTYPE expected [ or >, got: ' + char)\n }\n }else if(this.expect == '>'){\n if(! is_whitespace(char)){\n if(char == '>'){\n this.expect = 'no_whitespace'\n }else{\n raise_error(this.parser, 'DOCTYPE expected >, got: ' + char)\n }\n }\n }else if(this.expect = 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }\n return this\n}\n\n/*\nXMLDecl ::= ''\nVersionInfo ::= S 'version' Eq (\"'\" VersionNum \"'\" | '\"' VersionNum '\"')\nEq ::= S? '=' S?\nVersionNum ::= '1.0'\nEncodingDecl ::= S 'encoding' Eq ('\"' EncName '\"' | \"'\" EncName \"'\" )\nEncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*\nSDDecl ::= S 'standalone' Eq\n ((\"'\" ('yes' | 'no') \"'\") | ('\"' ('yes' | 'no') '\"'))\n*/\nfunction XMLDECL(parser, origin){\n this.parser = parser\n this.expect = 'version_info'\n this.origin = origin\n}\n\nXMLDECL.prototype.feed = function(char){\n switch(this.expect){\n case 'version_info':\n var res = expect_literal(this, 'version', char)\n if(res.value){\n this.expect = 'eq'\n this.attr_name = 'version'\n }\n break\n case 'eq':\n if(char == '='){\n this.expect = 'quote'\n }else if(! is_whitespace(char)){\n raise_error(this.parser, 'expect =, got: ' + char)\n }\n break\n case 'quote':\n if(is_quote(char)){\n this.expect = char\n this.quoted = ''\n }else if(! is_whitespace(char)){\n raise_error(this.parser, 'expected quote, got: ' + char)\n }\n break\n case '\"':\n case \"'\":\n var res = expect_literal(this, this.expect, char)\n if(res.value){\n this[this.attr_name] = this.quoted\n this.expect = 'encoding_or_sd_or_close'\n }else{\n this.quoted += char\n }\n break\n case 'encoding_or_sd_or_close':\n switch(char){\n case 'e':\n if(! this.hasOwnProperty('encoding')){\n this.expect = 'encoding'\n return this.feed(char)\n }\n break\n case 's':\n if(! this.hasOwnProperty('standalone')){\n this.expect = 'standalone'\n return this.feed(char)\n }\n break\n case '?':\n this.expect = '>'\n break\n default:\n if(! is_whitespace(char)){\n raise_error(this.parser,\n 'expected encoding, standalone or ?, got: ' + char)\n }\n }\n break\n case 'encoding':\n case 'standalone':\n var res = expect_literal(this, this.expect, char)\n if(res.value){\n this.attr_name = this.expect\n this.expect = 'eq'\n }\n break\n case '>':\n if(char == '>'){\n this.closed = true\n }else if(! is_whitespace(char)){\n if(this.closed){\n return this.origin.feed(char)\n }\n raise_error(this.parser, 'expected >, got: ' + char)\n }\n break\n default:\n raise_error(this.parser, 'unhandled case: ' + this.expect)\n }\n return this\n}\n\n/*\nPI ::= '' Char*)))? '?>'\nPITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))\n*/\nfunction PI(parser, origin){\n this.parser = parser\n this.origin = origin\n this.expect = 'pi_target'\n}\n\nPI.prototype.feed = function(char){\n if(this.expect == 'pi_target'){\n var res = expect_name(this, char)\n if(res.value){\n this.pi_target = res.value\n this.expect = 'content'\n }\n }else if(this.expect == 'content'){\n var res = expect_chars(this, char, '?>')\n if(res.value){\n this.content = res.value\n this.closed = true\n this.expect = 'no_whitespace'\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }\n return this\n}\n\nfunction CDATA(){\n this.content = ''\n this.expect = ']'\n this.level = 1\n}\n\nCDATA.prototype.feed = function(char){\n switch(this.expect){\n case ']':\n if(char == '>'){\n throw Error('closed without closing ]')\n }else if(char == '['){\n this.level++\n }else if(char == ']'){\n if(this.level == 1){\n this.expect = '>'\n }else{\n this.level--\n }\n }else{\n this.content += char\n }\n break\n case '>':\n if(char != '>'){\n console.log('-- error', this, 'char', char)\n throw Error('expected \">\", got: ' + char)\n }\n this.closed = true\n break\n }\n return this\n}\n\nfunction DTD(parser){\n this.parser = parser\n this.expect = 'name_start'\n this.items = []\n}\n\nDTD.prototype.feed = function(char){\n if(this.expect == 'name_start'){\n if(is_id_start(char)){\n this.name = char\n this.expect = 'name_continue'\n }else if(char == '-'){\n this.expect = '-' // maybe comment start\n }else if(char == '['){\n return new CDATA()\n }else{\n throw Error('expected name, got ' + char)\n }\n }else if(this.expect == 'name_continue'){\n if(is_id_continue(char)){\n this.name += char\n }else{\n console.log('DD, name', this.name)\n if(this.name == 'DOCTYPE'){\n return new DOCTYPE(this.parser)\n }else if(this.name == 'ENTITY'){\n return new ENTITY(this.parser)\n }\n if(char == '>'){\n this.closed = true\n }else{\n this.expect == 'any'\n }\n }\n }else if(this.expect == '-'){\n if(char == '-'){\n // comment\n this.is_comment = true\n }else{\n throw Error('expected -, got: ' + char)\n }\n }else{\n if(char == '>'){\n this.closed = true\n }else{\n this.items.push(char)\n }\n }\n return this\n}\n\nDTD.prototype.toString = function(){\n var res = ` 0){\n res += ' '\n var items = this.items.map(x => x.toString())\n res += items.join(' ')\n }\n return res + '>'\n}\n\nfunction COMMENT(parser, origin){\n this.parser = parser\n this.origin = origin\n this.value = ''\n this.expect = '-->'\n}\n\nCOMMENT.prototype.feed = function(char){\n if(this.expect == '-->'){\n var res = expect_chars(this, char, '-->')\n if(res.value){\n this.content = res.value\n this.expect = 'no_whitespace'\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }\n return this\n}\n\n/*\nelement ::= EmptyElemTag | STag content ETag\nSTag ::= '<' Name (S Attribute)* S? '>'\nAttribute ::= Name Eq AttValue\nETag ::= ''\ncontent ::= CharData?\n ((element | Reference | CDSect | PI | Comment) CharData?)*\nEmptyElemTag ::= '<' Name (S Attribute)* S? '/>'\n*/\n\nfunction ELEMENT(origin) {\n this.origin = origin\n this.expect = '?_/_or_name_start'\n this.attrs = $B.empty_dict()\n}\n\nELEMENT.prototype.add_attribute_name = function(attr_name){\n if(_b_.dict.$contains(this.attrs, attr_name)){\n throw Error(`duplicate attribute name: ${attr_name}`)\n }\n _b_.dict.$setitem(this.attrs, attr_name, _b_.None)\n}\n\nELEMENT.prototype.set_attribute_value = function(value){\n _b_.dict.$setitem(this.attrs, this.attr_name, value)\n}\n\nELEMENT.prototype.feed = function(char){\n console.log('ELEMENT feed, expects', this.expect, 'char', char)\n if(this.expect == 'name_start'){\n if(char == '?'){\n if(this.is_declaration){\n throw Error('already got ?')\n }\n this.is_declaration = true\n }else if(char == '/'){\n if(this.is_end){\n throw Error('already got /')\n }\n this.is_end = true\n }else if(is_id_start(char)){\n this.name = char\n this.expect = 'name_continue'\n }\n }else if(this.expect == 'name_continue'){\n if(is_id_continue(char)){\n this.name += char\n }else{\n // end of element name\n if(this.is_declaration){\n if(this.name == 'xml'){\n this.is_xml_header = true\n }else{\n return new PROCESSING_INSTRUCTION(this.parser, this.name)\n }\n }\n if(is_whitespace(char)){\n this.expect = 'attr_name_start'\n }else if(char == '>'){\n this.closed = true\n }else if(char == '/'){\n this.self_closing = true\n this.expect = '>'\n }else{\n throw Error('unexpected at end of element name: ' + char)\n }\n }\n }else if(this.expect == 'attr_name_start'){\n if(char == '/'){\n this.self_closing = true\n }else if(char == '>'){\n this.expect = 'no_whitespace'\n }else if(is_id_start(char)){\n this.attr_name = char\n this.expect = 'attr_name_continue'\n }else if(char == '?' && this.is_declaration){\n this.expect = '>'\n }else if(! is_whitespace(char)){\n throw Error('expected attribute name, got: ' + char)\n }\n }else if(this.expect == 'attr_name_continue'){\n if(is_id_continue(char)){\n this.attr_name += char\n }else if(char == '='){\n this.add_attribute_name(this.attr_name)\n this.expect = 'attr_value_start'\n this.attr_value = ''\n }else if(is_whitespace(char)){\n this.add_attribute_name(this.attr_name)\n this.expect = '='\n }else if(char == '>'){\n this.add_attribute_name(this.attr_name)\n this.closed = true\n }else{\n throw Error('unexpected character in attribute name: ' + char)\n }\n }else if(this.expect == '='){\n if(char == '='){\n this.expect = 'attr_value_start'\n }else if(! is_whitespace(char)){\n raise_error1(this, char)\n }\n }else if(this.expect == 'attr_value'){\n if(char == '='){\n this.expect = 'attr_value_start'\n this.attr_value = ''\n }else if(char == '>'){\n this.closed = true\n }else if(is_id_start(char)){\n this.attr_name = char\n this.expect = 'attr_name_continue'\n }else if(! is_whitespace(char)){\n throw Error('expected attribute value or name, got: ' + char)\n }\n }else if(this.expect == 'attr_value_start'){\n if(char == '\"' || char == \"'\"){\n this.expect = 'quote'\n this.quote = char\n this.attr_value = ''\n }else if(! is_whitespace(char)){\n throw Error('unexpect attribute value start: ' + char)\n }\n }else if(this.expect == \"quote\"){\n if(char == this.quote){\n this.set_attribute_value(this.attr_value)\n this.expect = 'attr_name_start'\n }else{\n this.attr_value += char\n }\n }else if(this.expect == '>'){\n if(char == '>'){\n this.closed = true\n }else{\n throw Error('expected >, got: ' + char)\n }\n }else if(this.expect == 'attr_name'){\n if(char instanceof Name){\n if(_b_.dict.__contains__(this.attrs, char.value)){\n throw Error('duplicate value ' + char.value)\n }\n _b_.dict.$setitem(this.attrs, char.value, _b_.None)\n this.last_attr = char.value\n }else if(char.value == '?' && this.is_declaration){\n if(this.question_mark){\n throw Error('already ?')\n }\n this.question_mark = true\n }else if(char == END){\n if(this.is_declaration && ! this.question_mark){\n throw Error('missing ')\n }\n }else if(char instanceof Punctuation && char.value == '/'){\n this.no_end = true\n this.expect = END\n }else{\n throw Error('expected attribute name, got ' + char)\n }\n }else if(this.expect == 'attr_value'){\n _b_.dict.$setitem(this.attrs, this.last_attr, char)\n this.expect = 'attr_name'\n }else if(this.expect == END){\n // after \"/\"\n if(char != END){\n throw Error('nothing after /')\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }else{\n raise_error1(this, char)\n }\n return this\n}\n\nELEMENT.prototype.toString = function() {\n var res = `<`\n res += this.is_end ? '/' : ''\n res += this.name\n if(this.attrs.length > 0){\n res += ' '\n }\n var attrs = []\n for(var item of _b_.dict.$iter_items(this.attrs)){\n console.log('item', item)\n attrs.push(`${item.key}: ${item.value.toString()}`)\n }\n res += attrs.join(' ')\n if(this.no_end){\n res += '/'\n }\n return res + '>'\n}\n\n/*\nEntityDecl ::= GEDecl | PEDecl\nPEDecl ::= ''\nPEDef ::= EntityValue | ExternalID\n*/\nfunction ENTITY(parser){\n this.parser = parser\n}\n\nENTITY.prototype.feed = function(char){\n if(! is_whitespace(char)){\n if(is_id_start(char)){\n return new GEDecl(this.parser, char)\n }else if(char == \"%\"){\n return new PEDecl(this.parser)\n }\n throw Error('unexpected after ENTITY: ' + char)\n }\n}\n\n/*\nGEDecl ::= ''\nEntityDef ::= EntityValue | (ExternalID NDataDecl?)\nExternalID ::= 'SYSTEM' S SystemLiteral\n | 'PUBLIC' S PubidLiteral S SystemLiteral\nNDataDecl ::= S 'NDATA' S Name\nEntityValue ::= '\"' ([^%&\"] | PEReference | Reference)* '\"'\n | \"'\" ([^%&'] | PEReference | Reference)* \"'\"\n\n*/\nfunction GEDecl(parser, char){\n this.parser = parser\n this.expect = 'name_continue'\n this.name = char\n this.state = 'name'\n}\n\nGEDecl.prototype.feed = function(char){\n switch(this.expect){\n case 'name_start':\n if(is_id_start(char)){\n if(this.state == 'NDATA'){\n this.ndata_name = char\n }\n this.expect = 'name_continue'\n }else if(! is_whitespace(char)){\n throw Error('GEDecl expected name start, got: ' + char)\n }\n break\n case 'name_continue':\n if(is_id_continue(char)){\n if(this.state == 'name'){\n this.name += char\n }else if(this.state == 'NDATA'){\n this.ndata_name += char\n }\n }else if(is_whitespace(char)){\n if(this.state == 'NDATA'){\n this.expect = '>'\n }else{\n this.expect = 'entity_def'\n }\n }else if(char == '>' && this.state == 'NDATA'){\n this.closed = true\n }else{\n throw Error('GEDecl expected name, got: ' + char)\n }\n break\n case 'entity_def':\n if(is_quote(char)){\n this.quoted = ''\n this.state = this.expect\n this.expect = char\n }else if(char == 'S' || char == 'P'){\n this.expect = char == 'S' ? 'SYSTEM' : 'PUBLIC'\n this.expect_pos = 1\n this.external_id = this.expect\n }else if(! is_whitespace(char)){\n throw Error('GEDCL expect quote, SYSTEM or PUBLIC, got: ' + char)\n }\n break\n case 'SYSTEM':\n case 'PUBLIC':\n if(char == this.expect[this.expect_pos]){\n this.expect_pos++\n if(this.expect_pos == this.expect.length){\n this.expect = this.expect == 'SYSTEM' ? 'system_literal' :\n 'pubid_literal'\n }\n }else{\n throw Error(`GEDecl expected ${this.expect}, got: ${char}`)\n }\n break\n case 'NDATA':\n if(char == this.expect[this.expect_pos]){\n this.expect_pos++\n if(this.expect_pos == this.expect.length){\n this.expect = 'name_start'\n this.ndata_name = ''\n this.state = 'NDATA'\n }\n }else{\n throw Error(`GEDecl expected ${this.expect}, got: ${char}`)\n }\n break\n case '\"':\n case \"'\":\n if(this.state == 'entity_def'){\n if(char == this.expect){\n this.entity_def = this.quoted\n this.expect = '>'\n }else{\n this.quoted += char\n }\n }else if(this.state == 'system_literal'){\n if(char == this.expect){\n this.system_literal = this.quoted\n this.expect = 'n_data_decl_or_close'\n }else{\n this.quoted += char\n }\n }\n break\n case 'system_literal':\n if(is_quote(char)){\n this.expect = char\n this.state = 'system_literal'\n this.quoted = ''\n }else if(! is_whitespace(char)){\n throw Error('GEDecl expected SystemLiteral, got: ' + char)\n }\n break\n case '>':\n if(! is_whitespace(char)){\n if(char == '>'){\n this.closed = true\n }else{\n throw Error('GEDecl expected >, got: ' + char)\n }\n }\n break\n case 'n_data_decl_or_close':\n if(char == '>'){\n this.closed = true\n }else if(char == 'N'){\n this.expect = 'NDATA'\n this.expect_pos = 1\n }else if(! is_whitespace(char)){\n throw Error('GEDecl expected NDATA or >, got: ' + char)\n }\n break\n default:\n console.log(this.parser._buffer.substr(0, this.parser._pos))\n throw Error('pas fini...')\n }\n return this\n}\n\n/*\nExternalID ::= 'SYSTEM' S SystemLiteral\n | 'PUBLIC' S PubidLiteral S SystemLiteral\n*/\nfunction ExternalID(origin){\n this.origin = origin\n this.expect = 'first'\n}\n\nExternalID.prototype.feed = function(char){\n if(this.expect == 'first'){\n if(! is_whitespace(char)){\n if(char == 'S'){\n this.expect = 'SYSTEM'\n return this.feed(char)\n }else if(char == 'P'){\n this.expect = 'PUBLIC'\n return this.feed(char)\n }else{\n raise_error(this, 'ExternalID expected SYSTME or PUBLIC, got: ' + char)\n }\n }\n }else if(this.expect == 'SYSTEM' || this.expect == 'PUBLIC'){\n var res = expect_literal(this, this.expect, char)\n if(res.value){\n this.type = this.expect\n if(this.type == 'SYSTEM'){\n this.expect = '[_or_>'\n return new SystemLiteral(this)\n }else{\n this.expect = 'system_after_pubid'\n return new PubidLiteral(this)\n }\n }\n }else if(this.expect == 'system_after_pubid'){\n if(! is_whitespace(char)){\n this.expect = '[_or_>'\n return (new SystemLiteral(this)).feed(char)\n }\n }else if(this.expect == '[_or_>'){\n if(char == '['){\n this.expect = '>'\n return new intSubset(this)\n }else if(char == '>'){\n return this.origin.feed(char)\n }else{\n raise_error1(this, char)\n }\n }else if(this.expect == '>'){\n if(char == '>'){\n this.expect = 'no_whitespace'\n }else if(! is_whitespace(char)){\n raise_error1(this, char)\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n console.log('return to origin', this.origin, 'char', char)\n return this.origin.feed(char)\n }\n }\n return this\n}\n\n/*\nPubidLiteral ::= '\"' PubidChar* '\"' | \"'\" (PubidChar - \"'\")* \"'\"\nPubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9]\n | [-'()+,./:=?;!*#@$_%]\n*/\nfunction PubidLiteral(origin){\n this.origin = origin\n this.expect = 'quote'\n}\n\n\nfunction is_pubid_char(char){\n /*\n#x20 | #xD | #xA | [a-zA-Z0-9]\n | [-'()+,./:=?;!*#@$_%]\n*/\n return char.match(new RegExp(\"[a-zA-Z0-9-'()+,./:=?;!*#@$_%]\")) ||\n ' \\n\\r'.includes(char)\n}\n\nPubidLiteral.prototype.feed = function(char){\n if(this.expect == 'quote'){\n if(is_quote(char)){\n this.expect = char\n this.content = ''\n }else if(! is_whitespace(char)){\n raise_error1(this, char)\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }else{\n if(char == this.expect){\n this.expect = 'no_whitespace'\n }else if(is_pubid_char(char)){\n this.content += char\n }else{\n console.log('PubidLiteral expects', this.expect, 'char', char)\n console.log(is_pubid_char(char))\n raise_error1(this, char)\n }\n }\n return this\n}\n\nfunction SystemLiteral(origin){\n this.origin = origin\n this.expect = 'quote'\n}\n\nSystemLiteral.prototype.feed = function(char){\n console.log('SystemLiteral expects', this.expect, 'char', char)\n if(this.expect == 'quote'){\n if(is_quote(char)){\n this.expect = char\n this.content = ''\n }else if(! is_whitespace(char)){\n raise_error1(this, char)\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }else{\n if(char == this.expect){\n this.expect = 'no_whitespace'\n }else{\n this.content += char\n }\n }\n return this\n}\n\nfunction PROCESSING_INSTRUCTION(parser, name){\n this.parser = parser\n this.name = name\n this.expect = '?'\n this.content = ''\n}\n\nPROCESSING_INSTRUCTION.prototype.feed = function(char){\n // capture everything until the sequence ?>\n if(this.expect == '?'){\n if(char == '?'){\n this.expect = '>'\n }else{\n this.content += char\n }\n }else if(this.expect == '>'){\n if(char == '>'){\n this.closed = true\n }else{\n this.content += '?' + char\n this.expect = '-'\n }\n }\n return this\n}\n\nfunction ATTR(name){\n this.name = name\n}\n\nATTR.prototype.toString = function(){\n var res = this.name\n if(this.hasOwnProperty('value')){\n res += '=' + this.value\n }\n return res\n}\n\nfunction DATA(value) {\n this.value = value\n}\n\nDATA.prototype.toString = function() {\n return `${this.value}`\n}\n\nvar START = 'START'\nvar END = 'END'\n\n\nfunction Name(value){\n this.value = value\n}\n\nName.prototype.toString = function(){\n return this.value\n}\n\nfunction Punctuation(value){\n this.value = value\n}\n\nfunction String(quote, value){\n this.quote = quote\n this.value = value\n}\n\nString.prototype.toString = function(){\n return this.quote + this.value + this.quote\n}\n\nconst punctuations = '!?/'\n\nfunction open(url){\n var xhr = new XMLHttpRequest()\n xhr.open('GET', url, false)\n xhr.onreadystatechange = function(ev){\n if(this.readyState == 4){\n process(this.responseText)\n }\n }\n xhr.send()\n}\n\nfunction create_parser(){\n var $ = $B.args('ParserCreate', 3,\n {encoding: null, namespace_separator: null, intern: null},\n ['encoding', 'namespace_separator', 'intern'], arguments,\n {encoding: _b_.None, namespace_separator: _b_.None, intern: _b_.None},\n null, null),\n encoding = $.encoding,\n ns_sep = $.namespace_separator,\n intern = $.intern\n if(encoding !== _b_.None && ! _b_.isinstance(encoding, _b_.str)){\n throw _b_.TypeError.$factory(\n `ParserCreate() argument 'encoding' must be ` +\n `str or None, not ${$B.class_name(encoding)}`)\n }\n if(ns_sep !== _b_.None){\n if(! _b_.isinstance(ns_sep, _b_.str)){\n throw _b_.TypeError.$factory(\n `ParserCreate() argument 'namespace_separator' must be ` +\n `str or None, not ${$B.class_name(ns_sep)}`)\n }\n if(ns_sep.length != 1){\n throw _b_.ValueError.$factory(\"namespace_separator must be at \" +\n \"most one character, omitted, or None\")\n }\n }\n if(intern === _b_.None){\n intern = $B.empty_dict()\n }else if(! _b_.isinstance(intern, _b_.dict)){\n throw _b_.TypeError.$factory('intern must be a dictionary')\n }\n return xmlparser.$factory(encoding, ns_sep, intern)\n}\n\nfunction display(text){\n report.value += text + '\\n'\n}\n\nfunction process(src){\n var indent = 0\n for(var token of xml_tokenizer(src)){\n if(indent > 50){\n break\n }\n var head = ' '.repeat(indent)\n if(token instanceof DATA){\n display(head + ' ' + token.toString())\n }else if(token instanceof ELEMENT){\n if(token.is_end){\n indent--\n }\n head = ' '.repeat(indent)\n display(head + token.toString())\n if(token.is_end || token.self_closing || token.is_declaration){\n //\n }else{\n indent++\n }\n }else if(token instanceof DECLARATION){\n display(head + token.toString())\n }else{\n console.log(head + 'token', token, token.toString())\n }\n }\n}\n\nfunction is_id_start(char){\n return char.match(/\\p{L}/u) || char == \"_\"\n}\n\nfunction is_id_continue(char){\n return char.match(/\\p{L}/u) || \"-_:\".includes(char) || char.match(/\\d/)\n}\n\nfunction is_whitespace(s){\n for(let char of s){\n if(! ' \\n\\r\\t'.includes(char)){\n return false\n }\n }\n return s.length > 0\n}\n\nfunction is_quote(char){\n return char == '\"' || char == \"'\"\n}\n\nfunction is_char(char){\n // #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n var cp = char.codePointAt(0)\n return ([0x9, 0xa, 0xd].includes(cp)) ||\n (0x20 <= cp && cp <= 0xd7ff) ||\n (0xe000 <= cp && cp <= 0xfffd) ||\n (0x10000 <= cp && cp <= 0x10ffff)\n}\n\nvar errors = 'errors'\n\n$B.addToImported('pyexpat',\n {\n create_parser,\n ParserCreate: create_parser,\n model,\n error,\n errors,\n XML_PARAM_ENTITY_PARSING_NEVER,\n XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE,\n XML_PARAM_ENTITY_PARSING_ALWAYS\n }\n)\n\n})(__BRYTHON__)"], "python_re": [".js", "// Regular expression\n(function($B){\n\nvar _debug = {value: 0}\n\nvar _b_ = $B.builtins\n\nvar MAXGROUPS = 2147483647,\n MAXREPEAT = 2147483648\n\nvar word_gcs = ['Ll', 'Lu', 'Lm', 'Lt', 'Lo',\n 'Nd',\n 'Mc', 'Me', 'Mn',\n 'Pc']\n\nfunction is_word(cp){\n if((cp >= 97 && cp <= 122) // a-z\n || (cp >= 65 && cp <= 90) // A-Z\n ){\n return true\n }\n for(var word_gc of word_gcs){\n if($B.in_unicode_category(word_gc, cp)){\n return true\n }\n }\n return false\n}\n\nvar ascii_word = {}\n\nfor(var cp = 0; cp <= 127; cp++){\n if(is_word(cp)){\n ascii_word[cp] = true\n }\n}\n\nfunction is_ascii_word(cp){\n return ascii_word[cp] !== undefined\n}\n\nfunction is_digit(cp){\n if(cp >= 48 && cp <= 57){\n return true\n }\n return $B.in_unicode_category('Nd', cp)\n}\n\nfunction is_ascii_digit(cp){\n return cp <= 127 && is_digit(cp)\n}\n\nvar $error_2 = {\n $name: \"error\",\n $qualname: \"error\",\n $is_class: true,\n __module__: \"re\"\n}\n\nvar error = $B.make_class(\"error\",\n function(message){\n return {\n __class__: error,\n msg: message,\n args: $B.fast_tuple([]),\n __cause__: _b_.None,\n __context__: _b_.None,\n __suppress_context__: false\n }\n })\nerror.__bases__ = [_b_.Exception, _b_.object]\nerror.__mro__ = [_b_.Exception, _b_.BaseException, _b_.object]\n\nerror.__str__ = function(self){\n var s = self.msg + ' at position ' + self.pos\n if(self.lineno > 1){\n s += ` (line ${self.lineno}, column ${self.colno})`\n }\n return s\n}\n\n$B.set_func_names(error, \"re\")\n\nfunction $last(t){\n return t[t.length - 1]\n}\n\nfunction fail(message, pos, pattern){\n var err = error.$factory(message)\n err.msg = message\n err.pos = pos\n if(pattern){\n err.pattern = pattern.py_obj // Python object passed to compile()\n err.lineno = 1\n var linestart = 0\n for(var i = 0, len = pattern.string.length; i < pos; i++){\n if(pattern.string[i] == '\\n'){\n err.lineno++\n linestart = i + 1\n }\n }\n err.colno = pos - linestart + 1\n }\n throw err\n}\n\nfunction warn(klass, message, pos, text){\n var frame = $B.frame_obj.frame,\n file = frame[3].__file__,\n src = $B.file_cache[file]\n if(text === undefined){\n var lineno = frame[1].$lineno\n var lines = src.split('\\n'),\n line = lines[lineno - 1]\n }else{\n if(Array.isArray(text)){\n text = from_codepoint_list(text)\n }\n var lineno = 1,\n line_start = 0\n for(var i = 0; i < pos; i++){\n if(text[i] == '\\n'){\n lineno++\n line_start = i + 1\n }\n }\n var line_end = text.substr(line_start).search('\\n'),\n line\n if(line_end == -1){\n line = text.substr(line_start)\n }else{\n line = text.substr(line_start, line_end)\n }\n var col_offset = pos - line_start\n }\n var warning = klass.$factory(message)\n warning.pos = pos\n warning.args[1] = [file, lineno, col_offset, lineno, col_offset,\n line]\n warning.filename = file\n warning.lineno = warning.end_lineno = lineno\n warning.offset = warning.end_offset = col_offset\n warning.line = line\n // module _warning is in builtin_modules.js\n $B.imported._warnings.warn(warning)\n}\n\nfunction chr(i){\n if(i < 0 || i > 1114111){\n throw _b_.ValueError.$factory('Outside valid range')\n }else if(i >= 0x10000 && i <= 0x10FFFF){\n var code = (i - 0x10000)\n return String.fromCodePoint(0xD800 | (code >> 10)) +\n String.fromCodePoint(0xDC00 | (code & 0x3FF))\n }else{\n return String.fromCodePoint(i)\n }\n}\n\nfunction ord(char){\n return char.charCodeAt(0)\n}\n\nconst LETTERS = {\n b: ord('b'),\n N: ord('N'),\n P: ord('P'),\n u: ord('u'),\n U: ord('U'),\n x: ord('x')\n}\n\nconst PARENTH_OPEN = ord('('),\n PARENTH_CLOSE = ord(')'),\n BRACKET_OPEN = ord('['),\n BRACKET_CLOSE = ord(']'),\n BRACE_OPEN = ord('{'),\n BRACE_CLOSE = ord('}'),\n EQUAL = ord('='),\n SUP = ord('>'),\n INF = ord('<'),\n MINUS = ord('-'),\n PLUS = ord('+'),\n OR = ord('|'),\n DOT = ord('.'),\n QUESTION_MARK = ord('?'),\n EXCLAMATION_MARK = ord('!'),\n COLON = ord(':'),\n BACKSLASH = ord('\\\\'),\n DOLLAR = ord('$'),\n CARET = ord('^'),\n LINEFEED = ord('\\n')\n\n// pattern tokenizer\n\nfunction is_ascii(name){\n return /^[\\x00-\\x7F]*$/.test(name)\n}\n\nfunction open_unicode_db(){\n if($B.unicodedb === undefined){\n var xhr = new XMLHttpRequest\n xhr.open(\"GET\",\n $B.brython_path + \"unicode.txt?\" + (new Date()).getTime(), false)\n xhr.onreadystatechange = function(){\n if(this.readyState == 4){\n if(this.status == 200){\n $B.unicodedb = this.responseText\n }else{\n console.log(\n \"Warning - could not load unicode.txt\")\n }\n }\n }\n xhr.send()\n }\n}\n\nfunction validate_named_char(description, pos){\n // validate that \\N{} is in the Unicode db\n // Load unicode table if not already loaded\n if(description.length == 0){\n fail(\"missing character name\", pos)\n }\n open_unicode_db()\n if($B.unicodedb !== undefined){\n var re = new RegExp(\"^([0-9A-F]+);\" +\n description.toUpperCase() + \";.*$\", \"m\")\n search = re.exec($B.unicodedb)\n if(search === null){\n fail(`undefined character name '${description}'`, pos)\n }\n return parseInt(search[1], 16)\n }else{\n fail(\"could not load unicode.txt\", pos)\n }\n}\n\nfunction validate_group_name(sname, pos, is_bytes){\n // sname is an instance of StringObj\n if(! _b_.str.isidentifier(sname.string)){\n fail(`bad character in group name '${sname.string}'`, pos + 4)\n }\n if(is_bytes && ! is_ascii(sname.string)){\n var s = _b_.bytes.decode(_b_.bytes.$factory(sname.codepoints),\n 'ascii', 'backslashreplace')\n warn(_b_.DeprecationWarning,\n `bad character in group name '${s}' at position ${pos + 4}`)\n }\n return true\n}\n\nfunction validate_group_num(so, pos){\n var s = so.string\n if(s.match(/^\\d+$/)){\n return true\n }\n try{\n var num = _b_.int.$factory(s)\n warn(_b_.DeprecationWarning,\n `bad character in group name '${s}' at position ${pos + 3}`,\n pos + 3, s)\n so.string = num + ''\n return true\n }catch(err){\n return false\n }\n}\n\nfunction validate_num_or_name(so, pos, is_bytes){\n return validate_group_num(so, pos, is_bytes) ||\n validate_group_name(so, pos - 1, is_bytes)\n}\n\nvar character_classes = {\n in_charset: to_codepoint_list('dDsSwW'),\n in_re: to_codepoint_list('AbBdDsSwWZ')\n}\n\nfunction escaped_char(args){\n var cps = args.codepoints,\n pos = args.pos,\n in_charset = args.in_charset,\n is_bytes = args.is_bytes // if pattern is bytes\n var special = cps[pos + 1]\n if(special === undefined){\n fail('bad escape (end of pattern)', pos)\n }\n var key = in_charset ? 'in_charset' : 'in_re'\n if(in_charset && special == LETTERS.b){\n // Inside a character range, \\b represents the backspace character,\n // for compatibility with Python\u2019s string literals.\n return '\\b'\n }\n if(character_classes[key].indexOf(special) > -1){\n return new CharacterClass(pos, special, 2)\n }else if(special == LETTERS.N && ! is_bytes){\n if(cps[pos + 2] != BRACE_OPEN){\n fail('missing {', pos)\n }\n var i = pos + 3,\n description = []\n while(i < cps.length){\n if(cps[i] == BRACE_CLOSE){\n break\n }\n description.push(cps[i])\n i++\n }\n if(description.length == 0){\n fail(\"missing character name\", pos)\n }\n if(i == cps.length){\n fail(\"missing }, unterminated name\", pos)\n }\n var cp = validate_named_char(from_codepoint_list(description), pos)\n return {\n type: 'N',\n ord: cp,\n char: chr(cp),\n length: i - pos + 1\n }\n }else if(special == LETTERS.x){\n // \\xhh = character with hex value hh\n var rest = from_codepoint_list(cps.slice(pos + 2)),\n mo = /^[0-9a-fA-F]{0,2}/.exec(rest),\n hh = mo ? mo[0] : ''\n if(mo && mo[0].length == 2){\n var cp = parseInt(mo[0], 16)\n return {\n type: 'x',\n ord: cp,\n char: chr(cp),\n length: 2 + mo[0].length\n }\n }\n fail('incomplete escape \\\\x' + hh, pos)\n }else if(special == LETTERS.u){\n // \\uxxxx = character with 16-bit hex value xxxx\n var rest = from_codepoint_list(cps.slice(pos + 2)),\n mo = /^[0-9a-fA-F]{0,4}/.exec(rest),\n xx = mo ? mo[0] : ''\n if(mo && mo[0].length == 4){\n var cp = parseInt(mo[0], 16)\n return {\n type: 'u',\n ord: cp,\n char: chr(cp),\n length: 2 + mo[0].length\n }\n }\n fail('incomplete escape \\\\u' + xx, pos)\n }else if(special == LETTERS.U){\n // \\Uxxxxxxxx = character with 32-bit hex value xxxxxxxx\n var rest = from_codepoint_list(cps.slice(pos + 2)),\n mo = /^[0-9a-fA-F]{0,8}/.exec(rest),\n xx = mo ? mo[0] : ''\n if(mo && mo[0].length == 8){\n var cp = parseInt(mo[0], 16)\n if(cp > 0x10FFFF){\n fail(`bad escape \\\\U${mo[0]}`, pos)\n }\n return {\n type: 'U',\n ord: cp,\n char: chr(cp),\n length: 2 + mo[0].length\n }\n }\n fail('incomplete escape \\\\U' + xx, pos)\n }else{\n // octal ?\n // If the first digit of number is 0, or number is 3 octal digits\n // long, it will not be interpreted as a group match, but as the\n // character with octal value number\n var rest = from_codepoint_list(cps.slice(pos + 1)),\n mo = /^[0-7]{3}/.exec(rest)\n if(in_charset){\n try{\n var res = $B.test_escape(rest, -1)\n if(res){\n return {\n type: 'u',\n ord: res[0].codePointAt(0),\n char: res[0],\n length: res[1]\n }\n }\n }catch(err){\n // ignore\n }\n }\n if(mo == null){\n mo = /^0[0-7]*/.exec(rest)\n }\n if(mo){\n var octal_value = parseInt(mo[0], 8)\n if(octal_value > 0o377){\n fail(`octal escape value \\\\` +\n `${mo[0]} outside of range 0-0o377`, pos)\n }\n return {\n type: 'o',\n ord: octal_value,\n char: chr(octal_value),\n length: 1 + mo[0].length\n }\n }\n var mo = /^\\d{1,2}/.exec(rest) // backref is at most 99\n if(mo){\n return {\n type: 'backref',\n value: parseInt(mo[0]),\n length: 1 + mo[0].length\n }\n }\n var trans = {a: chr(7), f: '\\f', n: '\\n', r: '\\r', t: '\\t', v: '\\v'},\n res = trans[chr(special)]\n if(res){\n return ord(res)\n }\n if(chr(special).match(/[a-zA-Z]/)){\n fail(\"bad escape \\\\\" + chr(special), pos)\n }else{\n return special\n }\n }\n}\n\nfunction check_character_range(t, positions){\n // Check if last 2 items in t are a valid character range\n var start = t[t.length - 2],\n end = t[t.length - 1]\n if(start instanceof CharacterClass || end instanceof CharacterClass){\n fail(`bad character range ${start}-${end}`,\n positions[positions.length - 2])\n }else if(end < start){\n fail(`bad character range ${start}-${end}`,\n positions[positions.length - 2])\n }\n t.splice(t.length - 2, 2, {\n type: 'character_range',\n start: start,\n end: end,\n ord: [start.ord, end.ord]\n })\n}\n\nfunction parse_character_set(text, pos, is_bytes){\n // Parse character set starting at position \"pos\" in \"text\"\n // pos is the position of the leading \"[\"\n var start = pos,\n result = {items: []},\n positions = []\n pos++\n if(text[pos] == CARET){\n result.neg = true\n pos++\n }else if(text[pos] == BRACKET_CLOSE){\n // a leading ] is the character \"]\", not the set end\n result.items.push(']')\n positions.push(pos)\n pos++\n }else if(text[pos] == BRACKET_OPEN){\n // send FutureWarning\n warn(_b_.FutureWarning, \"Possible nested set\", pos, text)\n }\n var range = false\n while(pos < text.length){\n var cp = text[pos],\n char = chr(cp)\n if(char == ']'){\n if(pos == start + 2 && result.neg){\n // in \"[^]]\", the first ] is the character \"]\"\n result.items.push(']')\n }else{\n return [result, pos]\n }\n }\n if(char == '\\\\'){\n var escape = escaped_char({\n codepoints: text,\n pos,\n in_charset: true,\n is_bytes\n })\n if(typeof escape == \"number\"){\n var s = chr(escape)\n escape = {\n ord: escape,\n length: 2,\n toString: function(){\n return s\n }\n }\n }\n if(escape.type == \"num\"){\n // [\\9] is invalid\n fail(\"bad escape 1 \\\\\" +\n escape.value.toString()[0], pos)\n }\n result.items.push(escape)\n positions.push(pos)\n if(range){\n check_character_range(result.items, positions)\n }\n range = false\n pos += escape.length\n }else if(char == '-'){\n // Character range, or character \"-\"\n if(pos == start + 1 ||\n (result.neg && pos == start + 2) ||\n pos == text.length - 2 || // [a-]\n range ||\n (result.items.length > 0 &&\n result.items[result.items.length - 1].type ==\n \"character_range\")){\n result.items.push({\n ord: cp,\n char,\n toString: function(){\n return this.char\n }\n })\n if(text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set difference\", pos, text)\n }\n pos++\n if(range){\n check_character_range(result.items, positions)\n }\n range = false\n }else{\n range = true\n if(text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set difference\", pos, text)\n }\n pos++\n }\n }else{\n positions.push(pos)\n result.items.push({\n ord: cp,\n char,\n toString: function(){\n return this.char\n }\n })\n if(range){\n check_character_range(result.items, positions)\n }\n range = false\n // FutureWarning for consecutive \"&\", \"|\" or \"~\"\n if(char == \"&\" && text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set intersection\", pos, text)\n }else if(char == \"|\" && text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set union\", pos, text)\n }else if(char == \"~\" && text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set symmetric difference\",\n pos, text)\n }\n pos++\n }\n }\n fail(\"unterminated character set\", start)\n}\n\nfunction* tokenize(pattern, type, _verbose){\n // pattern is a list of codepoints\n var is_bytes = type == \"bytes\"\n // verbose_stack is the stack of verbose state for each group in the regex\n var verbose_stack = [_verbose],\n verbose = _verbose,\n parenth_pos\n var pos = 0\n while(pos < pattern.length){\n var cp = pattern[pos],\n char = String.fromCharCode(cp)\n if(verbose){\n // current group is in verbose mode\n if(char == \"#\"){\n // skip until next line feed\n while(pos < pattern.length && pattern[pos] != 10){\n pos++\n }\n pos++\n continue\n }else{\n while(pos < pattern.length &&\n [9, 10, 11, 12, 13, 32].indexOf(pattern[pos]) > -1){\n pos++\n }\n }\n cp = pattern[pos]\n if(cp === undefined){\n break\n }\n char = String.fromCharCode(cp)\n if(char == '#'){\n continue\n }\n }\n if(char == '('){\n parenth_pos = pos\n if(pattern[pos + 1] == QUESTION_MARK){\n if(pattern[pos + 2] == LETTERS.P){\n if(pattern[pos + 3] == INF){\n var name = [],\n i = pos + 4\n while(i < pattern.length){\n if(pattern[i] == SUP){\n break\n }else if(pattern[i] == PARENTH_CLOSE){\n fail(\"missing >, unterminated name\", pos)\n }\n name.push(pattern[i])\n i++\n }\n var sname = StringObj.from_codepoints(name)\n validate_group_name(sname, pos, is_bytes)\n name = sname\n if(i == pattern.length){\n fail(\"missing >, unterminated name\", pos)\n }\n yield new Group(pos, {type: 'name_def', value: name})\n verbose_stack.push(verbose)\n pos = i + 1\n continue\n }else if(pattern[pos + 3] == EQUAL){\n var name = [],\n i = pos + 4\n while(i < pattern.length){\n if(pattern[i] == PARENTH_CLOSE){\n break\n }\n name.push(pattern[i])\n i++\n }\n name = StringObj.from_codepoints(name)\n validate_group_name(name, pos, is_bytes)\n if(i == pattern.length){\n fail(\"missing ), unterminated name\", pos)\n }\n yield new BackReference(pos, 'name', name.string)\n pos = i + 1\n continue\n }else if(pattern[pos + 3] === undefined){\n fail(\"unexpected end of pattern\", pos)\n }else{\n fail(\"unknown extension ?P\" + chr(pattern[pos + 3]), pos)\n }\n }else if(pattern[pos + 2] == PARENTH_OPEN){\n var ref = [],\n i = pos + 3\n while(i < pattern.length){\n if(pattern[i] == PARENTH_CLOSE){\n break\n }\n ref.push(pattern[i])\n i++\n }\n var sref = StringObj.from_codepoints(ref)\n if(sref.string.match(/^\\d+$/)){\n ref = parseInt(sref.string)\n }else{\n validate_num_or_name(sref, pos, is_bytes)\n ref = sref.string\n }\n if(i == pattern.length){\n fail(\"missing ), unterminated name\", pos)\n }\n yield new ConditionalBackref(pos, ref)\n pos = i + 1\n continue\n }else if(pattern[pos + 2] == EQUAL){\n // (?=...) : lookahead assertion\n yield new Group(pos, {type: 'lookahead_assertion'})\n verbose_stack.push(verbose)\n pos += 3\n continue\n }else if(pattern[pos + 2] == EXCLAMATION_MARK){\n // (?!...) : negative lookahead assertion\n yield new Group(pos, {type: 'negative_lookahead_assertion'})\n verbose_stack.push(verbose)\n pos += 3\n continue\n }else if(from_codepoint_list(pattern.slice(pos + 2, pos + 4)) == ' -1){\n if(pattern[pos + 2] == MINUS){\n var on_flags = [],\n has_off = true,\n off_flags = []\n pos += 3\n }else{\n var on_flags = [chr(pattern[pos + 2])],\n has_off = false,\n off_flags = [],\n auL = auL_flags.indexOf(pattern[pos + 2]) > -1 ?\n 1 : 0,\n closed = false\n pos += 3\n while(pos < pattern.length){\n if(flags.indexOf(pattern[pos]) > -1){\n if(auL_flags.indexOf(pattern[pos]) > -1){\n auL++\n if(auL > 1){\n fail(\"bad inline flags: flags 'a', 'u'\" +\n \" and 'L' are incompatible\", pos)\n }\n }\n on_flags.push(chr(pattern[pos]))\n pos++\n }else if(pattern[pos] == MINUS){\n has_off = true\n closed = true\n pos++\n break\n }else if(String.fromCharCode(pattern[pos]).\n match(/[a-zA-Z]/)){\n fail(\"unknown flag\", pos)\n }else if(pattern[pos] == PARENTH_CLOSE){\n closed = true\n break\n }else if(pattern[pos] == COLON){\n yield new Group(pos, {name: \"Group\", type: \"flags\"})\n verbose_stack.push(verbose)\n closed = true\n break\n }else{\n fail(\"missing -, : or )\", pos)\n }\n }\n if(! closed){\n fail(\"missing -, : or )\", pos)\n }\n }\n if(has_off){\n while(pos < pattern.length){\n if(flags.indexOf(pattern[pos]) > -1){\n if(auL_flags.indexOf(pattern[pos]) > -1){\n fail(\"bad inline flags: cannot turn off \" +\n \"flags 'a', 'u' and 'L'\", pos)\n }\n if(on_flags.indexOf(chr(pattern[pos])) > -1){\n fail(\"bad inline flags: flag turned on and off\", pos)\n }\n off_flags.push(chr(pattern[pos]))\n pos++\n }else if(pattern[pos] == COLON){\n yield new Group(pos, {name: \"Group\", type: \"flags\"})\n verbose_stack.push(verbose)\n break\n }else if(String.fromCharCode(pattern[pos]).\n match(/[a-zA-Z]/)){\n fail(\"unknown flag\", pos)\n }else if(off_flags.length == 0){\n fail(\"missing flag\", pos)\n }else{\n fail(\"missing :\", pos)\n }\n }\n if(off_flags.length == 0){\n fail(\"missing flag\", pos)\n }\n }\n if(has_off && pattern[pos] != COLON){\n fail(\"missing :\", pos)\n }\n if(on_flags.length == 0 && off_flags.length == 0){\n fail(\"missing flag\", pos)\n }\n var set_flags = new SetFlags(flags_start,\n {on_flags, off_flags})\n\n yield set_flags\n // reset verbose\n if(on_flags.indexOf('x') > -1){\n verbose = true\n verbose_stack.push(verbose)\n }\n if(off_flags.indexOf('x') > -1){\n verbose = false\n }\n if(! closed){\n node = set_flags\n }\n pos++\n }else if(pattern[pos + 2] == ord('#')){\n pos += 3\n while(pos < pattern.length){\n if(pattern[pos] == PARENTH_CLOSE){\n break\n }\n pos++\n }\n if(pos == pattern.length){\n fail(\"missing ), unterminated comment\", pos)\n }\n pos++\n continue\n }else{\n fail(\"unknown extension ?\" + _b_.chr(pattern[pos + 2]),\n pos)\n }\n }else{\n yield new Group(pos)\n verbose_stack.push(verbose)\n pos++\n }\n }else if(cp == PARENTH_CLOSE){\n yield new GroupEnd(pos)\n verbose_stack.pop()\n verbose = $last(verbose_stack)\n pos++\n }else if(cp == BACKSLASH){\n var escape = escaped_char({codepoints: pattern, pos, is_bytes})\n if(escape instanceof CharacterClass){\n yield escape\n pos += escape.length\n }else if(escape.char !== undefined){\n yield new Char(pos, escape.ord)\n pos += escape.length\n }else if(escape.type == \"backref\"){\n var len = escape.length\n if(escape.value.length > 2){\n escape.value = escape.value.substr(0, 2)\n len = 2\n }\n yield new BackReference(pos, \"num\", escape.value)\n pos += len\n }else if(typeof escape == \"number\"){\n // eg \"\\.\"\n var esc = new Char(pos, escape)\n esc.escaped = true\n yield esc\n pos += 2\n }else{\n yield new Char(pos, escape)\n pos += escape.length\n }\n }else if(cp == BRACKET_OPEN){\n // Set of characters\n var set,\n end_pos\n [set, end_pos] = parse_character_set(pattern, pos, is_bytes)\n yield new CharacterSet(pos, set)\n pos = end_pos + 1\n }else if('+?*'.indexOf(char) > -1){\n yield new Repeater(pos, char)\n pos++\n }else if(cp == BRACE_OPEN){\n var reps = /\\{(\\d*)((,)(\\d*))?\\}/.exec(\n from_codepoint_list(pattern.slice(pos)))\n if(reps && reps[0] != '{}'){\n if(reps[1] == \"\"){\n var limits = [0]\n }else{\n var limits = [parseInt(reps[1])]\n }\n if(reps[4] !== undefined){\n if(reps[4] == \"\"){\n var max = Number.POSITIVE_INFINITY\n }else{\n var max = parseInt(reps[4])\n }\n limits.push(max)\n }\n yield new Repeater(pos, limits)\n pos += reps[0].length\n }else if(pattern[pos + 1] == BRACE_CLOSE){\n // {} is the characters \"{\" and \"}\"\n yield new Char(pos, BRACE_OPEN)\n pos++\n }else{\n yield new Char(pos, BRACE_OPEN)\n pos++\n }\n }else if(cp == OR){\n yield new Or(pos)\n pos++\n }else if(cp == DOT){\n yield new CharacterClass(pos, cp, 1)\n pos++\n }else if(cp == CARET){\n yield new StringStart(pos)\n pos++\n }else if(cp == DOLLAR){\n yield new StringEnd(pos)\n pos++\n }else{\n yield new Char(pos, cp)\n pos++\n }\n }\n}\n\nfunction transform_repl(data, pattern){\n // data.repl is a StringObj instance\n var repl = data.repl.string\n repl = repl.replace(/\\\\n/g, '\\n')\n repl = repl.replace(/\\\\r/g, '\\r')\n repl = repl.replace(/\\\\t/g, '\\t')\n repl = repl.replace(/\\\\b/g, '\\b')\n repl = repl.replace(/\\\\v/g, '\\v')\n repl = repl.replace(/\\\\f/g, '\\f')\n repl = repl.replace(/\\\\a/g, '\\x07')\n // detect backreferences\n var pos = 0,\n escaped = false,\n br = false,\n repl1 = \"\",\n has_backref = false\n while(pos < repl.length){\n br = false\n if(repl[pos] == \"\\\\\"){\n escaped = ! escaped\n if(escaped){\n pos++\n continue\n }\n }else if(escaped){\n escaped = false\n var mo = /^\\d+/.exec(repl.substr(pos))\n if(mo){\n var cps = to_codepoint_list(repl)\n var escape = escaped_char({\n codepoints: cps,\n pos: pos - 1,\n is_bytes: cps.type == \"bytes\"\n })\n if(escape.type == \"o\"){\n if(escape.ord > 0o377){\n fail(`octal escape value \\\\${mo[0]} ` +\n \" outside of range 0-0o377\", pos)\n }\n repl1 += escape.char\n pos += escape.length - 1\n continue\n }else if(escape.type != \"backref\"){\n var group_num = mo[0].substr(0,\n Math.min(2, mo[0].length))\n fail(`invalid group reference ${group_num}`, pos)\n }else{\n // only keep first 2 digits\n var group_num = mo[0].substr(0,\n Math.min(2, mo[0].length))\n // check that pattern has the specified group num\n if(pattern.groups === undefined){\n throw _b_.AttributeError.$factory(\"$groups\")\n }\n if(pattern.groups[group_num] === undefined){\n fail(`invalid group reference ${group_num}`,\n pos)\n }else{\n mo[0] = group_num\n }\n }\n if(! has_backref){\n var parts = [repl.substr(0, pos - 1),\n parseInt(mo[0])]\n }else{\n parts.push(repl.substring(next_pos, pos - 1))\n parts.push(parseInt(mo[0]))\n }\n has_backref = true\n var next_pos = pos + mo[0].length\n br = true\n pos += mo[0].length\n }else if(repl[pos] == \"g\"){\n pos++\n if(repl[pos] != '<'){\n fail(\"missing <\", pos)\n }\n pos++\n mo = /(.*?)>/.exec(repl.substr(pos))\n if(mo){\n if(mo[1] == \"\"){\n pos += mo[0].length\n fail(\"missing group name\", pos - 1)\n }\n var group_name = mo[1]\n if(group_name == '0'){\n // The backreference \\g<0> substitutes in the entire\n // substring matched by the RE.\n }else if(/^\\d+$/.exec(group_name)){\n if(pattern.groups[group_name] === undefined){\n fail(`invalid group reference ${group_name}`,\n pos)\n }\n }else{\n try{\n var group_num = _b_.int.$factory(group_name)\n if(group_num < 0){\n fail(`bad character in group name ` +\n `'${group_name}' at position ${pos}`, pos)\n }\n warn(_b_.DeprecationWarning,\n `bad character in group name '${group_name}' ` +\n `at position ${pos}`)\n mo[1] = group_name = group_num + ''\n }catch(err){\n if(! _b_.str.isidentifier(group_name)){\n var cps = to_codepoint_list(group_name)\n if(! $B.is_XID_Start(cps[0])){\n fail(\"bad character in group name '\" +\n group_name + \"'\", pos)\n }else{\n for(cp of cps.slice(1)){\n if(! $B.is_XID_Continue(cp)){\n fail(\"bad character in group name '\" +\n group_name + \"'\", pos)\n }\n }\n }\n }else if(data.type == \"bytes\" && ! is_ascii(group_name)){\n var b = _b_.bytes.$factory(group_name, 'latin-1'),\n s = _b_.bytes.decode(b, 'ascii', 'backslashreplace')\n warn(_b_.DeprecationWarning,\n `bad character in group name '${s}'` +\n ` at position ${pos}`)\n }\n }\n if(pattern.groups[group_name] === undefined){\n throw _b_.IndexError.$factory(\n `unknown group name '${group_name}'`,\n pos)\n }\n }\n if(! has_backref){\n var parts = [repl.substr(0, pos - 3),\n mo[1]]\n }else{\n parts.push(repl.substring(next_pos, pos - 3))\n parts.push(mo[1])\n }\n has_backref = true\n var next_pos = pos + mo[0].length\n br = true\n pos = next_pos\n }else{\n if(repl.substr(pos).length > 0){\n fail(\"missing >, unterminated name\", pos)\n }else{\n fail(\"missing group name\", pos)\n }\n }\n }else{\n if(/[a-zA-Z]/.exec(repl[pos])){\n fail(\"unknown escape\", pos)\n }\n pos += repl[pos]\n }\n }\n if(! br){\n repl1 += repl[pos]\n pos ++\n }\n }\n data.repl1 = repl1\n if(has_backref){\n parts.push(repl.substr(next_pos))\n data.repl = function(bmo){\n var mo = bmo.mo,\n res = parts[0],\n groups = mo.$groups,\n s = mo.string,\n group,\n is_bytes = s.type == 'bytes'\n for(var i = 1, len = parts.length; i < len; i += 2){\n if(parts[i] == 0){\n var x = s.substring(mo.start, mo.end)\n if(is_bytes){\n x = _b_.bytes.decode(x, 'latin-1')\n }\n res += x\n }else if(groups[parts[i]] === undefined){\n if(mo.node.$groups[parts[i]] !== undefined){\n // group is defined in the RE, but didn't contribute\n // to the match\n // groups[parts[i]] = ''\n }else{\n // group is not defined in the RE\n pos++\n group_num = parts[i].toString().substr(0, 2)\n fail(`invalid group reference ${group_num}`, pos)\n }\n }else{\n group = groups[parts[i]]\n var x = s.substring(group.start, group.end)\n if(is_bytes){\n x = _b_.bytes.decode(x, 'latin-1')\n }\n res += x\n }\n res += parts[i + 1]\n }\n return res\n }\n }else{\n data.repl = new StringObj(repl)\n }\n return data\n}\n\n\n\nvar Flag = $B.make_class(\"Flag\",\n function(value){\n return {\n __class__: Flag,\n value\n }\n }\n)\n\nFlag.__and__ = function(self, other){\n if(other.__class__ === Flag){\n return Flag.$factory(self.value & other.value)\n }else if(typeof other == \"number\" || typeof other == \"boolean\"){\n return Flag.$factory(self.value & other)\n }\n return _b_.NotImplemented\n}\n\nFlag.__index__ = function(self){\n return self.value\n}\n\nFlag.__invert__ = function(self){\n return Flag.$factory(~self.value)\n}\n\nFlag.__eq__ = function(self, other){\n return self.value == other.value\n}\n\nFlag.__or__ = function(self, other){\n if(other.__class__ === Flag){\n return Flag.$factory(self.value | other.value)\n }else if(typeof other == \"number\" || typeof other == \"boolean\"){\n return Flag.$factory(self.value | other)\n }\n return _b_.NotImplemented\n}\n\nFlag.__rand__ = function(self, other){\n if(typeof other == \"number\" || $B.$isinstance(other, _b_.int)){\n if(other == 0){\n return false // Flag.$factory(self.value)\n }\n return self.value & other\n }\n return _b_.NotImplemented\n}\n\nFlag.__ror__ = function(self, other){\n if(typeof other == \"number\" || $B.$isinstance(other, _b_.int)){\n if(other == 0){\n return self.value\n }\n return self.value | other\n }\n return _b_.NotImplemented\n}\n\nFlag.__repr__ = Flag.__str__ = function(self){\n if(self.value == 0){\n return \"re.none\"\n }\n var inverted = self.value < 0\n\n var t = [],\n value = inverted ? ~self.value : self.value\n for(var flag in inline_flags){\n if(value & inline_flags[flag].value){\n t.push('re.' + flag_names[flag])\n value &= ~inline_flags[flag].value\n }\n }\n if(value > 0){\n t.push('0x' + value.toString(16))\n }\n var res = t.join('|')\n if(inverted){\n if(t.length > 1){\n return '~(' + res + ')'\n }else{\n return '~' + res\n }\n }\n return res\n}\n\nFlag.__xor__ = function(self, other){\n return Flag.$factory(self.value ^ other.value)\n}\n\n$B.set_func_names(Flag, \"re\")\n\nvar no_flag = {}\n\nvar Scanner = $B.make_class(\"Scanner\",\n function(pattern, string, pos, endpos){\n var $ = $B.args('__init__', 4,\n {pattern: null, string: null, pos: null, endpos:null},\n ['pattern', 'string', 'pos', 'endpos'],\n arguments, {pos: 0, endpos: _b_.None}, null, null),\n endpos = endpos === _b_.None ? $.string.length : endpos\n return {\n __class__: Scanner,\n $string: $.string,\n pattern: $.pattern,\n pos: $.pos,\n endpos\n }\n }\n)\n\nScanner.match = function(self){\n return Pattern.match(self.pattern, self.$string)\n}\n\nScanner.search = function(self){\n if(! self.$iterator){\n self.$iterator = module.finditer(self.pattern, self.$string)\n }\n // return last match\n var mo = _b_.None\n for(mo of self.$iterator.js_gen){\n // set mo\n }\n return mo\n}\n\nvar GroupIndex = $B.make_class(\"GroupIndex\",\n function(self, _default){\n var res = $B.empty_dict()\n res.__class__ = GroupIndex\n for(var key in self.$groups){\n if(isNaN(parseInt(key))){\n _b_.dict.$setitem(res, key, self.$groups[key].num)\n }\n }\n return res\n }\n)\nGroupIndex.__mro__ = [_b_.dict, _b_.object]\nGroupIndex.__setitem__ = function(){\n throw _b_.TypeError.$factory(\"read only\")\n}\n\n$B.set_func_names(GroupIndex, \"re\")\n\nvar Pattern = $B.make_class(\"Pattern\",\n function(pattern){\n var nb_groups = 0\n for(var key in pattern.groups){\n if(isFinite(key)){\n nb_groups++\n }\n }\n return {\n __class__: Pattern,\n pattern: pattern.text,\n groups: nb_groups,\n flags: pattern.flags,\n $groups: pattern.groups,\n $pattern: pattern\n }\n }\n)\n\nPattern.__copy__ = function(self){\n return self\n}\n\nPattern.__deepcopy__ = function(self){\n return self\n}\n\nPattern.__eq__ = function(self, other){\n if(other.$pattern && self.$pattern.type != other.$pattern.$type){\n // warn(_b_.BytesWarning, \"cannot compare str and bytes pattern\", 1)\n }\n return self.pattern == other.pattern &&\n self.flags.value == other.flags.value\n}\n\nPattern.__hash__ = function(self){\n // best effort ;-)\n return _b_.hash(self.pattern) + self.flags.value\n}\n\nPattern.__new__ = Pattern.$factory\n\nPattern.__reduce__ = function(self){\n return Pattern.__reduce_ex__(self, 4)\n}\n\nPattern.__reduce_ex__ = function(self, protocol){\n var res = _reconstructor,\n state = [self.__class__].concat(self.__class__.__mro__)\n var d = $B.empty_dict()\n _b_.dict.$setitem(d, 'pattern', self.pattern)\n _b_.dict.$setitem(d, 'flags', self.flags.value)\n state.push(d)\n return $B.fast_tuple([res, $B.fast_tuple(state)])\n}\n\nfunction _reconstructor(cls, base, state){\n var pattern = _b_.dict.$getitem(state, 'pattern'),\n flags = Flag.$factory(_b_.dict.$getitem(state, 'flags'))\n return module.compile(pattern, flags)\n}\n\nPattern.__repr__ = Pattern.__str__ = function(self){\n var text = self.$pattern.text,\n s = text\n if(self.$pattern.type == \"bytes\"){\n s = _b_.str.$factory(_b_.str.encode(s, 'latin-1'))\n }else{\n s = _b_.repr(s)\n }\n s = s.substr(0, 200)\n var res = `re.compile(${s}`,\n flags = self.$pattern.flags\n if(flags === no_flag){\n return res + ')'\n }\n // mask UNICODE flag\n if(flags.__class__ === Flag){\n // copy flag, otherwise U.value would become 0\n flags = Flag.$factory(flags.value)\n flags.value &= ~U.value\n }else if(typeof flags == \"number\"){\n flags &= ~U.value\n }\n if(flags != 0 && flags.value != 0){\n res += `, ${_b_.str.$factory(flags)}`\n }\n return res + ')'\n}\n\nPattern.findall = function(self){\n var iter = Pattern.finditer.apply(null, arguments).js_gen,\n res = []\n\n while(true){\n var next = iter.next()\n if(next.done){\n return $B.$list(res)\n }\n var bmo = next.value,\n mo = bmo.mo,\n groups = MatchObject.groups(bmo)\n\n // replace None by the empty string\n for(var i = 0, len = groups.length; i < len; i++){\n groups[i] = groups[i] === _b_.None ? \"\" : groups[i]\n }\n if(groups.length > 0){\n if(groups.length == 1){\n res.push(groups[0])\n }else{\n res.push($B.fast_tuple(groups))\n }\n }else{\n res.push(mo.string.substring(mo.start, mo.end))\n }\n }\n}\n\nPattern.finditer = function(self){\n var $ = $B.args(\"finditer\", 4,\n {self: null, string: null, pos: null, endpos: null},\n 'self string pos endpos'.split(' '), arguments,\n {pos: 0, endpos: _b_.None}, null, null)\n var data = prepare({string: $.string})\n var endpos = $.endpos === _b_.None ? data.string.length : $.endpos\n return $B.generator.$factory(iterator)(self.$pattern, data.string,\n self.flags, $.string, $.pos, endpos)\n}\n\nPattern.fullmatch = function(self, string){\n var $ = $B.args(\"match\", 4,\n {self: null, string: null, pos: null, endpos: null},\n [\"self\", \"string\", \"pos\", \"endpos\"], arguments,\n {pos: 0, endpos: _b_.None}, null, null)\n if($.endpos === _b_.None){\n $.endpos = $.string.length\n }\n var data = prepare({string: $.string})\n if(self.$pattern.type != data.string.type){\n throw _b_.TypeError.$factory(\"not the same type for pattern \" +\n \"and string\")\n }\n var fullmatch_pattern = create_fullmatch_pattern($.self.$pattern)\n var mo = match(fullmatch_pattern, data.string, $.pos, $.endpos)\n if(mo && mo.end - mo.start == $.endpos - $.pos){\n return MatchObject.$factory(mo)\n }else{\n return _b_.None\n }\n}\n\nPattern.groupindex = {\n __get__: function(self){\n return GroupIndex.$factory(self)\n }\n}\n\nPattern.match = function(self, string){\n var $ = $B.args(\"match\", 4,\n {self: null, string: null, pos: null, endpos: null},\n [\"self\", \"string\", \"pos\", \"endpos\"], arguments,\n {pos: 0, endpos: _b_.None}, null, null)\n if($.endpos === _b_.None){\n $.endpos = $.string.length\n }\n var data = prepare({string: $.string})\n if(self.$pattern.type != data.string.type){\n throw _b_.TypeError.$factory(\"not the same type for pattern \" +\n \"and string\")\n }\n var mo = match($.self.$pattern, data.string, $.pos,\n $.endpos)\n return mo ? MatchObject.$factory(mo) : _b_.None\n}\n\nPattern.scanner = function(self, string, pos, endpos){\n return Scanner.$factory.apply(null, arguments) // self, string, pos, endpos)\n}\n\nPattern.search = function(self, string){\n var $ = $B.args(\"match\", 4,\n {self: null, string: null, pos: null, endpos: null},\n [\"self\", \"string\", \"pos\", \"endpos\"], arguments,\n {pos: 0, endpos: _b_.None}, null, null)\n var data = prepare({string: $.string})\n if(self.$pattern.type != data.string.type){\n throw _b_.TypeError.$factory(\"not the same type for pattern \" +\n \"and string\")\n }\n if($.endpos === _b_.None){\n $.endpos = data.string.length\n }\n var pos = $.pos\n while(pos <= $.endpos){\n var mo = match(self.$pattern, data.string, pos)\n if(mo){\n return MatchObject.$factory(mo)\n }else{\n pos++\n }\n }\n return _b_.None\n}\n\nPattern.split = function(){\n return module.split.apply(null, arguments)\n}\n\nPattern.sub = function(){\n var $ = $B.args(\"match\", 4,\n {self: null, repl: null, string: null, count: null},\n \"self repl string count\".split(' '), arguments,\n {count: 0}, null, null)\n var data = prepare({string: $.string})\n if($.self.$pattern.type != data.string.type){\n throw _b_.TypeError.$factory(\"not the same type for pattern \" +\n \"and string\")\n }\n\n return module.sub($.self, $.repl, $.string, $.count)\n}\n\n$B.set_func_names(Pattern, \"re\")\n\nfunction Node(parent){\n this.parent = parent\n this.items = []\n}\n\nNode.prototype.add = function(item){\n this.items.push(item)\n item.parent = this\n}\n\nNode.prototype.fixed_length = function(){\n // Return the sum of items lengths if fixed, else undefined\n if(this.repeat){\n return false\n }\n var len = 0\n for(var item of this.items){\n if(item.fixed_length === undefined){\n console.log(\"pas de fixed length\", item)\n alert()\n }\n var sublen = item.fixed_length()\n if(sublen === false){\n return false\n }\n len += sublen\n }\n return len\n}\n\nfunction get_top(node){\n var top = node.parent\n while(top.parent){\n top = top.parent\n }\n return top\n}\n\nvar BackReference = function(pos, type, value){\n // for \"\\number\"\n this.name = \"BackReference\"\n this.pos = pos\n this.type = type // \"name\" or \"num\"\n this.value = value\n this.groups = []\n}\n\nBackReference.prototype.fixed_length = function(){\n // Return length of referenced group if it is fixed, else undefined\n if(this.repeat){\n return undefined\n }\n var group = this.get_group()\n if(group.fixed_length === undefined){\n console.log(\"group\", group, \"no fixed length\")\n }\n return group === undefined ? false : group.fixed_length()\n}\n\nBackReference.prototype.get_group = function(){\n var top = get_top(this)\n return top.$groups[this.value]\n}\n\nBackReference.prototype.match = function(string, pos, endpos, groups){\n this.repeat = this.repeat || {min: 1, max: 1}\n\n var group = groups[this.value]\n if(group === undefined){\n if(this.repeat.min == 0){\n return {\n nb_min: 0,\n nb_max: 0\n }\n }\n return false\n }\n\n // Get the codepoints matched by the referenced group\n group_cps = string.codepoints.slice(group.start, group.end)\n\n // search (repetitions of) the matched group codepoints\n var _pos = pos,\n nb = 0,\n group_len = group_cps.length,\n flag,\n cp\n while(string.cp_at(_pos) !== undefined && nb < this.repeat.max){\n flag = true\n for(var i = 0; i < group_len; i++){\n cp = string.cp_at(_pos + i)\n if(cp != group_cps[i]){\n flag = false\n break\n }\n }\n if(flag){\n nb++\n _pos += group_len\n }else{\n break\n }\n }\n if(nb >= this.repeat.min){\n // Returns the accepted minimum and maximum number of repeats\n // and the length of each repeat\n return {\n nb_min: this.repeat.min,\n nb_max: nb,\n group_len\n }\n }\n return false\n}\n\nBackReference.prototype.toString = function(){\n return \"BackRef to group\" + this.value\n}\n\nvar Case = function(){\n this.name = \"Case\"\n this.items = []\n this.groups = []\n this.text = 'Case '\n}\n\nCase.prototype.add = function(item){\n this.items.push(item)\n item.parent = this\n}\n\nCase.prototype.fixed_length = function(){\n var len\n for(var item of this.items){\n var fl = item.fixed_length()\n if(fl === false){\n return false\n }else if(len === undefined){\n len = fl\n }else{\n len += fl\n }\n }\n return len\n}\n\nCase.prototype.toString = function(){\n var res = 'Case '\n res += this.items.map(x => x + '').join(' ')\n return this.text = res\n}\n\nvar Choice = function(){\n this.type = \"choice\"\n this.items = []\n this.groups = []\n}\n\nChoice.prototype.add = Node.prototype.add\n\nChoice.prototype.fixed_length = function(){\n var len\n for(var item of this.items){\n var fl = item.fixed_length()\n if(fl === false){\n return false\n }else if(len === undefined){\n len = fl\n }else if(len != fl){\n return false\n }\n }\n return len\n}\n\nChoice.prototype.toString = function(){\n return 'Choice'\n}\n\nvar EmptyString = {\n toString: function(){\n return ''\n },\n match: function(string, pos, endpos){\n return {nb_min: 0, nb_max: 0}\n },\n fixed_length: function(){\n return 1\n },\n length: 0\n },\n Flags = function(flags){\n this.flags = flags\n },\n GroupEnd = function(pos){\n this.name = \"GroupEnd\"\n this.pos = pos\n this.text = ')'\n this.toString = function(){\n return '[end of group #' + this.group.num + ']'\n }\n },\n Or = function(pos){\n this.name = \"Or\"\n this.pos = pos\n this.text = '|'\n this.toString = function(){\n return '|'\n }\n },\n Repeater = function(pos, op){\n this.name = \"Repeater\"\n this.pos = pos\n this.op = op\n }\n\nfunction cased_cps(cp, ignore_case, ascii){\n // If cp is the codepoint of a cased Unicode character, return the list\n // of the codepoints that match the character in a case-insensitive way\n\n // ignore_case = this.flags && this.flags.value & IGNORECASE.value\n // ascii = this.flags.value & ASCII.value\n var cps,\n char = $B.codepoint2jsstring(cp)\n if(! ignore_case){\n return [cp]\n }\n if(ascii){\n // only test ASCII letters\n ignore_case = ignore_case && (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z'))\n }\n if(ignore_case){\n var char_up = char.toUpperCase(),\n char_low = char.toLowerCase(),\n cps = new Set([cp, $B.jsstring2codepoint(char_low),\n $B.jsstring2codepoint(char_up)])\n // special cases\n if(char.toLowerCase() == \"k\"){\n cps.add(0x212a) // Kelvin sign\n }\n if(cp == 0x212a){\n cps.add(ord('k'))\n cps.add(ord('K'))\n }\n if(char.toLowerCase() == \"s\"){\n cps.add(0x017f) // (Latin small letter long s)\n }\n if(cp == 0x017f){\n cps.add(ord('s'))\n cps.add(ord('S'))\n }\n if(char.toLowerCase() == 'i'){\n cps.add(0x0130) // (Latin capital letter I with dot above)\n cps.add(0x0131) // (Latin small letter dotless i)\n }\n if(cp == 0x0130 || cp == 0x0131){\n cps.add(ord('i'))\n cps.add(ord('I'))\n }\n return Array.from(cps)\n }else{\n cps = [cp]\n }\n return cps\n}\n\nvar Char = function(pos, cp, groups){\n // character in a regular expression or in a character set\n // pos : position of the character in the pattern string\n // cp : the character's codepoint\n // groups (optional) : the groups that contain the character\n this.pos = pos\n this.cp = cp\n this.char = chr(this.cp)\n this.text = this.char\n}\n\nChar.prototype.fixed_length = function(){\n if(this.repeat){\n return this.repeat.min\n }\n return this.char === EmptyString ? 0 : 1\n}\n\nChar.prototype.match = function(string, pos, endpos){\n // Returns {pos1, pos2} such that \"this\" matches all the substrings\n // string[pos:i] with pos1 <= i < pos2, or false if no match\n this.repeat = this.repeat || {min: 1, max: 1}\n\n var i = 0\n\n // browse string codepoints until they don't match, or the number of\n // matches is above the maximum allowed\n if(this.flags){\n if(this.flags.value & ASCII.value){\n if(this.cp > 127){\n return false\n }\n }\n if(this.flags.value & IGNORECASE.value &&\n (! this.is_bytes || this.cp <= 127)){\n // Flag IGNORECASE set\n // For bytes pattern, case insensitive matching only works\n // for ASCII characters\n var char_upper = this.char.toUpperCase(),\n char_lower = this.char.toLowerCase(),\n cp\n while(i < this.repeat.max && pos + i < endpos){\n cp = string.cp_at(pos + i)\n var char = chr(cp)\n if(char.toUpperCase() != char_upper &&\n char.toLowerCase() != char_lower){\n break\n }\n i++\n }\n }else{\n while(pos + i < endpos &&\n string.cp_at(pos + i) == this.cp &&\n i < this.repeat.max){\n i++\n }\n }\n }else{\n while(pos + i < endpos &&\n string.cp_at(pos + i) == this.cp &&\n i < this.repeat.max){\n i++\n }\n }\n var nb = i\n if(nb >= this.repeat.min){\n // Number of repeats ok\n return {\n nb_min: this.repeat.min,\n nb_max: nb\n }\n }else{\n return false\n }\n}\n\nChar.prototype.toString = function(){\n var res = 'Char ' + this.text\n if(this.repeat !== undefined){\n res += ' repeat {' + this.repeat.min + ',' + this.repeat.max + '}'\n if(this.non_greedy){\n res += '?'\n }\n }\n return res\n}\n\nfunction CharSeq(chars, flags){\n // sequence of consecutive characters\n this.chars = chars\n this.flags = flags\n this.merge_same_chars()\n}\n\nCharSeq.prototype.add_char = function(char){\n this.chars.push(char)\n this.merge_same_chars()\n}\n\nCharSeq.prototype.fixed_length = function(){\n var len = 0,\n cps = [],\n char_len\n for(var char of this.chars){\n if(! char.repeat){\n char_len = 1\n }else if(char.repeat.min == char.repeat.max){\n char_len = char.repeat.min\n }else{\n len = false\n break\n }\n for(var i = 0; i < char_len; i++){\n cps.push(char.cp)\n }\n len += char_len\n }\n this.cps = cps\n return this.len = len\n}\n\nCharSeq.prototype.match = function(string, pos, endpos){\n var mos = [],\n i = 0,\n backtrack,\n nb\n this.len = this.len === undefined ? this.fixed_length() : this.len\n // optimization if character sequence has a fixed length\n if(this.len !== false && ! (this.flags.value & IGNORECASE.value)){\n for(var i = 0; i < this.len; i++){\n if(string.cp_at(pos + i) !== this.cps[i]){\n return false\n }\n }\n return {nb_min: this.len, nb_max: this.len}\n }\n for(var i = 0, len = this.chars.length; i < len; i++){\n var char = this.chars[i],\n mo = char.match(string, pos, endpos) // form {nb_min, nb_max}\n if(_debug.value){\n console.log('CharSeq match, pos', pos, 'char', char, 'mo', mo)\n alert()\n }\n if(mo){\n nb = char.non_greedy ? mo.nb_min : mo.nb_max\n mos.push({nb,\n nb_min: mo.nb_min,\n nb_max: mo.nb_max,\n non_greedy: !!char.non_greedy\n })\n pos += nb\n }else{\n // backtrack\n backtrack = false\n while(mos.length > 0){\n i--\n mo = mos.pop()\n pos -= mo.nb\n nb = mo.nb\n if(mo.non_greedy && nb < mo.nb_max){\n nb += 1\n backtrack = true\n }else if(! mo.non_greedy && nb - 1 >= mo.nb_min){\n nb -= 1\n backtrack = true\n }\n if(backtrack){\n pos += nb\n mo.nb = nb\n mos.push(mo)\n break\n }\n }\n if(mos.length == 0){\n return false\n }\n }\n }\n var nb = 0,\n last_mo = $B.last(mos)\n for(var mo of mos.slice(0, mos.length - 1)){\n nb += mo.nb\n }\n var res = {\n nb_min: nb + last_mo.nb_min,\n nb_max: nb + last_mo.nb_max\n }\n return res\n}\n\nCharSeq.prototype.merge_same_chars = function(){\n // b?b merged into b+ etc.\n var current,\n chars = [],\n merged\n for(var item of this.chars){\n if(current && current.char == item.char &&\n current.non_greedy === item.non_greedy){\n if(! current.repeat){\n current.repeat = {min: 1, max: 1}\n }\n if(item.repeat){\n current.repeat.min += item.repeat.min\n current.repeat.max += item.repeat.max\n }else{\n current.repeat.min += 1\n current.repeat.max += 1\n }\n merged = true\n }else{\n chars.push(item)\n }\n current = item\n }\n if(merged){\n this.chars = chars\n }\n}\n\nCharSeq.prototype.toString = function(){\n var res = ''\n for(var char of this.chars){\n res += char.text\n }\n return 'CharSeq ' + res\n}\n\nfunction CharacterClass(pos, cp, length, groups){\n this.cp = cp\n this.value = chr(cp)\n this.length = length\n this.pos = pos\n\n var flags = this.flags\n\n // Test function : test(string, pos) returns:\n // - true if \"this\" matches 1 character string[pos]\n // - [true, 0] if \"this\" matches the empty string at pos\n // - false or undefined if \"this\" doesn't match\n switch(this.value){\n case 'A':\n this.test_func = function(string, pos){\n if(pos == 0){\n return [true, 0]\n }\n }\n break\n case 's':\n this.test_func = function(string, pos){\n var cp = string.cp_at(pos)\n return $B.in_unicode_category('Zs', cp) ||\n $B.unicode_bidi_whitespace.indexOf(cp) > -1\n }\n break\n case 'S':\n this.test_func = function(string, pos){\n var cp = string.cp_at(pos)\n return cp !== undefined &&\n ! $B.in_unicode_category('Zs', cp) &&\n $B.unicode_bidi_whitespace.indexOf(cp) == -1\n }\n break\n case '.':\n this.test_func = function(string, pos){\n if(string.cp_at(pos) === undefined){\n return false\n }\n if(this.flags.value & DOTALL.value){\n return true\n }else{\n return string.cp_at(pos) != 10\n }\n }\n break\n case 'd':\n this.test_func = function(string, pos){\n if(this.flags === undefined){\n console.log(\"\\\\d, no flags\", this)\n }\n var cp = string.cp_at(pos),\n tester = (this.flags.value & ASCII.value) ?\n is_ascii_digit : is_digit\n return tester(cp)\n }\n break\n case 'D':\n this.test_func = function(string, pos){\n var cp = string.cp_at(pos),\n tester = (this.flags.value & ASCII.value) ?\n is_ascii_digit : is_digit\n return ! tester(cp)\n }\n break\n case 'b':\n this.test_func = function(string, pos){\n var tester = is_word\n if(this.is_bytes || (this.flags.value & ASCII.value)){\n tester = is_ascii_word\n }\n var cp = string.cp_at(pos),\n ok = {nb_min: 0, nb_max: 0}\n\n // return true if char at pos is at the beginning or start\n // of a word\n if(pos == 0 && tester(cp)){\n return ok\n }\n if(string.cp_at(pos) === undefined && tester(string.cp_at(pos - 1))){\n return ok\n }\n if(pos > 0 && string.cp_at(pos) !== undefined){\n if((tester(string.cp_at(pos - 1))) !==\n tester(cp)){\n return ok\n }\n }\n return false\n }\n break\n case 'B':\n this.test_func = function(string, pos){\n var tester = is_word\n if(this.is_bytes || (this.flags.value & ASCII.value)){\n tester = is_ascii_word\n }\n\n var cp = string.cp_at(pos),\n ok = {nb_min: 0, nb_max: 0}\n // test is true if char at pos is not at the beginning or\n // start of a word\n if(pos == 0 && cp === undefined){\n // empty string\n return false\n }\n if(pos == 0 && tester(cp)){\n return false\n }\n if(cp === undefined &&\n tester(string.cp_at(pos - 1))){\n return false\n }\n if(pos > 0 && cp !== undefined){\n if(tester(string.cp_at(pos - 1)) !== tester(cp)){\n return false\n }\n }\n return ok\n }\n break\n case 'w':\n this.test_func = function(string, pos){\n var tester = is_word\n if(this.is_bytes || (this.flags.value & ASCII.value)){\n tester = is_ascii_word\n }\n return tester(string.cp_at(pos))\n }\n break\n case 'W':\n this.test_func = function(string, pos){\n var tester = is_word\n if(this.is_bytes || (this.flags.value & ASCII.value)){\n tester = is_ascii_word\n }\n return ! tester(string.cp_at(pos))\n }\n break\n case 'Z':\n this.test_func = function(string, pos){\n if(string.cp_at(pos) === undefined){\n return {nb_min: 0, nb_max: 0}\n }\n }\n break\n }\n}\n\nCharacterClass.prototype.fixed_length = function(){\n return this.repeat ? false : 1\n}\n\nCharacterClass.prototype.match = function(string, pos, endpos){\n // Returns {pos1, pos2} such that \"this\" matches all the substrings\n // string[pos:i] with pos1 <= i < pos2, or false if no match\n if(pos === undefined){\n console.log('no pos')\n throw Error()\n }\n var len = string.length\n this.repeat = this.repeat || {min: 1, max: 1}\n\n // browse string codepoints until they don't match, or the number of\n // matches is above the maximum allowed\n var i = 0\n while(i < this.repeat.max && i < len){\n var test = this.test_func(string, pos + i, this.flags)\n if(! test){\n break\n }\n i++\n }\n\n var nb = i\n if(nb >= this.repeat.min){\n // Number of repeats ok\n if('bBAZ'.indexOf(this.value) > -1 ){\n return {nb_min: 0, nb_max: 0}\n }\n return {\n nb_min: this.repeat.min,\n nb_max: nb\n }\n }else{\n return false\n }\n}\n\nCharacterClass.prototype.nb_repeats = Char.prototype.nb_repeats\n\nCharacterClass.prototype.toString = function(){\n return '\\\\' + this.value\n}\n\nvar CharacterSet = function(pos, set, groups){\n // character set\n this.pos = pos\n this.set = set\n this.neg = set.neg\n}\n\nCharacterSet.prototype.fixed_length = function(){\n return 1\n}\n\nCharacterSet.prototype.match = function(string, pos, endpos){\n var ignore_case = this.flags && (this.flags.value & IGNORECASE.value),\n test,\n match = false,\n i = 0,\n cp\n\n this.repeat = this.repeat || {min: 1, max: 1}\n\n while(i < this.repeat.max && (cp = string.cp_at(pos + i)) !== undefined){\n test = false\n\n if(string.cp_at(pos) === undefined){\n cp = EmptyString\n }\n try{\n $B.codepoint2jsstring(cp)\n }catch(err){\n console.log(err.message)\n console.log('cp', cp, '\\nstring', string, 'pos', pos)\n console.log($B.print_stack())\n throw _b_.Exception.$factory('bad codepoint')\n }\n var char = $B.codepoint2jsstring(cp),\n cps = cased_cps(cp, ignore_case, this.flags.value & ASCII.value),\n char_is_cased = cps.length > 1\n\n for(var cp1 of cps){\n for(var item of this.set.items){\n if(Array.isArray(item.ord)){\n if(cp1 >= item.ord[0] &&\n cp1 <= item.ord[1]){\n test = true\n break\n }else if(ignore_case && char_is_cased){\n var start1 = chr(item.ord[0]).toUpperCase(),\n end1 = chr(item.ord[1]).toUpperCase(),\n char1 = char.toUpperCase()\n if(char1 >= start1 && char1 <= end1){\n test = true\n }\n var start1 = chr(item.ord[0]).toLowerCase(),\n end1 = chr(item.ord[1]).toLowerCase(),\n char1 = char.toLowerCase()\n if(char1 >= start1 && char1 <= end1){\n test = true\n }\n }\n }else if(item instanceof CharacterClass){\n test = !! item.match(string, pos + i, endpos) // boolean\n if(test){\n break\n }\n }else{\n if(item.ord == cp1){\n test = true\n break\n }\n item_str = typeof item == 'string' ? item : chr(item.ord)\n if(item_str == char){\n test = true\n break\n }\n if(ignore_case && char_is_cased &&\n (char.toUpperCase() == item_str.toUpperCase() ||\n char.toLowerCase() == item_str.toLowerCase())){\n test = true\n break\n }\n }\n }\n }\n if(this.neg){\n test = ! test\n }\n if(test){\n i++\n }else{\n break\n }\n }\n var nb = i\n if(nb >= this.repeat.min){\n // Number of repeats ok\n return {\n nb_min: this.repeat.min,\n nb_max: nb\n }\n }else{\n return false\n }\n\n}\n\nCharacterSet.prototype.nb_repeats = Char.prototype.nb_repeats\n\nCharacterSet.prototype.toString = function(){\n return 'CharSet'\n}\n\nvar ConditionalBackref = function(pos, group_ref){\n this.type = \"conditional backref\"\n this.pos = pos\n this.group_ref = group_ref\n this.chars = []\n this.match_codepoints = []\n this.nb_success = 0\n this.re_if_exists = new Group(pos)\n this.re_if_not_exists = new Group(pos)\n this.nb_options = 1\n}\n\nConditionalBackref.prototype.add = function(item){\n if(this.nb_options == 1){\n this.re_if_exists.add(item)\n }else if(this.nb_options == 2){\n this.re_if_not_exists.add(item)\n }\n item.parent = this\n}\n\nConditionalBackref.prototype.fixed_length = function(){\n var len = this.re_if_exists.fixed_length()\n if(len !== false && len == this.re_if_not_exists.fixed_length()){\n return len\n }\n return false\n}\n\nConditionalBackref.prototype.match = function(string, pos, endpos, groups){\n var re = groups[this.group_ref] ? this.re_if_exists :\n this.re_if_not_exists,\n pattern = {node: re, text: re + ''},\n mo = match(pattern, string, pos, endpos, false, groups)\n if(mo){\n return {nb_min: mo.end - mo.start, nb_max: mo.end - mo.start}\n }\n return false\n}\n\nConditionalBackref.prototype.toString = function(){\n return 'ConditionalBackref'\n}\n\nvar Group = function(pos, extension){\n this.type = \"group\"\n this.pos = pos\n this.items = []\n this.chars = []\n this.groups = []\n for(var key in extension){\n this[key] = extension[key]\n }\n if(extension && extension.type){\n if(extension.type.indexOf('lookahead') > -1){\n this.is_lookahead = true\n }else if(extension.type.indexOf('lookbehind') > -1){\n this.is_lookbehind = true\n }\n }\n}\n\nGroup.prototype.add = Node.prototype.add\n\nGroup.prototype.toString = function(){\n if(this.num === undefined){\n var res = 'Group ' + this.type + ' ' + this.pattern\n }else{\n var res = 'Group #' + this.num + ' ' + this.pattern\n }\n if(this.repeat !== undefined){\n res += ' repeat {' + this.repeat.min + ',' + this.repeat.max + '}'\n if(this.non_greedy){\n res += '?'\n }\n }\n return res\n}\n\nBackReference.prototype.nb_repeats = Group.prototype.nb_repeats\n\nGroup.prototype.fixed_length = Node.prototype.fixed_length\n\nfunction groups_in(pattern, group_list){\n if(group_list === undefined){\n group_list = new Set()\n }\n if(pattern instanceof Group && pattern.hasOwnProperty('num')){\n group_list.add(pattern.num)\n }\n if(pattern.items){\n for(var subpattern of pattern.items){\n for(var group of groups_in(subpattern, group_list)){\n group_list.add(group)\n }\n }\n }\n return group_list\n}\n\nfunction GroupRef(group_num, item){\n this.num = group_num\n this.item = item\n}\n\nGroupRef.prototype.fixed_length = function(){\n return this.item.fixed_length()\n}\n\nfunction Lookbehind(item){\n this.re = item\n this.neg = this.re.type == \"negative_lookbehind\"\n}\n\nLookbehind.prototype.match = function(string, pos, endpos, groups){\n var ok = {nb_min: 0, nb_max: 0},\n pattern = {node: this.re, text: this.re + ''},\n length = this.re.length,\n mo\n if(pos - length < 0){\n mo = false\n }else{\n mo = match(pattern, string, pos - length, endpos, false, groups)\n }\n if(mo){\n return this.neg ? false : ok\n }else{\n return this.neg ? ok : false\n }\n}\n\nLookbehind.prototype.fixed_length = function(){\n return this.re.fixed_length()\n}\n\nLookbehind.prototype.toString = function(){\n return \"Lookbehind\"\n}\n\nfunction SetFlags(pos, flags){\n this.pos = pos\n this.on_flags = flags.on_flags\n this.off_flags = flags.off_flags\n this.items = []\n}\n\nSetFlags.prototype.add = Node.prototype.add\n\nfunction StringStart(pos){\n this.pos = pos\n}\n\nStringStart.prototype.match = function(string, pos, endpos){\n var ok = {nb_min:0, nb_max: 0}\n if(this.flags.value & MULTILINE.value){\n return (pos == 0 || string.cp_at(pos - 1) == 10) ? ok : false\n }\n return pos == 0 ? ok : false\n}\n\nStringStart.prototype.fixed_length = function(){\n return 0\n}\n\nStringStart.prototype.toString = function(){\n return '^'\n}\n\nfunction StringEnd(pos){\n this.pos = pos\n}\n\nStringEnd.prototype.match = function(string, pos, endpos){\n var ok = {nb_min:0, nb_max: 0},\n cp = string.cp_at(pos)\n if(this.flags.value & MULTILINE.value){\n return (pos > string.codepoints.length - 1 ||\n cp == 10) ? ok : false\n }\n return pos > endpos - 1 ? ok :\n (pos == endpos - 1 && cp == 10) ? ok : false\n}\n\nStringEnd.prototype.fixed_length = function(){\n return 0\n}\n\nStringEnd.prototype.toString = function(){\n return '$'\n}\n\nvar cache = new Map()\n\nfunction compile(pattern, flags){\n if(pattern.__class__ === Pattern){\n if(flags !== no_flag){\n throw _b_.ValueError.$factory(\"no flags\")\n }\n return pattern\n }\n if(cache.has(pattern.py_obj)){\n if(cache.get(pattern.py_obj).has(flags.value || 0)){\n return cache.get(pattern.py_obj).get(flags.value || 0)\n }\n }\n var original_pattern = pattern,\n original_flags = flags,\n type = pattern.type,\n choices,\n allow_global_flags = true\n pattern = pattern.codepoints\n var is_bytes = type !== \"str\"\n if(is_bytes && flags && (flags.value & U.value)){\n throw _b_.ValueError.$factory(\"cannot use UNICODE flag with \" +\n \"a bytes pattern\")\n }\n if(flags && (flags.value & U.value) &&\n (flags.value & ASCII.value)){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n if(is_bytes){\n // bytes patterns ignore re.ASCII flag\n flags = Flag.$factory(flags.value || 0)\n //flags.value &= ~ASCII.value\n }\n var group_num = 0,\n group_stack = [],\n groups = {},\n pos,\n lookbehind,\n node = new Node(),\n accept_inline_flag = true,\n verbose = (flags.value || 0) & VERBOSE.value,\n comment = false,\n backrefs = {}\n node.$groups = groups\n for(var item of tokenize(pattern, type, verbose)){\n item.flags = flags\n item.is_bytes = is_bytes\n if(lookbehind){\n item.lookbehind = lookbehind\n lookbehind.parent = item\n lookbehind = false\n }\n if(allow_global_flags &&\n (group_stack.length > 0 || ! (item instanceof SetFlags))){\n allow_global_flags = false\n }\n if(item instanceof Group){\n group_stack.push(item)\n node.add(item)\n item.state = \"open\"\n group_num++\n item.num = group_num\n node = item // next items will be stored as group's items\n pos = item.pos\n if(item.non_capturing){\n delete item.num\n group_num--\n }else if(item.type == \"name_def\"){\n var value = item.value\n if(groups[value.string] !== undefined){\n fail(`redefinition of group name` +\n ` '${value.string}' as group ${group_num}; was group` +\n ` ${groups[value.string].num}`, pos)\n }\n item.name = value.string\n groups[value.string] = groups[group_num] =\n new GroupRef(group_num, item)\n }else if(item.is_lookahead){\n // a lookahead assertion is relative to the previous regexp\n group_num--\n while(node.items.length > 0){\n item.add(node.items.shift())\n }\n node = item\n }else if(item.is_lookbehind){\n // a lookbehind assertion is relative to the next regexp\n node.parent.items.pop() // remove from node items\n // temporarily create a group\n groups[group_num] = new GroupRef(group_num, item)\n }else if(item.type == \"flags\"){\n // save flags before a group with inline flags, eg \"(?i:a)\"\n item.flags_before = Flag.$factory(flags.value | 0)\n }else{\n groups[group_num] = new GroupRef(group_num, item)\n }\n }else if(item instanceof GroupEnd){\n end_pos = item.pos\n if(group_stack.length == 0){\n fail(\"unbalanced parenthesis\", end_pos, original_pattern)\n }\n var item = group_stack.pop()\n item.end_pos = end_pos\n try{\n item.pattern = from_codepoint_list(\n pattern.slice(item.pos, end_pos + 1))\n }catch(err){\n console.log(\"err avec pattern substring\", pattern)\n throw err\n }\n if(item.is_lookbehind){\n delete groups[group_num]\n group_num--\n // check that all elements have a fixed length\n item.length = item.fixed_length()\n if(item.length === false){\n fail(\"look-behind requires fixed-width pattern\", pos)\n }\n item.parent.add(new Lookbehind(item))\n item.non_capturing = true\n // store in variable \"lookbehind\", will be applied to next item\n lookbehind = item\n }else if(item.is_lookahead){\n delete item.num\n }\n if(item instanceof Group && item.items.length == 0){\n item.add(EmptyString)\n }else if(item instanceof ConditionalBackref){\n if(groups[item.group_ref] === undefined){\n // might be defined later; store in backrefs and check\n // when all items have been processed\n backrefs[item.group_ref] = backrefs[item.group_ref] | pos + 3\n }\n if(item.re_if_exists.items.length == 0){\n item.re_if_exists.add(EmptyString)\n }else if(item.re_if_not_exists.items.length == 0){\n item.re_if_not_exists.pos = pos\n item.re_if_not_exists.add(EmptyString)\n }\n }else if(item.type == \"flags\"){\n // restore flags when entering the group\n flags = Flag.$factory(item.flags_before.value)\n }\n item.state = 'closed'\n node = item.parent\n }else if(item instanceof ConditionalBackref){\n var pos = item.pos,\n group_ref = item.group_ref\n if(typeof group_ref == \"number\"){\n if(group_ref == 0){\n fail(`bad group number`, pos + 3)\n }else if(group_ref >= MAXGROUPS){\n fail(`invalid group reference ${group_ref}`, pos + 1)\n }else if(groups[group_ref] &&\n groups[group_ref].item.state == \"open\"){\n fail(\"cannot refer to an open group\", pos)\n }\n }else if(groups[group_ref] !== undefined){\n if(groups[group_ref].item.state == \"open\"){\n fail(\"cannot refer to an open group\", pos)\n }\n }else{\n fail(`unknown group name '${group_ref}'`, pos)\n }\n group_stack.push(item)\n node.add(item)\n item.state = \"open\"\n node = item // next items will be stored as group's items\n }else if(item instanceof BackReference){\n pos = item.pos\n if(item.type == \"num\" && item.value > 99){\n var head = item.value.toString().substr(0, 2)\n fail(`invalid group reference ${head}`, pos + 1)\n }\n if(groups[item.value] !== undefined){\n if(groups[item.value].item.state == \"open\"){\n fail(\"cannot refer to an open group\", pos)\n }\n var ref_item = groups[item.value].item.parent\n while(ref_item){\n if(ref_item.is_lookbehind){\n fail(\"cannot refer to group defined in the same lookbehind subpattern\", pos)\n }\n ref_item = ref_item.parent\n }\n }else if(item.type == \"name\"){\n fail(`unknown group name '${item.value}'`, pos)\n }else if(item.type == \"num\"){\n fail(`invalid group reference ${item.value}`, pos)\n }\n node.add(item)\n }else if(item instanceof Char ||\n item instanceof CharacterClass ||\n item instanceof CharacterSet){\n if(item instanceof CharacterSet){\n for(var elt of item.set.items){\n elt.flags = flags\n }\n }\n var added_to_charseq = false\n if(item instanceof Char){\n if(node.items && node.items.length > 0){\n var previous = $last(node.items)\n if(previous instanceof CharSeq){\n previous.add_char(item)\n added_to_charseq = true\n }else if(previous instanceof Char && ! previous.repeater){\n node.items.pop()\n node.items.push(new CharSeq([previous, item], flags))\n added_to_charseq = true\n }\n }\n }\n if(! added_to_charseq){\n node.add(item)\n }\n }else if(item instanceof Repeater){\n // check that item is not in a lookbehind group\n var pnode = node\n while(pnode){\n if(pnode.extension && pnode.extension.type &&\n pnode.extension.type.indexOf(\"lookbehind\") > -1){\n fail(\"look-behind requires fixed-width pattern\", pos)\n }\n pnode = pnode.parent\n }\n pos = item.pos\n if(node.items.length == 0){\n fail(\"nothing to repeat\", pos)\n }\n previous = $last(node.items)\n if(previous instanceof Char ||\n previous instanceof CharSeq ||\n previous instanceof CharacterClass ||\n previous instanceof CharacterSet ||\n previous instanceof Group ||\n previous instanceof BackReference){\n if(previous instanceof GroupEnd){\n // associate repeat with Group\n previous = previous.group\n }else if(previous instanceof CharSeq){\n previous = $last(previous.chars)\n }\n if(previous.repeater){\n if(item.op == '?' && ! previous.non_greedy){\n if(previous.possessive){\n fail('multiple repeat', pos)\n }\n previous.non_greedy = true\n if(previous instanceof CharacterClass &&\n previous.value == '.'){\n previous.min_repeat_one = true\n }\n }else{\n if(item instanceof Repeater && item.op == '+'){\n if(previous.possessive || previous.non_greedy){\n fail('multiple repeat', pos)\n }\n previous.possessive = true\n }else{\n fail(\"multiple repeat\", pos)\n }\n }\n }else{\n // convert to minimum and maximum number of repeats\n var min = 1,\n max = 1\n if(Array.isArray(item.op)){\n min = item.op[0]\n if(min >= MAXREPEAT){\n throw _b_.OverflowError.$factory(\n \"the repetition number is too large\")\n }\n max = item.op[1] === undefined ? min : item.op[1]\n if(isFinite(max) && max >= MAXREPEAT){\n throw _b_.OverflowError.$factory(\n \"the repetition number is too large\")\n }\n if(max < min){\n fail('min repeat greater than max repeat', pos)\n }\n }else if(item.op == \"?\"){\n min = 0\n max = 1\n }else if(item.op == \"*\"){\n min = 0\n max = Number.POSITIVE_INFINITY\n }else if(item.op == \"+\"){\n min = 1\n max = Number.POSITIVE_INFINITY\n }\n previous.repeater = item\n previous.repeat = {min, max}\n // mark all parents of item as no fixed length\n var parent = item\n while(parent){\n parent.fixed_length = false\n parent = parent.parent\n }\n }\n }else{\n fail(\"nothing to repeat\", pos)\n }\n }else if(item instanceof Or){\n if(group_stack.length > 0){\n item.group = group_stack[group_stack.length - 1]\n }else{\n item.group = false\n }\n pos = item.pos\n if(node instanceof ConditionalBackref){\n // case '(?(num)a|'\n if(node.nb_options == 1){\n node.nb_options++\n }else{\n fail('conditional backref with more than ' +\n 'two branches', pos)\n }\n }else if(node.items.length == 0){\n // token \"|\" in \"(|...)\" : first option is the empty string\n var choice = new Choice(),\n case1 = new Case()\n case1.add(new Char(pos, EmptyString))\n choice.add(case1)\n node.add(choice)\n var case2 = new Case()\n choice.add(case2)\n node = case2\n }else if(node instanceof Case){\n // node.parent is already a Choice\n var new_case = new Case()\n node.parent.add(new_case)\n node = new_case\n }else{\n // token \"|\" in \"(ab|...)\"\n var previous = node.items[node.items.length - 1]\n if(previous instanceof Case){\n var new_case = new Case()\n previous.add(new_case)\n node = new_case\n }else{\n var choice = new Choice(),\n case1 = new Case(),\n first_rank = node.items[0].rank\n while(node.items.length > 0){\n case1.add(node.items.shift())\n }\n case1.groups = node.$groups\n for(var group of group_stack){\n choice.groups.push(group)\n }\n choice.add(case1)\n node.add(choice)\n var case2 = new Case()\n choice.add(case2)\n node = case2\n }\n }\n }else if(item instanceof StringStart ||\n item instanceof StringEnd){\n node.add(item)\n }else if(item instanceof SetFlags){\n if(group_stack.length == 0 && ! allow_global_flags){\n // pattern like (?x) only allowed as first in reg exp\n fail('global flags not at the start of the ' +\n 'expression', item.pos)\n }\n // copy flags, otherwise re.ASCII etc might be modified\n flags = Flag.$factory(flags.value || U.value)\n if(item.on_flags.indexOf('u') > -1){\n if(is_bytes){\n fail(\"re.error: bad inline flags: cannot use 'u' flag \" +\n \"with a bytes pattern\", pos)\n }\n if(flags && flags.value & ASCII.value){\n // switch to Unicode\n flags.value ^= ASCII.value\n }\n if(group_stack.length == 0 &&\n original_flags && original_flags.value & ASCII.value){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n if(item.on_flags.indexOf('a') > -1){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n }\n if(item.on_flags.indexOf('a') > -1){\n if(group_stack.length == 0 &&\n original_flags && original_flags.value & U.value){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n if(flags && flags.value & U.value){\n // switch to ASCII\n flags.value ^= U.value\n }\n if(item.on_flags.indexOf('u') > -1){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n }\n if(flags.value === undefined){\n flags.value = 32\n }\n if(item.items.length == 0){\n if(! accept_inline_flag && group_stack.length == 0){\n var s = from_codepoint_list(pattern)\n warn(_b_.DeprecationWarning,\n `Flags not at the start of the expression '${s}'`,\n pos)\n }\n for(var on_flag of item.on_flags){\n if(! is_bytes || on_flag !== 'a'){\n flags.value |= inline_flags[on_flag].value\n }\n }\n for(var off_flag of item.off_flags){\n if(! is_bytes || off_flag !== 'a'){\n flags.value ^= inline_flags[off_flag].value\n }\n }\n }else{\n node.add(item)\n }\n }else{\n fail(\"unknown item type \" + item, pos)\n }\n if(! (item instanceof SetFlags) &&\n ! (item instanceof Group && item.type == \"flags\")){\n accept_inline_flag = false\n }\n }\n for(ref in backrefs){\n if(groups[ref] === undefined){\n fail('invalid group name ' + ref, backrefs[ref])\n }\n }\n if(group_stack.length > 0){\n var last = group_stack[group_stack.length - 1]\n fail(\"missing ), unterminated subpattern\", last.pos)\n }\n while(node.parent){\n node = node.parent\n }\n node.pattern = from_codepoint_list(pattern)\n node.groups = group_num\n flags = flags === no_flag ? 32 : flags\n node.flags = flags\n var res = {\n node,\n groups,\n flags,\n original_flags,\n text: from_codepoint_list(pattern),\n type, // \"str\" or \"bytes\"\n fixed_length: node.fixed_length()\n }\n if(! cache.has(original_pattern.py_obj)){\n cache.set(original_pattern.py_obj, new Map())\n }\n cache.get(original_pattern.py_obj).set(original_flags.value || 0, res)\n if(_debug.value){\n show(node)\n }\n return res\n}\n\nfunction show(node, indent){\n indent = indent === undefined ? 0 : indent\n if(indent == 0){\n log('root', node)\n }\n log(' '.repeat(indent) + node)\n if(node.items !== undefined){\n for(var item of node.items){\n show(item, indent + 1)\n }\n }\n}\n\nfunction to_codepoint_list(s){\n var items = []\n if(typeof s == \"string\" || $B.$isinstance(s, _b_.str)){\n if(typeof s != \"string\"){\n s = s.valueOf()\n }\n for(var char of s){\n items.push(char.codePointAt(0))\n }\n items.type = \"unicode\"\n }else if($B.$isinstance(s, [_b_.bytes, _b_.bytearray, _b_.memoryview])){\n if($B.$isinstance(s, _b_.memoryview)){\n items = s.obj.source\n }else{\n items = s.source\n }\n items.type = \"bytes\"\n }else{\n throw Error('invalid type ' + $B.class_name(s))\n }\n return items\n}\n\n$B.nb_from_cp = 0\nfunction from_codepoint_list(codepoints, type){\n $B.nb_from_cp++\n // Return a string\n if(type == \"bytes\"){\n return _b_.bytes.$factory(codepoints)\n }\n var s = ''\n for(var cp of codepoints){\n s += _b_.chr(cp)\n }\n return $B.String(s)\n}\n\nfunction string2bytes(s){\n var t = []\n for(var i = 0, len = s.length; i < len; i++){\n t.push(s.charCodeAt(i))\n }\n return _b_.bytes.$factory(t)\n}\n\nfunction check_pattern_flags(pattern, flags){\n if(pattern.__class__ === Pattern){\n if(flags !== no_flag){\n throw _b_.ValueError.$factory(\n \"cannot process flags argument with a compiled pattern\")\n }\n }\n return pattern\n}\n\nfunction StringObj(obj){\n // A StringObj object is a bridge between a Python string or bytes-like\n // object and Javascript\n // obj is the Python object\n // this.string is a Javascript string\n this.py_obj = obj\n this.codepoints = []\n this.type = \"str\"\n this.is_string = typeof obj == 'string'\n if(typeof obj == \"string\" ||\n (obj instanceof String && ! obj.codepoints)){\n // Python object represented as a Javascript string\n this.string = obj\n // Maps a position in codepoints to position in string\n this.index_map = {}\n for(var i = 0, len = obj.length; i < len; i++){\n this.index_map[this.codepoints.length] = i\n var cp = obj.codePointAt(i)\n this.codepoints.push(cp)\n if(cp >= 0x10000){\n i++\n }\n }\n this.length = _b_.str.__len__(obj)\n if(obj instanceof String){\n // store for next use\n obj.codepoints = this.codepoints\n obj.index_map = this.index_map\n }\n }else if(obj instanceof String){\n // string with surrogate pairs\n this.string = obj.string\n this.codepoints = obj.codepoints\n this.index_map = obj.index_map\n this.length = _b_.str.__len__(obj)\n }else if($B.$isinstance(obj, _b_.str)){ // str subclass\n var so = new StringObj(_b_.str.$factory(obj))\n this.string = so.string\n this.codepoints = so.codepoints\n this.length = _b_.str.__len__(obj)\n }else if($B.$isinstance(obj, [_b_.bytes, _b_.bytearray])){\n this.string = _b_.bytes.decode(obj, 'latin1')\n this.codepoints = obj.source\n this.type = \"bytes\"\n }else if($B.$isinstance(obj, _b_.memoryview)){\n this.string = _b_.bytes.decode(obj.obj, 'latin1')\n this.codepoints = obj.obj.source\n this.type = \"bytes\"\n }else if(obj.__class__ && obj.__class__.$buffer_protocol){\n // eg array.array\n this.codepoints = _b_.list.$factory(obj)\n this.string = from_codepoint_list(this.codepoints, \"bytes\")\n this.type = \"bytes\"\n }else if(Array.isArray(obj)){\n // list of codepoints\n this.codepoints = obj\n }else{\n throw _b_.TypeError.$factory(\n `expected string or bytes-like object, got '${$B.class_name(obj)}'`)\n }\n if(this.length === undefined){\n this.length = this.codepoints.length\n }\n}\n\nStringObj.prototype.cp_at = function(pos){\n if(pos >= this.length){\n return undefined\n }\n /*\n if(typeof this.string == 'string'){\n return this.string.charCodeAt(pos)\n }\n */\n var res = this.codepoints[pos]\n if(res !== undefined){\n return res\n }\n}\n\nStringObj.prototype.substring = function(start, end){\n // Returns a string\n var s\n if(this.string && this.index_map){\n if(this.index_map[start] === undefined){\n return ''\n }\n if(end === undefined){\n return this.string.substr(this.index_map[start])\n }\n return this.string.substring(this.index_map[start],\n this.index_map[end])\n }\n var codepoints,\n res = ''\n if(end === undefined){\n codepoints = this.codepoints.slice(start)\n }else{\n codepoints = this.codepoints.slice(start, end)\n }\n return from_codepoint_list(codepoints, this.type)\n}\n\nStringObj.prototype.to_str = function(){\n if(this.hasOwnProperty('string')){\n return this.string\n }\n return from_codepoint_list(this.codepoints, this.type)\n}\n\nStringObj.from_codepoints = function(cps){\n var res = new StringObj('')\n res.codepoints = cps\n for(var cp of cps){\n res.string += _b_.chr(cp)\n }\n return res\n}\n\nfunction prepare(args){\n // Check that all arguments are of the same type (string or bytes-like).\n // Return an object with all attributes transformed into StringObj\n // instances\n var res = {},\n keys = Object.keys(args),\n first = keys[0]\n res[first] = new StringObj(args[first])\n res.type = res[first].type\n for(var key of keys.slice(1)){\n res[key] = new StringObj(args[key])\n if(res[key].type != res.type){\n throw _b_.TypeError.$factory(`not the same type for ${first} and ${key}`)\n }\n }\n return res\n}\n\n\nfunction subn(pattern, repl, string, count, flags){\n // string is a StringObj instance\n // pattern is either a Pattern instance or a StringObj instance\n var res = '',\n pos = 0,\n nb_sub = 0\n\n if(pattern instanceof StringObj){\n pattern = compile(pattern, flags)\n }\n if(typeof repl != \"function\"){\n var data1 = transform_repl({repl}, pattern)\n repl1 = data1.repl1\n }\n pos = 0\n var s = string.to_str()\n for(var bmo of module.finditer(Pattern.$factory(pattern), s).js_gen){\n // finditer yields instances of MatchObject\n var mo = bmo.mo // instance of MO\n res += from_codepoint_list(string.codepoints.slice(pos, mo.start))\n if(typeof repl == \"function\"){\n var x = $B.$call(repl)(bmo)\n if(x.__class__ === _b_.bytes){\n x = _b_.bytes.decode(x, 'latin-1')\n }\n res += x // $B.$call(repl)(bmo)\n }else{\n res += repl1\n }\n nb_sub++\n pos = mo.end\n if(count != 0 && nb_sub >= count){\n break\n }\n }\n if(string.is_string){\n res += string.string.substr(pos)\n }else{\n res += from_codepoint_list(string.codepoints.slice(pos))\n }\n if(pattern.type === \"bytes\"){\n res = _b_.str.encode(res, \"latin-1\")\n }\n return [res, nb_sub]\n}\n\n// escaped chars : '\\t\\n\\x0b\\x0c\\r #$&()*+-.?[\\\\]^{|}~'\nvar escaped = [9, 10, 11, 12, 13, 32, 35, 36, 38, 40, 41, 42, 43, 45, 46, 63,\n 91, 92, 93, 94, 123, 124, 125, 126]\n\nfunction starts_with_string_start(pattern){\n // returns true if the pattern starts with ^ or \\A\n if(pattern.node){\n pattern = pattern.node\n }\n if(pattern.items){\n if(pattern.items.length == 0){\n return false\n }\n return starts_with_string_start(pattern.items[0])\n }else if(pattern instanceof CharacterClass){\n return pattern.value == 'A'\n }else if(pattern instanceof StringStart){\n return true\n }else{\n return false\n }\n}\n\nfunction* iterator(pattern, string, flags, original_string, pos, endpos){\n var result = [],\n pos = pos | 0,\n cp,\n accept_one = true // used to test one position after string end\n while((cp = string.cp_at(pos)) !== undefined || accept_one){\n var mo = match(pattern, string, pos, endpos)\n if(mo){\n yield MatchObject.$factory(mo)\n if(mo.end == mo.start){\n // If match has zero with, retry at the same position but\n // with the flag no_zero_width set, to avoid infinite loops\n mo = match(pattern, string, pos, endpos, true)\n if(mo){\n yield MatchObject.$factory(mo)\n pos = mo.end\n }else{\n pos++ // at least 1, else infinite loop\n }\n }else{\n pos = mo.end\n }\n }else{\n pos++\n }\n if(cp === undefined){\n accept_one = false\n }\n if (starts_with_string_start(pattern) && !(flags.value & MULTILINE.value)) {\n break\n }\n }\n delete original_string.in_iteration\n}\n\n\nfunction MO(node, pos, mo, len){\n // Match Object\n this.node = node\n this.start = pos\n this.mo = mo\n this.nb_min = mo.nb_min\n this.nb_max = mo.nb_max\n this.len = len\n this.nb = this.node.non_greedy ? mo.nb_min : mo.nb_max\n this.end = pos + len * this.nb\n}\n\nMO.prototype.backtrack = function(string, groups){\n if(this.node.possessive){\n return false\n }\n if(this.node.non_greedy && this.nb < this.nb_max){\n this.nb++\n this.end = this.start + this.len * this.nb\n return true\n }else if((! this.node.non_greedy) && this.nb > this.nb_min){\n this.nb--\n this.end = this.start + this.len * this.nb\n return true\n }else{\n return false\n }\n}\n\nfunction del_groups(groups, node){\n if(node.num !== undefined){\n delete groups[node.num]\n groups.$last.splice(groups.$last.indexOf(node.num), 1)\n if(node.name !== undefined){\n delete groups[node.name]\n }\n }\n for(var child of node.items){\n if(child instanceof Group){\n del_groups(groups, child)\n }\n }\n}\n\nfunction GroupMO(node, start, matches, string, groups, endpos){\n // Match Object for Groups\n this.node = node\n this.start = start\n this._matches = matches\n this.matches = this.node.non_greedy ? matches.slice(0, this.node.repeat.min) : matches.slice()\n this.string = string\n this.end = this.matches.length > 0 ? $last(matches).end : start\n this.endpos = endpos === undefined\n ? matches.length > 0\n ? $last(matches).end\n : start\n : endpos\n this.$groups = groups\n}\n\nGroupMO.prototype.backtrack = function(string, groups){\n if(_debug.value){\n console.log('group MO backtrack, this', this)\n alert()\n }\n // Try backtracking in the last match\n if(this.node.possessive || this.node.atomic){\n return false\n }\n if(this.matches.length > 0){\n var _match = $last(this.matches),\n mos = _match.mos,\n nb0 = mos.length\n while(mos.length > 0){\n var mo = mos.pop()\n if(mo.node instanceof Case){\n var rank = mo.node.parent.items.indexOf(mo.node)\n for(var _case of mo.node.parent.items.slice(rank + 1)){\n var _mo = match({node: _case, text: _case.text},\n string, mo.start)\n if(_mo){\n // update GroupMO object\n mos.push(_mo)\n this.end = _mo.end\n if(this.$groups.$last.length > 0){\n var ix = this.$groups.$last[this.$groups.$last.length - 1]\n this.$groups[ix].end = _mo.end\n }\n return true\n }\n }\n }\n if(mo.backtrack(string, groups)){\n mos.push(mo)\n if(this.node.num !== undefined){\n groups[this.node.num].end = mo.end\n }\n this.end = mo.end\n return true\n }\n }\n }\n // Else, remove last match if possible\n if(this.node.non_greedy){\n if(this.matches.length < this._matches.length){\n this.matches.push(this._matches[this.matches.length])\n this.end = $last(this.matches).end\n return true\n }else{\n // remove this group and its children from groups\n del_groups(groups, this.node)\n this.end = this.start\n }\n }else{\n if(this.matches.length > this.node.repeat.min &&\n this.matches.length >= 1){\n this.matches.pop()\n if(this.matches.length > 0){\n this.end = $last(this.matches).end\n }else{\n // remove this group and its children from groups\n del_groups(groups, this.node)\n this.end = this.start\n }\n return true\n }\n }\n // Group fails; if some of its subgroups succeded, remove them from\n // groups\n if(this.node.repeat.min > 0){\n del_groups(groups, this.node)\n }\n return false\n}\n\nGroupMO.prototype.toString = function(){\n var repr = _b_.repr(this.string.substring(this.start, this.end))\n repr = repr.substring(0, 50)\n return ''\n}\n\nGroupMO.prototype.groups = function(_default){\n var res = [],\n groupobj = this.$groups\n\n for(var key in this.node.$groups){\n if(isFinite(key)){\n res[key] = groupobj[key] === undefined ? _default :\n this.string.substring(groupobj[key].start, groupobj[key].end)\n }\n }\n res.shift()\n return $B.fast_tuple(res)\n}\n\n// Brython MatchObject\nvar MatchObject = $B.make_class(\"Match\",\n function(mo){\n return {\n __class__: MatchObject,\n mo\n }\n }\n)\n\nMatchObject.__copy__ = function(self){\n return self\n}\n\nMatchObject.__deepcopy__ = function(self){\n return self\n}\n\nMatchObject.__getitem__ = function(){\n var $ = $B.args(\"__getitem__\", 2, {self: null, key: null},\n ['self', 'key'], arguments, {}, null, null),\n self = $.self,\n key = $.key\n if(Array.isArray(key)){\n throw _b_.IndexError.$factory(\"no such group\")\n }\n if(key == 0){\n return self.mo.string.substring(self.mo.start, self.mo.end)\n }\n var match = self.mo.$groups[key]\n if(match !== undefined){\n return self.mo.string.substring(match.start, match.end)\n }else if(self.mo.node.$groups[key] !== undefined){\n return _b_.None\n }\n throw _b_.IndexError.$factory(\"no such group\")\n}\n\nMatchObject.__repr__ = MatchObject.__str__ = function(self){\n return self.mo.toString()\n}\n\nMatchObject.end = function(self){\n var $ = $B.args('end', 2, {self: null, group: null}, ['self', 'group'],\n arguments, {group: 0}, null, null)\n var group = MatchObject.group(self, $.group)\n if(group === _b_.None){\n return -1\n }else if($.group == 0){\n return self.mo.end\n }else{\n return self.mo.$groups[$.group].end\n }\n}\n\nMatchObject.endpos = _b_.property.$factory(\n function(self){\n return self.mo.endpos\n }\n)\n\nMatchObject.expand = function(){\n var $ = $B.args(\"expand\", 2, {self: null, template: null},\n ['self', 'template'], arguments, {}, null, null)\n var data = {\n repl: new StringObj($.template),\n }\n data = transform_repl(data, {groups: $.self.mo.node.$groups})\n if(typeof data.repl == \"function\"){\n return $B.$call(data.repl)(MatchObject.$factory($.self.mo))\n }else{\n return data.repl1\n }\n}\n\nMatchObject.group = function(self){\n var $ = $B.args(\"group\", 1, {self: null}, ['self'], arguments,\n {}, 'args', null),\n self = $.self,\n args = $.args\n if(args.length == 0){\n args[0] = 0\n }\n var groupobj = self.mo.$groups,\n result = []\n for(var group_id of args){\n if($B.rich_comp('__eq__', group_id, 0)){\n result.push(self.mo.string.substring(self.mo.start, self.mo.end))\n continue\n }\n try{\n // Convert group_id to int if possible\n group_id = $B.PyNumber_Index(group_id) // in py_utils.js\n }catch(err){\n // group_id can be an identifier\n }\n if(self.mo.node.$groups[group_id] === undefined){\n throw _b_.IndexError.$factory(\"no such group\")\n }\n var group = groupobj[group_id] // found in match\n result.push(group === undefined ?\n _b_.None :\n self.mo.string.substring(group.start, group.end))\n }\n if(args.length == 1){\n return result[0]\n }\n return $B.fast_tuple(result)\n}\n\nMatchObject.groupdict = function(){\n /*\n Return a dictionary containing all the named subgroups of the match, keyed\n by the subgroup name. The default argument is used for groups that did not\n participate in the match; it defaults to None.\n */\n var $ = $B.args(\"groupdict\", 2, {self: null, default: null},\n ['self', 'default'], arguments, {default: _b_.None},\n null, null),\n self = $.self,\n groupobj = $.self.mo.$groups,\n d = $B.empty_dict()\n for(var key in $.self.mo.node.$groups){\n if(! isFinite(key)){\n var value = groupobj[key] === undefined ? $.default :\n groupobj[key]\n if(value !== $.default){\n value = self.mo.string.substring(value.start, value.end)\n }\n _b_.dict.$setitem(d, key, value)\n }\n }\n return d\n}\n\nMatchObject.groups = function(self){\n var $ = $B.args(\"group\", 2, {self: null, default: null},\n ['self', 'default'], arguments,\n {default: _b_.None}, null, null),\n self = $.self,\n _default = $.default\n return self.mo.groups(_default)\n}\n\nMatchObject.lastindex = _b_.property.$factory(\n function(self){\n /* The integer index of the last matched capturing group, or None if\n no group was matched at all.\n */\n var last = self.mo.$groups.$last\n if(last.length == 0){\n return _b_.None\n }\n return parseInt($last(last))\n }\n)\n\nMatchObject.lastgroup = _b_.property.$factory(\n function(self){\n /* The name of the last matched capturing group, or None if the group\n didn't have a name, or if no group was matched at all.\n */\n var lastindex = MatchObject.lastindex.fget(self)\n if(lastindex === _b_.None){\n return _b_.None\n }\n var group = self.mo.node.$groups[lastindex],\n name = group.item.name\n return name === undefined ? _b_.None : name\n }\n)\n\nMatchObject.pos = _b_.property.$factory(\n function(self){\n return self.mo.start\n }\n)\n\nMatchObject.re = _b_.property.$factory(\n function(self){\n return self.mo.node.pattern\n }\n)\n\nMatchObject.regs = _b_.property.$factory(\n function(self){\n var res = [$B.fast_tuple($B.fast_tuple([self.mo.start, self.mo.end]))]\n for(var group_num in self.mo.node.$groups){\n if(isFinite(group_num)){\n var group = self.mo.node.$groups[group_num].item\n // group.pattern includes the opening and closing brackets\n res.push($B.fast_tuple([group.pos,\n group.pos + group.pattern.length - 2]))\n }\n }\n return $B.fast_tuple(res)\n }\n)\n\nMatchObject.span = function(){\n /*\n Match.span([group])\n\n For a match m, return the 2-tuple (m.start(group), m.end(group)). Note\n that if group did not contribute to the match, this is (-1, -1). group\n defaults to zero, the entire match.\n */\n var $ = $B.args(\"span\", 2, {self: null, group: null},\n ['self', 'group'], arguments,\n {group: 0}, null, null),\n self = $.self,\n group = $.group\n if(group == 0){\n return $B.fast_tuple([self.mo.start, self.mo.end])\n }\n var span = self.mo.$groups[group]\n if(span === undefined){\n return $B.fast_tuple([-1, -1])\n }\n return $B.fast_tuple([span.start, span.end])\n}\n\nMatchObject.start = function(self){\n var $ = $B.args('end', 2, {self: null, group: null}, ['self', 'group'],\n arguments, {group: 0}, null, null)\n var group = MatchObject.group(self, $.group)\n if(group === _b_.None){\n return -1\n }else if($.group == 0){\n return self.mo.start\n }else{\n return self.mo.$groups[$.group].start\n }\n}\n\nMatchObject.string = _b_.property.$factory(\n function(self){\n return self.mo.string.to_str()\n }\n)\n\n$B.set_func_names(MatchObject, 're')\n\nfunction log(){\n if(_debug.value){\n console.log.apply(null, arguments)\n }\n}\n\nfunction create_fullmatch_pattern(pattern){\n // transform into \"(?:)$\"\n // use a new pattern object, otherwise if pattern is in cache the\n // value in cache would be changed\n var new_pattern = {}\n for(var key in pattern){\n if(key == 'node'){\n continue\n }\n new_pattern[key] = pattern[key]\n }\n\n var ncgroup = new Group() // non-capturing group\n ncgroup.pos = 0\n ncgroup.non_capturing = true\n for(var item of pattern.node.items){\n ncgroup.add(item)\n }\n var se = new StringEnd()\n se.flags = Flag.$factory(32)\n new_pattern.node = new Node()\n new_pattern.node.add(ncgroup)\n new_pattern.node.add(se)\n return new_pattern\n}\n\nfunction match(pattern, string, pos, endpos, no_zero_width, groups){\n // Follow the pattern tree structure\n if(_debug.value){\n console.log('match pattern', pattern.text, 'pos', pos, string.substring(pos))\n if(pattern.text == \"\\\\.\"){\n console.log(' ', pattern)\n }\n alert()\n }\n if(endpos !== undefined){\n if(endpos < pos){\n return false\n }\n }else{\n endpos = string.length\n }\n if(pattern.node instanceof Node){\n show(pattern.node)\n }\n if(groups === undefined){\n groups = {$last:[]}\n }\n if(pattern.text === undefined){\n console.log('no text', pattern)\n }\n var node = pattern.node,\n mo\n if(node.items){\n // node is either a Choice between several items, or a sequence of\n // items\n if(node instanceof Choice){\n mo = false\n for(var _case of node.items){\n mo = match({node: _case, text: _case.text}, string, pos,\n endpos, no_zero_width, groups)\n if(mo){\n // remove groups inside choice and before successful case\n // that did not contribute to the match\n var groups_succeed = groups_in(_case),\n min_num = Math.min(Array.from(groups_succeed))\n for(var group_num of groups_in(node)){\n if(group_num < min_num){\n delete groups[group_num]\n }\n }\n if(_debug.value){\n console.log('case', _case + '', 'of choice', node +\n ' succeeds, groups', groups)\n }\n return mo\n }else{\n if(_debug.value){\n console.log('case', _case + '', 'of choice', node +\n ' fails')\n }\n }\n }\n return false\n }else{\n // sequence of items\n node.repeat = node.repeat === undefined ? {min: 1, max: 1} :\n node.repeat\n var start = pos,\n nb_repeat = 0,\n nb_zerolength_repeat = 0,\n matches = [],\n mos,\n match_start,\n empty_matches = {}\n // loop until we get enough repetitions\n while(true){\n if(empty_matches[pos]){\n // no use trying again\n return matches.length == 0 ? false :\n new GroupMO(node, start, matches, string, groups,\n endpos)\n }\n var initial_groups = Object.keys(groups)\n mos = []\n match_start = pos\n if(_debug.value){\n console.log(\"pattern\", pattern.text,\n \"loop in group match, match start\", match_start)\n }\n var i = 0\n while(i < node.items.length){\n var item = node.items[i]\n if(_debug.value){\n console.log('item', i, '/', node.items.length - 1,\n 'of pattern', pattern.text)\n }\n var mo = match({node: item, text: item + ''}, string, pos,\n endpos, no_zero_width, groups)\n if(mo){\n if(item instanceof Group &&\n item.type == \"lookahead_assertion\"){\n log(\"lookahead assertion\", item + '',\n \"succeeds, mo\", mo)\n }else{\n mos.push(mo)\n pos = mo.end\n }\n i++\n }else{\n if(_debug.value){\n console.log('item ' + item, 'of group fails, nb_repeat',\n nb_repeat, 'node repeat', node.repeat)\n }\n var backtrack = false\n while(mos.length > 0){\n var mo = mos.pop()\n if(mo.backtrack === undefined){\n log('no backtrack for', mo)\n }\n if(_debug.value){\n console.log('try backtrack on mo', mo)\n }\n if(mo.backtrack(string, groups)){\n log('can backtrack, mo', mo)\n mos.push(mo)\n i = mos.length\n log('mos', mos, 'restart at item', i)\n pos = mo.end\n backtrack = true\n break\n }\n }\n if(backtrack){\n log('backtrack ok')\n continue\n }else{\n if(node.type == \"negative_lookahead_assertion\"){\n // If a negative lookahead assertion fails,\n // return a match\n var res = new GroupMO(node, start, matches,\n string, groups, endpos)\n return res\n }\n if(nb_repeat == 0){\n // remove the groups introduced before\n // reaching this point\n for(var key in groups){\n if(initial_groups.indexOf(key) == -1){\n delete groups[key]\n }\n }\n }\n if(nb_repeat >= node.repeat.min){\n log(\"enough repetitions for node\", node)\n if(node.type == \"negative_lookahead_assertion\"){\n return false\n }\n return new GroupMO(node, start, matches, string,\n groups, endpos)\n }\n return false\n }\n }\n }\n if(node.type == \"negative_lookahead_assertion\"){\n // If a negative lookahead succeeds, return false\n return false\n }\n nb_repeat++\n if(pos > match_start){\n nb_zerolength_repeat = 0\n }else{\n nb_zerolength_repeat++\n empty_matches[pos] = true\n }\n matches.push({start: match_start, end: pos, mos})\n if(node.num !== undefined){\n groups[node.num] = $last(matches)\n if(node.name !== undefined){\n groups[node.name] = groups[node.num]\n }\n if(node.num != $last(groups.$last)){\n var ix = groups.$last.indexOf(node.num)\n if(ix > -1){\n groups.$last.splice(ix, 1)\n }\n groups.$last.push(node.num)\n }\n }\n if(nb_repeat >= node.repeat.max){\n var res = new GroupMO(node, start, matches, string,\n groups, endpos)\n if(res.start == res.end && no_zero_width){\n // no_zero_width is set when previous match in\n // iterator() had length 0; avoids infinite loops\n return false\n }\n return res\n }\n log('loop on group', pattern.text, 'nb repeats', nb_repeat,\n 'nb zero length', nb_zerolength_repeat, 'groups', groups)\n if(nb_zerolength_repeat == 65535){\n return matches.length == 0 ? false :\n new GroupMO(node, start, matches, string, groups,\n endpos)\n }\n }\n }\n }else{\n // for BackReference, Char, CharSeq, CharacterClass, CharacterSet,\n // ConditionalBackref, Lookbehind, StringStart, StringEnd\n var mo = node.match(string, pos, endpos, groups)\n if(_debug.value){\n console.log(node + '', \"mo\", mo)\n }\n if(mo){\n var len = mo.group_len === undefined ? 1 : mo.group_len,\n ix = node.non_greedy ? mo.nb_min : mo.nb_max,\n end = pos + len * ix\n return new MO(node, pos, mo, len)\n }else{\n return false\n }\n }\n}\n\n// expose re module API\nvar module = {\n cache: cache,\n compile: function(){\n var $ = $B.args(\"compile\", 2, {pattern: null, flags: null},\n ['pattern', 'flags'], arguments, {flags: no_flag},\n null, null)\n if($.pattern && $.pattern.__class__ === Pattern){\n if($.flags !== no_flag){\n throw _b_.ValueError.$factory(\n \"cannot process flags argument with a compiled pattern\")\n }\n return $.pattern\n }\n $.pattern = check_pattern_flags($.pattern, $.flags)\n var data = prepare({pattern: $.pattern})\n if(typeof $.flags == \"number\"){\n $.flags = Flag.$factory($.flags)\n }\n var jspat = compile(data.pattern, $.flags)\n return Pattern.$factory(jspat)\n },\n error: error,\n escape: function(){\n var $ = $B.args(\"escape\", 1, {pattern: null}, ['pattern'], arguments,\n {}, null, null),\n data = prepare({pattern: $.pattern}),\n pattern = data.pattern,\n res = []\n for(var cp of pattern.codepoints){\n if(escaped.indexOf(cp) > -1){\n res.push(BACKSLASH)\n }\n res.push(cp)\n }\n res = from_codepoint_list(res, data.type)\n if(data.type == \"bytes\" && $B.$isinstance(res, _b_.str)){\n res = _b_.str.encode(res, 'latin1')\n }\n return res\n },\n findall: function(){\n /* Return all non-overlapping matches of pattern in string, as a list\n of strings. The string is scanned left-to-right, and matches are\n returned in the order found. If one or more groups are present in\n the pattern, return a list of groups; this will be a list of tuples\n if the pattern has more than one group. Empty matches are included\n in the result.\n */\n var $ = $B.args(\"findall\", 3,\n {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags,\n data\n pattern = check_pattern_flags(pattern, flags)\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n }else{\n data = prepare({string, pattern})\n pattern = Pattern.$factory(compile(data.pattern, flags))\n }\n if(data.type === \"str\"){\n function conv(s){\n return s === EmptyString ? '' : s\n }\n }else{\n function conv(s){\n return string2bytes(s)\n }\n }\n\n var iter = module.finditer.apply(null, arguments).js_gen,\n res = []\n while(true){\n var next = iter.next()\n if(next.done){\n return $B.$list(res)\n }\n var bmo = next.value,\n mo = bmo.mo,\n groups = MatchObject.groups(bmo)\n\n // replace None by the empty string\n for(var i = 0, len = groups.length; i < len; i++){\n groups[i] = groups[i] === _b_.None ? \"\" : groups[i]\n }\n if(groups.length > 0){\n if(groups.length == 1){\n res.push(groups[0])\n }else{\n res.push($B.fast_tuple(groups))\n }\n }else{\n res.push(mo.string.substring(mo.start, mo.end))\n }\n }\n console.log(\"end findall\")\n },\n finditer: function(){\n var $ = $B.args(\"finditer\", 3,\n {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags\n if($B.$isinstance(string, [_b_.bytearray, _b_.memoryview])){\n string.in_iteration = true\n }\n var original_string = string,\n data\n pattern = check_pattern_flags(pattern, flags)\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n flags = pattern.flags\n }else{\n data = prepare({string, pattern})\n pattern = Pattern.$factory(compile(data.pattern, flags))\n }\n if(pattern.__class__ !== Pattern){\n throw Error(\"pattern not a Python object\")\n }\n return $B.generator.$factory(iterator)(pattern.$pattern, data.string,\n flags, original_string)\n },\n fullmatch: function(){\n var $ = $B.args(\"fullmatch\", 3, {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags\n pattern = check_pattern_flags(pattern, flags)\n var data\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n pattern = pattern.$pattern\n }else{\n data = prepare({pattern, string})\n pattern = compile(data.pattern, flags)\n }\n\n var new_pattern = create_fullmatch_pattern(pattern)\n\n // match transformed RE\n var res = match(new_pattern, data.string, 0)\n var bmo = res === false ? _b_.None : MatchObject.$factory(res)\n if(bmo !== _b_.None){\n if(bmo.mo.string.codepoints.length != bmo.mo.end - bmo.mo.start){\n return _b_.None\n }else{\n return bmo\n }\n }\n return _b_.None\n },\n Match: MatchObject,\n match: function(){\n var $ = $B.args(\"match\", 3, {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags\n pattern = check_pattern_flags(pattern, flags)\n var data\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n pattern = pattern.$pattern\n }else{\n data = prepare({pattern, string})\n pattern = compile(data.pattern, flags)\n }\n var res = match(pattern, data.string, 0)\n return res === false ? _b_.None : MatchObject.$factory(res)\n },\n Pattern,\n purge: function(){\n var $ = $B.args(\"purge\", 0, {}, [], arguments, {}, null, null)\n cache.clear()\n return _b_.None\n },\n _reconstructor,\n Scanner,\n search: function(){\n var $ = $B.args(\"search\", 3, {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags,\n data\n pattern = check_pattern_flags(pattern, flags)\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n }else{\n data = prepare({string, pattern})\n pattern = Pattern.$factory(compile(data.pattern, flags))\n }\n data.pattern = pattern\n // optimizations\n if(pattern.pattern.startsWith('\\\\A') ||\n pattern.pattern.startsWith('^')){\n if(! (pattern.$pattern.node.items[0] instanceof Choice)){\n var mo = match(data.pattern.$pattern, data.string, 0)\n if(mo){\n return MatchObject.$factory(mo)\n }else if(pattern.flags.value & MULTILINE.value){\n var pos = 0,\n cp\n while((cp = data.string.cp_at(pos)) !== undefined){\n if(cp == LINEFEED){\n mo = match(data.pattern.$pattern, data.string, pos + 1)\n if(mo){\n return MatchObject.$factory(mo)\n }\n }\n pos++\n }\n }else{\n return _b_.None\n }\n }\n }\n if(pattern.$pattern.fixed_length !== false &&\n isFinite(pattern.$pattern.fixed_length) &&\n pattern.pattern.endsWith('$') &&\n ! (pattern.flags.value & MULTILINE.value)){\n var mo = match(data.pattern.$pattern, data.string,\n data.string.length - pattern.$pattern.fixed_length)\n if(mo){\n return MatchObject.$factory(mo)\n }\n return _b_.None\n }\n var pos = 0\n if(data.string.codepoints.length == 0){\n mo = match(data.pattern.$pattern, data.string, 0)\n if(mo){\n mo.start = mo.end = 0\n }\n return mo ? MatchObject.$factory(mo) : _b_.None\n }\n while(pos < data.string.codepoints.length){\n var mo = match(data.pattern.$pattern, data.string, pos)\n if(mo){\n return MatchObject.$factory(mo)\n }else{\n pos++\n }\n }\n return _b_.None\n },\n set_debug: function(value){\n _debug.value = value\n },\n split: function(){\n var $ = $B.args(\"split\", 4,\n {pattern: null, string: null, maxsplit: null, flags: null},\n ['pattern', 'string', 'maxsplit', 'flags'],\n arguments, {maxsplit: 0, flags: no_flag}, null, null)\n var res = [],\n pattern = $.pattern,\n string = $.string,\n flags = $.flags,\n pos = 0,\n nb_split = 0,\n data\n if(pattern.__class__ !== Pattern){\n data = prepare({pattern, string})\n var comp = compile(data.pattern, flags)\n pattern = Pattern.$factory(comp)\n }else{\n data = {pattern, string}\n }\n for(var bmo of module.finditer(pattern, $.string).js_gen){\n var mo = bmo.mo, // finditer returns instances of MatchObject\n groupobj = mo.$groups\n res.push(data.string.substring(pos, mo.start))\n for(var key in mo.node.$groups){\n if(isFinite(key)){\n if(groupobj[key] !== undefined){\n res.push(data.string.substring(groupobj[key].start,\n groupobj[key].end))\n }else{\n res.push(_b_.None)\n }\n }\n }\n nb_split++\n pos = mo.end\n if(pos >= $.string.length){\n break\n }\n if($.maxsplit != 0 && nb_split >= $.maxsplit){\n break\n }\n }\n res.push(data.string.substring(pos))\n if(data.type === \"bytes\"){\n res = res.map(\n function(x){\n return $B.$isinstance(x, _b_.bytes) ?\n x :\n _b_.str.encode(x, \"latin-1\")\n }\n )\n }\n return $B.$list(res)\n },\n sub: function(){\n var $ = $B.args(\"sub\", 5,\n {pattern: null, repl: null, string: null, count: null, flags: null},\n ['pattern', 'repl', 'string', 'count', 'flags'],\n arguments, {count: 0, flags: no_flag}, null, null),\n pattern = $.pattern,\n repl = $.repl,\n string = $.string,\n count = $.count,\n flags = $.flags,\n data\n check_pattern_flags(pattern, flags)\n if(typeof repl != \"function\"){\n if(pattern.__class__ != Pattern){\n data = prepare({pattern, string, repl})\n pattern = compile(data.pattern, flags)\n }else{\n data = prepare({string, repl})\n flags = pattern.flags\n pattern = pattern.$pattern\n }\n data = transform_repl(data, pattern)\n }else{\n if(pattern.__class__ != Pattern){\n data = prepare({pattern, string})\n pattern = compile(data.pattern, flags)\n }else{\n data = prepare({string})\n flags = pattern.flags\n pattern = pattern.$pattern\n }\n data.repl = repl\n }\n return subn(pattern, data.repl, data.string, count, flags)[0]\n },\n subn: function(){\n var $ = $B.args(\"sub\", 5,\n {pattern: null, repl: null, string: null, count: null, flags: null},\n ['pattern', 'repl', 'string', 'count', 'flags'],\n arguments, {count: 0, flags: no_flag}, null, null),\n pattern = $.pattern,\n repl = $.repl,\n string = $.string,\n count = $.count,\n flags = $.flags,\n data\n if(pattern.__class__ != Pattern){\n data = prepare({pattern, repl, string})\n }else{\n data = prepare({repl, string})\n data.pattern = pattern.$pattern\n }\n return $B.fast_tuple(subn(data.pattern, data.repl, data.string, count,\n flags))\n }\n\n}\n\nvar ASCII = module.A = module.ASCII = Flag.$factory(256)\nvar IGNORECASE = module.I = module.IGNORECASE = Flag.$factory(2)\nvar LOCALE = module.L = module.LOCALE = Flag.$factory(4)\nvar MULTILINE = module.M = module.MULTILINE = Flag.$factory(8)\nvar DOTALL = module.S = module.DOTALL = Flag.$factory(16)\nvar U = module.U = module.UNICODE = Flag.$factory(32)\nvar VERBOSE = module.X = module.VERBOSE = Flag.$factory(64)\nmodule.cache = cache\nmodule._compile = module.compile\n\n\nvar inline_flags = {\n i: IGNORECASE,\n L: LOCALE,\n m: MULTILINE,\n s: DOTALL,\n u: U,\n x: VERBOSE,\n a: ASCII\n}\n\nvar flag_names = {\n i: 'IGNORECASE',\n L: 'LOCALE',\n m: 'MULTILINE',\n s: 'DOTALL',\n u: 'U',\n x: 'VERBOSE',\n a: 'ASCII'\n}\n\n$B.addToImported('python_re', module)\n\n})(__BRYTHON__)"], "unicodedata": [".js", "// Implementation of unicodedata\n(function($B){\n\n var _b_ = $B.builtins\n\n // Load unicode table if not already loaded\n if($B.unicodedb === undefined){\n var xhr = new XMLHttpRequest\n xhr.open(\"GET\",\n $B.brython_path + \"unicode.txt\", false)\n xhr.onreadystatechange = function(){\n if(this.readyState == 4){\n if(this.status == 200){\n $B.unicodedb = this.responseText\n }else{\n console.log(\"Warning - could not \" +\n \"load unicode.txt\")\n }\n }\n }\n xhr.send()\n }\n\n function _info(chr){\n var ord = _b_.ord(chr),\n hex = ord.toString(16).toUpperCase()\n while(hex.length < 4){hex = \"0\" + hex}\n var re = new RegExp(\"^\" + hex +\";(.+?);(.*?);(.*?);(.*?);(.*?);(.*);(.*);(.*)$\",\n \"m\"),\n search = re.exec($B.unicodedb)\n if(search === null){\n return null\n }else{\n return {\n name: search[1],\n category: search[2],\n combining: search[3],\n bidirectional: search[4],\n decomposition: search[5],\n decimal: search[6],\n digit: search[7],\n numeric: search[8]\n }\n }\n }\n\n function bidirectional(chr){\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr, hex)\n throw _b_.KeyError.$factory(chr)\n }\n return search.bidirectional\n }\n\n function category(chr){\n // Returns the general category assigned to the character chr as\n // string.\n if(/\\p{Cn}/u.test(chr.charAt(0))){\n return \"Cn\"\n }\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return search.category\n }\n\n function combining(chr){\n // Returns the general category assigned to the character chr as\n // string.\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return parseInt(search.combining)\n }\n\n function decimal(chr, _default){\n // Returns the decimal value assigned to the character chr as integer.\n // If no such value is defined, default is returned, or, if not given,\n // ValueError is raised.\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return parseInt(search.decimal)\n }\n\n function decomposition(chr, _default){\n // Returns the decimal value assigned to the character chr as integer.\n // If no such value is defined, default is returned, or, if not given,\n // ValueError is raised.\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return search.decomposition\n }\n\n function digit(chr, _default){\n // Returns the decimal value assigned to the character chr as integer.\n // If no such value is defined, default is returned, or, if not given,\n // ValueError is raised.\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return parseInt(search.digit)\n }\n\n function lookup(name){\n // Look up character by name. If a character with the given name is\n // found, return the corresponding character. If not found, KeyError\n // is raised.\n var re = new RegExp(\"^([0-9A-F]+);\" +\n name + \";(.*)$\", \"m\")\n search = re.exec($B.unicodedb)\n if(search === null){\n throw _b_.KeyError.$factory(\"undefined character name '\" +\n name + \"'\")\n }\n var res = parseInt(search[1], 16)\n return _b_.chr(res)\n }\n\n function name(chr, _default){\n // Returns the name assigned to the character chr as a string. If no\n // name is defined, default is returned, or, if not given, ValueError\n // is raised.\n var search = _info(chr)\n if(search === null){\n if(_default){return _default}\n throw _b_.KeyError.$factory(\"undefined character name '\" +\n chr + \"'\")\n }\n return search.name\n }\n\n function _norm(form, chr){\n var search = _info(chr)\n if(search === null){\n throw _b_.KeyError.$factory(chr)\n }\n switch(form){\n case \"NFC\":\n return chr\n case \"NFD\":\n var decomp = decomposition(chr),\n parts = decomp.split(\" \"),\n res = \"\"\n if(parts[0].startsWith(\"<\")){\n return chr\n }\n parts.forEach(function(part){\n if(! part.startsWith(\"<\")){\n res += _b_.chr(parseInt(part, 16))\n }\n })\n return res\n case \"NFKC\":\n var decomp = decomposition(chr),\n parts = decomp.split(\" \")\n if(parts[0] == \"\"){\n var res = \"\"\n parts.slice(1).forEach(function(part){\n res += _b_.chr(parseInt(part, 16))\n })\n return res\n }\n return chr\n case \"NFKD\":\n var decomp = decomposition(chr),\n parts = decomp.split(\" \")\n if(parts[0] == \"\"){\n var res = \"\"\n parts.slice(1).forEach(function(part){\n res += _b_.chr(parseInt(part, 16))\n })\n return res\n }\n return chr\n\n default:\n throw _b_.ValueError.$factory(\"invalid normalization form\")\n }\n }\n\n function normalize(form, unistr){\n var res = \"\"\n for(var i = 0, len = unistr.length; i < len; i++){\n res += _norm(form, unistr.charAt(i))\n }\n return res\n }\n\n function numeric(chr, _default){\n // Returns the decimal value assigned to the character chr as integer.\n // If no such value is defined, default is returned, or, if not given,\n // ValueError is raised.\n var search = _info(chr)\n if(search === null){\n if(_default){return _default}\n throw _b_.KeyError.$factory(chr)\n }\n var parts = search.numeric.split('/'),\n value\n if(parts.length == 1){\n value = parseFloat(search.numeric)\n }else{\n value = parseInt(parts[0]) / parseInt(parts[1])\n }\n return $B.fast_float(value)\n }\n\n var module = {\n bidirectional: bidirectional,\n category: category,\n combining: combining,\n decimal: decimal,\n decomposition: decomposition,\n digit: digit,\n lookup: lookup,\n name: name,\n normalize: normalize,\n numeric: numeric,\n unidata_version: \"11.0.0\"\n }\n module.ucd_3_2_0 = {}\n for(var key in module){\n if(key == \"unidata_version\"){\n module.ucd_3_2_0[key] = '3.2.0'\n }else{\n module.ucd_3_2_0[key] = module[key] // approximation...\n }\n }\n $B.addToImported('unicodedata', module)\n\n})(__BRYTHON__)"], "xml_helpers": [".js", "var _b_ = $B.builtins\n\nvar FAIL = {FAIL: true}\nvar DONE = {DONE: true}\nvar END = {END: true}\n\nfunction is_id_start(char){\n return char !== END && char.match(/[a-zA-Z_]/)\n}\n\nfunction is_id_continue(char){\n return char !== END && (\".-:_\".includes(char) || char.match(/[a-zA-Z_0-9]/))\n}\n\nfunction is_space(char){\n return char !== END && ' \\t\\r\\n'.includes(char)\n}\n\nfunction is_num(char){\n return char !== END && char.match(/\\d/)\n}\n\nfunction is_char(char){\n return char !== END && ! '<&\"'.includes(char)\n}\n\nfunction get_top(element){\n while(element.origin){\n element = element.origin\n }\n return element\n}\n\nfunction get_pos(element){\n return get_top(element)._pos\n}\n\nfunction get_sub(element, start, end){\n return get_top(element)._buffer.substring(start, end)\n}\n\nfunction show_position(element, pos){\n var src = get_top(element)._buffer\n console.log(' ' + src)\n console.log(' ' + ' '.repeat(pos) + '^')\n}\n\nfunction reset_pos(element, pos){\n if(pos === undefined){\n throw Error('reset at undefined')\n }\n get_top(element)._pos = pos\n}\n\nfunction update_pos(element, pos){\n element.pos = pos\n}\n\nfunction show_path(rule){\n if(rule.constructor === undefined){\n console.log('rule', rule, 'no constructor')\n alert()\n }\n var name = rule.constructor.name\n if(name.endsWith('_rule')){\n name = name.substr(0, name.length - 5)\n }\n var t = [name + '@' + rule.pos]\n while(rule.origin){\n if(rule.origin.constructor === Object){\n break\n }\n name = rule.origin.constructor.name\n if(name.endsWith('_rule_')){\n name = name.substr(0, name.length - 5)\n }\n t.push(name + '@' + rule.origin.pos)\n rule = rule.origin\n }\n\n console.log('show path', t)\n}\n\nfunction set_expect(element, expect){\n var test = false // element.constructor.name == 'Attribute_rule' && expect == 1\n if(test){\n console.log('set expect of', element)\n console.log(` >>> set expect of ${element.constructor.name} to ${expect}`)\n alert()\n }\n element.expect = expect\n if(element.rules[expect]){\n var rule = element.rules[expect]\n rule.start = get_pos(element)\n }\n if(test){\n console.log(' !!! after set expect', element)\n alert()\n }\n}\n\nfunction read_char(element){\n var parser = get_top(element)\n return parser._buffer[parser._pos] || END\n}\n\nfunction raise_error_known_position(parser, message){\n var pos = parser._pos\n message += ' at position ' + pos\n var ix = pos\n while(ix >= 0 && parser._buffer[ix] !== '\\\\n'){\n ix--\n }\n message += '\\\\n' + parser._buffer.substring(ix, pos + 1)\n message += '\\\\n' + ' '.repeat(pos - ix - 1) + '^'\n throw Error(message)\n}\n\nfunction raise_error(element, char){\n var head = element\n while(head.origin){\n head = head.origin\n }\n console.log('head', head)\n var cls = element.constructor.name,\n message = cls + ' expected ' + element.expect +\n ', got: ' + char\n raise_error_known_position(head, message)\n}\n\nfunction get_string(rule){\n if(rule instanceof LITERAL){\n return rule.string\n }else if(rule instanceof Letter_rule ||\n rule instanceof CHARSET_rule){\n var s = get_sub(rule, rule.pos, rule.pos + 1)\n return s\n }\n if(rule.items === undefined){\n console.log('no items for rule', rule)\n }\n if(rule.constructor.name == 'element_rule'){\n console.log('get string of', rule)\n alert()\n }\n var s = ''\n for(var i = 0, len = rule.items.length; i < len; i++){\n var item = rule.items[i],\n last = item[item.length - 1]\n if(rule.result_store[i] === undefined){\n continue\n }\n if('?+*'.includes(last)){\n s += rule.result_store[i].join('')\n }else{\n s += rule.result_store[i]\n }\n }\n return s\n}\n\nfunction get_value(rule){\n // get string value for rule\n if(rule === undefined){\n console.log(Error().stack)\n }\n var res = ''\n if(rule.value){\n return rule.value\n }else if(rule.alt && rule.selected_rule){\n if(false){ //get_parent(rule, tmp_7_rule)){\n console.log('get_value, selected rule', rule.selected_rule)\n }\n return get_value(rule.selected_rule)\n }else{\n for(var rank in rule.result_store){\n var rules = rule.result_store[rank]\n if(Array.isArray(rules)){\n res += rules.map(get_value).join('')\n }else{\n res += get_value(rules)\n }\n }\n }\n return res\n}\n\nfunction get_rank(rule){\n return parseInt(Object.keys(rule.result_store)[0])\n}\n\nfunction get_parent(rule, type){\n var parent = rule.origin\n while(parent){\n if(parent instanceof type){\n return parent\n }\n parent = parent.origin\n }\n return null\n}\n\nfunction get_doctype_info(rule){\n console.log('get doctype info', rule)\n var systemId = _b_.None,\n publicId = _b_.None\n if(get_value(rule.rules[3])){\n ext_id = external_id(rule.rules[3].rules[1])\n console.log('ext_id 259', ext_id)\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n }\n var name = get_value(rule.rules[2])\n return {name, systemId, publicId}\n}\n\nfunction external_id(ext_id){\n var ext_id_value = get_value(ext_id),\n systemId = _b_.None,\n publicId = _b_.None\n if(ext_id_value){\n switch(ext_id.selected_option){\n case 0:\n systemId = get_value(ext_id.selected_rule.rules[2])\n systemId = systemId.substr(1, systemId.length - 2)\n break\n case 1:\n publicId = get_value(ext_id.selected_rule.rules[2])\n systemId = get_value(ext_id.selected_rule.rules[4])\n publicId = publicId.substr(1, publicId.length - 2)\n systemId = systemId.substr(1, systemId.length - 2)\n break\n }\n }\n return {publicId, systemId}\n}\n\nfunction fromCharRef(v){\n if(v.startsWith('&#x')){\n v = String.fromCodePoint(parseInt(v.substr(3)))\n }else if(v.startsWith('&#')){\n v = String.fromCodePoint(parseInt(v.substr(2)))\n }\n return v\n}\n\nvar handler = {\n AttDef: function(parser, rule){\n // S Name S AttType S DefaultDecl\n var defaultdecl = rule.rules[5],\n def_value = _b_.None,\n required = 0\n switch(defaultdecl.selected_option){\n case 0:\n required = true\n break\n case 2:\n def_value = get_value(defaultdecl.rules[2].rules[1])\n break\n }\n var res = {\n elname: get_value(rule.origin.rules[2]),\n attname: get_value(rule.rules[1]),\n type: get_value(rule.rules[3]),\n default: def_value,\n required\n }\n var f = $B.$getattr(parser, \"AttlistDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.elname, res.attname, res.type, res.default, res.required)\n }\n return res\n },\n CData: function(parser, rule){\n var f = $B.$getattr(parser, \"StartCdataSectionHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n var chardata = get_value(rule)\n var f = $B.$getattr(parser, \"CharacterDataHandler\", null)\n if(f !== null){\n $B.$call(f)(chardata)\n }\n var f = $B.$getattr(parser, \"EndCdataSectionHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n return {value: get_value(rule)}\n },\n CharData: function(parser, rule){\n console.log('chardata', rule)\n var value = get_value(rule)\n var f = $B.$getattr(parser, \"CharacterDataHandler\", null)\n if(f !== null){\n $B.$call(f)(value)\n }\n return {value: get_value(rule)}\n },\n Comment: function(parser, rule){\n console.log('comment', rule)\n var value = get_value(rule.rules[1])\n var f = $B.$getattr(parser, \"CommentHandler\", null)\n if(f !== null){\n $B.$call(f)(value)\n }\n return {value}\n },\n doctypedecl: function(parser, rule){\n console.log('doctype', rule, 'ext id', get_value(rule.rules[3]))\n if(! rule.start_done){\n // if doctype has no intSubset\n var info = get_doctype_info(rule)\n var f = $B.$getattr(parser, \"StartDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(info.name, info.systemId, info.publicId, false)\n }\n }\n if(rule.hasExternal && parser.standalone == 0){\n var f = $B.$getattr(parser, \"NotStandaloneHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n }\n var f = $B.$getattr(parser, \"EndDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n\n },\n elementdecl: function(parser, rule){\n console.log('element decl', rule)\n var name = get_value(rule.rules[2]),\n model = get_value(rule.rules[4])\n switch(model){\n case 'ANY':\n model = $B.fast_tuple([models.XML_CTYPE_ANY, 0, _b_.None, $B.fast_tuple([])])\n break\n }\n var f = $B.$getattr(parser, \"ElementDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(name, model)\n }\n\n return {name, model}\n },\n ETag: function(parser, rule){\n var name = get_value(rule.rules[1]),\n is_ns_decl\n if(parser.namespaces && parser.namespaces.hasOwnProperty(name)){\n var ns_name = name.split(':')[0]\n is_ns_decl = true\n name = parser.namespaces[name]\n }\n var f = $B.$getattr(parser, \"EndElementHandler\", null)\n if(f !== null){\n $B.$call(f)(name)\n }\n if(is_ns_decl){\n var f = $B.$getattr(parser, \"EndNamespaceDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(ns_name)\n }\n }\n return {name: get_value(rule.rules[1])}\n },\n ExternalID: function(parser, rule){\n var doctype = get_parent(rule, doctypedecl_rule)\n doctype.hasExternal = true\n },\n GEDecl: function(parser, rule){\n // ''\n var entitydef = rule.rules[4],\n value = _b_.None,\n base = _b_.None,\n systemId = _b_.None,\n publicId = _b_.None,\n notationName = _b_.None\n // EntityValue | (ExternalID NDataDecl?)\n switch(entitydef.selected_option){\n case 0:\n // EntityValue ::= '\"' ([^%&\"] | PEReference | Reference)* '\"'\n // | \"'\" ([^%&'] | PEReference | Reference)* \"'\"\n var entity_value = entitydef.selected_rule.selected_rule\n console.log('entity value', entity_value)\n var value = ''\n for(var item of entity_value.result_store[1]){\n var v = get_value(entity_value.result_store[1][0])\n value += fromCharRef(v)\n }\n console.log('value', v)\n break\n case 1:\n var ext_id = external_id(entitydef.selected_rule.rules[0])\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n if(entitydef.selected_rule.result_store[1]){\n // NDataDecl ::= S 'NDATA' S Name\n notationName = get_value(entitydef.selected_rule.rules[1].rules[3])\n }\n }\n // EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)\n var res = {\n name: get_value(rule.rules[2]),\n is_parameter_entity: 0,\n value,\n systemId,\n publicId,\n notationName\n }\n var unparsed_handled\n if(res.name == \"unparsed_entity\"){\n var f = $B.$getattr(parser, \"UnparsedEntityDeclHandler\", null)\n if(f !== null){\n unparsed_handled = true\n $B.$call(f)(res.name, base,\n res.systemId, res.publicId, res.notationName)\n }\n }\n if(! unparsed_handled){\n var f = $B.$getattr(parser, \"EntityDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.name, res.is_parameter_entity, res.value, base,\n res.systemId, res.publicId, res.notationName)\n }\n }\n return res\n },\n start_intSubset: function(parser, rule){\n // Found when starting an internal subset inside a doctype declaration\n // Used to call StartDoctypeHandler with has_internal_subset set\n var doctype_decl = get_parent(rule, doctypedecl_rule),\n info = get_doctype_info(doctype_decl)\n if(doctype_decl.hasExternal && ! parser.standalone){\n var f = $B.$getattr(parser, \"NotStandaloneHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n }\n doctype_decl.start_done = true\n delete doctype_decl.sentNotStandalone\n var f = $B.$getattr(parser, \"StartDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(info.name, info.systemId, info.publicId, true)\n }\n\n },\n NotationDecl: function(parser, rule){\n // ''\n var base = _b_.None,\n systemId = _b_.None,\n publicId = _b_.None,\n ext_or_public = rule.rules[4]\n\n switch(ext_or_public.selected_option){\n case 0:\n var ext_id = external_id(ext_or_public.selected_rule)\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n break\n case 1:\n publicId = get_value(ext_or_public.selected_rule.rules[2])\n break\n }\n var res = {\n name: get_value(rule.rules[2]),\n base,\n systemId,\n publicId\n }\n var f = $B.$getattr(parser, \"NotationDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.name, res.base, res.systemId, res.publicId)\n }\n\n return res\n },\n PI: function(parser, rule){\n console.log('PI', rule)\n var name = get_value(rule.rules[1].rules[0]),\n attrs = get_value(rule.rules[2]).trimLeft()\n var f = $B.$getattr(parser, \"ProcessingInstructionHandler\", null)\n if(f !== null){\n $B.$call(f)(name, attrs)\n }\n return {name, attrs}\n },\n STag: function(parser, rule){\n var name = get_value(rule.rules[1])\n var attrs = rule.result_store[2],\n attr_result = $B.empty_dict()\n if(attrs){\n for(var attr of attrs){\n var attr_value_store = attr.result_store[1].result_store[2].selected_rule.result_store[1],\n attr_value = ''\n for(var item of attr_value_store){\n var v = get_value(item)\n attr_value += fromCharRef(v)\n }\n var attr_name = get_value(attr.result_store[1].result_store[0])\n if(attr_name.startsWith('xmlns:')){\n var prefix = attr_name.substr(6),\n uri = attr_value\n var name1 = uri + '!' + name.split(':')[1]\n parser.namespaces = parser.namespaces ?? {}\n parser.namespaces[name] = name1\n name = name1\n var f = $B.$getattr(parser, \"StartNamespaceDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(prefix, uri)\n }\n }else{\n _b_.dict.$setitem(attr_result, attr_name, attr_value)\n }\n }\n }\n var f = $B.$getattr(parser, \"StartElementHandler\", null)\n if(f !== null){\n $B.$call(f)(name, attr_result)\n }\n return {name, attr_result}\n },\n XMLDecl: function(parser, rule){\n // ''\n var encoding,\n standalone = -1\n if(rule.result_store[2]){\n // S 'encoding' Eq ('\"' EncName '\"' | \"'\" EncName \"'\" )\n encoding = get_value(rule.rules[2].rules[3].selected_rule.rules[1])\n }\n if(rule.result_store[3]){\n // S 'standalone' Eq ((\"'\" ('yes' | 'no') \"'\") | ('\"' ('yes' | 'no') '\"'))\n sddecl = rule.rules[3]\n standalone = get_value(sddecl.rules[3].selected_rule.rules[1])\n standalone = standalone == 'yes' ? 1 : 0\n }\n parser.standalone = standalone // used for NotStandaloneHandler\n var attr_result = $B.empty_dict(),\n attrs = {\n version: get_value(rule.rules[1].rules[3].selected_rule.rules[1]),\n encoding,\n standalone\n }\n for(var attr in attrs){\n _b_.dict.$setitem(attr_result, attr, attrs[attr])\n }\n var f = $B.$getattr(parser, \"XmlDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(attrs.version, attrs.encoding, attrs.standalone)\n }\n return {name, attr_result}\n }\n}\n\n\nfunction emit(rule){\n // called when a rule is done\n var rname = rule.constructor.name\n rname = rname.substr(0, rname.length - 5)\n if(handler[rname]){\n var parser = get_top(rule)\n // console.log('emit', rname)\n handler[rname](parser, rule)\n }\n}\n\nfunction handle_simple(element, next_if_ok, rule, char){\n if(char === FAIL){\n if(typeof element.origin.feed !== 'function'){\n console.log('not a func', element)\n }\n return element.origin.feed(FAIL)\n }else if(char === DONE){\n element.result_store[element.expect] = rule // get_sub(rule, rule.pos, get_pos(rule)) // get_string(rule)\n var test = (rule.constructor.name == 'element_rule' ||\n rule.constructor.name == 'Attribute_rule')\n rule.reset()\n emit(rule)\n set_expect(element, next_if_ok)\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_plus(element, rank, next_if_ok, rule, char){\n if(char === FAIL){\n if(element.repeats[rank] == 0){\n reset_pos(element, rule.pos)\n return element.origin.feed(FAIL)\n }\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n //rule.reset()\n emit(rule)\n set_expect(element, next_if_ok)\n delete element.rules[rank]\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_star(element, rank, next_if_ok, rule, char){\n var test = false // rule instanceof tmp_6_rule\n if(test){\n console.log('HANDLE STAR', rule, 'char', char)\n }\n if(char === FAIL){\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n if(test){\n console.log(rule, 'DONE')\n }\n if(rule.alt){\n element.selected_option = element.expect\n element.selected_rule = rule\n }\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n //rule.reset()\n emit(rule)\n delete element.rules[rank]\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_zero_or_one(element, rank, next_if_ok, rule, char){\n if(char === FAIL){\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n emit(rule)\n rule.reset()\n set_expect(element, next_if_ok)\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_alt(element, alt_index, rule, char){\n if(char === FAIL){\n set_expect(element, alt_index)\n reset_pos(element, element.pos)\n return element.origin.feed(read_char(element))\n }else if(char === DONE){\n if(['AttValue_rule'].includes(rule.constructor.name)){\n console.log('DONE', rule.constructor.name, get_sub(rule, rule.pos, get_pos(rule)))\n console.log(' ', rule)\n alert()\n }\n element.selected_option = element.expect\n element.selected_rule = rule\n element.result_store[element.expect] = rule\n emit(rule)\n rule.reset()\n return element.origin.feed(char)\n }else if(char === END){\n set_expect(element, -1)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_last(element, rule, char){\n var test = false // element instanceof tmp_6_rule\n if(test){\n console.log('handle_last', rule, char)\n alert()\n }\n if(char === FAIL){\n return element.origin.feed(FAIL)\n }else if(char === DONE){\n element.result_store[element.expect] = rule\n if(element.alt){\n element.selected_option = element.expect\n element.selected_rule = rule\n if(test){\n console.log('set selected', element)\n console.log('value', get_value(rule))\n element.coucou = 'ici'\n alert()\n }\n }\n emit(rule)\n rule.reset()\n set_expect(element, -1)\n if(test){\n console.log('return control to element', element)\n alert()\n }\n return element.feed(char)\n }else if(char === END){\n set_expect(element, -1)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction expect_literal(element, literal, char){\n if(! element.hasOwnProperty('expected_pos')){\n element.expected_pos = 0\n }\n if(literal[element.expected_pos] == char){\n element.expected_pos++\n if(element.expected_pos == literal.length){\n delete element.expected_pos\n return {value: literal}\n }else{\n return {value: null}\n }\n }\n return FAIL\n}\n\nfunction LITERAL(origin, string, next_if_ok, args){\n this.origin = origin\n this.string = string\n this.next_if_ok = next_if_ok\n this.args = args\n this.pos = get_pos(this)\n this.str_pos = 0\n}\n\nLITERAL.prototype.reset = function(){\n this.str_pos = 0\n}\n\nLITERAL.prototype.feed = function(char){\n //console.log('LITERAL', this.string, 'expects', this.string[this.str_pos], 'char', char)\n if(this.string == ''){\n console.log('LITERAL feed', this.string, char, this.str_pos)\n }\n if(this.str_pos == this.string.length){\n this.value = this.string\n return this.origin.feed(DONE)\n }\n if(char == this.string[this.str_pos]){\n this.str_pos++\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction NAME_rule(origin, next_if_ok){\n this.origin = origin\n this.rank = this.origin.expect\n this.next_if_ok = next_if_ok\n this.value = ''\n this.pos = get_pos(this)\n}\n\nNAME_rule.prototype.reset = function(){\n this.value = ''\n}\n\nNAME_rule.prototype.feed = function(char){\n console.log('NAME_rule, value', this.value, 'char', char)\n if(this.value == ''){\n if(is_id_start(char)){\n this.value = char\n }else{\n return this.origin.feed(FAIL)\n }\n }else if(is_id_continue(char)){\n this.value += char\n }else{\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction NUMBER_rule(origin, next_if_ok, args){\n this.origin = origin\n this.rank = this.origin.expect\n this.next_if_ok = next_if_ok\n this.args = args\n this.pos = get_pos(this)\n this.value = ''\n}\n\nNUMBER_rule.prototype.reset = function(){\n this.value = ''\n}\n\nNUMBER_rule.prototype.feed = function(char){\n if(this.value == ''){\n if(is_num(char)){\n this.value = char\n }else if(this.args.next_if_fail !== undefined){\n this.origin.expect = this.args.next_if_fail\n return this.origin.feed(char)\n }else{\n return FAIL\n }\n }else if(is_num(char)){\n this.value += char\n }else{\n this.origin.expect = this.next_if_ok\n this.origin.store_result(this)\n return this.origin.feed(char)\n }\n return this\n}\n\nfunction start_intSubset_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.rank = this.origin.expect\n this.value = ''\n}\n\nstart_intSubset_rule.prototype.feed = function(char){\n // always succeeds\n return this.origin.feed(DONE)\n}\n\nstart_intSubset_rule.prototype.reset = function(){\n // ignore\n}\n\nfunction S_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.rank = this.origin.expect\n this.value = ''\n}\n\nS_rule.prototype.reset = function(){\n this.value = ''\n}\n\nS_rule.prototype.feed = function(char){\n if(is_space(char)){\n this.value += char\n return this\n }else if(this.value.length > 0){\n return this.origin.feed(DONE)\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction CHAR_rule(origin, next_if_ok, args){\n this.origin = origin\n this.next_if_ok = next_if_ok\n this.args = args\n}\n\nCHAR_rule.prototype.feed = function(char){\n if(is_char(char)){\n this.value = char\n return this.origin\n }else{\n return FAIL\n }\n}\n\nvar hex_range_re = /^#x([a-fA-F0-9]+)-#x([a-fA-F0-9]+)$/\nvar charset_range_re = /(\\w)-(\\w)/g\n\n\nfunction CHARSET_rule(origin, charset, next_if_ok){\n this.origin = origin\n this.charset = charset\n this.next_if_ok = next_if_ok\n this.pos = get_pos(origin)\n this.value = ''\n var negative = charset.startsWith('^'),\n body = negative ? charset.substr(1) : charset\n\n var mo = body.match(hex_range_re)\n if(mo){\n var left = parseInt(`0x${mo[1]}`, 16),\n right = parseInt(`0x${mo[2]}`, 16)\n if(negative){\n this.test = function(char){\n var cp = char.charCodeAt(0)\n return (cp < left) || (cp > right)\n }\n }else{\n this.test = function(char){\n var cp = char.charCodeAt(0)\n return (cp >= left) && (cp <= right)\n }\n }\n return\n }\n\n var ranges = []\n for(var mo of body.matchAll(charset_range_re)){\n ranges.push(mo.slice(1))\n }\n if(ranges.length > 0){\n if(negative){\n this.test = function(char){\n for(var range of ranges){\n if(char >= range[0] && char <= range[1]){\n return false\n }\n }\n return true\n }\n }else{\n this.test = function(char){\n for(var range of ranges){\n if(char >= range[0] && char <= range[1]){\n return true\n }\n }\n return false\n }\n }\n return\n }\n\n if(charset.startsWith('^')){\n this.test = char => ! charset.substr(1).includes(char)\n }else{\n this.test = char => charset.includes(char)\n }\n}\n\nCHARSET_rule.prototype.reset = function(){\n delete this.done\n}\n\nCHARSET_rule.prototype.feed = function(char){\n if(char !== END && this.test(char)){\n this.value += char\n return this\n }else if(this.value.length > 0){\n return this.origin.feed(DONE)\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction BaseChar_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n}\n\nBaseChar_rule.prototype.reset = function(){\n delete this.done\n}\n\nBaseChar_rule.prototype.feed = function(char){\n //console.log('BaseChar_rule, char', char, 'this.done', this.done)\n if(this.done){\n return this.origin.feed(DONE)\n }else if(/\\p{L}/u.exec(char)){\n this.done = true\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction Letter_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n}\n\nLetter_rule.prototype.reset = function(){\n delete this.done\n}\n\nLetter_rule.prototype.feed = function(char){\n if(this.done){\n return this.origin.feed(DONE)\n }else if(/\\p{L}/u.exec(char)){\n this.done = true\n this.value = char\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction NameChar_rule(origin){\n this.origin = origin\n this.rank = origin.expect\n this.value = ''\n var result_store = this.origin.result_store\n result_store[this.rank] = result_store[this.rank] ?? []\n this.pos = get_pos(origin)\n}\n\nNameChar_rule.prototype.reset = function(){\n delete this.done\n}\n\nNameChar_rule.prototype.feed = function(char){\n if(this.done){\n return this.origin.feed(DONE)\n }else if(is_id_continue(char)){\n this.value += char\n return this\n }else{\n if(this.value == ''){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n}\n\nfunction PIText_rule(origin){\n this.origin = origin\n this.value = ''\n this.pos = get_pos(origin)\n}\n\nPIText_rule.prototype.reset = function(){}\n\nPIText_rule.prototype.feed = function(char){\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('?>')){\n reset_pos(this, get_pos(this) - 1)\n this.value = this.value.substr(0, this.value.length - 2)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CommentText_rule(origin){\n this.origin = origin\n this.value = ''\n this.pos = get_pos(origin)\n}\n\nCommentText_rule.prototype.reset = function(){}\n\nCommentText_rule.prototype.feed = function(char){\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('-->')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n if(this.value.endsWith('-')){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CharData_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nCharData_rule.prototype.reset = function(){}\n\nCharData_rule.prototype.feed = function(char){\n // [^<&]* - ([^<&]* ']]>' [^<&]*)\n if(char === END){\n return this.origin.feed(FAIL)\n }\n if('<&'.includes(char)){\n return this.origin.feed(DONE)\n }\n this.value += char\n if(this.value.endsWith(']]>')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CData_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nCData_rule.prototype.reset = function(){}\n\nCData_rule.prototype.feed = function(char){\n // (Char* - (Char* ']]>' Char*))\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith(']]>')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction Ignore_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nIgnore_rule.prototype.reset = function(){}\n\nIgnore_rule.prototype.feed = function(char){\n // Char* - (Char* ('') Char*)\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction PITarget_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'tmp_21']\n this.rules = []\n this.repeats = []\n}\n\nPITarget_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case 1: // tmp_21\n if(! this.rules[1]){\n this.rules[1] = new tmp_21_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n var value = get_value(this)\n if(value.toLowerCase() == 'xml'){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPITarget_rule.prototype.reset = function(){\n this.expect = 0\n}\n"], "xml_parser": [".js", "(function($B){\nvar _b_ = $B.builtins\n\nvar FAIL = {FAIL: true}\nvar DONE = {DONE: true}\nvar END = {END: true}\n\nfunction is_id_start(char){\n return char !== END && char.match(/[a-zA-Z_]/)\n}\n\nfunction is_id_continue(char){\n return char !== END && (\".-:_\".includes(char) || char.match(/[a-zA-Z_0-9]/))\n}\n\nfunction is_space(char){\n return char !== END && ' \\t\\r\\n'.includes(char)\n}\n\nfunction is_num(char){\n return char !== END && char.match(/\\d/)\n}\n\nfunction is_char(char){\n return char !== END && ! '<&\"'.includes(char)\n}\n\nfunction get_top(element){\n while(element.origin){\n element = element.origin\n }\n return element\n}\n\nfunction get_pos(element){\n return get_top(element)._pos\n}\n\nfunction get_sub(element, start, end){\n return get_top(element)._buffer.substring(start, end)\n}\n\nfunction show_position(element, pos){\n var src = get_top(element)._buffer\n console.log(' ' + src)\n console.log(' ' + ' '.repeat(pos) + '^')\n}\n\nfunction reset_pos(element, pos){\n if(pos === undefined){\n throw Error('reset at undefined')\n }\n get_top(element)._pos = pos\n}\n\nfunction update_pos(element, pos){\n element.pos = pos\n}\n\nfunction show_path(rule){\n if(rule.constructor === undefined){\n console.log('rule', rule, 'no constructor')\n alert()\n }\n var name = rule.constructor.name\n if(name.endsWith('_rule')){\n name = name.substr(0, name.length - 5)\n }\n var t = [name + '@' + rule.pos]\n while(rule.origin){\n if(rule.origin.constructor === Object){\n break\n }\n name = rule.origin.constructor.name\n if(name.endsWith('_rule_')){\n name = name.substr(0, name.length - 5)\n }\n t.push(name + '@' + rule.origin.pos)\n rule = rule.origin\n }\n\n console.log('show path', t)\n}\n\nfunction set_expect(element, expect){\n var test = false // element.constructor.name == 'Attribute_rule' && expect == 1\n if(test){\n console.log('set expect of', element)\n console.log(` >>> set expect of ${element.constructor.name} to ${expect}`)\n alert()\n }\n element.expect = expect\n if(element.rules[expect]){\n var rule = element.rules[expect]\n rule.start = get_pos(element)\n }\n if(test){\n console.log(' !!! after set expect', element)\n alert()\n }\n}\n\nfunction read_char(element){\n var parser = get_top(element)\n return parser._buffer[parser._pos] || END\n}\n\nfunction raise_error_known_position(parser, message){\n var pos = parser._pos\n message += ' at position ' + pos\n var ix = pos\n while(ix >= 0 && parser._buffer[ix] !== '\\\\n'){\n ix--\n }\n message += '\\\\n' + parser._buffer.substring(ix, pos + 1)\n message += '\\\\n' + ' '.repeat(pos - ix - 1) + '^'\n throw Error(message)\n}\n\nfunction raise_error(element, char){\n var head = element\n while(head.origin){\n head = head.origin\n }\n console.log('head', head)\n var cls = element.constructor.name,\n message = cls + ' expected ' + element.expect +\n ', got: ' + char\n raise_error_known_position(head, message)\n}\n\nfunction get_string(rule){\n if(rule instanceof LITERAL){\n return rule.string\n }else if(rule instanceof Letter_rule ||\n rule instanceof CHARSET_rule){\n var s = get_sub(rule, rule.pos, rule.pos + 1)\n return s\n }\n if(rule.items === undefined){\n console.log('no items for rule', rule)\n }\n if(rule.constructor.name == 'element_rule'){\n console.log('get string of', rule)\n alert()\n }\n var s = ''\n for(var i = 0, len = rule.items.length; i < len; i++){\n var item = rule.items[i],\n last = item[item.length - 1]\n if(rule.result_store[i] === undefined){\n continue\n }\n if('?+*'.includes(last)){\n s += rule.result_store[i].join('')\n }else{\n s += rule.result_store[i]\n }\n }\n return s\n}\n\nfunction get_value(rule){\n // get string value for rule\n if(rule === undefined){\n console.log(Error().stack)\n }\n var res = ''\n if(rule.value){\n return rule.value\n }else if(rule.alt && rule.selected_rule){\n if(false){ //get_parent(rule, tmp_7_rule)){\n console.log('get_value, selected rule', rule.selected_rule)\n }\n return get_value(rule.selected_rule)\n }else{\n for(var rank in rule.result_store){\n var rules = rule.result_store[rank]\n if(Array.isArray(rules)){\n res += rules.map(get_value).join('')\n }else{\n res += get_value(rules)\n }\n }\n }\n return res\n}\n\nfunction get_rank(rule){\n return parseInt(Object.keys(rule.result_store)[0])\n}\n\nfunction get_parent(rule, type){\n var parent = rule.origin\n while(parent){\n if(parent instanceof type){\n return parent\n }\n parent = parent.origin\n }\n return null\n}\n\nfunction get_doctype_info(rule){\n console.log('get doctype info', rule)\n var systemId = _b_.None,\n publicId = _b_.None\n if(get_value(rule.rules[3])){\n ext_id = external_id(rule.rules[3].rules[1])\n console.log('ext_id 259', ext_id)\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n }\n var name = get_value(rule.rules[2])\n return {name, systemId, publicId}\n}\n\nfunction external_id(ext_id){\n var ext_id_value = get_value(ext_id),\n systemId = _b_.None,\n publicId = _b_.None\n if(ext_id_value){\n switch(ext_id.selected_option){\n case 0:\n systemId = get_value(ext_id.selected_rule.rules[2])\n systemId = systemId.substr(1, systemId.length - 2)\n break\n case 1:\n publicId = get_value(ext_id.selected_rule.rules[2])\n systemId = get_value(ext_id.selected_rule.rules[4])\n publicId = publicId.substr(1, publicId.length - 2)\n systemId = systemId.substr(1, systemId.length - 2)\n break\n }\n }\n return {publicId, systemId}\n}\n\nfunction fromCharRef(v){\n if(v.startsWith('&#x')){\n v = String.fromCodePoint(parseInt(v.substr(3)))\n }else if(v.startsWith('&#')){\n v = String.fromCodePoint(parseInt(v.substr(2)))\n }\n return v\n}\n\nvar handler = {\n AttDef: function(parser, rule){\n // S Name S AttType S DefaultDecl\n var defaultdecl = rule.rules[5],\n def_value = _b_.None,\n required = 0\n switch(defaultdecl.selected_option){\n case 0:\n required = true\n break\n case 2:\n def_value = get_value(defaultdecl.rules[2].rules[1])\n break\n }\n var res = {\n elname: get_value(rule.origin.rules[2]),\n attname: get_value(rule.rules[1]),\n type: get_value(rule.rules[3]),\n default: def_value,\n required\n }\n var f = $B.$getattr(parser, \"AttlistDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.elname, res.attname, res.type, res.default, res.required)\n }\n return res\n },\n CData: function(parser, rule){\n var f = $B.$getattr(parser, \"StartCdataSectionHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n var chardata = get_value(rule)\n var f = $B.$getattr(parser, \"CharacterDataHandler\", null)\n if(f !== null){\n $B.$call(f)(chardata)\n }\n var f = $B.$getattr(parser, \"EndCdataSectionHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n return {value: get_value(rule)}\n },\n CharData: function(parser, rule){\n console.log('chardata', rule)\n var value = get_value(rule)\n var f = $B.$getattr(parser, \"CharacterDataHandler\", null)\n if(f !== null){\n $B.$call(f)(value)\n }\n return {value: get_value(rule)}\n },\n Comment: function(parser, rule){\n console.log('comment', rule)\n var value = get_value(rule.rules[1])\n var f = $B.$getattr(parser, \"CommentHandler\", null)\n if(f !== null){\n $B.$call(f)(value)\n }\n return {value}\n },\n doctypedecl: function(parser, rule){\n console.log('doctype', rule, 'ext id', get_value(rule.rules[3]))\n if(! rule.start_done){\n // if doctype has no intSubset\n var info = get_doctype_info(rule)\n var f = $B.$getattr(parser, \"StartDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(info.name, info.systemId, info.publicId, false)\n }\n }\n if(rule.hasExternal && parser.standalone == 0){\n var f = $B.$getattr(parser, \"NotStandaloneHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n }\n var f = $B.$getattr(parser, \"EndDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n\n },\n elementdecl: function(parser, rule){\n console.log('element decl', rule)\n var name = get_value(rule.rules[2]),\n model = get_value(rule.rules[4])\n switch(model){\n case 'ANY':\n model = $B.fast_tuple([models.XML_CTYPE_ANY, 0, _b_.None, $B.fast_tuple([])])\n break\n }\n var f = $B.$getattr(parser, \"ElementDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(name, model)\n }\n\n return {name, model}\n },\n ETag: function(parser, rule){\n var name = get_value(rule.rules[1]),\n is_ns_decl\n if(parser.namespaces && parser.namespaces.hasOwnProperty(name)){\n var ns_name = name.split(':')[0]\n is_ns_decl = true\n name = parser.namespaces[name]\n }\n var f = $B.$getattr(parser, \"EndElementHandler\", null)\n if(f !== null){\n $B.$call(f)(name)\n }\n if(is_ns_decl){\n var f = $B.$getattr(parser, \"EndNamespaceDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(ns_name)\n }\n }\n return {name: get_value(rule.rules[1])}\n },\n ExternalID: function(parser, rule){\n var doctype = get_parent(rule, doctypedecl_rule)\n doctype.hasExternal = true\n },\n GEDecl: function(parser, rule){\n // ''\n var entitydef = rule.rules[4],\n value = _b_.None,\n base = _b_.None,\n systemId = _b_.None,\n publicId = _b_.None,\n notationName = _b_.None\n // EntityValue | (ExternalID NDataDecl?)\n switch(entitydef.selected_option){\n case 0:\n // EntityValue ::= '\"' ([^%&\"] | PEReference | Reference)* '\"'\n // | \"'\" ([^%&'] | PEReference | Reference)* \"'\"\n var entity_value = entitydef.selected_rule.selected_rule\n console.log('entity value', entity_value)\n var value = ''\n for(var item of entity_value.result_store[1]){\n var v = get_value(entity_value.result_store[1][0])\n value += fromCharRef(v)\n }\n console.log('value', v)\n break\n case 1:\n var ext_id = external_id(entitydef.selected_rule.rules[0])\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n if(entitydef.selected_rule.result_store[1]){\n // NDataDecl ::= S 'NDATA' S Name\n notationName = get_value(entitydef.selected_rule.rules[1].rules[3])\n }\n }\n // EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)\n var res = {\n name: get_value(rule.rules[2]),\n is_parameter_entity: 0,\n value,\n systemId,\n publicId,\n notationName\n }\n var unparsed_handled\n if(res.name == \"unparsed_entity\"){\n var f = $B.$getattr(parser, \"UnparsedEntityDeclHandler\", null)\n if(f !== null){\n unparsed_handled = true\n $B.$call(f)(res.name, base,\n res.systemId, res.publicId, res.notationName)\n }\n }\n if(! unparsed_handled){\n var f = $B.$getattr(parser, \"EntityDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.name, res.is_parameter_entity, res.value, base,\n res.systemId, res.publicId, res.notationName)\n }\n }\n return res\n },\n start_intSubset: function(parser, rule){\n // Found when starting an internal subset inside a doctype declaration\n // Used to call StartDoctypeHandler with has_internal_subset set\n var doctype_decl = get_parent(rule, doctypedecl_rule),\n info = get_doctype_info(doctype_decl)\n if(doctype_decl.hasExternal && ! parser.standalone){\n var f = $B.$getattr(parser, \"NotStandaloneHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n }\n doctype_decl.start_done = true\n delete doctype_decl.sentNotStandalone\n var f = $B.$getattr(parser, \"StartDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(info.name, info.systemId, info.publicId, true)\n }\n\n },\n NotationDecl: function(parser, rule){\n // ''\n var base = _b_.None,\n systemId = _b_.None,\n publicId = _b_.None,\n ext_or_public = rule.rules[4]\n\n switch(ext_or_public.selected_option){\n case 0:\n var ext_id = external_id(ext_or_public.selected_rule)\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n break\n case 1:\n publicId = get_value(ext_or_public.selected_rule.rules[2])\n break\n }\n var res = {\n name: get_value(rule.rules[2]),\n base,\n systemId,\n publicId\n }\n var f = $B.$getattr(parser, \"NotationDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.name, res.base, res.systemId, res.publicId)\n }\n\n return res\n },\n PI: function(parser, rule){\n console.log('PI', rule)\n var name = get_value(rule.rules[1].rules[0]),\n attrs = get_value(rule.rules[2]).trimLeft()\n var f = $B.$getattr(parser, \"ProcessingInstructionHandler\", null)\n if(f !== null){\n $B.$call(f)(name, attrs)\n }\n return {name, attrs}\n },\n STag: function(parser, rule){\n var name = get_value(rule.rules[1])\n var attrs = rule.result_store[2],\n attr_result = $B.empty_dict()\n if(attrs){\n for(var attr of attrs){\n var attr_value_store = attr.result_store[1].result_store[2].selected_rule.result_store[1],\n attr_value = ''\n for(var item of attr_value_store){\n var v = get_value(item)\n attr_value += fromCharRef(v)\n }\n var attr_name = get_value(attr.result_store[1].result_store[0])\n if(attr_name.startsWith('xmlns:')){\n var prefix = attr_name.substr(6),\n uri = attr_value\n var name1 = uri + '!' + name.split(':')[1]\n parser.namespaces = parser.namespaces ?? {}\n parser.namespaces[name] = name1\n name = name1\n var f = $B.$getattr(parser, \"StartNamespaceDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(prefix, uri)\n }\n }else{\n _b_.dict.$setitem(attr_result, attr_name, attr_value)\n }\n }\n }\n var f = $B.$getattr(parser, \"StartElementHandler\", null)\n if(f !== null){\n $B.$call(f)(name, attr_result)\n }\n return {name, attr_result}\n },\n XMLDecl: function(parser, rule){\n // ''\n var encoding,\n standalone = -1\n if(rule.result_store[2]){\n // S 'encoding' Eq ('\"' EncName '\"' | \"'\" EncName \"'\" )\n encoding = get_value(rule.rules[2].rules[3].selected_rule.rules[1])\n }\n if(rule.result_store[3]){\n // S 'standalone' Eq ((\"'\" ('yes' | 'no') \"'\") | ('\"' ('yes' | 'no') '\"'))\n sddecl = rule.rules[3]\n standalone = get_value(sddecl.rules[3].selected_rule.rules[1])\n standalone = standalone == 'yes' ? 1 : 0\n }\n parser.standalone = standalone // used for NotStandaloneHandler\n var attr_result = $B.empty_dict(),\n attrs = {\n version: get_value(rule.rules[1].rules[3].selected_rule.rules[1]),\n encoding,\n standalone\n }\n for(var attr in attrs){\n _b_.dict.$setitem(attr_result, attr, attrs[attr])\n }\n var f = $B.$getattr(parser, \"XmlDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(attrs.version, attrs.encoding, attrs.standalone)\n }\n return {name, attr_result}\n }\n}\n\n\nfunction emit(rule){\n // called when a rule is done\n var rname = rule.constructor.name\n rname = rname.substr(0, rname.length - 5)\n if(handler[rname]){\n var parser = get_top(rule)\n // console.log('emit', rname)\n handler[rname](parser, rule)\n }\n}\n\nfunction handle_simple(element, next_if_ok, rule, char){\n if(char === FAIL){\n if(typeof element.origin.feed !== 'function'){\n console.log('not a func', element)\n }\n return element.origin.feed(FAIL)\n }else if(char === DONE){\n element.result_store[element.expect] = rule // get_sub(rule, rule.pos, get_pos(rule)) // get_string(rule)\n var test = (rule.constructor.name == 'element_rule' ||\n rule.constructor.name == 'Attribute_rule')\n rule.reset()\n emit(rule)\n set_expect(element, next_if_ok)\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_plus(element, rank, next_if_ok, rule, char){\n if(char === FAIL){\n if(element.repeats[rank] == 0){\n reset_pos(element, rule.pos)\n return element.origin.feed(FAIL)\n }\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n //rule.reset()\n emit(rule)\n set_expect(element, next_if_ok)\n delete element.rules[rank]\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_star(element, rank, next_if_ok, rule, char){\n var test = false // rule instanceof tmp_6_rule\n if(test){\n console.log('HANDLE STAR', rule, 'char', char)\n }\n if(char === FAIL){\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n if(test){\n console.log(rule, 'DONE')\n }\n if(rule.alt){\n element.selected_option = element.expect\n element.selected_rule = rule\n }\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n //rule.reset()\n emit(rule)\n delete element.rules[rank]\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_zero_or_one(element, rank, next_if_ok, rule, char){\n if(char === FAIL){\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n emit(rule)\n rule.reset()\n set_expect(element, next_if_ok)\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_alt(element, alt_index, rule, char){\n if(char === FAIL){\n set_expect(element, alt_index)\n reset_pos(element, element.pos)\n return element.origin.feed(read_char(element))\n }else if(char === DONE){\n if(['AttValue_rule'].includes(rule.constructor.name)){\n console.log('DONE', rule.constructor.name, get_sub(rule, rule.pos, get_pos(rule)))\n console.log(' ', rule)\n alert()\n }\n element.selected_option = element.expect\n element.selected_rule = rule\n element.result_store[element.expect] = rule\n emit(rule)\n rule.reset()\n return element.origin.feed(char)\n }else if(char === END){\n set_expect(element, -1)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_last(element, rule, char){\n var test = false // element instanceof tmp_6_rule\n if(test){\n console.log('handle_last', rule, char)\n alert()\n }\n if(char === FAIL){\n return element.origin.feed(FAIL)\n }else if(char === DONE){\n element.result_store[element.expect] = rule\n if(element.alt){\n element.selected_option = element.expect\n element.selected_rule = rule\n if(test){\n console.log('set selected', element)\n console.log('value', get_value(rule))\n element.coucou = 'ici'\n alert()\n }\n }\n emit(rule)\n rule.reset()\n set_expect(element, -1)\n if(test){\n console.log('return control to element', element)\n alert()\n }\n return element.feed(char)\n }else if(char === END){\n set_expect(element, -1)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction expect_literal(element, literal, char){\n if(! element.hasOwnProperty('expected_pos')){\n element.expected_pos = 0\n }\n if(literal[element.expected_pos] == char){\n element.expected_pos++\n if(element.expected_pos == literal.length){\n delete element.expected_pos\n return {value: literal}\n }else{\n return {value: null}\n }\n }\n return FAIL\n}\n\nfunction LITERAL(origin, string, next_if_ok, args){\n this.origin = origin\n this.string = string\n this.next_if_ok = next_if_ok\n this.args = args\n this.pos = get_pos(this)\n this.str_pos = 0\n}\n\nLITERAL.prototype.reset = function(){\n this.str_pos = 0\n}\n\nLITERAL.prototype.feed = function(char){\n //console.log('LITERAL', this.string, 'expects', this.string[this.str_pos], 'char', char)\n if(this.string == ''){\n console.log('LITERAL feed', this.string, char, this.str_pos)\n }\n if(this.str_pos == this.string.length){\n this.value = this.string\n return this.origin.feed(DONE)\n }\n if(char == this.string[this.str_pos]){\n this.str_pos++\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction NAME_rule(origin, next_if_ok){\n this.origin = origin\n this.rank = this.origin.expect\n this.next_if_ok = next_if_ok\n this.value = ''\n this.pos = get_pos(this)\n}\n\nNAME_rule.prototype.reset = function(){\n this.value = ''\n}\n\nNAME_rule.prototype.feed = function(char){\n console.log('NAME_rule, value', this.value, 'char', char)\n if(this.value == ''){\n if(is_id_start(char)){\n this.value = char\n }else{\n return this.origin.feed(FAIL)\n }\n }else if(is_id_continue(char)){\n this.value += char\n }else{\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction NUMBER_rule(origin, next_if_ok, args){\n this.origin = origin\n this.rank = this.origin.expect\n this.next_if_ok = next_if_ok\n this.args = args\n this.pos = get_pos(this)\n this.value = ''\n}\n\nNUMBER_rule.prototype.reset = function(){\n this.value = ''\n}\n\nNUMBER_rule.prototype.feed = function(char){\n if(this.value == ''){\n if(is_num(char)){\n this.value = char\n }else if(this.args.next_if_fail !== undefined){\n this.origin.expect = this.args.next_if_fail\n return this.origin.feed(char)\n }else{\n return FAIL\n }\n }else if(is_num(char)){\n this.value += char\n }else{\n this.origin.expect = this.next_if_ok\n this.origin.store_result(this)\n return this.origin.feed(char)\n }\n return this\n}\n\nfunction start_intSubset_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.rank = this.origin.expect\n this.value = ''\n}\n\nstart_intSubset_rule.prototype.feed = function(char){\n // always succeeds\n return this.origin.feed(DONE)\n}\n\nstart_intSubset_rule.prototype.reset = function(){\n // ignore\n}\n\nfunction S_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.rank = this.origin.expect\n this.value = ''\n}\n\nS_rule.prototype.reset = function(){\n this.value = ''\n}\n\nS_rule.prototype.feed = function(char){\n if(is_space(char)){\n this.value += char\n return this\n }else if(this.value.length > 0){\n return this.origin.feed(DONE)\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction CHAR_rule(origin, next_if_ok, args){\n this.origin = origin\n this.next_if_ok = next_if_ok\n this.args = args\n}\n\nCHAR_rule.prototype.feed = function(char){\n if(is_char(char)){\n this.value = char\n return this.origin\n }else{\n return FAIL\n }\n}\n\nvar hex_range_re = /^#x([a-fA-F0-9]+)-#x([a-fA-F0-9]+)$/\nvar charset_range_re = /(\\w)-(\\w)/g\n\n\nfunction CHARSET_rule(origin, charset, next_if_ok){\n this.origin = origin\n this.charset = charset\n this.next_if_ok = next_if_ok\n this.pos = get_pos(origin)\n this.value = ''\n var negative = charset.startsWith('^'),\n body = negative ? charset.substr(1) : charset\n\n var mo = body.match(hex_range_re)\n if(mo){\n var left = parseInt(`0x${mo[1]}`, 16),\n right = parseInt(`0x${mo[2]}`, 16)\n if(negative){\n this.test = function(char){\n var cp = char.charCodeAt(0)\n return (cp < left) || (cp > right)\n }\n }else{\n this.test = function(char){\n var cp = char.charCodeAt(0)\n return (cp >= left) && (cp <= right)\n }\n }\n return\n }\n\n var ranges = []\n for(var mo of body.matchAll(charset_range_re)){\n ranges.push(mo.slice(1))\n }\n if(ranges.length > 0){\n if(negative){\n this.test = function(char){\n for(var range of ranges){\n if(char >= range[0] && char <= range[1]){\n return false\n }\n }\n return true\n }\n }else{\n this.test = function(char){\n for(var range of ranges){\n if(char >= range[0] && char <= range[1]){\n return true\n }\n }\n return false\n }\n }\n return\n }\n\n if(charset.startsWith('^')){\n this.test = char => ! charset.substr(1).includes(char)\n }else{\n this.test = char => charset.includes(char)\n }\n}\n\nCHARSET_rule.prototype.reset = function(){\n delete this.done\n}\n\nCHARSET_rule.prototype.feed = function(char){\n if(char !== END && this.test(char)){\n this.value += char\n return this\n }else if(this.value.length > 0){\n return this.origin.feed(DONE)\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction BaseChar_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n}\n\nBaseChar_rule.prototype.reset = function(){\n delete this.done\n}\n\nBaseChar_rule.prototype.feed = function(char){\n //console.log('BaseChar_rule, char', char, 'this.done', this.done)\n if(this.done){\n return this.origin.feed(DONE)\n }else if(/\\p{L}/u.exec(char)){\n this.done = true\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction Letter_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n}\n\nLetter_rule.prototype.reset = function(){\n delete this.done\n}\n\nLetter_rule.prototype.feed = function(char){\n if(this.done){\n return this.origin.feed(DONE)\n }else if(/\\p{L}/u.exec(char)){\n this.done = true\n this.value = char\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction NameChar_rule(origin){\n this.origin = origin\n this.rank = origin.expect\n this.value = ''\n var result_store = this.origin.result_store\n result_store[this.rank] = result_store[this.rank] ?? []\n this.pos = get_pos(origin)\n}\n\nNameChar_rule.prototype.reset = function(){\n delete this.done\n}\n\nNameChar_rule.prototype.feed = function(char){\n if(this.done){\n return this.origin.feed(DONE)\n }else if(is_id_continue(char)){\n this.value += char\n return this\n }else{\n if(this.value == ''){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n}\n\nfunction PIText_rule(origin){\n this.origin = origin\n this.value = ''\n this.pos = get_pos(origin)\n}\n\nPIText_rule.prototype.reset = function(){}\n\nPIText_rule.prototype.feed = function(char){\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('?>')){\n reset_pos(this, get_pos(this) - 1)\n this.value = this.value.substr(0, this.value.length - 2)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CommentText_rule(origin){\n this.origin = origin\n this.value = ''\n this.pos = get_pos(origin)\n}\n\nCommentText_rule.prototype.reset = function(){}\n\nCommentText_rule.prototype.feed = function(char){\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('-->')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n if(this.value.endsWith('-')){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CharData_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nCharData_rule.prototype.reset = function(){}\n\nCharData_rule.prototype.feed = function(char){\n // [^<&]* - ([^<&]* ']]>' [^<&]*)\n if(char === END){\n return this.origin.feed(FAIL)\n }\n if('<&'.includes(char)){\n return this.origin.feed(DONE)\n }\n this.value += char\n if(this.value.endsWith(']]>')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CData_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nCData_rule.prototype.reset = function(){}\n\nCData_rule.prototype.feed = function(char){\n // (Char* - (Char* ']]>' Char*))\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith(']]>')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction Ignore_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nIgnore_rule.prototype.reset = function(){}\n\nIgnore_rule.prototype.feed = function(char){\n // Char* - (Char* ('') Char*)\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction PITarget_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'tmp_21']\n this.rules = []\n this.repeats = []\n}\n\nPITarget_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case 1: // tmp_21\n if(! this.rules[1]){\n this.rules[1] = new tmp_21_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n var value = get_value(this)\n if(value.toLowerCase() == 'xml'){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPITarget_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nvar rules = {\ndocument: `[prolog, element, Misc*, ]`,\nChar: `['\\\\t', '\\\\n', '\\\\r', [#x20-#xD7FF], [#xE000-#xFFFD], [#x10000-#x10FFFF]]`,\nS: `[tmp_1+]`,\ntmp_1: `[' ', '\\\\t', '\\\\r', '\\\\n']`,\nName: `[tmp_2, NameChar*]`,\ntmp_2: `[Letter, '_', ':']`,\nNames: `[Name, tmp_3*]`,\ntmp_3: `[' ', Name]`,\nNmtoken: `[NameChar+]`,\nNmtokens: `[Nmtoken, tmp_4*]`,\ntmp_4: `[' ', Nmtoken]`,\nEntityValue: `[tmp_7, tmp_8]`,\ntmp_5: `[[^%&'], PEReference, Reference]`,\ntmp_6: `[[^%&\"], PEReference, Reference]`,\ntmp_7: `['\"', tmp_6*, '\"']`,\ntmp_8: `[\"'\", tmp_5*, \"'\"]`,\nAttValue: `[tmp_11, tmp_12]`,\ntmp_9: `[[^<&'], Reference]`,\ntmp_10: `[[^<&\"], Reference]`,\ntmp_11: `['\"', tmp_10*, '\"']`,\ntmp_12: `[\"'\", tmp_9*, \"'\"]`,\nSystemLiteral: `[tmp_14, tmp_13]`,\ntmp_13: `[\"'\", [^'], \"'\"]`,\ntmp_14: `['\"', [^\"], '\"']`,\nPubidLiteral: `[tmp_15, tmp_16]`,\ntmp_15: `['\"', PubidChar*, '\"']`,\ntmp_16: `[\"'\", PubidCharNoQuote*, \"'\"]`,\nPubidChar: `[' ', '\\\\r', '\\\\n', [a-zA-Z0-9], [-'()+,./:=?;!*#@$_%]]`,\nPubidCharNoQuote: `[' ', '\\\\r', '\\\\n', [a-zA-Z0-9], [-()+,./:=?;!*#@$_%]]`,\nComment: `['']`,\nPI: `['']`,\ntmp_17: `[S, PIText]`,\nCDSect: `[CDStart, CData, CDEnd]`,\nCDStart: `['']`,\nprolog: `[XMLDecl?, Misc*, tmp_18?]`,\ntmp_18: `[doctypedecl, Misc*]`,\nXMLDecl: `['']`,\nVersionInfo: `[S, 'version', Eq, tmp_19]`,\ntmp_19: `[tmp_20, tmp_21]`,\ntmp_20: `[\"'\", VersionNum, \"'\"]`,\ntmp_21: `['\"', VersionNum, '\"']`,\nEq: `[S?, '=', S?]`,\nVersionNum: `['1.0']`,\nMisc: `[Comment, PI, S]`,\ndoctypedecl: `['']`,\ntmp_22: `['[', start_intSubset, intSubset, ']', S?]`,\ntmp_23: `[S, ExternalID]`,\nDeclSep: `[PEReference, S]`,\nintSubset: `[tmp_24*]`,\ntmp_24: `[markupdecl, DeclSep]`,\nmarkupdecl: `[elementdecl, AttlistDecl, EntityDecl, NotationDecl, PI, Comment]`,\nextSubset: `[TextDecl?, extSubsetDecl]`,\nextSubsetDecl: `[tmp_25*]`,\ntmp_25: `[markupdecl, conditionalSect, DeclSep]`,\nSDDecl: `[S, 'standalone', Eq, tmp_30]`,\ntmp_26: `['yes', 'no']`,\ntmp_27: `['yes', 'no']`,\ntmp_28: `['\"', tmp_26, '\"']`,\ntmp_29: `[\"'\", tmp_27, \"'\"]`,\ntmp_30: `[tmp_29, tmp_28]`,\nelement: `[EmptyElemTag, tmp_31]`,\ntmp_31: `[STag, content, ETag]`,\nSTag: `['<', Name, tmp_32*, S?, '>']`,\ntmp_32: `[S, Attribute]`,\nAttribute: `[Name, Eq, AttValue]`,\nETag: `['']`,\ncontent: `[CharData?, tmp_34*]`,\ntmp_33: `[element, Reference, CDSect, PI, Comment]`,\ntmp_34: `[tmp_33, CharData?]`,\nEmptyElemTag: `['<', Name, tmp_35*, S?, '/>']`,\ntmp_35: `[S, Attribute]`,\nelementdecl: `['']`,\ncontentspec: `['EMPTY', 'ANY', Mixed, children]`,\nchildren: `[tmp_37, tmp_36?]`,\ntmp_36: `['?', '*', '+']`,\ntmp_37: `[choice, seq]`,\ncp: `[tmp_39, tmp_38?]`,\ntmp_38: `['?', '*', '+']`,\ntmp_39: `[Name, choice, seq]`,\nchoice: `['(', S?, cp, tmp_40+, S?, ')']`,\ntmp_40: `[S?, '|', S?, cp]`,\nseq: `['(', S?, cp, tmp_41*, S?, ')']`,\ntmp_41: `[S?, ',', S?, cp]`,\nMixed: `[tmp_43, tmp_44]`,\ntmp_42: `[S?, '|', S?, Name]`,\ntmp_43: `['(', S?, '#PCDATA', tmp_42*, S?, ')*']`,\ntmp_44: `['(', S?, '#PCDATA', S?, ')']`,\nAttlistDecl: `['']`,\nAttDef: `[S, Name, S, AttType, S, DefaultDecl]`,\nAttType: `[StringType, TokenizedType, EnumeratedType]`,\nStringType: `['CDATA']`,\nTokenizedType: `['ID', 'IDREF', 'IDREFS', 'ENTITY', 'ENTITIES', 'NMTOKEN', 'NMTOKENS']`,\nEnumeratedType: `[NotationType, Enumeration]`,\nNotationType: `['NOTATION', S, '(', S?, Name, tmp_45*, S?, ')']`,\ntmp_45: `[S?, '|', S?, Name]`,\nEnumeration: `['(', S?, Nmtoken, tmp_46*, S?, ')']`,\ntmp_46: `[S?, '|', S?, Nmtoken]`,\nDefaultDecl: `['#REQUIRED', '#IMPLIED', tmp_48]`,\ntmp_47: `['#FIXED', S]`,\ntmp_48: `[tmp_47?, AttValue]`,\nconditionalSect: `[includeSect, ignoreSect]`,\nincludeSect: `['']`,\nignoreSect: `['']`,\nignoreSectContents: `[Ignore, tmp_49*]`,\ntmp_49: `['', Ignore]`,\nCharRef: `[tmp_50, tmp_51]`,\ntmp_50: `['&#', [0-9], ';']`,\ntmp_51: `['&#x', [0-9a-fA-F], ';']`,\nReference: `[EntityRef, CharRef]`,\nEntityRef: `['&', Name, ';']`,\nPEReference: `['%', Name, ';']`,\nEntityDecl: `[GEDecl, PEDecl]`,\nGEDecl: `['']`,\nPEDecl: `['']`,\nEntityDef: `[EntityValue, tmp_52]`,\ntmp_52: `[ExternalID, NDataDecl?]`,\nPEDef: `[EntityValue, ExternalID]`,\nExternalID: `[tmp_53, tmp_54]`,\ntmp_53: `['SYSTEM', S, SystemLiteral]`,\ntmp_54: `['PUBLIC', S, PubidLiteral, S, SystemLiteral]`,\nNDataDecl: `[S, 'NDATA', S, Name]`,\nTextDecl: `['']`,\nextParsedEnt: `[TextDecl?, content]`,\nEncodingDecl: `[S, 'encoding', Eq, tmp_55]`,\ntmp_55: `[tmp_56, tmp_57]`,\ntmp_56: `['\"', EncName, '\"']`,\ntmp_57: `[\"'\", EncName, \"'\"]`,\nEncName: `[[A-Za-z], tmp_58*]`,\ntmp_58: `[[A-Za-z0-9._], '-']`,\nNotationDecl: `['']`,\ntmp_59: `[ExternalID, PublicID]`,\nPublicID: `['PUBLIC', S, PubidLiteral]`,\n}\nfunction document_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // prolog\n this.items = ['prolog', 'element', 'Misc*', \"\"]\n this.rules = []\n this.repeats = []\n}\n\ndocument_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // prolog\n if(! this.rules[0]){\n this.rules[0] = new prolog_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // element\n if(! this.rules[1]){\n this.rules[1] = new element_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // Misc*\n if(! this.rules[2]){\n this.rules[2] = new Misc_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 2, 3, rule, char)\n case -1:\n case 3:\n if(char == END){\n return DONE\n }\n return FAIL\n }\n return this\n}\n\ndocument_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Char_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\\t'\n this.items = [\"'\\\\t'\", \"'\\\\n'\", \"'\\\\r'\", '[#x20-#xD7FF]', '[#xE000-#xFFFD]', '[#x10000-#x10FFFF]']\n this.rules = []\n this.repeats = []\n}\n\nChar_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\\t'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(9))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '\\n'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, String.fromCharCode(10))\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '\\r'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, String.fromCharCode(13))\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // [#x20-#xD7FF]\n if(! this.rules[3]){\n this.rules[3] = new CHARSET_rule(this, '#x20-#xD7FF')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // [#xE000-#xFFFD]\n if(! this.rules[4]){\n this.rules[4] = new CHARSET_rule(this, '#xE000-#xFFFD')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 5, rule, char)\n case 5: // [#x10000-#x10FFFF]\n if(! this.rules[5]){\n this.rules[5] = new CHARSET_rule(this, '#x10000-#x10FFFF')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nChar_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction S_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_1+\n this.items = ['tmp_1+']\n this.rules = []\n this.repeats = []\n}\n\nS_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_1+\n if(! this.rules[0]){\n this.rules[0] = new tmp_1_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 0,-1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nS_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_1_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", \"'\\\\t'\", \"'\\\\r'\", \"'\\\\n'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_1_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '\\t'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, String.fromCharCode(9))\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '\\r'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, String.fromCharCode(13))\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // '\\n'\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, String.fromCharCode(10))\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_1_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Name_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_2\n this.items = ['tmp_2', 'NameChar*']\n this.rules = []\n this.repeats = []\n}\n\nName_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_2\n if(! this.rules[0]){\n this.rules[0] = new tmp_2_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // NameChar*\n if(! this.rules[1]){\n this.rules[1] = new NameChar_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nName_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_2_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Letter\n this.items = ['Letter', \"'_'\", \"':'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_2_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Letter\n if(! this.rules[0]){\n this.rules[0] = new Letter_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '_'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '_')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // ':'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ':')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_2_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Names_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'tmp_3*']\n this.rules = []\n this.repeats = []\n}\n\nNames_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_3*\n if(! this.rules[1]){\n this.rules[1] = new tmp_3_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNames_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_3_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", 'Name']\n this.rules = []\n this.repeats = []\n}\n\ntmp_3_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_3_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Nmtoken_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // NameChar+\n this.items = ['NameChar+']\n this.rules = []\n this.repeats = []\n}\n\nNmtoken_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // NameChar+\n if(! this.rules[0]){\n this.rules[0] = new NameChar_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 0,-1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNmtoken_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Nmtokens_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Nmtoken\n this.items = ['Nmtoken', 'tmp_4*']\n this.rules = []\n this.repeats = []\n}\n\nNmtokens_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Nmtoken\n if(! this.rules[0]){\n this.rules[0] = new Nmtoken_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_4*\n if(! this.rules[1]){\n this.rules[1] = new tmp_4_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNmtokens_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_4_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", 'Nmtoken']\n this.rules = []\n this.repeats = []\n}\n\ntmp_4_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Nmtoken\n if(! this.rules[1]){\n this.rules[1] = new Nmtoken_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_4_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EntityValue_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_7\n this.items = ['tmp_7', 'tmp_8']\n this.rules = []\n this.repeats = []\n}\n\nEntityValue_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_7\n if(! this.rules[0]){\n this.rules[0] = new tmp_7_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_8\n if(! this.rules[1]){\n this.rules[1] = new tmp_8_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEntityValue_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_5_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [^%&']\n this.items = [\"[^%&']\", 'PEReference', 'Reference']\n this.rules = []\n this.repeats = []\n}\n\ntmp_5_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [^%&']\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, '^%&\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PEReference\n if(! this.rules[1]){\n this.rules[1] = new PEReference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // Reference\n if(! this.rules[2]){\n this.rules[2] = new Reference_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_5_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_6_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [^%&\"]\n this.items = ['[^%&\"]', 'PEReference', 'Reference']\n this.rules = []\n this.repeats = []\n}\n\ntmp_6_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [^%&\"]\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, '^%&\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PEReference\n if(! this.rules[1]){\n this.rules[1] = new PEReference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // Reference\n if(! this.rules[2]){\n this.rules[2] = new Reference_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_6_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_7_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'tmp_6*', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_7_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_6*\n if(! this.rules[1]){\n this.rules[1] = new tmp_6_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_7_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_8_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'tmp_5*', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_8_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_5*\n if(! this.rules[1]){\n this.rules[1] = new tmp_5_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_8_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction AttValue_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_11\n this.items = ['tmp_11', 'tmp_12']\n this.rules = []\n this.repeats = []\n}\n\nAttValue_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_11\n if(! this.rules[0]){\n this.rules[0] = new tmp_11_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_12\n if(! this.rules[1]){\n this.rules[1] = new tmp_12_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttValue_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_9_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [^<&']\n this.items = [\"[^<&']\", 'Reference']\n this.rules = []\n this.repeats = []\n}\n\ntmp_9_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [^<&']\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, '^<&\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // Reference\n if(! this.rules[1]){\n this.rules[1] = new Reference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_9_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_10_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [^<&\"]\n this.items = ['[^<&\"]', 'Reference']\n this.rules = []\n this.repeats = []\n}\n\ntmp_10_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [^<&\"]\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, '^<&\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // Reference\n if(! this.rules[1]){\n this.rules[1] = new Reference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_10_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_11_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'tmp_10*', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_11_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_10*\n if(! this.rules[1]){\n this.rules[1] = new tmp_10_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_11_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_12_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'tmp_9*', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_12_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_9*\n if(! this.rules[1]){\n this.rules[1] = new tmp_9_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_12_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction SystemLiteral_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_14\n this.items = ['tmp_14', 'tmp_13']\n this.rules = []\n this.repeats = []\n}\n\nSystemLiteral_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_14\n if(! this.rules[0]){\n this.rules[0] = new tmp_14_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_13\n if(! this.rules[1]){\n this.rules[1] = new tmp_13_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nSystemLiteral_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_13_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', \"[^']\", '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_13_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // [^']\n if(! this.rules[1]){\n this.rules[1] = new CHARSET_rule(this, '^\\'')\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_13_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_14_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', '[^\"]', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_14_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // [^\"]\n if(! this.rules[1]){\n this.rules[1] = new CHARSET_rule(this, '^\"')\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_14_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PubidLiteral_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_15\n this.items = ['tmp_15', 'tmp_16']\n this.rules = []\n this.repeats = []\n}\n\nPubidLiteral_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_15\n if(! this.rules[0]){\n this.rules[0] = new tmp_15_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_16\n if(! this.rules[1]){\n this.rules[1] = new tmp_16_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPubidLiteral_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_15_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'PubidChar*', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_15_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // PubidChar*\n if(! this.rules[1]){\n this.rules[1] = new PubidChar_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_15_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_16_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'PubidCharNoQuote*', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_16_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // PubidCharNoQuote*\n if(! this.rules[1]){\n this.rules[1] = new PubidCharNoQuote_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_16_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PubidChar_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", \"'\\\\r'\", \"'\\\\n'\", '[a-zA-Z0-9]', \"[-'()+,./:=?;!*#@$_%]\"]\n this.rules = []\n this.repeats = []\n}\n\nPubidChar_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '\\r'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, String.fromCharCode(13))\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '\\n'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, String.fromCharCode(10))\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // [a-zA-Z0-9]\n if(! this.rules[3]){\n this.rules[3] = new CHARSET_rule(this, 'a-zA-Z0-9')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // [-'()+,./:=?;!*#@$_%]\n if(! this.rules[4]){\n this.rules[4] = new CHARSET_rule(this, '-\\'()+,./:=?;!*#@$_%')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPubidChar_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PubidCharNoQuote_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", \"'\\\\r'\", \"'\\\\n'\", '[a-zA-Z0-9]', '[-()+,./:=?;!*#@$_%]']\n this.rules = []\n this.repeats = []\n}\n\nPubidCharNoQuote_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '\\r'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, String.fromCharCode(13))\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '\\n'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, String.fromCharCode(10))\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // [a-zA-Z0-9]\n if(! this.rules[3]){\n this.rules[3] = new CHARSET_rule(this, 'a-zA-Z0-9')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // [-()+,./:=?;!*#@$_%]\n if(! this.rules[4]){\n this.rules[4] = new CHARSET_rule(this, '-()+,./:=?;!*#@$_%')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPubidCharNoQuote_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Comment_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nComment_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '-->')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nComment_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PI_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nPI_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, '?>')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPI_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_17_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'PIText']\n this.rules = []\n this.repeats = []\n}\n\ntmp_17_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // PIText\n if(! this.rules[1]){\n this.rules[1] = new PIText_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_17_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction CDSect_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // CDStart\n this.items = ['CDStart', 'CData', 'CDEnd']\n this.rules = []\n this.repeats = []\n}\n\nCDSect_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // CDStart\n if(! this.rules[0]){\n this.rules[0] = new CDStart_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // CData\n if(! this.rules[1]){\n this.rules[1] = new CData_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // CDEnd\n if(! this.rules[2]){\n this.rules[2] = new CDEnd_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nCDSect_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction CDStart_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\n this.items = [\"']]>'\"]\n this.rules = []\n this.repeats = []\n}\n\nCDEnd_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ']]>'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, ']]>')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nCDEnd_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction prolog_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // XMLDecl?\n this.items = ['XMLDecl?', 'Misc*', 'tmp_18?']\n this.rules = []\n this.repeats = []\n}\n\nprolog_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // XMLDecl?\n if(! this.rules[0]){\n this.rules[0] = new XMLDecl_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // Misc*\n if(! this.rules[1]){\n this.rules[1] = new Misc_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // tmp_18?\n if(! this.rules[2]){\n this.rules[2] = new tmp_18_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nprolog_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_18_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // doctypedecl\n this.items = ['doctypedecl', 'Misc*']\n this.rules = []\n this.repeats = []\n}\n\ntmp_18_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // doctypedecl\n if(! this.rules[0]){\n this.rules[0] = new doctypedecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Misc*\n if(! this.rules[1]){\n this.rules[1] = new Misc_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_18_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction XMLDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nXMLDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, '?>')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nXMLDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction VersionInfo_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', \"'version'\", 'Eq', 'tmp_19']\n this.rules = []\n this.repeats = []\n}\n\nVersionInfo_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // 'version'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'version')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // Eq\n if(! this.rules[2]){\n this.rules[2] = new Eq_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_19\n if(! this.rules[3]){\n this.rules[3] = new tmp_19_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nVersionInfo_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_19_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_20\n this.items = ['tmp_20', 'tmp_21']\n this.rules = []\n this.repeats = []\n}\n\ntmp_19_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_20\n if(! this.rules[0]){\n this.rules[0] = new tmp_20_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_21\n if(! this.rules[1]){\n this.rules[1] = new tmp_21_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_19_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_20_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'VersionNum', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_20_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // VersionNum\n if(! this.rules[1]){\n this.rules[1] = new VersionNum_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_20_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_21_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'VersionNum', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_21_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // VersionNum\n if(! this.rules[1]){\n this.rules[1] = new VersionNum_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_21_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Eq_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'='\", 'S?']\n this.rules = []\n this.repeats = []\n}\n\nEq_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '='\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '=')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEq_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction VersionNum_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '1.0'\n this.items = [\"'1.0'\"]\n this.rules = []\n this.repeats = []\n}\n\nVersionNum_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '1.0'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '1.0')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nVersionNum_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Misc_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Comment\n this.items = ['Comment', 'PI', 'S']\n this.rules = []\n this.repeats = []\n}\n\nMisc_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Comment\n if(! this.rules[0]){\n this.rules[0] = new Comment_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PI\n if(! this.rules[1]){\n this.rules[1] = new PI_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // S\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nMisc_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction doctypedecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\ndoctypedecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, '>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ndoctypedecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_22_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '['\n this.items = [\"'['\", 'start_intSubset', 'intSubset', \"']'\", 'S?']\n this.rules = []\n this.repeats = []\n}\n\ntmp_22_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '['\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '[')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // start_intSubset\n if(! this.rules[1]){\n this.rules[1] = new start_intSubset_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // intSubset\n if(! this.rules[2]){\n this.rules[2] = new intSubset_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // ']'\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, ']')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_22_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_23_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'ExternalID']\n this.rules = []\n this.repeats = []\n}\n\ntmp_23_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // ExternalID\n if(! this.rules[1]){\n this.rules[1] = new ExternalID_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_23_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction DeclSep_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // PEReference\n this.items = ['PEReference', 'S']\n this.rules = []\n this.repeats = []\n}\n\nDeclSep_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // PEReference\n if(! this.rules[0]){\n this.rules[0] = new PEReference_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nDeclSep_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction intSubset_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_24*\n this.items = ['tmp_24*']\n this.rules = []\n this.repeats = []\n}\n\nintSubset_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_24*\n if(! this.rules[0]){\n this.rules[0] = new tmp_24_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 0, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nintSubset_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_24_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // markupdecl\n this.items = ['markupdecl', 'DeclSep']\n this.rules = []\n this.repeats = []\n}\n\ntmp_24_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // markupdecl\n if(! this.rules[0]){\n this.rules[0] = new markupdecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // DeclSep\n if(! this.rules[1]){\n this.rules[1] = new DeclSep_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_24_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction markupdecl_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // elementdecl\n this.items = ['elementdecl', 'AttlistDecl', 'EntityDecl', 'NotationDecl', 'PI', 'Comment']\n this.rules = []\n this.repeats = []\n}\n\nmarkupdecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // elementdecl\n if(! this.rules[0]){\n this.rules[0] = new elementdecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // AttlistDecl\n if(! this.rules[1]){\n this.rules[1] = new AttlistDecl_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // EntityDecl\n if(! this.rules[2]){\n this.rules[2] = new EntityDecl_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // NotationDecl\n if(! this.rules[3]){\n this.rules[3] = new NotationDecl_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // PI\n if(! this.rules[4]){\n this.rules[4] = new PI_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 5, rule, char)\n case 5: // Comment\n if(! this.rules[5]){\n this.rules[5] = new Comment_rule(this)\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nmarkupdecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction extSubset_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // TextDecl?\n this.items = ['TextDecl?', 'extSubsetDecl']\n this.rules = []\n this.repeats = []\n}\n\nextSubset_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // TextDecl?\n if(! this.rules[0]){\n this.rules[0] = new TextDecl_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // extSubsetDecl\n if(! this.rules[1]){\n this.rules[1] = new extSubsetDecl_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nextSubset_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction extSubsetDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_25*\n this.items = ['tmp_25*']\n this.rules = []\n this.repeats = []\n}\n\nextSubsetDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_25*\n if(! this.rules[0]){\n this.rules[0] = new tmp_25_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 0, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nextSubsetDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_25_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // markupdecl\n this.items = ['markupdecl', 'conditionalSect', 'DeclSep']\n this.rules = []\n this.repeats = []\n}\n\ntmp_25_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // markupdecl\n if(! this.rules[0]){\n this.rules[0] = new markupdecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // conditionalSect\n if(! this.rules[1]){\n this.rules[1] = new conditionalSect_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // DeclSep\n if(! this.rules[2]){\n this.rules[2] = new DeclSep_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_25_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction SDDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', \"'standalone'\", 'Eq', 'tmp_30']\n this.rules = []\n this.repeats = []\n}\n\nSDDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // 'standalone'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'standalone')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // Eq\n if(! this.rules[2]){\n this.rules[2] = new Eq_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_30\n if(! this.rules[3]){\n this.rules[3] = new tmp_30_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nSDDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_26_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'yes'\n this.items = [\"'yes'\", \"'no'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_26_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'yes'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'yes')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // 'no'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'no')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_26_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_27_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'yes'\n this.items = [\"'yes'\", \"'no'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_27_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'yes'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'yes')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // 'no'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'no')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_27_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_28_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'tmp_26', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_28_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_26\n if(! this.rules[1]){\n this.rules[1] = new tmp_26_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_28_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_29_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'tmp_27', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_29_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_27\n if(! this.rules[1]){\n this.rules[1] = new tmp_27_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_29_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_30_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_29\n this.items = ['tmp_29', 'tmp_28']\n this.rules = []\n this.repeats = []\n}\n\ntmp_30_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_29\n if(! this.rules[0]){\n this.rules[0] = new tmp_29_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_28\n if(! this.rules[1]){\n this.rules[1] = new tmp_28_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_30_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction element_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // EmptyElemTag\n this.items = ['EmptyElemTag', 'tmp_31']\n this.rules = []\n this.repeats = []\n}\n\nelement_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // EmptyElemTag\n if(! this.rules[0]){\n this.rules[0] = new EmptyElemTag_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_31\n if(! this.rules[1]){\n this.rules[1] = new tmp_31_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nelement_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_31_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // STag\n this.items = ['STag', 'content', 'ETag']\n this.rules = []\n this.repeats = []\n}\n\ntmp_31_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // STag\n if(! this.rules[0]){\n this.rules[0] = new STag_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // content\n if(! this.rules[1]){\n this.rules[1] = new content_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // ETag\n if(! this.rules[2]){\n this.rules[2] = new ETag_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_31_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction STag_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '<'\n this.items = [\"'<'\", 'Name', 'tmp_32*', 'S?', \"'>'\"]\n this.rules = []\n this.repeats = []\n}\n\nSTag_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '<'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '<')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // tmp_32*\n if(! this.rules[2]){\n this.rules[2] = new tmp_32_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 2, 3, rule, char)\n case 3: // S?\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 3, 4, rule, char)\n case 4: // '>'\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, '>')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nSTag_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_32_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'Attribute']\n this.rules = []\n this.repeats = []\n}\n\ntmp_32_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Attribute\n if(! this.rules[1]){\n this.rules[1] = new Attribute_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_32_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Attribute_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'Eq', 'AttValue']\n this.rules = []\n this.repeats = []\n}\n\nAttribute_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Eq\n if(! this.rules[1]){\n this.rules[1] = new Eq_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // AttValue\n if(! this.rules[2]){\n this.rules[2] = new AttValue_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttribute_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction ETag_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nETag_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, '>')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nETag_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction content_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // CharData?\n this.items = ['CharData?', 'tmp_34*']\n this.rules = []\n this.repeats = []\n}\n\ncontent_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // CharData?\n if(! this.rules[0]){\n this.rules[0] = new CharData_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // tmp_34*\n if(! this.rules[1]){\n this.rules[1] = new tmp_34_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ncontent_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_33_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // element\n this.items = ['element', 'Reference', 'CDSect', 'PI', 'Comment']\n this.rules = []\n this.repeats = []\n}\n\ntmp_33_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // element\n if(! this.rules[0]){\n this.rules[0] = new element_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // Reference\n if(! this.rules[1]){\n this.rules[1] = new Reference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // CDSect\n if(! this.rules[2]){\n this.rules[2] = new CDSect_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // PI\n if(! this.rules[3]){\n this.rules[3] = new PI_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // Comment\n if(! this.rules[4]){\n this.rules[4] = new Comment_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_33_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_34_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_33\n this.items = ['tmp_33', 'CharData?']\n this.rules = []\n this.repeats = []\n}\n\ntmp_34_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_33\n if(! this.rules[0]){\n this.rules[0] = new tmp_33_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // CharData?\n if(! this.rules[1]){\n this.rules[1] = new CharData_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_34_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EmptyElemTag_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '<'\n this.items = [\"'<'\", 'Name', 'tmp_35*', 'S?', \"'/>'\"]\n this.rules = []\n this.repeats = []\n}\n\nEmptyElemTag_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '<'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '<')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // tmp_35*\n if(! this.rules[2]){\n this.rules[2] = new tmp_35_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 2, 3, rule, char)\n case 3: // S?\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 3, 4, rule, char)\n case 4: // '/>'\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, '/>')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEmptyElemTag_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_35_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'Attribute']\n this.rules = []\n this.repeats = []\n}\n\ntmp_35_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Attribute\n if(! this.rules[1]){\n this.rules[1] = new Attribute_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_35_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction elementdecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nelementdecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, '>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nelementdecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction contentspec_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'EMPTY'\n this.items = [\"'EMPTY'\", \"'ANY'\", 'Mixed', 'children']\n this.rules = []\n this.repeats = []\n}\n\ncontentspec_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'EMPTY'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'EMPTY')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // 'ANY'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'ANY')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // Mixed\n if(! this.rules[2]){\n this.rules[2] = new Mixed_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // children\n if(! this.rules[3]){\n this.rules[3] = new children_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ncontentspec_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction children_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_37\n this.items = ['tmp_37', 'tmp_36?']\n this.rules = []\n this.repeats = []\n}\n\nchildren_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_37\n if(! this.rules[0]){\n this.rules[0] = new tmp_37_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_36?\n if(! this.rules[1]){\n this.rules[1] = new tmp_36_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nchildren_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_36_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '?'\n this.items = [\"'?'\", \"'*'\", \"'+'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_36_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '?'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '?')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '*'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '*')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '+'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '+')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_36_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_37_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // choice\n this.items = ['choice', 'seq']\n this.rules = []\n this.repeats = []\n}\n\ntmp_37_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // choice\n if(! this.rules[0]){\n this.rules[0] = new choice_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // seq\n if(! this.rules[1]){\n this.rules[1] = new seq_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_37_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction cp_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_39\n this.items = ['tmp_39', 'tmp_38?']\n this.rules = []\n this.repeats = []\n}\n\ncp_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_39\n if(! this.rules[0]){\n this.rules[0] = new tmp_39_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_38?\n if(! this.rules[1]){\n this.rules[1] = new tmp_38_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ncp_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_38_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '?'\n this.items = [\"'?'\", \"'*'\", \"'+'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_38_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '?'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '?')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '*'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '*')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '+'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '+')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_38_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_39_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'choice', 'seq']\n this.rules = []\n this.repeats = []\n}\n\ntmp_39_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // choice\n if(! this.rules[1]){\n this.rules[1] = new choice_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // seq\n if(! this.rules[2]){\n this.rules[2] = new seq_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_39_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction choice_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', 'cp', 'tmp_40+', 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\nchoice_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // cp\n if(! this.rules[2]){\n this.rules[2] = new cp_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_40+\n if(! this.rules[3]){\n this.rules[3] = new tmp_40_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 3,4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, 5, rule, char)\n case 5: // ')'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, ')')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nchoice_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_40_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'|'\", 'S?', 'cp']\n this.rules = []\n this.repeats = []\n}\n\ntmp_40_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '|'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '|')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // cp\n if(! this.rules[3]){\n this.rules[3] = new cp_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_40_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction seq_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', 'cp', 'tmp_41*', 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\nseq_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // cp\n if(! this.rules[2]){\n this.rules[2] = new cp_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_41*\n if(! this.rules[3]){\n this.rules[3] = new tmp_41_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 3, 4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, 5, rule, char)\n case 5: // ')'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, ')')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nseq_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_41_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"','\", 'S?', 'cp']\n this.rules = []\n this.repeats = []\n}\n\ntmp_41_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // ','\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, ',')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // cp\n if(! this.rules[3]){\n this.rules[3] = new cp_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_41_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Mixed_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_43\n this.items = ['tmp_43', 'tmp_44']\n this.rules = []\n this.repeats = []\n}\n\nMixed_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_43\n if(! this.rules[0]){\n this.rules[0] = new tmp_43_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_44\n if(! this.rules[1]){\n this.rules[1] = new tmp_44_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nMixed_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_42_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'|'\", 'S?', 'Name']\n this.rules = []\n this.repeats = []\n}\n\ntmp_42_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '|'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '|')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // Name\n if(! this.rules[3]){\n this.rules[3] = new Name_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_42_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_43_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', \"'#PCDATA'\", 'tmp_42*', 'S?', \"')*'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_43_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // '#PCDATA'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '#PCDATA')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_42*\n if(! this.rules[3]){\n this.rules[3] = new tmp_42_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 3, 4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, 5, rule, char)\n case 5: // ')*'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, ')*')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_43_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_44_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', \"'#PCDATA'\", 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_44_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // '#PCDATA'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '#PCDATA')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // S?\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 3, 4, rule, char)\n case 4: // ')'\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, ')')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_44_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction AttlistDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nAttlistDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, '>')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttlistDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction AttDef_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'Name', 'S', 'AttType', 'S', 'DefaultDecl']\n this.rules = []\n this.repeats = []\n}\n\nAttDef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // AttType\n if(! this.rules[3]){\n this.rules[3] = new AttType_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 4, rule, char)\n case 4: // S\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 5, rule, char)\n case 5: // DefaultDecl\n if(! this.rules[5]){\n this.rules[5] = new DefaultDecl_rule(this)\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttDef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction AttType_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // StringType\n this.items = ['StringType', 'TokenizedType', 'EnumeratedType']\n this.rules = []\n this.repeats = []\n}\n\nAttType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // StringType\n if(! this.rules[0]){\n this.rules[0] = new StringType_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // TokenizedType\n if(! this.rules[1]){\n this.rules[1] = new TokenizedType_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // EnumeratedType\n if(! this.rules[2]){\n this.rules[2] = new EnumeratedType_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction StringType_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'CDATA'\n this.items = [\"'CDATA'\"]\n this.rules = []\n this.repeats = []\n}\n\nStringType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'CDATA'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'CDATA')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nStringType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction TokenizedType_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'ID'\n this.items = [\"'ID'\", \"'IDREF'\", \"'IDREFS'\", \"'ENTITY'\", \"'ENTITIES'\", \"'NMTOKEN'\", \"'NMTOKENS'\"]\n this.rules = []\n this.repeats = []\n}\n\nTokenizedType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'ID'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'ID')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // 'IDREF'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'IDREF')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // 'IDREFS'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, 'IDREFS')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // 'ENTITY'\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, 'ENTITY')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // 'ENTITIES'\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, 'ENTITIES')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 5, rule, char)\n case 5: // 'NMTOKEN'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, 'NMTOKEN')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 6, rule, char)\n case 6: // 'NMTOKENS'\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, 'NMTOKENS')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nTokenizedType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EnumeratedType_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // NotationType\n this.items = ['NotationType', 'Enumeration']\n this.rules = []\n this.repeats = []\n}\n\nEnumeratedType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // NotationType\n if(! this.rules[0]){\n this.rules[0] = new NotationType_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // Enumeration\n if(! this.rules[1]){\n this.rules[1] = new Enumeration_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEnumeratedType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction NotationType_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'NOTATION'\n this.items = [\"'NOTATION'\", 'S', \"'('\", 'S?', 'Name', 'tmp_45*', 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\nNotationType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'NOTATION'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'NOTATION')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // '('\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '(')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // S?\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 3, 4, rule, char)\n case 4: // Name\n if(! this.rules[4]){\n this.rules[4] = new Name_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 5, rule, char)\n case 5: // tmp_45*\n if(! this.rules[5]){\n this.rules[5] = new tmp_45_rule(this)\n this.repeats[5] = 0\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 5, 6, rule, char)\n case 6: // S?\n if(! this.rules[6]){\n this.rules[6] = new S_rule(this)\n this.repeats[6] = 0\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 6, 7, rule, char)\n case 7: // ')'\n if(! this.rules[7]){\n this.rules[7] = new LITERAL(this, ')')\n }\n rule = this.rules[7]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNotationType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_45_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'|'\", 'S?', 'Name']\n this.rules = []\n this.repeats = []\n}\n\ntmp_45_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '|'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '|')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // Name\n if(! this.rules[3]){\n this.rules[3] = new Name_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_45_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Enumeration_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', 'Nmtoken', 'tmp_46*', 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\nEnumeration_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // Nmtoken\n if(! this.rules[2]){\n this.rules[2] = new Nmtoken_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_46*\n if(! this.rules[3]){\n this.rules[3] = new tmp_46_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 3, 4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, 5, rule, char)\n case 5: // ')'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, ')')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEnumeration_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_46_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'|'\", 'S?', 'Nmtoken']\n this.rules = []\n this.repeats = []\n}\n\ntmp_46_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '|'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '|')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // Nmtoken\n if(! this.rules[3]){\n this.rules[3] = new Nmtoken_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_46_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction DefaultDecl_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '#REQUIRED'\n this.items = [\"'#REQUIRED'\", \"'#IMPLIED'\", 'tmp_48']\n this.rules = []\n this.repeats = []\n}\n\nDefaultDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '#REQUIRED'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '#REQUIRED')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '#IMPLIED'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '#IMPLIED')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // tmp_48\n if(! this.rules[2]){\n this.rules[2] = new tmp_48_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nDefaultDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_47_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '#FIXED'\n this.items = [\"'#FIXED'\", 'S']\n this.rules = []\n this.repeats = []\n}\n\ntmp_47_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '#FIXED'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '#FIXED')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_47_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_48_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_47?\n this.items = ['tmp_47?', 'AttValue']\n this.rules = []\n this.repeats = []\n}\n\ntmp_48_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_47?\n if(! this.rules[0]){\n this.rules[0] = new tmp_47_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // AttValue\n if(! this.rules[1]){\n this.rules[1] = new AttValue_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_48_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction conditionalSect_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // includeSect\n this.items = ['includeSect', 'ignoreSect']\n this.rules = []\n this.repeats = []\n}\n\nconditionalSect_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // includeSect\n if(! this.rules[0]){\n this.rules[0] = new includeSect_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // ignoreSect\n if(! this.rules[1]){\n this.rules[1] = new ignoreSect_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nconditionalSect_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction includeSect_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nincludeSect_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, ']]>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nincludeSect_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction ignoreSect_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nignoreSect_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, ']]>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nignoreSect_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction ignoreSectContents_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Ignore\n this.items = ['Ignore', 'tmp_49*']\n this.rules = []\n this.repeats = []\n}\n\nignoreSectContents_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Ignore\n if(! this.rules[0]){\n this.rules[0] = new Ignore_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_49*\n if(! this.rules[1]){\n this.rules[1] = new tmp_49_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nignoreSectContents_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_49_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\", 'Ignore']\n this.rules = []\n this.repeats = []\n}\n\ntmp_49_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ']]>')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // Ignore\n if(! this.rules[3]){\n this.rules[3] = new Ignore_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_49_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction CharRef_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_50\n this.items = ['tmp_50', 'tmp_51']\n this.rules = []\n this.repeats = []\n}\n\nCharRef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_50\n if(! this.rules[0]){\n this.rules[0] = new tmp_50_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_51\n if(! this.rules[1]){\n this.rules[1] = new tmp_51_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nCharRef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_50_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '&#'\n this.items = [\"'&#'\", '[0-9]', \"';'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_50_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '&#'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '&#')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // [0-9]\n if(! this.rules[1]){\n this.rules[1] = new CHARSET_rule(this, '0-9')\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 1,2, rule, char)\n case 2: // ';'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ';')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_50_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_51_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '&#x'\n this.items = [\"'&#x'\", '[0-9a-fA-F]', \"';'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_51_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '&#x'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '&#x')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // [0-9a-fA-F]\n if(! this.rules[1]){\n this.rules[1] = new CHARSET_rule(this, '0-9a-fA-F')\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 1,2, rule, char)\n case 2: // ';'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ';')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_51_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Reference_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // EntityRef\n this.items = ['EntityRef', 'CharRef']\n this.rules = []\n this.repeats = []\n}\n\nReference_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // EntityRef\n if(! this.rules[0]){\n this.rules[0] = new EntityRef_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // CharRef\n if(! this.rules[1]){\n this.rules[1] = new CharRef_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nReference_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EntityRef_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '&'\n this.items = [\"'&'\", 'Name', \"';'\"]\n this.rules = []\n this.repeats = []\n}\n\nEntityRef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '&'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '&')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // ';'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ';')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEntityRef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PEReference_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '%'\n this.items = [\"'%'\", 'Name', \"';'\"]\n this.rules = []\n this.repeats = []\n}\n\nPEReference_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '%'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '%')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // ';'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ';')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPEReference_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EntityDecl_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // GEDecl\n this.items = ['GEDecl', 'PEDecl']\n this.rules = []\n this.repeats = []\n}\n\nEntityDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // GEDecl\n if(! this.rules[0]){\n this.rules[0] = new GEDecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PEDecl\n if(! this.rules[1]){\n this.rules[1] = new PEDecl_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEntityDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction GEDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nGEDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, '>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nGEDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PEDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nPEDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[8]){\n this.rules[8] = new LITERAL(this, '>')\n }\n rule = this.rules[8]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPEDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EntityDef_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // EntityValue\n this.items = ['EntityValue', 'tmp_52']\n this.rules = []\n this.repeats = []\n}\n\nEntityDef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // EntityValue\n if(! this.rules[0]){\n this.rules[0] = new EntityValue_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_52\n if(! this.rules[1]){\n this.rules[1] = new tmp_52_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEntityDef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_52_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ExternalID\n this.items = ['ExternalID', 'NDataDecl?']\n this.rules = []\n this.repeats = []\n}\n\ntmp_52_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ExternalID\n if(! this.rules[0]){\n this.rules[0] = new ExternalID_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // NDataDecl?\n if(! this.rules[1]){\n this.rules[1] = new NDataDecl_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_52_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PEDef_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // EntityValue\n this.items = ['EntityValue', 'ExternalID']\n this.rules = []\n this.repeats = []\n}\n\nPEDef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // EntityValue\n if(! this.rules[0]){\n this.rules[0] = new EntityValue_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // ExternalID\n if(! this.rules[1]){\n this.rules[1] = new ExternalID_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPEDef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction ExternalID_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_53\n this.items = ['tmp_53', 'tmp_54']\n this.rules = []\n this.repeats = []\n}\n\nExternalID_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_53\n if(! this.rules[0]){\n this.rules[0] = new tmp_53_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_54\n if(! this.rules[1]){\n this.rules[1] = new tmp_54_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nExternalID_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_53_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'SYSTEM'\n this.items = [\"'SYSTEM'\", 'S', 'SystemLiteral']\n this.rules = []\n this.repeats = []\n}\n\ntmp_53_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'SYSTEM'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'SYSTEM')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // SystemLiteral\n if(! this.rules[2]){\n this.rules[2] = new SystemLiteral_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_53_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_54_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'PUBLIC'\n this.items = [\"'PUBLIC'\", 'S', 'PubidLiteral', 'S', 'SystemLiteral']\n this.rules = []\n this.repeats = []\n}\n\ntmp_54_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'PUBLIC'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'PUBLIC')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // PubidLiteral\n if(! this.rules[2]){\n this.rules[2] = new PubidLiteral_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // S\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 4, rule, char)\n case 4: // SystemLiteral\n if(! this.rules[4]){\n this.rules[4] = new SystemLiteral_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_54_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction NDataDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', \"'NDATA'\", 'S', 'Name']\n this.rules = []\n this.repeats = []\n}\n\nNDataDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // 'NDATA'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'NDATA')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // Name\n if(! this.rules[3]){\n this.rules[3] = new Name_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNDataDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction TextDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nTextDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, '?>')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nTextDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction extParsedEnt_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // TextDecl?\n this.items = ['TextDecl?', 'content']\n this.rules = []\n this.repeats = []\n}\n\nextParsedEnt_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // TextDecl?\n if(! this.rules[0]){\n this.rules[0] = new TextDecl_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // content\n if(! this.rules[1]){\n this.rules[1] = new content_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nextParsedEnt_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EncodingDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', \"'encoding'\", 'Eq', 'tmp_55']\n this.rules = []\n this.repeats = []\n}\n\nEncodingDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // 'encoding'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'encoding')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // Eq\n if(! this.rules[2]){\n this.rules[2] = new Eq_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_55\n if(! this.rules[3]){\n this.rules[3] = new tmp_55_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEncodingDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_55_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_56\n this.items = ['tmp_56', 'tmp_57']\n this.rules = []\n this.repeats = []\n}\n\ntmp_55_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_56\n if(! this.rules[0]){\n this.rules[0] = new tmp_56_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_57\n if(! this.rules[1]){\n this.rules[1] = new tmp_57_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_55_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_56_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'EncName', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_56_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // EncName\n if(! this.rules[1]){\n this.rules[1] = new EncName_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_56_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_57_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'EncName', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_57_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // EncName\n if(! this.rules[1]){\n this.rules[1] = new EncName_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_57_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EncName_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [A-Za-z]\n this.items = ['[A-Za-z]', 'tmp_58*']\n this.rules = []\n this.repeats = []\n}\n\nEncName_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [A-Za-z]\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, 'A-Za-z')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_58*\n if(! this.rules[1]){\n this.rules[1] = new tmp_58_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEncName_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_58_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [A-Za-z0-9._]\n this.items = ['[A-Za-z0-9._]', \"'-'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_58_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [A-Za-z0-9._]\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, 'A-Za-z0-9._')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '-'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '-')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_58_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction NotationDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nNotationDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, '>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNotationDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_59_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ExternalID\n this.items = ['ExternalID', 'PublicID']\n this.rules = []\n this.repeats = []\n}\n\ntmp_59_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ExternalID\n if(! this.rules[0]){\n this.rules[0] = new ExternalID_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PublicID\n if(! this.rules[1]){\n this.rules[1] = new PublicID_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_59_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PublicID_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'PUBLIC'\n this.items = [\"'PUBLIC'\", 'S', 'PubidLiteral']\n this.rules = []\n this.repeats = []\n}\n\nPublicID_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'PUBLIC'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'PUBLIC')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // PubidLiteral\n if(! this.rules[2]){\n this.rules[2] = new PubidLiteral_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPublicID_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nvar models = {\n XML_CTYPE_ANY: 2,\n XML_CTYPE_CHOICE: 5,\n XML_CTYPE_EMPTY: 1,\n XML_CTYPE_MIXED: 3,\n XML_CTYPE_NAME: 4,\n XML_CTYPE_SEQ: 6,\n}\n\n__BRYTHON__.addToImported('xml_parser', {\n DOCUMENT: document_rule,\n models\n})\n\n})(__BRYTHON__)"], "_ajax": [".js", "// ajax\n__BRYTHON__.imported._ajax = (function($B){\n\n\nvar $N = $B.builtins.None,\n _b_ = $B.builtins\n\nvar add_to_res = function(res, key, val) {\n if($B.$isinstance(val, _b_.list)){\n for (j = 0; j < val.length; j++) {\n add_to_res(res, key, val[j])\n }\n }else if (val instanceof File || val instanceof Blob){\n res.append(key, val)\n }else{\n res.append(key, _b_.str.$factory(val))\n }\n}\n\nfunction set_timeout(self, timeout){\n if(timeout.seconds !== undefined){\n self.js.$requestTimer = setTimeout(\n function() {\n self.js.abort()\n if(timeout.func){\n timeout.func()\n }\n },\n timeout.seconds * 1000)\n }\n}\n\nfunction _read(req){\n var xhr = req.js\n if(xhr.responseType == \"json\"){\n return $B.structuredclone2pyobj(xhr.response)\n }\n if(req.charset_user_defined){\n // on blocking mode, xhr.response is a string\n var bytes = []\n for(var i = 0, len = xhr.response.length; i < len; i++){\n var cp = xhr.response.codePointAt(i)\n if(cp > 0xf700){\n bytes.push(cp - 0xf700)\n }else{\n bytes.push(cp)\n }\n }\n }else if(typeof xhr.response == \"string\"){\n if(req.mode == 'binary'){\n return _b_.str.encode(xhr.response,\n $B.$getattr(req, 'encoding', 'utf-8'))\n }\n return xhr.response\n }else{\n // else it's an ArrayBuffer\n var buf = new Uint8Array(xhr.response),\n bytes = Array.from(buf.values())\n }\n var b = _b_.bytes.$factory(bytes),\n mode = $B.$getattr(req, 'mode', null)\n if(mode == \"binary\"){\n return b\n }else if(mode == \"document\"){\n return $B.jsobj2pyobj(xhr.response)\n }else{\n var encoding = $B.$getattr(req, 'encoding', \"utf-8\")\n return _b_.bytes.decode(b, encoding)\n }\n}\n\nfunction stringify(d){\n var items = []\n for(var entry of _b_.dict.$iter_items(d)){\n items.push(encodeURIComponent(entry.key) + \"=\" +\n encodeURIComponent(entry.value))\n }\n return items.join(\"&\")\n}\n\nfunction handle_kwargs(self, kw, method){\n var data,\n encoding,\n headers = {},\n cache,\n mode = \"text\",\n timeout = {},\n rawdata\n\n for(var item of _b_.dict.$iter_items(kw)){\n var key = item.key\n if(key == \"data\"){\n var rawdata = item.value\n if(typeof rawdata == \"string\" || rawdata instanceof FormData){\n data = rawdata\n }else if(rawdata.__class__ === _b_.dict){\n data = stringify(rawdata)\n }else{\n throw _b_.TypeError.$factory(\"wrong type for data: \" +\n $B.class_name(rawdata))\n }\n }else if(key == \"encoding\"){\n encoding = item.value\n }else if(key == \"headers\"){\n var value = item.value\n if(! $B.$isinstance(value, _b_.dict)){\n throw _b_.ValueError.$factory(\n \"headers must be a dict, not \" + $B.class_name(value))\n }\n for(var subitem of _b_.dict.$iter_items(value)){\n headers[subitem.key.toLowerCase()] = subitem.value\n }\n }else if(key.startsWith(\"on\")){\n var event = key.substr(2)\n if(event == \"timeout\"){\n timeout.func = item.value\n }else{\n var f = item.value\n ajax.bind(self, event, f)\n }\n }else if(key == \"mode\"){\n var mode = item.value\n }else if(key == \"timeout\"){\n timeout.seconds = item.value\n }else if(key == \"cache\"){\n cache = item.value\n }\n }\n if(encoding && mode != \"text\"){\n throw _b_.ValueError.$factory(\"encoding not supported for mode \" +\n mode)\n }\n if((method == \"post\" || method == \"put\") && ! headers){\n // For POST requests, set default header\n self.js.setRequestHeader(\"Content-type\",\n \"application/x-www-form-urlencoded\")\n }\n\n return {cache, data, rawdata, encoding, headers, mode, timeout}\n}\n\nvar ajax = $B.make_class('ajax')\n\najax.__repr__ = function(self){\n return ''\n}\n\najax.__getattribute__ = function(self, attr){\n if(ajax[attr] !== undefined){\n return function(){\n return ajax[attr].call(null, self, ...arguments)\n }\n }else if(attr == \"text\"){\n return _read(self)\n }else if(attr == \"json\"){\n if(self.js.responseType == \"json\"){\n return _read(self)\n }else{\n var resp = _read(self)\n try{\n return $B.structuredclone2pyobj(JSON.parse(resp))\n }catch(err){\n console.log('attr json, invalid resp', resp)\n throw err\n }\n }\n }else if(self.js[attr] !== undefined){\n if(typeof self.js[attr] == \"function\"){\n return function(){\n if(attr == \"setRequestHeader\"){\n ajax.set_header.call(null, self, ...arguments)\n }else{\n if(attr == 'overrideMimeType'){\n console.log('override mime type')\n self.hasMimeType = true\n }\n return self.js[attr](...arguments)\n }\n }\n }else{\n return self.js[attr]\n }\n }else if(attr == \"xml\"){\n return $B.jsobj2pyobj(self.js.responseXML)\n }\n return _b_.object.__getattribute__(self, attr)\n}\n\najax.bind = function(self, evt, func){\n // req.bind(evt,func) is the same as req.onevt = func\n self.js['on' + evt] = function(){\n try{\n return func.apply(null, arguments)\n }catch(err){\n $B.handle_error(err)\n }\n }\n return _b_.None\n}\n\najax.open = function(){\n var $ = $B.args('open', 4,\n {self: null, method: null, url: null, async: null},\n ['self', 'method', 'url', 'async'], arguments,\n {async: true}, null, null),\n self = $.self,\n method = $.method,\n url = $.url,\n async = $.async\n if(typeof method !== \"string\"){\n throw _b_.TypeError.$factory(\n 'open() argument method should be string, got ' +\n $B.class_name(method))\n }\n if(typeof url !== \"string\"){\n throw _b_.TypeError.$factory(\n 'open() argument url should be string, got ' +\n $B.class_name(url))\n }\n self.$method = method\n self.blocking = ! self.async\n self.js.open(method, url, async)\n}\n\najax.read = function(self){\n return _read(self)\n}\n\najax.send = function(self, params){\n // params can be Python dictionary or string\n var content_type\n for(var key in self.headers){\n var value = self.headers[key]\n self.js.setRequestHeader(key, value)\n if(key == 'content-type'){\n content_type = value\n }\n }\n if(($B.$getattr(self, 'encoding', false) ||\n $B.$getattr(self, 'blocking', false)) && ! self.hasMimeType){\n // On blocking mode, or if an encoding has been specified,\n // override Mime type so that bytes are not processed\n // (unless the Mime type has been explicitely set)\n self.js.overrideMimeType('text/plain;charset=x-user-defined')\n self.charset_user_defined = true\n }\n var res = ''\n if(! params){\n self.js.send()\n return _b_.None\n }\n if($B.$isinstance(params, _b_.str)){\n res = params\n }else if($B.$isinstance(params, _b_.dict)){\n if(content_type == 'multipart/form-data'){\n // The FormData object serializes the data in the 'multipart/form-data'\n // content-type so we may as well override that header if it was set\n // by the user.\n res = new FormData()\n var items = _b_.list.$factory(_b_.dict.items(params))\n for(var i = 0, len = items.length; i < len; i++){\n add_to_res(res, _b_.str.$factory(items[i][0]), items[i][1])\n }\n }else{\n if(self.$method && self.$method.toUpperCase() == \"POST\" &&\n ! content_type){\n // Set default Content-Type for POST requests\n self.js.setRequestHeader(\"Content-Type\",\n \"application/x-www-form-urlencoded\")\n }\n var items = _b_.list.$factory(_b_.dict.items(params))\n for(var i = 0, len = items.length; i < len; i++){\n var key = encodeURIComponent(_b_.str.$factory(items[i][0]));\n if($B.$isinstance(items[i][1], _b_.list)){\n for (j = 0; j < items[i][1].length; j++) {\n res += key +'=' +\n encodeURIComponent(_b_.str.$factory(items[i][1][j])) + '&'\n }\n }else{\n res += key + '=' +\n encodeURIComponent(_b_.str.$factory(items[i][1])) + '&'\n }\n }\n res = res.substr(0, res.length - 1)\n }\n }else if(params instanceof FormData){\n res = params\n }else{\n throw _b_.TypeError.$factory(\n \"send() argument must be string or dictionary, not '\" +\n _b_.str.$factory(params.__class__) + \"'\")\n }\n self.js.send(res)\n return _b_.None\n}\n\najax.responseType = _b_.property.$factory(\n function(_self){\n return _self.responseType\n },\n function(_self, value){\n _self.js.responseType = value\n }\n)\n\najax.withCredentials = _b_.property.$factory(\n function(_self){\n return _self.withCredentials\n },\n function(_self, value){\n _self.js.withCredentials = value\n }\n)\n\najax.set_header = function(self, key, value){\n self.headers[key.toLowerCase()] = value\n}\n\najax.set_timeout = function(self, seconds, func){\n self.js.$requestTimer = setTimeout(\n function() {\n self.js.abort()\n func()\n },\n seconds * 1000)\n}\n\najax.$factory = function(){\n\n var xmlhttp = new XMLHttpRequest()\n\n xmlhttp.onreadystatechange = function(){\n // here, \"this\" refers to xmlhttp\n var state = this.readyState\n if(this.responseType == \"\" || this.responseType == \"text\"){\n res.js.text = this.responseText\n }\n var timer = this.$requestTimer\n if(state == 0 && this.onuninitialized){\n this.onuninitialized(res)\n }else if(state == 1 && this.onloading){\n this.onloading(res)\n }else if(state == 2 && this.onloaded){\n this.onloaded(res)\n }else if(state == 3 && this.oninteractive){\n this.oninteractive(res)\n }else if(state == 4 && this.oncomplete){\n if(timer !== null){\n globalThis.clearTimeout(timer)\n }\n this.oncomplete(res)\n }\n }\n var res = {\n __class__: ajax,\n __dict__: $B.empty_dict(),\n js: xmlhttp,\n headers: {}\n }\n return res\n}\n\n\nfunction _request_without_body(method){\n var $ = $B.args(method, 3, {method: null, url: null, blocking: null},\n [\"method\", \"url\", \"blocking\"], arguments, {blocking: false},\n null, \"kw\"),\n method = $.method,\n url = $.url,\n async = !$.blocking,\n kw = $.kw\n\n var self = ajax.$factory()\n self.blocking = $.blocking\n var items = handle_kwargs(self, kw, method),\n mode = items.mode,\n encoding = items.encoding,\n qs = items.data\n $B.$setattr(self, 'mode', mode)\n $B.$setattr(self, 'encoding', encoding)\n if(qs){\n url += \"?\" + qs\n }\n if(! (items.cache === true)){\n url += (qs ? \"&\" : \"?\") + (new Date()).getTime()\n }\n self.js.open(method.toUpperCase(), url, async)\n\n if(async){\n if(mode == \"json\" || mode == \"document\"){\n self.js.responseType = mode\n }else{\n self.js.responseType = \"arraybuffer\"\n if(mode != \"text\" && mode != \"binary\"){\n throw _b_.ValueError.$factory(\"invalid mode: \" + mode)\n }\n }\n }else{\n self.js.overrideMimeType('text/plain;charset=x-user-defined')\n self.charset_user_defined = true\n }\n for(var key in items.headers){\n self.js.setRequestHeader(key, items.headers[key])\n }\n var timeout = items.timeout\n if(timeout.seconds){\n ajax.set_timeout(self, timeout.seconds, timeout.func)\n }\n // Add function read() to return str or bytes according to mode\n self.js.send()\n}\n\nfunction _request_with_body(method){\n var $ = $B.args(method, 3, {method: null, url: null, blocking: null},\n [\"method\", \"url\", \"blocking\"], arguments, {blocking: false},\n null, \"kw\"),\n method = $.method,\n url = $.url,\n async = !$.blocking,\n kw = $.kw,\n content_type\n var self = ajax.$factory()\n self.js.open(method.toUpperCase(), url, async)\n var items = handle_kwargs(self, kw, method), // common with browser.aio\n data = items.data\n\n if($B.$isinstance(data, _b_.dict)){\n data = stringify(data)\n }\n for(var key in items.headers){\n var value = items.headers[key]\n self.js.setRequestHeader(key, value)\n if(key == 'content-type'){\n content_type = value\n }\n }\n if(method.toUpperCase() == 'POST' && !content_type){\n // set default Content-Type for POST requests\n self.js.setRequestHeader('Content-Type',\n 'application/x-www-form-urlencoded')\n }\n\n // Add function read() to return str or bytes according to mode\n self.js.read = function(){\n return _read(self)\n }\n self.js.send(data)\n}\n\nfunction form_data(form){\n var missing = {},\n $ = $B.args('form_data', 1, {form: null}, ['form'], arguments,\n {form: missing}, null, null)\n if($.form === missing){\n return new FormData()\n }else{\n return new FormData($.form)\n }\n}\n\nfunction connect(){\n _request_without_body.call(null, \"connect\", ...arguments)\n}\n\nfunction _delete(){\n _request_without_body.call(null, \"delete\", ...arguments)\n}\n\nfunction get(){\n _request_without_body.call(null, \"get\", ...arguments)\n}\n\nfunction head(){\n _request_without_body.call(null, \"head\", ...arguments)\n}\n\nfunction options(){\n _request_without_body.call(null, \"options\", ...arguments)\n}\n\nfunction patch(){\n _request_with_body.call(null, \"put\", ...arguments)\n}\n\nfunction post(){\n _request_with_body.call(null, \"post\", ...arguments)\n}\n\nfunction put(){\n _request_with_body.call(null, \"put\", ...arguments)\n}\n\nfunction trace(){\n _request_without_body.call(null, \"trace\", ...arguments)\n}\n\nfunction file_upload(){\n // ajax.file_upload(url, file, method=\"POST\", **callbacks)\n var $ = $B.args(\"file_upload\", 2, {url: null, \"file\": file},\n [\"url\", \"file\"], arguments, {}, null, \"kw\"),\n url = $.url,\n file = $.file,\n kw = $.kw\n\n var self = ajax.$factory()\n\n var items = handle_kwargs(self, kw, method),\n rawdata = items.rawdata,\n headers = items.headers\n\n for(var key in headers){\n var value = headers[key]\n self.js.setRequestHeader(key, value)\n if(key == 'content-type'){\n content_type = value\n }\n }\n\n var timeout = items.timeout\n if(timeout.seconds){\n ajax.set_timeout(self, timeout.seconds, timeout.func)\n }\n\n var method = _b_.dict.$get_string(kw, 'method', 'POST'),\n field_name = _b_.dict.$get_string(kw, 'field_name', 'filetosave')\n\n var formdata = new FormData()\n formdata.append(field_name, file, file.name)\n\n if(rawdata){\n if(rawdata instanceof FormData){\n // append additional data\n for(var d of rawdata){\n formdata.append(d[0], d[1])\n }\n }else if($B.$isinstance(rawdata, _b_.dict)){\n for(var item of _b_.dict.$iter_items(rawdata)){\n formdata.append(item.key, item.value)\n }\n }else{\n throw _b_.ValueError.$factory(\n 'data value must be a dict of form_data')\n }\n }\n\n self.js.open(method, url, _b_.True)\n self.js.send(formdata)\n\n}\n\n$B.set_func_names(ajax)\n\nreturn {\n ajax: ajax,\n Ajax: ajax,\n delete: _delete,\n file_upload: file_upload,\n connect,\n form_data,\n get,\n head,\n options,\n patch,\n post,\n put,\n trace\n}\n\n})(__BRYTHON__)\n"], "_ast": [".js", "(function($B){\n\nvar _b_ = $B.builtins,\n ast = $B.ast, // created in py2js\n mod = {}\nmod.PyCF_ONLY_AST = $B.PyCF_ONLY_AST\nmod.PyCF_TYPE_COMMENTS = $B.PyCF_TYPE_COMMENTS\nmod.AST = $B.AST // in builtin_modules.js\n$B.create_python_ast_classes() // in py_ast.js\nfor(var klass in ast){\n mod[klass] = $B.python_ast_classes[klass]\n}\n\nvar Load = 'Load',\n Store = 'Store',\n Del = 'Del'\n\n// Note: the ensure_literal_* functions are only used to validate a restricted\n// set of non-recursive literals that have already been checked with\n// validate_expr, so they don't accept the validator state\nfunction ensure_literal_number(exp, allow_real, allow_imaginary){\n if(exp.__class__ !== mod.Constant){\n return false\n }\n var value = exp.value\n if(allow_real && $B.$isinstance(value, [_b_.int, _b_.float])){\n return true\n }\n if(allow_imaginary && $B.$isinstance(value, _b_.complex)){\n return true\n }\n return false\n}\n\nfunction ensure_literal_negative(exp, allow_real, allow_imaginary){\n if(exp.__class__ !== mod.UnaryOp){\n return false\n }\n // Must be negation ...\n if(exp.op !== mod.USub) {\n return false\n }\n // ... of a constant ...\n var operand = exp.operand\n if(operand.__class__ !== mod.Constant){\n return false\n }\n // ... number\n return ensure_literal_number(operand, allow_real, allow_imaginary)\n}\n\nfunction ensure_literal_complex(exp){\n if(exp.__class__ !== mod.BinOp){\n return false\n }\n var left = exp.left,\n right = exp.right;\n // Ensure op is addition or subtraction\n if(exp.op !== mod.Add && exp.op !== mod.Sub){\n return false\n }\n // Check LHS is a real number (potentially signed)\n switch(left.__class__){\n case mod.Constant:\n if(!ensure_literal_number(left, true, false)){\n return false\n }\n break;\n case mod.UnaryOp:\n if(!ensure_literal_negative(left, true, false)){\n return false\n }\n break;\n default:\n return false\n }\n // Check RHS is an imaginary number (no separate sign allowed)\n switch(right.__class__){\n case mod.Constant:\n if(!ensure_literal_number(right, false, true)){\n return false\n }\n break;\n default:\n return false\n }\n return true\n}\n\nfunction validate_arguments(args){\n validate_args(args.posonlyargs)\n validate_args(args.args)\n if(args.vararg && args.vararg.annotation){\n validate_expr(args.vararg.annotation, Load)\n }\n validate_args(args.kwonlyargs)\n if(args.kwarg && args.kwarg.annotation){\n validate_expr(args.kwarg.annotation, Load)\n }\n if(args.defaults.length > args.posonlyargs.length + args.args.length){\n throw _b_.ValueError.$factory(\n \"more positional defaults than args on arguments\")\n }\n if(args.kw_defaults.length != args.kwonlyargs.length){\n throw _b_.ValueError.$factory(\n \"length of kwonlyargs is not the same as \" +\n \"kw_defaults on arguments\")\n }\n validate_exprs(args.defaults, Load, 0)\n validate_exprs(args.kw_defaults, Load, 1)\n}\n\nfunction validate_pattern(p, star_ok){\n var ret = -1\n switch(p.__class__) {\n case mod.MatchValue:\n validate_pattern_match_value(p.value)\n break;\n case mod.MatchSingleton:\n if([_b_.None, _b_.True, _b_.False].indexOf(p.value) == -1){\n throw _b_.ValueError(\n \"MatchSingleton can only contain True, False and None\")\n }\n break;\n case mod.MatchSequence:\n validate_patterns(p.patterns, 1);\n break;\n case mod.MatchMapping:\n if(p.keys.length != p.patterns.length){\n throw _b_.ValueError.$factory(\n \"MatchMapping doesn't have the same number of keys as patterns\");\n }\n if(p.rest){\n validate_capture(p.rest)\n }\n\n var keys = p.keys;\n for(var key of keys){\n if(key.__class__ === mod.Constant) {\n var literal = key.value;\n if([_b_.None, _b_.True, _b_.False].indexOf(literal) > -1){\n /* validate_pattern_match_value will ensure the key\n doesn't contain True, False and None but it is\n syntactically valid, so we will pass those on in\n a special case. */\n continue;\n }\n }\n validate_pattern_match_value(key)\n }\n validate_patterns(p.patterns, 0);\n break;\n case mod.MatchClass:\n if(p.kwd_attrs.length != p.kwd_patterns.length){\n throw _b_.ValueError.$factory(\n \"MatchClass doesn't have the same number of \" +\n \"keyword attributes as patterns\")\n }\n validate_expr(p.cls, Load)\n var cls = p.cls;\n while(true){\n if(cls.__class__ === mod.Name){\n break\n }else if(cls.__class__ === mod.Attribute) {\n cls = cls.value;\n continue;\n }else {\n throw _b_.ValueError.$factory(\n \"MatchClass cls field can only contain Name \" +\n \"or Attribute nodes.\")\n }\n }\n\n for(var identifier of p.kwd_attrs){\n validate_name(identifier)\n }\n\n validate_patterns(p.patterns, 0)\n validate_patterns(p.kwd_patterns, 0);\n break;\n case mod.MatchStar:\n if (!star_ok) {\n throw _b_.ValueError.$factory(\"can't use MatchStar here\")\n }\n if(p.name === undefined){\n validate_capture(p.name)\n }\n break;\n case mod.MatchAs:\n if(p.name){\n validate_capture(p.name)\n }\n if(p.pattern == undefined){\n ret = 1;\n }else if(p.name == undefined){\n throw _b_.ValueError.$factory(\n \"MatchAs must specify a target name if a pattern is given\")\n }else{\n validate_pattern(p.pattern, 0);\n }\n break;\n case mod.MatchOr:\n if(p.patterns.length < 2){\n throw _b_.ValueError.$factory(\n \"MatchOr requires at least 2 patterns\")\n }\n validate_patterns(p.patterns, 0)\n break;\n // No default case, so the compiler will emit a warning if new pattern\n // kinds are added without being handled here\n }\n if(ret < 0){\n throw _b_.SystemError.$factory(\"unexpected pattern\")\n }\n return true\n}\n\nfunction validate_patterns(patterns, star_ok){\n for(var pattern of patterns){\n validate_pattern(pattern, star_ok)\n }\n return true\n}\n\nfunction validate_pattern_match_value(exp){\n validate_expr(exp, Load)\n switch (exp.__class__){\n case mod.Constant:\n /* Ellipsis and immutable sequences are not allowed.\n For True, False and None, MatchSingleton() should\n be used */\n validate_expr(exp, Load)\n var literal = exp.value\n if($B.$isinstance(literal, [_b_.int, _b_.float, _b_.bytes,\n _b_.complex, _b_.str])){\n return true\n }\n throw _b_.ValueError.$factory(\n \"unexpected constant inside of a literal pattern\")\n case mod.Attribute:\n // Constants and attribute lookups are always permitted\n return true\n case mod.UnaryOp:\n // Negated numbers are permitted (whether real or imaginary)\n // Compiler will complain if AST folding doesn't create a constant\n if(ensure_literal_negative(exp, true, true)){\n return true\n }\n break;\n case mod.BinOp:\n // Complex literals are permitted\n // Compiler will complain if AST folding doesn't create a constant\n if(ensure_literal_complex(exp)){\n return true\n }\n break;\n case mod.JoinedStr:\n // Handled in the later stages\n return 1;\n default:\n break;\n }\n throw _b_.ValueError.$factory(\n \"patterns may only match literals and attribute lookups\")\n}\n\nfunction validate_capture(name){\n if(name == \"_\"){\n throw _b_.ValueError.$factory(\"can't capture name '_' in patterns\")\n }\n validate_name(name)\n}\n\nfunction validate_name(name){\n var forbidden = [\"None\", \"True\", \"False\"]\n if(forbidden.indexOf(name) > -1){\n throw _b_.ValueError.$factory(`identifier field can't represent` +\n ` '${name}' constant\", forbidden[i]`)\n }\n return true\n}\n\nfunction validate_comprehension(gens){\n if(gens.length == 0) {\n throw _b_.ValueError.$factory(\"comprehension with no generators\")\n }\n for(var comp of gens){\n validate_expr(comp.target, Store)\n validate_expr(comp.iter, Load)\n validate_exprs(comp.ifs, Load, 0)\n }\n return true\n}\n\nfunction validate_keywords(keywords){\n for(var keyword of keywords){\n validate_expr(keyword.value, Load)\n }\n return true\n}\n\nfunction validate_args(args){\n for(var arg of args){\n if(arg.annotation){\n validate_expr(arg.annotation, Load)\n }\n }\n return true\n}\n\nfunction validate_nonempty_seq(seq, what, owner){\n if(seq.length > 0){\n return true\n }\n throw _b_.ValueError.$factory(`empty ${what} on ${owner}`)\n}\n\nfunction validate_assignlist(targets, ctx){\n validate_nonempty_seq(targets, \"targets\", ctx == Del ? \"Delete\" : \"Assign\")\n validate_exprs(targets, ctx, 0)\n}\n\nfunction validate_body(body, owner){\n validate_nonempty_seq(body, \"body\", owner)\n validate_stmts(body)\n}\n\nfunction validate_exprs(exprs, ctx, null_ok){\n for(var expr of exprs){\n if(expr !== _b_.None){\n validate_expr(expr, ctx)\n }else if(!null_ok){\n throw _b_.ValueError.$factory(\n \"None disallowed in expression list\")\n }\n\n }\n return true\n}\n\nfunction validate_expr(exp, ctx){\n var check_ctx = 1,\n actual_ctx;\n\n /* First check expression context. */\n switch (exp.__class__) {\n case mod.Name:\n validate_name(exp.id)\n actual_ctx = exp.ctx\n break;\n case mod.Attribute:\n case mod.Subscript:\n case mod.Starred:\n case mod.List:\n case mod.Tuple:\n actual_ctx = exp.ctx;\n break\n default:\n if(ctx != Load){\n throw _b_.ValueError.$factory(\"expression which can't be \" +\n `assigned to in ${ctx} context`)\n }\n check_ctx = 0;\n /* set actual_ctx to prevent gcc warning */\n actual_ctx = 0;\n }\n actual_ctx = actual_ctx === 0 ? actual_ctx :\n actual_ctx.__class__.__name__\n if(check_ctx && actual_ctx != ctx){\n throw _b_.ValueError.$factory(`expression must have ` +\n `${ctx} context but has ${actual_ctx} instead`)\n }\n\n /* Now validate expression. */\n switch (exp.__class__) {\n case mod.BoolOp:\n if(exp.values.length < 2){\n throw _b_.ValueError.$factory(\"BoolOp with less than 2 values\")\n }\n validate_exprs(exp.values, Load, 0);\n break;\n case mod.BinOp:\n validate_expr(exp.left, Load)\n validate_expr(exp.right, Load)\n break;\n case mod.UnaryOp:\n validate_expr(exp.operand, Load);\n break;\n case mod.Lambda:\n validate_arguments(exp.args)\n validate_expr(exp.body, Load);\n break;\n case mod.IfExp:\n validate_expr(exp.test, Load)\n validate_expr(exp.body, Load)\n validate_expr(exp.orelse, Load)\n break;\n case mod.Dict:\n if(exp.keys.length != exp.values.length){\n throw _b_.ValueError.$factory(\n \"Dict doesn't have the same number of keys as values\");\n }\n /* null_ok=1 for keys expressions to allow dict unpacking to work in\n dict literals, i.e. ``{**{a:b}}`` */\n validate_exprs(exp.keys, Load, 1)\n validate_exprs(exp.values, Load, 0);\n break;\n case mod.Set:\n validate_exprs(exp.elts, Load, 0);\n break;\n case mod.ListComp:\n case mod.SetComp:\n case mod.GeneratorExp:\n validate_comprehension(exp.generators)\n validate_expr(exp.elt, Load)\n break;\n case mod.DictComp:\n validate_comprehension(exp.generators)\n validate_expr(exp.key, Load)\n validate_expr(exp.value, Load)\n break;\n case mod.Yield:\n if(exp.value){\n validate_expr(exp.value, Load)\n }\n break;\n case mod.YieldFrom:\n validate_expr(exp.value, Load)\n break;\n case mod.Await:\n validate_expr(exp.value, Load)\n break;\n case mod.Compare:\n if(exp.comparators.length == 0){\n throw _b_.ValueError.$factory(\"Compare with no comparators\")\n }\n if(exp.comparators.length != exp.ops){\n throw _b_.ValueError.$factory(\"Compare has a different number \" +\n \"of comparators and operands\")\n }\n validate_exprs(exp.comparators, Load, 0)\n validate_expr(exp.left, Load)\n break;\n case mod.Call:\n validate_expr(exp.func, Load)\n validate_exprs(exp.args, Load, 0)\n validate_keywords(exp.keywords)\n break;\n case mod.Constant:\n validate_constant(exp.value)\n break;\n case mod.JoinedStr:\n validate_exprs(exp.values, Load, 0)\n break;\n case mod.FormattedValue:\n validate_expr(exp.value, Load)\n if (exp.format_spec) {\n validate_expr(exp.format_spec, Load)\n break;\n }\n break;\n case mod.Attribute:\n validate_expr(exp.value, Load)\n break;\n case mod.Subscript:\n validate_expr(exp.slice, Load)\n validate_expr(exp.value, Load)\n break;\n case mod.Starred:\n validate_expr(exp.value, ctx)\n break;\n case mod.Slice:\n if(exp.lower){\n validate_expr(exp.lower, Load)\n }\n if(exp.upper){\n validate_expr(exp.upper, Load)\n }\n if(exp.step){\n validate_expr(exp.step, Load)\n }\n break;\n case mod.List:\n validate_exprs(exp.elts, ctx, 0)\n break;\n case mod.Tuple:\n validate_exprs(exp.elts, ctx, 0)\n break;\n case mod.NamedExpr:\n validate_expr(exp.value, Load)\n break;\n /* This last case doesn't have any checking. */\n case mod.Name:\n ret = 1;\n break;\n // No default case mod.so compiler emits warning for unhandled cases\n }\n return true\n}\n\nfunction validate_constant(value){\n if (value == _b_.None || value == _b_.Ellipsis){\n return true\n }\n if($B.$isinstance(value,\n [_b_.int, _b_.float, _b_.complex, _b_.bool, _b_.bytes, _b_.str])){\n return true\n }\n\n if($B.$isinstance(value, [_b_.tuple, _b_.frozenset])){\n var it = _b_.iter(value)\n while(true){\n try{\n var item = _b_.next(it)\n validate_constant(item)\n }catch(err){\n if($B.is_exc(err, [_b_.StopIteration])){\n return true\n }\n throw err\n }\n }\n }\n}\n\nfunction validate_stmts(seq){\n for(var stmt of seq) {\n if(stmt !== _b_.None){\n validate_stmt(stmt)\n }else{\n throw _b_.ValueError.$factory(\"None disallowed in statement list\");\n }\n }\n}\n\nfunction validate_stmt(stmt){\n switch (stmt.__class__) {\n case mod.FunctionDef:\n validate_body(stmt.body, \"FunctionDef\")\n validate_arguments(stmt.args)\n validate_exprs(stmt.decorator_list, Load, 0)\n if(stmt.returns){\n validate_expr(stmt.returns, Load)\n }\n break;\n case mod.ClassDef:\n validate_body(stmt.body, \"ClassDef\")\n validate_exprs(stmt.bases, Load, 0)\n validate_keywords(stmt.keywords)\n validate_exprs(stmtdecorator_list, Load, 0)\n break;\n case mod.Return:\n if(stmt.value){\n validate_expr(stmt.value, Load)\n }\n break;\n case mod.Delete:\n validate_assignlist(stmt.targets, Del);\n break;\n case mod.Assign:\n validate_assignlist(stmt.targets, Store)\n validate_expr(stmt.value, Load)\n break;\n case mod.AugAssign:\n validate_expr(stmt.target, Store) &&\n validate_expr(stmt.value, Load);\n break;\n case mod.AnnAssign:\n if(stmt.target.__class__ != mod.Name && stmt.simple){\n throw _b_.TypeError.$factory(\n \"AnnAssign with simple non-Name target\")\n }\n validate_expr(stmt.target, Store)\n if(stmt.value){\n validate_expr(stmt.value, Load)\n validate_expr(stmt.annotation, Load);\n }\n break;\n case mod.For:\n validate_expr(stmt.target, Store)\n validate_expr(stmt.iter, Load)\n validate_body(stmt.body, \"For\")\n validate_stmts(stmt.orelse)\n break;\n case mod.AsyncFor:\n validate_expr(stmt.target, Store)\n validate_expr(stmt.iter, Load)\n validate_body(stmt.body, \"AsyncFor\")\n validate_stmts(stmt.orelse)\n break;\n case mod.While:\n validate_expr(stmt.test, Load)\n validate_body(stmt.body, \"While\")\n validate_stmts(stmt.orelse)\n break;\n case mod.If:\n validate_expr(stmt.test, Load)\n validate_body(stmt.body, \"If\")\n validate_stmts(stmt.orelse)\n break;\n case mod.With:\n validate_nonempty_seq(stmt.items, \"items\", \"With\")\n for (var item of stmt.items){\n validate_expr(item.context_expr, Load) &&\n (! item.optional_vars || validate_expr(item.optional_vars, Store))\n }\n validate_body(stmt.body, \"With\");\n break;\n case mod.AsyncWith:\n validate_nonempty_seq(stmt.items, \"items\", \"AsyncWith\")\n for(var item of stmt.items){\n validate_expr(item.context_expr, Load)\n if(item.optional_vars){\n validate_expr(item.optional_vars, Store)\n }\n }\n validate_body(stmt.body, \"AsyncWith\");\n break;\n case mod.Match:\n validate_expr(stmt.subject, Load)\n validate_nonempty_seq(stmt.cases, \"cases\", \"Match\")\n for(var m of stmt.cases){\n validate_pattern(m.pattern, 0)\n if(m.guard){\n validate_expr(m.guard, Load)\n }\n validate_body(m.body, \"match_case\")\n }\n break;\n case mod.Raise:\n if(stmt.exc){\n validate_expr(stmt.exc, Load)\n if(stmt.cause){\n validate_expr(stmt.cause, Load)\n }\n break;\n }\n if(stmt.cause) {\n throw _b_.ValueError.$factory(\"Raise with cause but no exception\");\n }\n break;\n case mod.Try:\n validate_body(stmt.body, \"Try\")\n if(stmt.handlers.length == 0 + stmt.finalbody.length == 0){\n throw _b_.ValueError.$factor(\n \"Try has neither except handlers nor finalbody\");\n }\n if(stmt.handlers.length == 0 && stmt.orelse.length > 0){\n throw _b_.ValueError.$factory(\n \"Try has orelse but no except handlers\");\n }\n for(var handler of stmt.handlers){\n if(handler.type){\n validate_expr(handler.type, Load)\n validate_body(handler.body, \"ExceptHandler\")\n }\n }\n if(stmt.finalbody.length > 0){\n validate_stmts(stmt.finalbody)\n }\n if(stmt.orelse.length > 0){\n validate_stmts(stmt.orelse)\n }\n break;\n case mod.TryStar:\n validate_body(stmt.body, \"TryStar\")\n if(stmt.handlers.length + stmt.finalbody.length == 0){\n throw _b_.ValueError.$factory(\n \"TryStar has neither except handlers nor finalbody\");\n }\n if(stmt.handlers.length == 0 && stmt.orelse.length > 0){\n throw _b_.ValueError.$factory(\n \"TryStar has orelse but no except handlers\");\n }\n for(var handler of stm.handlers){\n if(handler.type){\n validate_expr(handler.type, Load)\n validate_body(handler.body, \"ExceptHandler\")\n }\n }\n if(stmt.finalbody.length > 0){\n validate_stmts(stmt.finalbody)\n }\n if(stmt.orelse.length > 0){\n validate_stmts(stmt.orelse)\n }\n break;\n case mod.Assert:\n validate_expr(stmt.test, Load)\n if(stmt.msg){\n validate_expr(stmt.msg, Load)\n }\n break;\n case mod.Import:\n validate_nonempty_seq(stmt.names, \"names\", \"Import\");\n break;\n case mod.ImportFrom:\n if(stmt.level < 0) {\n throw _b_.ValueError.$factory(\"Negative ImportFrom level\")\n }\n validate_nonempty_seq(stmt.names, \"names\", \"ImportFrom\");\n break;\n case mod.Global:\n validate_nonempty_seq(stmt.names, \"names\", \"Global\");\n break;\n case mod.Nonlocal:\n validate_nonempty_seq(stmt.names, \"names\", \"Nonlocal\");\n break;\n case mod.Expr:\n validate_expr(stmt.value, Load);\n break;\n case mod.AsyncFunctionDef:\n validate_body(stmt.body, \"AsyncFunctionDef\")\n validate_arguments(stmt.args)\n validate_exprs(stmt.decorator_list, Load, 0)\n if(stmt.returns){\n validate_expr(stmt.returns, Load)\n }\n break;\n case mod.Pass:\n case mod.Break:\n case mod.Continue:\n break;\n // No default case so compiler emits warning for unhandled cases\n }\n}\n\n\nmod._validate = function(ast_obj){\n switch (ast_obj.__class__) {\n case mod.Module:\n validate_stmts(ast_obj.body);\n break;\n case mod.Interactive:\n validate_stmts(ast_obj.body);\n break;\n case mod.Expression:\n validate_expr(ast_obj.body, Load);\n break;\n case mod.FunctionType:\n validate_exprs(ast_obj.argtypes, Load, 0) &&\n validate_expr(ast_obj.returns, Load);\n break;\n // No default case so compiler emits warning for unhandled cases\n }\n}\n\n$B.imported._ast = mod\n\n}\n)(__BRYTHON__)\n"], "_base64": [".js", "(function($B){\n\nvar _b_ = $B.builtins,\n _keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"\n\nfunction make_alphabet(altchars){\n var alphabet = _keyStr\n if(altchars !== undefined && altchars !== _b_.None){\n // altchars is an instance of Python bytes\n var source = altchars.source\n alphabet = alphabet.substr(0,alphabet.length-3) +\n _b_.chr(source[0]) + _b_.chr(source[1]) + '='\n }\n return alphabet\n}\n\nvar Base64 = {\n error: function(){return 'binascii_error'},\n\n encode: function(bytes, altchars){\n\n var input = bytes.source,\n output = \"\",\n chr1, chr2, chr3, enc1, enc2, enc3, enc4\n var i = 0\n\n var alphabet = make_alphabet(altchars)\n\n while(i < input.length){\n\n chr1 = input[i++]\n chr2 = input[i++]\n chr3 = input[i++]\n\n enc1 = chr1 >> 2\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)\n enc4 = chr3 & 63\n\n if(isNaN(chr2)){\n enc3 = enc4 = 64\n }else if(isNaN(chr3)){\n enc4 = 64\n }\n\n output = output + alphabet.charAt(enc1) +\n alphabet.charAt(enc2) +\n alphabet.charAt(enc3) +\n alphabet.charAt(enc4)\n\n }\n return _b_.bytes.$factory(output, 'utf-8', 'strict')\n },\n\n\n decode: function(bytes, altchars, validate){\n var output = [],\n chr1, chr2, chr3,\n enc1, enc2, enc3, enc4\n\n var alphabet = make_alphabet(altchars)\n\n var input = bytes.source\n\n // If validate is set, check that all characters in input\n // are in the alphabet\n var _input = ''\n var padding = 0\n for(var i = 0, len = input.length; i < len; i++){\n var car = String.fromCharCode(input[i])\n var char_num = alphabet.indexOf(car)\n if(char_num == -1){\n if(validate){\n throw Base64.error(\"Non-base64 digit found: \" + car)\n }\n }else if(char_num == 64 && i < input.length - 2){\n if(validate){\n throw Base64.error(\"Non-base64 digit found: \" + car)\n }\n }else if(char_num == 64 && i >= input.length - 2){\n padding++\n _input += car\n }else{\n _input += car\n }\n }\n input = _input\n if(_input.length == padding){\n return _b_.bytes.$factory([])\n }\n if( _input.length % 4 > 0){\n throw Base64.error(\"Incorrect padding\")\n }\n\n var i = 0\n while(i < input.length){\n\n enc1 = alphabet.indexOf(input.charAt(i++))\n enc2 = alphabet.indexOf(input.charAt(i++))\n enc3 = alphabet.indexOf(input.charAt(i++))\n enc4 = alphabet.indexOf(input.charAt(i++))\n\n chr1 = (enc1 << 2) | (enc2 >> 4)\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)\n chr3 = ((enc3 & 3) << 6) | enc4\n\n output.push(chr1)\n\n if(enc3 != 64){\n output.push(chr2)\n }\n if(enc4 != 64){\n output.push(chr3)\n }\n\n }\n // return Python bytes\n return _b_.bytes.$factory(output, 'utf-8', 'strict')\n\n },\n\n _utf8_encode: function(string){\n string = string.replace(/\\r\\n/g, \"\\n\")\n var utftext = \"\";\n\n for(var n = 0; n < string.length; n++){\n\n var c = string.charCodeAt(n)\n\n if(c < 128){\n utftext += String.fromCharCode(c)\n }else if((c > 127) && (c < 2048)){\n utftext += String.fromCharCode((c >> 6) | 192)\n utftext += String.fromCharCode((c & 63) | 128)\n }else{\n utftext += String.fromCharCode((c >> 12) | 224)\n utftext += String.fromCharCode(((c >> 6) & 63) | 128)\n utftext += String.fromCharCode((c & 63) | 128)\n }\n\n }\n\n return utftext\n },\n\n _utf8_decode: function(utftext) {\n var string = \"\",\n i = 0,\n c = c1 = c2 = 0\n\n while(i < utftext.length){\n\n c = utftext.charCodeAt(i)\n\n if(c < 128){\n string += String.fromCharCode(c)\n i++\n }else if((c > 191) && (c < 224)){\n c2 = utftext.charCodeAt(i + 1)\n string += String.fromCharCode(((c & 31) << 6) | (c2 & 63))\n i += 2\n }else{\n c2 = utftext.charCodeAt(i + 1)\n c3 = utftext.charCodeAt(i + 2)\n string += String.fromCharCode(\n ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))\n i += 3\n }\n\n }\n\n return string\n }\n\n}\n\n$B.addToImported('_base64', {Base64:Base64})\n}\n\n)(__BRYTHON__)"], "_binascii": [".js", "(function($B){\n\nvar _b_ = $B.builtins,\n _keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"\n\nvar error = $B.make_class(\"error\", _b_.Exception.$factory)\nerror.__bases__ = [_b_.Exception]\n$B.set_func_names(error, \"binascii\")\n\nfunction decode(bytes, altchars, validate){\n var output = [],\n chr1, chr2, chr3,\n enc1, enc2, enc3, enc4\n\n var alphabet = make_alphabet(altchars)\n\n var input = bytes.source\n\n // If validate is set, check that all characters in input\n // are in the alphabet\n var _input = ''\n var padding = 0\n for(var i = 0, len = input.length; i < len; i++){\n var car = String.fromCharCode(input[i])\n var char_num = alphabet.indexOf(car)\n if(char_num == -1){\n if(validate){\n throw error.$factory(\"Non-base64 digit found: \" + car)\n }\n }else if(char_num == 64 && i < input.length - 2){\n if(validate){\n throw error.$factory(\"Non-base64 digit found: \" + car)\n }\n }else if(char_num == 64 && i >= input.length - 2){\n padding++\n _input += car\n }else{\n _input += car\n }\n }\n input = _input\n if(_input.length == padding){\n return _b_.bytes.$factory([])\n }\n if( _input.length % 4 > 0){\n throw error.$factory(\"Incorrect padding\")\n }\n\n var i = 0\n while(i < input.length){\n\n enc1 = alphabet.indexOf(input.charAt(i++))\n enc2 = alphabet.indexOf(input.charAt(i++))\n enc3 = alphabet.indexOf(input.charAt(i++))\n enc4 = alphabet.indexOf(input.charAt(i++))\n\n chr1 = (enc1 << 2) | (enc2 >> 4)\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)\n chr3 = ((enc3 & 3) << 6) | enc4\n\n output.push(chr1)\n\n if(enc3 != 64){output.push(chr2)}\n if(enc4 != 64){output.push(chr3)}\n\n }\n // return Python bytes\n return _b_.bytes.$factory(output)\n}\n\n\nvar hex2int = {},\n hex = '0123456789abcdef'\nfor(var i = 0; i < hex.length; i++){\n hex2int[hex[i]] = i\n hex2int[hex[i].toUpperCase()] = i\n}\n\nfunction make_alphabet(altchars){\n var alphabet = _keyStr\n if(altchars !== undefined && altchars !== _b_.None){\n // altchars is an instance of Python bytes\n var source = altchars.source\n alphabet = alphabet.substr(0,alphabet.length-3) +\n _b_.chr(source[0]) + _b_.chr(source[1]) + '='\n }\n return alphabet\n}\n\nvar module = {\n a2b_base64: function(){\n var $ = $B.args(\"a2b_base64\", 2, {s: null, strict_mode: null},\n ['s', 'strict_mode'],\n arguments, {strict_mode: false}, null, null)\n var bytes\n if($B.$isinstance($.s, _b_.str)){\n bytes = _b_.str.encode($.s, 'ascii')\n }else if($B.$isinstance($.s, [_b_.bytes, _b_.bytearray])){\n bytes = $.s\n }else{\n throw _b_.TypeError.$factory('wrong type: ' + $B.class_name($.s))\n }\n return decode(bytes)\n },\n a2b_hex: function(){\n var $ = $B.args(\"a2b_hex\", 1, {s: null}, ['s'],\n arguments, {}, null, null),\n s = $.s\n if($B.$isinstance(s, _b_.bytes)){\n s = _b_.bytes.decode(s, 'ascii')\n }\n if(typeof s !== \"string\"){\n throw _b_.TypeError.$factory(\"argument should be bytes, \" +\n \"buffer or ASCII string, not '\" + $B.class_name(s) + \"'\")\n }\n\n var len = s.length\n if(len % 2 == 1){\n throw _b_.TypeError.$factory('Odd-length string')\n }\n\n var res = []\n for(var i = 0; i < len; i += 2){\n res.push((hex2int[s.charAt(i)] << 4) + hex2int[s.charAt(i + 1)])\n }\n return _b_.bytes.$factory(res)\n },\n b2a_base64: function(){\n var $ = $B.args(\"b2a_base64\", 1, {data: null}, ['data'],\n arguments, {}, null, \"kw\")\n var newline = _b_.dict.$get_string($.kw, 'newline', false)\n\n var string = $B.to_bytes($.data),\n res = btoa(String.fromCharCode.apply(null, string))\n if(newline){\n res += \"\\n\"\n }\n return _b_.bytes.$factory(res, \"ascii\")\n },\n b2a_hex: function(obj){\n var string = $B.to_bytes(obj),\n res = []\n function conv(c){\n if(c > 9){\n c = c + 'a'.charCodeAt(0) - 10\n }else{\n c = c + '0'.charCodeAt(0)\n }\n return c\n }\n string.forEach(function(char){\n res.push(conv((char >> 4) & 0xf))\n res.push(conv(char & 0xf))\n })\n return _b_.bytes.$factory(res)\n },\n b2a_uu: function(obj){\n var string = _b_.bytes.decode(obj, 'ascii')\n var len = string.length,\n res = String.fromCharCode((0x20 + len) & 0x3F)\n while(string.length > 0){\n var s = string.slice(0, 3)\n while(s.length < 3){s.push(String.fromCharCode(0))}\n var A = s[0],\n B = s[1],\n C = s[2]\n var a = (A >> 2) & 0x3F,\n b = ((A << 4) | ((B >> 4) & 0xF)) & 0x3F,\n c = (((B << 2) | ((C >> 6) & 0x3)) & 0x3F),\n d = C & 0x3F\n res += String.fromCharCode(0x20 + a, 0x20 + b, 0x20 + c, 0x20 + d)\n string = string.slice(3)\n }\n return _b_.bytes.$factory(res + \"\\n\", \"ascii\")\n },\n error: error\n}\n\nmodule.hexlify = module.b2a_hex\nmodule.unhexlify = module.a2b_hex\n\n$B.imported._binascii = module\n}\n)(__BRYTHON__)"], "_io_classes": [".js", "var _b_ = __BRYTHON__.builtins\n\nfunction get_self(name, args){\n return $B.args(name, 1, {self: null}, [\"self\"], args, {}, null, null).self\n}\n\nvar _IOBase = $B.make_class(\"_IOBase\")\n_IOBase.__mro__ = [_b_.object]\n\n_IOBase.close = function(){\n get_self(\"close\", arguments).__closed = true\n}\n\n_IOBase.flush = function(){\n get_self(\"flush\", arguments)\n return _b_.None\n}\n\n$B.set_func_names(_IOBase, '_io')\n\n// Base class for binary streams that support some kind of buffering.\nvar _BufferedIOBase = $B.make_class(\"_BufferedIOBase\")\n_BufferedIOBase.__mro__ = [_IOBase, _b_.object]\n\n_BufferedIOBase.__enter__ = function(self){\n return self\n}\n_BufferedIOBase.__exit__ = function(self, type, value, traceback){\n try{\n $B.$call($B.$getattr(self, 'close'))()\n self.__closed = true\n return true\n }catch(err){\n return false\n }\n}\n\n$B.set_func_names(_BufferedIOBase, '_io')\n\n// Base class for raw binary I/O.\nvar _RawIOBase = $B.make_class(\"_RawIOBase\")\n\n_RawIOBase.__mro__ = [_IOBase, _b_.object]\n\n_RawIOBase.read = function(){\n var $ = $B.args(\"read\", 2, {self: null, size: null}, [\"self\", \"size\"],\n arguments, {size: -1}, null, null),\n self = $.self,\n size = $.size,\n res\n self.$pos = self.$pos || 0\n if(size == -1){\n if(self.$pos == 0){\n res = self.$content\n }else{\n res = _b_.bytes.$factory(self.$content.source.slice(self.$pos))\n }\n self.$pos = self.$content.source.length - 1\n }else{\n res = _b_.bytes.$factory(self.$content.source.slice(self.$pos, size))\n self.$pos += size\n }\n return res\n}\n\n_RawIOBase.readall = function(){\n return _RawIOBase.read(get_self(\"readall\", arguments))\n}\n\n$B.set_func_names(_RawIOBase, '_io')\n\n// Base class for text streams.\n_TextIOBase = $B.make_class(\"_TextIOBase\")\n_TextIOBase.__mro__ = [_IOBase, _b_.object]\n\nvar StringIO = $B.make_class(\"StringIO\",\n function(){\n var $ = $B.args(\"StringIO\", 2, {value: null, newline: null},\n [\"value\", \"newline\"], arguments, {value: '', newline: \"\\n\"},\n null, null)\n return {\n __class__: StringIO,\n $counter: 0,\n $content: $.value\n }\n }\n)\n\nStringIO.__mro__ = [$B.Reader, _b_.object]\n\nStringIO.getvalue = function(){\n var $ = $B.args(\"getvalue\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n return $.self.$content.substr(0) // copy\n}\n\nStringIO.truncate = function(self, size){\n var $ = $B.args('truncate', 2, {self: null, size: null}, ['self', 'size'],\n arguments, {size: _b_.None}, null, null),\n self = $.self,\n size = $.size\n if(size === _b_.None){\n size = self.$counter\n }\n self.$content = self.$content.substr(0, size)\n self.$counter = self.$content.length\n return self.$counter\n}\n\nStringIO.write = function(){\n var $ = $B.args(\"write\", 2, {self: null, data: null},\n [\"self\", \"data\"], arguments, {}, null, null)\n if(! $B.$isinstance($.data, _b_.str)){\n throw _b_.TypeError.$factory('string argument expected, got ' +\n `'${$B.class_name($.data)}'`)\n }\n var text = $.self.$content,\n position = $.self.$counter\n if(position > text.length){\n text += String.fromCodePoint(0).repeat(position - text.length)\n }\n text = text.substr(0, position) + $.data +\n text.substr(position + $.data.length)\n $.self.$content = text\n $.self.$counter = position + $.data.length\n return $.data.length\n}\n\n$B.set_func_names(StringIO, \"_io\")\n\nvar BytesIO = $B.make_class(\"BytesIO\",\n function(){\n var $ = $B.args(\"BytesIO\", 1, {value: null},\n [\"value\"], arguments, {value: _b_.bytes.$factory()},\n null, null)\n return {\n __class__: BytesIO,\n $binary: true,\n $content: $.value,\n $length: $.value.source.length,\n $counter: 0\n }\n }\n)\nBytesIO.__mro__ = [$B.Reader, _b_.object]\n\nBytesIO.getbuffer = function(){\n var self = get_self(\"getbuffer\", arguments)\n return _b_.memoryview.$factory(self.$content)\n}\n\nBytesIO.getvalue = function(){\n var self = get_self(\"getvalue\", arguments)\n return self.$content\n}\n\nBytesIO.read = function(){\n var $ = $B.args(\"read\", 2, {self: null, nbytes: null},\n [\"self\", \"nbytes\"], arguments, {nbytes: _b_.None}, null, null),\n self = $.self,\n nbytes = $.nbytes,\n res\n var source = self.$content.source\n if(nbytes === _b_.None){\n res = $B.fast_bytes(source.slice(self.$counter))\n self.$counter = source.length\n }else if(! _b_.isinstance(nbytes, _b_.int)){\n throw _b_.TypeError.$factory('number of bytes should be int, not ' +\n $B.class_name(nbytes))\n }else{\n res = $B.fast_bytes(source.slice(self.$counter,\n self.$counter + nbytes))\n self.$counter = Math.min(self.$counter + nbytes, source.length)\n }\n return res\n}\n\nBytesIO.write = function(){\n var $ = $B.args(\"write\", 2, {self: null, data: null},\n [\"self\", \"data\"], arguments, {}, null, null)\n var data_cls = $B.get_class($.data)\n if(! data_cls.$buffer_protocol){\n throw _b_.TypeError.$factory('a bytes-like object is required, ' +\n `not '${$B.class_name($.data)}'`)\n }\n var source = $.self.$content.source,\n counter = $.self.$counter,\n data = _b_.bytes.$factory($.data)\n if(counter > source.length){\n // pad with 0's\n var padding = (new Array(counter - source.length)).fill(0)\n source.splice(source.length, 0, ...padding)\n }\n source.splice(counter, data.source.length, ...data.source)\n $.self.$counter += data.source.length\n return _b_.None\n}\n\n$B.set_func_names(BytesIO, \"_io\")\n\nvar BlockingIOError = $B.make_class('BlockingIOError')\nBlockingIOError.__bases__ = [_b_.OSError]\n\n$B.set_func_names(BlockingIOError, '_io')\n\nvar $module = (function($B){\n return {\n _BufferedIOBase,\n _IOBase,\n _RawIOBase,\n _TextIOBase: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n BlockingIOError,\n BytesIO: BytesIO,\n FileIO: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n StringIO: StringIO,\n BufferedReader: $B.BufferedReader,\n BufferedWriter: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n BufferedRWPair: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n BufferedRandom: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n IncrementalNewlineDecoder: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n TextIOWrapper: $B.TextIOWrapper\n }\n})(__BRYTHON__)\n$module._IOBase.__doc__ = \"_IOBase\"\n\n__BRYTHON__.imported._io_classes = $module"], "_json": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nfunction simple(obj){\n switch(typeof obj){\n case 'string':\n case 'number':\n case 'boolean':\n return true\n }\n if(obj instanceof Number ||\n Array.isArray(obj) ||\n $B.$isinstance(obj, [_b_.list, _b_.tuple, _b_.dict])){\n return true\n }\n return false\n}\n\nfunction to_json(obj, level){\n var $defaults = {skipkeys:_b_.False, ensure_ascii:_b_.True,\n check_circular:_b_.True, allow_nan:_b_.True, cls:_b_.None,\n indent:_b_.None, separators:_b_.None, \"default\":_b_.None,\n sort_keys:_b_.False},\n $ = $B.args(\"to_json\", 2, {obj: null, level: null}, ['obj', 'level'],\n arguments, {level: 1}, null, \"kw\")\n\n var kw = _b_.dict.$to_obj($.kw)\n for(var key in $defaults){\n if(! kw.hasOwnProperty(key)){\n kw[key] = $defaults[key]\n }\n }\n\n var indent = kw.indent,\n ensure_ascii = kw.ensure_ascii,\n separators = kw.separators === _b_.None ?\n kw.indent === _b_.None ? [', ', ': '] : [',', ': '] :\n kw.separators,\n skipkeys = kw.skipkeys,\n _default = kw.default,\n sort_keys = kw.sort_keys,\n allow_nan = kw.allow_nan,\n check_circular = kw.check_circular\n\n var item_separator = separators[0],\n key_separator = separators[1]\n if(indent !== _b_.None){\n var indent_str\n if(typeof indent == \"string\"){\n indent_str = indent\n }else if(typeof indent == \"number\" && indent >= 1){\n indent_str = \" \".repeat(indent)\n }else{\n throw _b_.ValueError.$factory(\"invalid indent: \" +\n _b_.str.$factory(indent))\n }\n }\n var kwarg = {$kw: [{}]}\n for(var key in kw){\n kwarg.$kw[0][key] = kw[key]\n }\n\n switch(typeof obj){\n case 'string':\n var res = JSON.stringify(obj)\n if(ensure_ascii){\n var escaped = ''\n for(var i = 0, len = res.length; i < len; i++){\n var u = res.codePointAt(i)\n if(u > 127){\n u = u.toString(16)\n while(u.length < 4){\n u = \"0\" + u\n }\n escaped += '\\\\u' + u\n }else{\n escaped += res.charAt(i)\n }\n }\n return escaped\n }\n return res\n case 'boolean':\n return obj.toString()\n case 'number':\n if([Infinity, -Infinity].indexOf(obj) > -1 ||\n isNaN(obj)){\n if(! allow_nan){\n throw _b_.ValueError.$factory(\n 'Out of range float values are not JSON compliant')\n }\n }\n return obj.toString()\n }\n if(obj instanceof String){\n if(! ensure_ascii){\n return $B.String(obj)\n }\n // string with surrogate pairs. cf. issue #1903.\n var res = ''\n if(obj.surrogates){\n var s_ix = 0,\n s_pos = obj.surrogates[s_ix]\n for(var i = 0, len = obj.length; i < len; i++){\n if(i == s_pos){\n var code = obj.codePointAt(i) - 0x10000\n res += '\\\\u' + (0xD800 | (code >> 10)).toString(16) +\n '\\\\u' + (0xDC00 | (code & 0x3FF)).toString(16)\n i++\n s_ix++\n s_pos = obj.surrogates[s_ix]\n }else{\n var code = obj.charCodeAt(i)\n if(code < 127){\n var x = _b_.repr(obj[i])\n res += x.substr(1, x.length - 2)\n }else{\n var x = code.toString(16)\n while(x.length < 4){\n x = '0' + x\n }\n res += '\\\\u' + x\n }\n }\n }\n }\n return '\"' + res.replace(new RegExp('\"', \"g\"), '\\\\\"') + '\"'\n }\n\n if($B.$isinstance(obj, _b_.list)){\n var res = []\n var sep = item_separator,\n first = '[',\n last = ']'\n if(indent !== _b_.None){\n sep += \"\\n\" + indent_str.repeat(level)\n first = '[' + '\\n' + indent_str.repeat(level)\n last = '\\n' + indent_str.repeat(level - 1) + ']'\n level++\n }\n for(var i = 0, len = obj.length; i < len; i++){\n res.push(to_json(obj[i], level, kwarg))\n }\n return first + res.join(sep) + last\n }else if($B.$isinstance(obj, _b_.float)){\n return obj.value\n }else if(obj.__class__ === $B.long_int){\n return obj.value.toString()\n }else if(obj === _b_.None){\n return \"null\"\n }else if($B.$isinstance(obj, _b_.dict)){\n var res = [],\n items = Array.from($B.make_js_iterator(_b_.dict.items(obj)))\n if(sort_keys){\n // Sort keys by alphabetical order\n items.sort()\n }\n var sep = item_separator,\n first = '{',\n last = '}'\n if(indent !== _b_.None){\n sep += \"\\n\" + indent_str.repeat(level)\n first = '{' + '\\n' + indent_str.repeat(level)\n last = '\\n' + indent_str.repeat(level - 1) + '}'\n level++\n }\n for(var i = 0, len = items.length; i < len; i++){\n var item = items[i]\n if(! simple(item[0])){\n if(! skipkeys){\n throw _b_.TypeError.$factory(\"keys must be str, int, \" +\n \"float, bool or None, not \" + $B.class_name(obj))\n }\n }else{\n // In the result, key must be a string\n var key = _b_.str.$factory(item[0])\n // Check circular reference\n if(check_circular && $B.repr.enter(item[1])){\n throw _b_.ValueError.$factory(\"Circular reference detected\")\n }\n res.push(\n [to_json(key, level, kwarg), to_json(item[1], level, kwarg)].\n join(key_separator))\n if(check_circular){\n $B.repr.leave(item[1])\n }\n }\n }\n return first + res.join(sep) + last\n }\n // For other types, use function default if provided\n if(_default == _b_.None){\n throw _b_.TypeError.$factory(\"Object of type \" + $B.class_name(obj) +\n \" is not JSON serializable\")\n }else{\n return to_json($B.$call(_default)(obj), level, kwarg)\n }\n}\n\nfunction loads(s){\n var args = []\n for(var i = 1, len = arguments.length; i < len; i++){\n args.push(arguments[i])\n }\n var decoder = JSONDecoder.$factory.apply(null, args)\n return JSONDecoder.decode(decoder, s)\n}\n\nfunction to_py(obj, kw){\n // Conversion to Python objects\n // kw are the keyword arguments to loads()\n var res\n if(obj instanceof List){\n return $B.$list(obj.items.map(x => to_py(x, kw)))\n }else if(obj instanceof Dict){\n if(kw.object_pairs_hook !== _b_.None){\n var pairs = []\n for(var i = 0, len = obj.keys.length; i < len; i++){\n pairs.push($B.fast_tuple([obj.keys[i],\n to_py(obj.values[i], kw)]))\n }\n return $B.$call(kw.object_pairs_hook)(pairs)\n }else{\n var dict = $B.empty_dict()\n for(var i = 0, len = obj.keys.length; i < len; i++){\n _b_.dict.$setitem(dict, obj.keys[i], to_py(obj.values[i], kw))\n }\n return kw.object_hook === _b_.None ? dict :\n $B.$call(kw.object_hook)(dict)\n }\n }else if(obj.type == 'str'){\n return obj.value\n }else if(obj.type == 'num'){\n if(obj.value.search(/[.eE]/) > -1){\n // float\n if(kw.parse_float !== _b_.None){\n return $B.$call(kw.parse_float)(obj.value)\n }\n return $B.fast_float(parseFloat(obj.value))\n }else{\n // integer\n if(kw.parse_int !== _b_.None){\n return $B.$call(kw.parse_int)(obj.value)\n }\n var int = parseInt(obj.value)\n if(Math.abs(int) < $B.max_int){\n return int\n }else{\n return $B.fast_long_int(BigInt(obj.value))\n }\n }\n }else{\n if(obj instanceof Number && kw.parse_float !== _b_.None){\n return $B.$call(kw.parse_float)(obj)\n }else if(kw.parse_int !== _b_.None &&\n (typeof obj == 'number' || obj.__class__ === $B.long_int)){\n return $B.$call(kw.parse_int)(obj)\n }else if(kw.parse_constant !== _b_.None && ! isFinite(obj)){\n return kw.parse_constant(obj)\n }\n return obj\n }\n}\n\nvar escapes = {'n': '\\n',\n 't': '\\t',\n 'b': '\\b',\n 'r': '\\r',\n 'f': '\\f',\n '\\\\': '\\\\',\n '\"': '\\\"',\n \"'\": \"\\\\'\",\n '/': '/'\n }\n\nfunction string_at(s, i){\n var error = $B.$call($B.imported[\"json\"].JSONDecodeError)\n\n var j = i + 1,\n escaped = false,\n len = s.length,\n value = ''\n while(j < len){\n if(s[j] == '\"' && ! escaped){\n return [{type: 'str', value}, j + 1]\n }else if(! escaped && s[j] == '\\\\'){\n escaped = ! escaped\n j++\n }else if(escaped){\n var esc = escapes[s[j]]\n if(esc){\n value += esc\n j++\n escaped = false\n }else if(s[j] == 'u' &&\n s.substr(j + 1, 4).match(/[0-9a-fA-f]{4}/)){\n // unicode escape\n value += String.fromCharCode(parseInt(s.substr(j + 1, 4), 16))\n j += 5\n escaped = ! escaped\n }else{\n throw error('invalid escape \"' + s[j] + '\"', s, j)\n }\n }else{\n value += s[j]\n j++\n }\n }\n}\n\nfunction to_num(num_string, nb_dots, exp){\n // convert to correct Brython type\n if(exp || nb_dots){\n return new Number(num_string)\n }else{\n var int = parseInt(num_string)\n if(Math.abs(int) < $B.max_int){\n return int\n }else{\n if(num_string.startsWith('-')){\n return $B.fast_long_int(num_string.substr(1), false)\n }else{\n return $B.fast_long_int(num_string, true)\n }\n }\n }\n}\n\nfunction num_at(s, i){\n var res = s[i],\n j = i + 1,\n nb_dots = 0,\n exp = false,\n len = s.length\n while(j < len){\n if(s[j].match(/\\d/)){\n j++\n }else if(s[j] == '.' && nb_dots == 0){\n nb_dots++\n j++\n }else if('eE'.indexOf(s[j]) > -1 && ! exp){\n exp = ! exp\n j++\n }else if(s[j] == '-' && 'eE'.includes(s[j-1])){\n j++\n }else{\n return [{type: 'num', value: s.substring(i, j)}, j]\n }\n }\n return [{type: 'num', value: s.substring(i, j)}, j]\n}\n\nvar JSONError = $B.make_class('json.decoder.JSONError')\nJSONError.__bases__ = [_b_.Exception]\nJSONError.__mro__ = _b_.type.mro(JSONError)\n\n\nfunction* tokenize(s){\n var i = 0,\n len = s.length,\n line_num = 1,\n column_start = 0,\n value,\n end\n while(i < len){\n if(s[i] == \" \" || s[i] == '\\r' || s[i] == '\\n' || s[i] == '\\t'){\n i++\n line_num++\n column_start = i\n }else if('[]{}:,'.indexOf(s[i]) > -1){\n yield [s[i], i]\n i++\n }else if(s.substr(i, 4) == 'null'){\n yield [_b_.None , i]\n i += 4\n }else if(s.substr(i, 4) == 'true'){\n yield [true, i]\n i += 4\n }else if(s.substr(i, 5) == 'false'){\n yield [false, i]\n i += 5\n }else if(s.substr(i, 8) == 'Infinity'){\n yield [{type: 'num', value: 'Infinity'}, i]\n i += 8\n }else if(s.substr(i, 9) == '-Infinity'){\n yield [{type: 'num', value: '-Infinity'}, i]\n i += 9\n }else if(s.substr(i, 3) == 'NaN'){\n yield [{type: 'num', value: 'NaN'}, i]\n i += 3\n }else if(s[i] == '\"'){\n value = string_at(s, i)\n yield value\n i = value[1]\n }else if(s[i].match(/\\d/) || s[i] == '-'){\n value = num_at(s, i)\n yield value\n i = value[1]\n }else{\n throw $B.$call(JSONError)('Extra data: ' +\n `line ${line_num} column ${1 + i - column_start}`)\n }\n }\n}\n\nfunction Node(parent){\n this.parent = parent\n if(parent instanceof List){\n this.list = parent.items\n }else if(parent instanceof Dict){\n this.list = parent.values\n }else if(parent === undefined){\n this.list = []\n }\n}\n\nNode.prototype.transition = function(token){\n if([true, false, _b_.None].includes(token) ||\n ['str', 'num'].includes(token.type)){\n if(this.parent === undefined &&\n (this.list.length > 0 || this.content)){\n throw Error('Extra data')\n }\n this.list.push(token)\n return this.parent ? this.parent : this\n }else if(token == '{'){\n if(this.parent === undefined){\n this.content = new Dict(this)\n return this.content\n }\n return new Dict(this.parent)\n }else if(token == '['){\n if(this.parent === undefined){\n this.content = new List(this)\n return this.content\n }\n return new List(this.parent)\n }else{\n throw Error('unexpected item:' + token)\n }\n}\n\nfunction Dict(parent){\n this.parent = parent\n this.keys = []\n this.values = []\n this.expect = 'key'\n if(parent instanceof List){\n parent.items.push(this)\n }else if(parent instanceof Dict){\n parent.values.push(this)\n }\n}\n\nDict.prototype.transition = function(token){\n if(this.expect == 'key'){\n if(token.type == 'str'){\n this.keys.push(token.value)\n this.expect = ':'\n return this\n }else if(token == '}' && this.keys.length == 0){\n return this.parent\n }else{\n throw Error('expected str')\n }\n }else if(this.expect == ':'){\n if(token == ':'){\n this.expect = '}'\n return new Node(this)\n }else{\n throw Error('expected :')\n }\n }else if(this.expect == '}'){\n if(token == '}'){\n return this.parent\n }else if(token == ','){\n this.expect = 'key'\n return this\n }\n throw Error('expected }')\n }\n}\n\nfunction List(parent){\n if(parent instanceof List){\n parent.items.push(this)\n }\n this.parent = parent\n this.items = []\n this.expect = 'item'\n}\n\nList.prototype.transition = function(token){\n if(this.expect == 'item'){\n this.expect = ','\n if([true, false, _b_.None].indexOf(token) > -1){\n this.items.push(token)\n return this\n }else if(token.type == 'num' || token.type == 'str'){\n this.items.push(token)\n return this\n }else if(token == '{'){\n return new Dict(this)\n }else if(token == '['){\n return new List(this)\n }else if(token == ']'){\n if(this.items.length == 0){\n if(this.parent instanceof Dict){\n this.parent.values.push(this)\n }\n return this.parent\n }\n throw Error('unexpected ]')\n }else{\n console.log('token', token)\n throw Error('unexpected item:' + token)\n }\n\n }else if(this.expect == ','){\n this.expect = 'item'\n if(token == ','){\n return this\n }else if(token == ']'){\n if(this.parent instanceof Dict){\n this.parent.values.push(this)\n }\n return this.parent\n }else{\n throw Error('expected :')\n }\n }\n}\n\nfunction parse(s){\n var res,\n state,\n node = new Node(),\n root = node,\n token\n for(var item of tokenize(s)){\n token = item[0]\n try{\n node = node.transition(token)\n }catch(err){\n console.log('error, item', item)\n console.log(err, err.message)\n console.log('node', node)\n if(err.__class__){\n throw err\n }else{\n var error = $B.$call($B.imported[\"json\"].JSONDecodeError)\n throw error(err.message, s, item[1])\n }\n }\n }\n return root.content ? root.content : root.list[0]\n}\n\nvar JSONDecoder = $B.make_class(\"JSONDecoder\",\n function(){\n var $defaults = {cls: _b_.None, object_hook: _b_.None,\n parse_float: _b_.None, parse_int: _b_.None,\n parse_constant: _b_.None, object_pairs_hook: _b_.None},\n $ = $B.args(\"decode\", 0, {}, [], arguments, {}, null, \"kw\")\n var kw = _b_.dict.$to_obj($.kw)\n for(var key in $defaults){\n if(kw[key] === undefined){\n kw[key] = $defaults[key]\n }\n }\n return {\n __class__: JSONDecoder,\n object_hook: kw.object_hook,\n parse_float: kw.parse_float,\n parse_int: kw.parse_int,\n parse_constant: kw.parse_constant,\n object_pairs_hook: kw.object_pairs_hook,\n memo: $B.empty_dict()\n }\n }\n)\n\nJSONDecoder.decode = function(self, s){\n return to_py(parse(s), self)\n}\n\n$B.imported._json = {\n dumps: function(){\n return _b_.str.$factory(to_json.apply(null, arguments))\n },\n loads,\n JSONDecoder\n}\n\n})(__BRYTHON__)"], "_jsre": [".js", "(function($B){\n\n var _b_ = $B.builtins\n\n var MatchObject = $B.make_class(\"Match\",\n function(jsmatch, string, pattern){\n return {\n __class__: MatchObject,\n jsmatch: jsmatch,\n string: string\n }\n }\n )\n MatchObject.item = function(self, rank){\n return self.jsmatch[rank]\n }\n MatchObject.group = function(self){\n var res = []\n for(var i = 0, _len_i = arguments.length; i < _len_i; i++){\n if(self.jsmatch[arguments[i]] === undefined){res.push(_b_.None)}\n else{res.push(self.jsmatch[arguments[i]])}\n }\n if(arguments.length == 1){return res[0]}\n return _b_.tuple.$factory(res)\n }\n MatchObject.groups = function(self, _default){\n if(_default === undefined){_default = _b_.None}\n var res = []\n for(var i = 1, _len_i = self.length; i < _len_i; i++){\n if(self.jsmatch[i] === undefined){res.push(_default)}\n else{res.push(self.jsmatch[i])}\n }\n return _b_.tuple.$factory(res)\n }\n MatchObject.start = function(self){\n return self.index\n }\n MatchObject.end = function(self){\n return self.length - self.index\n }\n\n $B.set_func_names(MatchObject, '_jsre')\n\n var obj = {\n __str__: function(){return \"\"}\n }\n obj.A = obj.ASCII = 256\n obj.I = obj.IGNORECASE = 2 // 'i'\n obj.L = obj.LOCALE = 4\n obj.M = obj.MULTILINE = 8 // 'm'\n obj.S = obj.DOTALL = 16\n obj.U = obj.UNICODE = 32\n obj.X = obj.VERBOSE = 64\n obj._is_valid = function(pattern) {\n if ($B.$options.re == 'pyre'){return false} //force use of python's re module\n if ($B.$options.re == 'jsre'){return true} //force use of brythons re module\n // FIXME: Improve\n\n if(! $B.$isinstance(pattern, _b_.str)){\n // this is probably a SRE_PATTERN, so return false, and let\n // python's re module handle this.\n return false\n }\n var is_valid = false\n try{\n new RegExp(pattern)\n is_valid = true\n }\n catch(e){}\n if(! is_valid){return false} //if js won't parse the pattern return false\n\n // using reference http://www.regular-expressions.info/\n // to compare python re and javascript regex libraries\n\n // look for things javascript does not support\n // check for name capturing group\n var mylist = ['?P=', '?P<', '(?#', '(?<=', '(? -1) return false\n }\n\n var re_list=['\\{,\\d+\\}']\n for(var i=0, _len_i = re_list.length; i < _len_i; i++) {\n var _re = new RegExp(re_list[i])\n if (_re.test(pattern)){return false}\n }\n\n // it looks like the pattern has passed all our tests so lets assume\n // javascript can handle this pattern.\n return true\n }\n var $SRE_PatternDict = {\n __class__:_b_.type,\n $infos:{\n __name__:'SRE_Pattern'\n }\n }\n $SRE_PatternDict.__mro__ = [_b_.object]\n $SRE_PatternDict.findall = function(self, string){\n return obj.findall(self.pattern, string, self.flags)\n }\n $SRE_PatternDict.finditer = function(self, string){\n return obj.finditer(self.pattern, string, self.flags)\n }\n $SRE_PatternDict.match = function(self, string){\n return obj.match(self.pattern, string, self.flags)\n }\n $SRE_PatternDict.search = function(self, string){\n return obj.search(self.pattern, string, self.flags)\n }\n $SRE_PatternDict.sub = function(self,repl,string){\n return obj.sub(self.pattern,repl,string,self.flags)\n }\n $B.set_func_names($SRE_PatternDict, \"_jsre\")\n // TODO: groups\n // TODO: groupindex\n function normflags(flags){\n return ((flags & obj.I)? 'i' : '') + ((flags & obj.M)? 'm' : '');\n }\n // TODO: fullmatch()\n // TODO: split()\n // TODO: subn()\n obj.compile = function(pattern, flags){\n return {\n __class__: $SRE_PatternDict,\n pattern: pattern,\n flags: normflags(flags)\n }\n }\n obj.escape = function(string){\n // Escape all the characters in pattern except ASCII letters, numbers\n // and '_'. This is useful if you want to match an arbitrary literal\n // string that may have regular expression metacharacters in it.\n var res = ''\n var ok = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'\n for(var i = 0, _len_i = string.length; i < _len_i; i++){\n if(ok.search(string.charAt(i))>-1){res += string.charAt(i)}\n }\n return res\n }\n obj.findall = function(pattern, string, flags){\n var $ns=$B.args('re.findall', 2,\n {pattern:null, string:null}, ['pattern', 'string'],\n arguments,{}, 'args', 'kw') ,\n args = $ns['args'] ,\n _flags = 0;\n if(args.length>0){var flags = args[0]}\n else{var _flags = $B.$getattr($ns['kw'], 'get')('flags', 0)}\n\n var flags = normflags()\n flags += 'gm'\n var jsp = new RegExp(pattern,flags),\n jsmatch = string.match(jsp)\n if(jsmatch === null){return []}\n return jsmatch\n }\n obj.finditer = function(pattern, string, flags){\n var $ns=$B.args('re.finditer', 2,\n {pattern:null, string:null}, ['pattern', 'string'],\n arguments,{},'args','kw'),\n args = $ns['args'],\n _flags = 0;\n if(args.length>0){var flags=args[0]}\n else{var _flags = $B.$getattr($ns['kw'], 'get')('flags', 0)}\n\n var flags = normflags()\n flags += 'gm'\n var jsp = new RegExp(pattern, flags),\n jsmatch = string.match(jsp);\n if(jsmatch === null){return []}\n\n var _list = []\n for(var j = 0, _len_j = jsmatch.length; j < _len_j; j++) {\n var mo = {}\n mo._match=jsmatch[j]\n mo.group = function(){\n var res = []\n for(var i=0, _len_i = arguments.length; i < _len_i;i++){\n if(jsmatch[arguments[i]] === undefined){res.push(_b_.None)}\n else{res.push(jsmatch[arguments[i]])}\n }\n if(arguments.length == 1){return res[0]}\n return _b_.tuple.$factory(res)\n }\n mo.groups = function(_default){\n if(_default === undefined){_default = _b_.None}\n var res = []\n for(var i = 1, _len_i = jsmatch.length; i < _len_i; i++){\n if(jsmatch[i] === undefined){res.push(_default)}\n else{res.push(jsmatch[i])}\n }\n return _b_.tuple.$factory(res)\n }\n mo.start = function(){return mo._match.index}\n mo.end = function(){return mo._match.length - mo._match.index}\n mo.string = string\n _list.push(mo)\n }\n return _list\n }\n obj.search = function(pattern, string){\n var $ns = $B.args('re.search', 2,\n {pattern:null, string:null},['pattern', 'string'],\n arguments, {}, 'args', 'kw')\n var args = $ns['args']\n if(args.length>0){var flags = args[0]}\n else{var flags = $B.$getattr($ns['kw'], 'get')('flags', '')}\n flags = normflags(flags)\n var jsp = new RegExp(pattern, flags)\n var jsmatch = string.match(jsp)\n if(jsmatch === null){return _b_.None}\n return MatchObject.$factory(jsmatch, string, pattern)\n }\n obj.sub = function(pattern, repl, string){\n var $ns=$B.args('re.search', 3,\n {pattern: null, repl: null, string: null},\n ['pattern', 'repl', 'string'],\n arguments,{}, 'args', 'kw')\n for($var in $ns){eval(\"var \" + $var + \"=$ns[$var]\")}\n var args = $ns['args']\n var count = _b_.dict.get($ns['kw'], 'count', 0)\n var flags = _b_.dict.get($ns['kw'], 'flags', '')\n if(args.length > 0){var count = args[0]}\n if(args.length > 1){var flags = args[1]}\n flags = normflags(flags)\n if(typeof repl == \"string\"){\n // backreferences are \\1, \\2... in Python but $1,$2... in Javascript\n repl = repl.replace(/\\\\(\\d+)/g, '$$$1')\n }else if(typeof repl == \"function\"){\n // the argument passed to the Python function is the match object\n // the arguments passed to the Javascript function are :\n // - the matched substring\n // - the matched groups\n // - the offset of the matched substring inside the string\n // - the string being examined\n var $repl1 = function(){\n var mo = Object()\n mo.string = arguments[arguments.length - 1]\n var matched = arguments[0];\n var start = arguments[arguments.length - 2]\n var end = start + matched.length\n mo.start = function(){return start}\n mo.end = function(){return end}\n groups = []\n for(var i = 1, _len_i = arguments.length-2; i < _len_i; i++){\n groups.push(arguments[i])\n }\n mo.groups = function(_default){\n if(_default === undefined){_default = _b_.None}\n var res = []\n for(var i = 0, _len_i = groups.length; i < _len_i; i++){\n if(groups[i] === undefined){res.push(_default)}\n else{res.push(groups[i])}\n }\n return res\n }\n mo.group = function(i){\n if(i==0){return matched}\n return groups[i-1]\n }\n return repl(mo)\n }\n }\n if(count == 0){flags += 'g'}\n var jsp = new RegExp(pattern, flags)\n if(typeof repl == 'function'){return string.replace(jsp, $repl1)}\n else{return string.replace(jsp, repl)}\n }\n obj.match = (function(search_func){\n return function(){\n // match is like search but pattern must start with ^\n var pattern = arguments[0]\n if(pattern.charAt(0) != '^'){pattern = '^'+pattern}\n var args = [pattern]\n for(var i = 1, _len_i = arguments.length; i < _len_i; i++){\n args.push(arguments[i])\n }\n return search_func.apply(null, args)\n }\n })(obj.search)\n\n $B.addToImported('_jsre', obj)\n}\n)(__BRYTHON__)\n"], "_locale": [".js", "var am = {\n \"C\": \"AM\",\n \"aa\": \"saaku\",\n \"ab\": \"AM\",\n \"ae\": \"AM\",\n \"af\": \"vm.\",\n \"ak\": \"AN\",\n \"am\": \"\\u1325\\u12cb\\u1275\",\n \"an\": \"AM\",\n \"ar\": \"\\u0635\",\n \"as\": \"\\u09f0\\u09be\\u09a4\\u09bf\\u09aa\\u09c1\",\n \"av\": \"AM\",\n \"ay\": \"AM\",\n \"az\": \"AM\",\n \"ba\": \"\",\n \"be\": \"\",\n \"bg\": \"\",\n \"bh\": \"AM\",\n \"bi\": \"AM\",\n \"bm\": \"AM\",\n \"bn\": \"AM\",\n \"bo\": \"\\u0f66\\u0f94\\u0f0b\\u0f51\\u0fb2\\u0f7c\",\n \"br\": \"A.M.\",\n \"bs\": \"prijepodne\",\n \"ca\": \"a. m.\",\n \"ce\": \"AM\",\n \"ch\": \"AM\",\n \"co\": \"\",\n \"cr\": \"AM\",\n \"cs\": \"dop.\",\n \"cu\": \"\\u0414\\u041f\",\n \"cv\": \"AM\",\n \"cy\": \"yb\",\n \"da\": \"\",\n \"de\": \"\",\n \"dv\": \"\\u0789\\u0786\",\n \"dz\": \"\\u0f66\\u0f94\\u0f0b\\u0f46\\u0f0b\",\n \"ee\": \"\\u014bdi\",\n \"el\": \"\\u03c0\\u03bc\",\n \"en\": \"AM\",\n \"eo\": \"atm\",\n \"es\": \"\",\n \"et\": \"AM\",\n \"eu\": \"AM\",\n \"fa\": \"\\u0642.\\u0638\",\n \"ff\": \"\",\n \"fi\": \"ap.\",\n \"fj\": \"AM\",\n \"fo\": \"um fyr.\",\n \"fr\": \"\",\n \"fy\": \"AM\",\n \"ga\": \"r.n.\",\n \"gd\": \"m\",\n \"gl\": \"a.m.\",\n \"gn\": \"a.m.\",\n \"gu\": \"\\u0aaa\\u0ac2\\u0ab0\\u0acd\\u0ab5\\u00a0\\u0aae\\u0aa7\\u0acd\\u0aaf\\u0abe\\u0ab9\\u0acd\\u0aa8\",\n \"gv\": \"a.m.\",\n \"ha\": \"AM\",\n \"he\": \"AM\",\n \"hi\": \"\\u092a\\u0942\\u0930\\u094d\\u0935\\u093e\\u0939\\u094d\\u0928\",\n \"ho\": \"AM\",\n \"hr\": \"\",\n \"ht\": \"AM\",\n \"hu\": \"de.\",\n \"hy\": \"\",\n \"hz\": \"AM\",\n \"ia\": \"a.m.\",\n \"id\": \"AM\",\n \"ie\": \"AM\",\n \"ig\": \"A.M.\",\n \"ii\": \"\\ua0b5\\ua1aa\\ua20c\\ua210\",\n \"ik\": \"AM\",\n \"io\": \"AM\",\n \"is\": \"f.h.\",\n \"it\": \"\",\n \"iu\": \"AM\",\n \"ja\": \"\\u5348\\u524d\",\n \"jv\": \"\",\n \"ka\": \"AM\",\n \"kg\": \"AM\",\n \"ki\": \"Kiroko\",\n \"kj\": \"AM\",\n \"kk\": \"AM\",\n \"kl\": \"\",\n \"km\": \"\\u1796\\u17d2\\u179a\\u17b9\\u1780\",\n \"kn\": \"\\u0caa\\u0cc2\\u0cb0\\u0ccd\\u0cb5\\u0cbe\\u0cb9\\u0ccd\\u0ca8\",\n \"ko\": \"\\uc624\\uc804\",\n \"kr\": \"AM\",\n \"ks\": \"AM\",\n \"ku\": \"\\u067e.\\u0646\",\n \"kv\": \"AM\",\n \"kw\": \"a.m.\",\n \"ky\": \"\",\n \"la\": \"\",\n \"lb\": \"\",\n \"lg\": \"AM\",\n \"li\": \"AM\",\n \"ln\": \"nt\\u0254\\u0301ng\\u0254\\u0301\",\n \"lo\": \"\\u0e81\\u0ec8\\u0ead\\u0e99\\u0e97\\u0ec8\\u0ebd\\u0e87\",\n \"lt\": \"prie\\u0161piet\",\n \"lu\": \"Dinda\",\n \"lv\": \"priek\\u0161p.\",\n \"mg\": \"AM\",\n \"mh\": \"AM\",\n \"mi\": \"a.m.\",\n \"mk\": \"\\u043f\\u0440\\u0435\\u0442\\u043f\\u043b.\",\n \"ml\": \"AM\",\n \"mn\": \"??\",\n \"mo\": \"AM\",\n \"mr\": \"\\u092e.\\u092a\\u0942.\",\n \"ms\": \"PG\",\n \"mt\": \"AM\",\n \"my\": \"\\u1014\\u1036\\u1014\\u1000\\u103a\",\n \"na\": \"AM\",\n \"nb\": \"a.m.\",\n \"nd\": \"AM\",\n \"ne\": \"\\u092a\\u0942\\u0930\\u094d\\u0935\\u093e\\u0939\\u094d\\u0928\",\n \"ng\": \"AM\",\n \"nl\": \"\",\n \"nn\": \"f.m.\",\n \"no\": \"a.m.\",\n \"nr\": \"AM\",\n \"nv\": \"AM\",\n \"ny\": \"AM\",\n \"oc\": \"AM\",\n \"oj\": \"AM\",\n \"om\": \"WD\",\n \"or\": \"AM\",\n \"os\": \"AM\",\n \"pa\": \"\\u0a38\\u0a35\\u0a47\\u0a30\",\n \"pi\": \"AM\",\n \"pl\": \"AM\",\n \"ps\": \"\\u063a.\\u0645.\",\n \"pt\": \"\",\n \"qu\": \"a.m.\",\n \"rc\": \"AM\",\n \"rm\": \"AM\",\n \"rn\": \"Z.MU.\",\n \"ro\": \"a.m.\",\n \"ru\": \"\",\n \"rw\": \"AM\",\n \"sa\": \"\\u092e\\u0927\\u094d\\u092f\\u093e\\u0928\\u092a\\u0942\\u0930\\u094d\\u0935\",\n \"sc\": \"AM\",\n \"sd\": \"AM\",\n \"se\": \"i.b.\",\n \"sg\": \"ND\",\n \"sh\": \"AM\",\n \"si\": \"\\u0db4\\u0dd9.\\u0dc0.\",\n \"sk\": \"AM\",\n \"sl\": \"dop.\",\n \"sm\": \"AM\",\n \"sn\": \"AM\",\n \"so\": \"sn.\",\n \"sq\": \"e paradites\",\n \"sr\": \"pre podne\",\n \"ss\": \"AM\",\n \"st\": \"AM\",\n \"su\": \"AM\",\n \"sv\": \"\",\n \"sw\": \"AM\",\n \"ta\": \"\\u0b95\\u0bbe\\u0bb2\\u0bc8\",\n \"te\": \"\\u0c2a\\u0c42\\u0c30\\u0c4d\\u0c35\\u0c3e\\u0c39\\u0c4d\\u0c28\",\n \"tg\": \"\",\n \"th\": \"AM\",\n \"ti\": \"\\u1295\\u1309\\u1206 \\u1230\\u12d3\\u1270\",\n \"tk\": \"\",\n \"tl\": \"AM\",\n \"tn\": \"AM\",\n \"to\": \"AM\",\n \"tr\": \"\\u00d6\\u00d6\",\n \"ts\": \"AM\",\n \"tt\": \"\",\n \"tw\": \"AM\",\n \"ty\": \"AM\",\n \"ug\": \"\\u0686?\\u0634\\u062a\\u0649\\u0646 \\u0628?\\u0631?\\u0646\",\n \"uk\": \"AM\",\n \"ur\": \"AM\",\n \"uz\": \"TO\",\n \"ve\": \"AM\",\n \"vi\": \"SA\",\n \"vo\": \"AM\",\n \"wa\": \"AM\",\n \"wo\": \"\",\n \"xh\": \"AM\",\n \"yi\": \"\\ua0b5\\ua1aa\\ua20c\\ua210\",\n \"yo\": \"\\u00c0\\u00e1r?`\",\n \"za\": \"AM\",\n \"zh\": \"\\u4e0a\\u5348\",\n \"zu\": \"AM\"\n}\nvar pm = {\n \"C\": \"PM\",\n \"aa\": \"carra\",\n \"ab\": \"PM\",\n \"ae\": \"PM\",\n \"af\": \"nm.\",\n \"ak\": \"EW\",\n \"am\": \"\\u12a8\\u1230\\u12d3\\u1275\",\n \"an\": \"PM\",\n \"ar\": \"\\u0645\",\n \"as\": \"\\u0986\\u09ac\\u09c7\\u09b2\\u09bf\",\n \"av\": \"PM\",\n \"ay\": \"PM\",\n \"az\": \"PM\",\n \"ba\": \"\",\n \"be\": \"\",\n \"bg\": \"\",\n \"bh\": \"PM\",\n \"bi\": \"PM\",\n \"bm\": \"PM\",\n \"bn\": \"PM\",\n \"bo\": \"\\u0f55\\u0fb1\\u0f72\\u0f0b\\u0f51\\u0fb2\\u0f7c\",\n \"br\": \"G.M.\",\n \"bs\": \"popodne\",\n \"ca\": \"p. m.\",\n \"ce\": \"PM\",\n \"ch\": \"PM\",\n \"co\": \"\",\n \"cr\": \"PM\",\n \"cs\": \"odp.\",\n \"cu\": \"\\u041f\\u041f\",\n \"cv\": \"PM\",\n \"cy\": \"yh\",\n \"da\": \"\",\n \"de\": \"\",\n \"dv\": \"\\u0789\\u078a\",\n \"dz\": \"\\u0f55\\u0fb1\\u0f72\\u0f0b\\u0f46\\u0f0b\",\n \"ee\": \"\\u0263etr\\u0254\",\n \"el\": \"\\u03bc\\u03bc\",\n \"en\": \"PM\",\n \"eo\": \"ptm\",\n \"es\": \"\",\n \"et\": \"PM\",\n \"eu\": \"PM\",\n \"fa\": \"\\u0628.\\u0638\",\n \"ff\": \"\",\n \"fi\": \"ip.\",\n \"fj\": \"PM\",\n \"fo\": \"um sein.\",\n \"fr\": \"\",\n \"fy\": \"PM\",\n \"ga\": \"i.n.\",\n \"gd\": \"f\",\n \"gl\": \"p.m.\",\n \"gn\": \"p.m.\",\n \"gu\": \"\\u0a89\\u0aa4\\u0acd\\u0aa4\\u0ab0\\u00a0\\u0aae\\u0aa7\\u0acd\\u0aaf\\u0abe\\u0ab9\\u0acd\\u0aa8\",\n \"gv\": \"p.m.\",\n \"ha\": \"PM\",\n \"he\": \"PM\",\n \"hi\": \"\\u0905\\u092a\\u0930\\u093e\\u0939\\u094d\\u0928\",\n \"ho\": \"PM\",\n \"hr\": \"\",\n \"ht\": \"PM\",\n \"hu\": \"du.\",\n \"hy\": \"\",\n \"hz\": \"PM\",\n \"ia\": \"p.m.\",\n \"id\": \"PM\",\n \"ie\": \"PM\",\n \"ig\": \"P.M.\",\n \"ii\": \"\\ua0b5\\ua1aa\\ua20c\\ua248\",\n \"ik\": \"PM\",\n \"io\": \"PM\",\n \"is\": \"e.h.\",\n \"it\": \"\",\n \"iu\": \"PM\",\n \"ja\": \"\\u5348\\u5f8c\",\n \"jv\": \"\",\n \"ka\": \"PM\",\n \"kg\": \"PM\",\n \"ki\": \"Hwa\\u0129-in\\u0129\",\n \"kj\": \"PM\",\n \"kk\": \"PM\",\n \"kl\": \"\",\n \"km\": \"\\u179b\\u17d2\\u1784\\u17b6\\u1785\",\n \"kn\": \"\\u0c85\\u0caa\\u0cb0\\u0cbe\\u0cb9\\u0ccd\\u0ca8\",\n \"ko\": \"\\uc624\\ud6c4\",\n \"kr\": \"PM\",\n \"ks\": \"PM\",\n \"ku\": \"\\u062f.\\u0646\",\n \"kv\": \"PM\",\n \"kw\": \"p.m.\",\n \"ky\": \"\",\n \"la\": \"\",\n \"lb\": \"\",\n \"lg\": \"PM\",\n \"li\": \"PM\",\n \"ln\": \"mp\\u00f3kwa\",\n \"lo\": \"\\u0eab\\u0ebc\\u0eb1\\u0e87\\u0e97\\u0ec8\\u0ebd\\u0e87\",\n \"lt\": \"popiet\",\n \"lu\": \"Dilolo\",\n \"lv\": \"p\\u0113cp.\",\n \"mg\": \"PM\",\n \"mh\": \"PM\",\n \"mi\": \"p.m.\",\n \"mk\": \"\\u043f\\u043e\\u043f\\u043b.\",\n \"ml\": \"PM\",\n \"mn\": \"?\\u0425\",\n \"mo\": \"PM\",\n \"mr\": \"\\u092e.\\u0928\\u0902.\",\n \"ms\": \"PTG\",\n \"mt\": \"PM\",\n \"my\": \"\\u100a\\u1014\\u1031\",\n \"na\": \"PM\",\n \"nb\": \"p.m.\",\n \"nd\": \"PM\",\n \"ne\": \"\\u0905\\u092a\\u0930\\u093e\\u0939\\u094d\\u0928\",\n \"ng\": \"PM\",\n \"nl\": \"\",\n \"nn\": \"e.m.\",\n \"no\": \"p.m.\",\n \"nr\": \"PM\",\n \"nv\": \"PM\",\n \"ny\": \"PM\",\n \"oc\": \"PM\",\n \"oj\": \"PM\",\n \"om\": \"WB\",\n \"or\": \"PM\",\n \"os\": \"PM\",\n \"pa\": \"\\u0a36\\u0a3e\\u0a2e\",\n \"pi\": \"PM\",\n \"pl\": \"PM\",\n \"ps\": \"\\u063a.\\u0648.\",\n \"pt\": \"\",\n \"qu\": \"p.m.\",\n \"rc\": \"PM\",\n \"rm\": \"PM\",\n \"rn\": \"Z.MW.\",\n \"ro\": \"p.m.\",\n \"ru\": \"\",\n \"rw\": \"PM\",\n \"sa\": \"\\u092e\\u0927\\u094d\\u092f\\u093e\\u0928\\u092a\\u091a\\u094d\\u092f\\u093e\\u0924\",\n \"sc\": \"PM\",\n \"sd\": \"PM\",\n \"se\": \"e.b.\",\n \"sg\": \"LK\",\n \"sh\": \"PM\",\n \"si\": \"\\u0db4.\\u0dc0.\",\n \"sk\": \"PM\",\n \"sl\": \"pop.\",\n \"sm\": \"PM\",\n \"sn\": \"PM\",\n \"so\": \"gn.\",\n \"sq\": \"e pasdites\",\n \"sr\": \"po podne\",\n \"ss\": \"PM\",\n \"st\": \"PM\",\n \"su\": \"PM\",\n \"sv\": \"\",\n \"sw\": \"PM\",\n \"ta\": \"\\u0bae\\u0bbe\\u0bb2\\u0bc8\",\n \"te\": \"\\u0c05\\u0c2a\\u0c30\\u0c3e\\u0c39\\u0c4d\\u0c28\",\n \"tg\": \"\",\n \"th\": \"PM\",\n \"ti\": \"\\u12f5\\u1215\\u122d \\u1230\\u12d3\\u1275\",\n \"tk\": \"\",\n \"tl\": \"PM\",\n \"tn\": \"PM\",\n \"to\": \"PM\",\n \"tr\": \"\\u00d6S\",\n \"ts\": \"PM\",\n \"tt\": \"\",\n \"tw\": \"PM\",\n \"ty\": \"PM\",\n \"ug\": \"\\u0686?\\u0634\\u062a\\u0649\\u0646 \\u0643?\\u064a\\u0649\\u0646\",\n \"uk\": \"PM\",\n \"ur\": \"PM\",\n \"uz\": \"TK\",\n \"ve\": \"PM\",\n \"vi\": \"CH\",\n \"vo\": \"PM\",\n \"wa\": \"PM\",\n \"wo\": \"\",\n \"xh\": \"PM\",\n \"yi\": \"\\ua0b5\\ua1aa\\ua20c\\ua248\",\n \"yo\": \"?`s\\u00e1n\",\n \"za\": \"PM\",\n \"zh\": \"\\u4e0b\\u5348\",\n \"zu\": \"PM\"\n}\n\nvar X_format = {\n \"%H:%M:%S\": [\n \"C\",\n \"ab\",\n \"ae\",\n \"af\",\n \"an\",\n \"av\",\n \"ay\",\n \"az\",\n \"ba\",\n \"be\",\n \"bg\",\n \"bh\",\n \"bi\",\n \"bm\",\n \"bo\",\n \"br\",\n \"bs\",\n \"ca\",\n \"ce\",\n \"ch\",\n \"co\",\n \"cr\",\n \"cs\",\n \"cu\",\n \"cv\",\n \"cy\",\n \"da\",\n \"de\",\n \"dv\",\n \"eo\",\n \"es\",\n \"et\",\n \"eu\",\n \"ff\",\n \"fj\",\n \"fo\",\n \"fr\",\n \"fy\",\n \"ga\",\n \"gd\",\n \"gl\",\n \"gn\",\n \"gu\",\n \"gv\",\n \"ha\",\n \"he\",\n \"hi\",\n \"ho\",\n \"hr\",\n \"ht\",\n \"hu\",\n \"hy\",\n \"hz\",\n \"ia\",\n \"ie\",\n \"ig\",\n \"ik\",\n \"io\",\n \"is\",\n \"it\",\n \"ja\",\n \"ka\",\n \"kg\",\n \"ki\",\n \"kj\",\n \"kk\",\n \"kl\",\n \"km\",\n \"kn\",\n \"kv\",\n \"kw\",\n \"ky\",\n \"la\",\n \"lb\",\n \"lg\",\n \"li\",\n \"ln\",\n \"lo\",\n \"lt\",\n \"lu\",\n \"lv\",\n \"mg\",\n \"mh\",\n \"mk\",\n \"mn\",\n \"mo\",\n \"mr\",\n \"mt\",\n \"my\",\n \"na\",\n \"nb\",\n \"nd\",\n \"ng\",\n \"nl\",\n \"nn\",\n \"no\",\n \"nr\",\n \"nv\",\n \"ny\",\n \"oj\",\n \"or\",\n \"os\",\n \"pi\",\n \"pl\",\n \"ps\",\n \"pt\",\n \"rc\",\n \"rm\",\n \"rn\",\n \"ro\",\n \"ru\",\n \"rw\",\n \"sa\",\n \"sc\",\n \"se\",\n \"sg\",\n \"sh\",\n \"sk\",\n \"sl\",\n \"sm\",\n \"sn\",\n \"sr\",\n \"ss\",\n \"st\",\n \"su\",\n \"sv\",\n \"sw\",\n \"ta\",\n \"te\",\n \"tg\",\n \"th\",\n \"tk\",\n \"tl\",\n \"tn\",\n \"tr\",\n \"ts\",\n \"tt\",\n \"tw\",\n \"ty\",\n \"ug\",\n \"uk\",\n \"uz\",\n \"ve\",\n \"vo\",\n \"wa\",\n \"wo\",\n \"xh\",\n \"yo\",\n \"za\",\n \"zh\",\n \"zu\"\n ],\n \"%i:%M:%S %p\": [\n \"aa\",\n \"ak\",\n \"am\",\n \"bn\",\n \"el\",\n \"en\",\n \"iu\",\n \"kr\",\n \"ks\",\n \"mi\",\n \"ml\",\n \"ms\",\n \"ne\",\n \"om\",\n \"sd\",\n \"so\",\n \"sq\",\n \"ti\",\n \"to\",\n \"ur\",\n \"vi\"\n ],\n \"%I:%M:%S %p\": [\n \"ar\",\n \"fa\",\n \"ku\",\n \"qu\"\n ],\n \"%p %i:%M:%S\": [\n \"as\",\n \"ii\",\n \"ko\",\n \"yi\"\n ],\n \"\\u0f46\\u0f74\\u0f0b\\u0f5a\\u0f7c\\u0f51\\u0f0b%i:%M:%S %p\": [\n \"dz\"\n ],\n \"%p ga %i:%M:%S\": [\n \"ee\"\n ],\n \"%H.%M.%S\": [\n \"fi\",\n \"id\",\n \"jv\",\n \"oc\",\n \"si\"\n ],\n \"%p %I:%M:%S\": [\n \"pa\"\n ]\n}\nvar x_format = {\n \"%m/%d/%y\": [\n \"C\"\n ],\n \"%d/%m/%Y\": [\n \"aa\",\n \"am\",\n \"bm\",\n \"bn\",\n \"ca\",\n \"co\",\n \"cy\",\n \"el\",\n \"es\",\n \"ff\",\n \"fr\",\n \"ga\",\n \"gd\",\n \"gl\",\n \"gn\",\n \"gv\",\n \"ha\",\n \"he\",\n \"id\",\n \"ig\",\n \"it\",\n \"iu\",\n \"jv\",\n \"ki\",\n \"kr\",\n \"kw\",\n \"la\",\n \"lg\",\n \"ln\",\n \"lo\",\n \"lu\",\n \"mi\",\n \"ml\",\n \"ms\",\n \"mt\",\n \"nd\",\n \"oc\",\n \"om\",\n \"pt\",\n \"qu\",\n \"rn\",\n \"sd\",\n \"sg\",\n \"so\",\n \"sw\",\n \"ti\",\n \"to\",\n \"uk\",\n \"ur\",\n \"uz\",\n \"vi\",\n \"wo\",\n \"yo\"\n ],\n \"%m/%d/%Y\": [\n \"ab\",\n \"ae\",\n \"an\",\n \"av\",\n \"ay\",\n \"bh\",\n \"bi\",\n \"ch\",\n \"cr\",\n \"cv\",\n \"ee\",\n \"en\",\n \"fj\",\n \"ho\",\n \"ht\",\n \"hz\",\n \"ie\",\n \"ik\",\n \"io\",\n \"kg\",\n \"kj\",\n \"ks\",\n \"kv\",\n \"li\",\n \"mh\",\n \"mo\",\n \"na\",\n \"ne\",\n \"ng\",\n \"nv\",\n \"ny\",\n \"oj\",\n \"pi\",\n \"rc\",\n \"sc\",\n \"sh\",\n \"sm\",\n \"su\",\n \"tl\",\n \"tw\",\n \"ty\",\n \"wa\",\n \"za\",\n \"zu\"\n ],\n \"%Y-%m-%d\": [\n \"af\",\n \"br\",\n \"ce\",\n \"dz\",\n \"eo\",\n \"ko\",\n \"lt\",\n \"mg\",\n \"nr\",\n \"rw\",\n \"se\",\n \"si\",\n \"sn\",\n \"ss\",\n \"st\",\n \"sv\",\n \"tn\",\n \"ts\",\n \"ug\",\n \"ve\",\n \"vo\",\n \"xh\"\n ],\n \"%Y/%m/%d\": [\n \"ak\",\n \"bo\",\n \"eu\",\n \"ia\",\n \"ii\",\n \"ja\",\n \"ku\",\n \"yi\",\n \"zh\"\n ],\n \"null\": [\n \"ar\",\n \"fa\",\n \"ps\",\n \"th\"\n ],\n \"%d-%m-%Y\": [\n \"as\",\n \"da\",\n \"fy\",\n \"hi\",\n \"kl\",\n \"mr\",\n \"my\",\n \"nl\",\n \"rm\",\n \"sa\",\n \"ta\"\n ],\n \"%d.%m.%Y\": [\n \"az\",\n \"cs\",\n \"de\",\n \"et\",\n \"fi\",\n \"fo\",\n \"hy\",\n \"is\",\n \"ka\",\n \"kk\",\n \"lv\",\n \"mk\",\n \"nb\",\n \"nn\",\n \"no\",\n \"os\",\n \"pl\",\n \"ro\",\n \"ru\",\n \"sq\",\n \"tg\",\n \"tr\",\n \"tt\"\n ],\n \"%d.%m.%y\": [\n \"ba\",\n \"be\",\n \"lb\"\n ],\n \"%d.%m.%Y \\u0433.\": [\n \"bg\"\n ],\n \"%d.%m.%Y.\": [\n \"bs\",\n \"hr\",\n \"sr\"\n ],\n \"%Y.%m.%d\": [\n \"cu\",\n \"mn\"\n ],\n \"%d/%m/%y\": [\n \"dv\",\n \"km\"\n ],\n \"%d-%m-%y\": [\n \"gu\",\n \"kn\",\n \"or\",\n \"pa\",\n \"te\"\n ],\n \"%Y. %m. %d.\": [\n \"hu\"\n ],\n \"%d-%b %y\": [\n \"ky\"\n ],\n \"%d. %m. %Y\": [\n \"sk\",\n \"sl\"\n ],\n \"%d.%m.%y \\u00fd.\": [\n \"tk\"\n ]\n}\n\n\n\n__BRYTHON__.imported._locale = (function($B){\n var _b_ = $B.builtins\n return {\n CHAR_MAX: 127,\n LC_ALL: 6,\n LC_COLLATE: 3,\n LC_CTYPE: 0,\n LC_MESSAGES: 5,\n LC_MONETARY: 4,\n LC_NUMERIC: 1,\n LC_TIME: 2,\n Error: _b_.ValueError,\n\n _date_format: function(spec, hour){\n var t,\n locale = __BRYTHON__.locale.substr(0, 2)\n\n if(spec == \"p\"){\n var res = hours < 12 ? am[locale] : pm[locale]\n if(res === undefined){\n throw _b_.ValueError.$factory(\"no format \" + spec + \" for locale \" +\n locale)\n }\n return res\n }\n else if(spec == \"x\"){\n t = x_format\n }else if(spec == \"X\"){\n t = X_format\n }else{\n throw _b_.ValueError.$factory(\"invalid format\", spec)\n }\n for(var key in t){\n if(t[key].indexOf(locale) > -1){\n return key\n }\n }\n throw _b_.ValueError.$factory(\"no format \" + spec + \" for locale \" +\n locale)\n },\n\n localeconv: function(){\n var conv = {'grouping': $B.$list([127]),\n 'currency_symbol': '',\n 'n_sign_posn': 127,\n 'p_cs_precedes': 127,\n 'n_cs_precedes': 127,\n 'mon_grouping': $B.$list([]),\n 'n_sep_by_space': 127,\n 'decimal_point': '.',\n 'negative_sign': '',\n 'positive_sign': '',\n 'p_sep_by_space': 127,\n 'int_curr_symbol': '',\n 'p_sign_posn': 127,\n 'thousands_sep': '',\n 'mon_thousands_sep': '',\n 'frac_digits': 127,\n 'mon_decimal_point': '',\n 'int_frac_digits': 127\n }\n var res = $B.empty_dict()\n for(var key in conv){\n _b_.dict.$setitem(res, key, conv[key])\n }\n\n return res\n },\n\n setlocale : function(){\n var $ = $B.args(\"setlocale\", 2, {category: null, locale: null},\n [\"category\", \"locale\"], arguments, {locale: _b_.None},\n null, null)\n /// XXX category is currently ignored\n if($.locale == \"\"){\n // use browser language setting, if it is set\n var LANG = ($B.language || \"\").substr(0, 2)\n if(am.hasOwnProperty(LANG)){\n $B.locale = LANG\n return LANG\n }else{\n console.log(\"Unknown locale: \" + LANG)\n }\n }else if($.locale === _b_.None){\n // return current locale\n return $B.locale\n }else{\n // Only use 2 first characters\n try{$.locale.substr(0, 2)}\n catch(err){\n throw $module.Error.$factory(\"Invalid locale: \" + $.locale)\n }\n if(am.hasOwnProperty($.locale.substr(0, 2))){\n $B.locale = $.locale\n return $.locale\n }else{\n throw $module.Error.$factory(\"Unknown locale: \" + $.locale)\n }\n }\n }\n }\n})(__BRYTHON__)\n"], "_multiprocessing": [".js", "// multiprocessing\n(function($B){\n\nvar _b_ = $B.builtins\n\nvar Process = $B.make_class('Process')\n\nvar $convert_args=function(args) {\n var _list=[]\n for(var i=0, _len_i = args.length; i < _len_i; i++) {\n var _a=args[i]\n if($B.$isinstance(_a, _b_.str)){_list.push(\"'\"+_a+\"'\")} else {_list.push(_a)}\n }\n\n return _list.join(',')\n}\n\nProcess.is_alive = function(self){return self.$alive}\n\nProcess.join = function(self, timeout){\n // need to block until process is complete\n // could probably use a addEventListener to execute all existing code\n // after this join statement\n\n self.$worker.addEventListener('message', function (e) {\n var data=e.data\n if (data.stdout != '') { // output stdout from process\n $B.stdout.write(data.stdout)\n }\n }, false);\n}\n\nProcess.run = function(self){\n //fix me\n}\n\nProcess.start = function(self){\n self.$worker.postMessage({target: self.$target,\n args: $convert_args(self.$args),\n // kwargs: self.$kwargs\n })\n self.$worker.addEventListener('error', function(e) { throw e})\n self.$alive=true\n}\n\nProcess.terminate = function(self){\n self.$worker.terminate()\n self.$alive=false\n}\n\n// variables\n//name\n//daemon\n//pid\n//exitcode\n\nProcess. $factory = function(){\n //arguments group=None, target=None, name=None, args=(), kwargs=()\n\n var $ns=$B.args('Process',0,{},[],arguments,{},null,'kw')\n var kw=$ns['kw']\n\n var target=_b_.dict.get($ns['kw'],'target', _b_.None)\n var args=_b_.dict.get($ns['kw'],'args', _b_.tuple.$factory())\n\n var worker = new Worker('/src/web_workers/multiprocessing.js')\n\n var res = {\n __class__: Process,\n $worker: worker,\n name: $ns['name'] || _b_.None,\n $target: target + '',\n $args: args,\n $alive: false\n }\n return res\n}\n\n$B.set_func_names(Process, \"multiprocessing\")\n\nvar Pool = $B.make_class(\"Pool\")\n\nPool.__enter__ = function(self){}\nPool.__exit__ = function(self){}\n\nPool.__str__ = Pool.toString = Pool.__repr__=function(self){\n return ''\n}\n\nPool.map = function(){\n\n var $ns=$B.args('Pool.map', 3,\n {self:null, func:null, fargs:null}, ['self', 'func', 'fargs'],\n arguments,{},'args','kw')\n var func = $ns['func']\n var fargs = $ns['fargs']\n\n var _results = []\n\n fargs = _b_.iter(fargs)\n\n var _pos = 0\n var _workers =[]\n for(var i=0; i < self.$processes; i++) {\n _workers[i] = new Worker('/src/web_workers/multiprocessing.js')\n var arg\n\n try{\n arg = $B.$getattr(fargs, '__next__')()\n }catch(err) {\n if(err.__class__ !== _b_.StopIteration){\n throw err\n }\n }\n console.log(arg)\n _workers[i].finished = false\n _workers[i].postMessage({target: func+'', pos: _pos,\n args: $convert_args([arg])})\n _pos++\n\n _workers[i].addEventListener('message', function(e) {\n _results[e.data.pos]=e.data.result\n if (_results.length == args.length){\n return _results\n }\n try{\n arg = $B.$getattr(fargs, '__next__')()\n e.currentTarget.postMessage({target: func+'', pos: _pos,\n args: $convert_args([arg])})\n _pos++\n }catch(err){\n if (err.__class__ !== _b_.StopIteration){\n throw err\n }\n this.finished = true\n }\n }, false);\n }\n}\n\nPool.apply_async = function(){\n\n var $ns = $B.$args('apply_async', 3,\n {self:null, func:null, fargs:null}, ['self', 'func', 'fargs'],\n arguments,{},'args','kw')\n var func = $ns['func']\n var fargs = $ns['fargs']\n\n fargs = _b_.iter(fargs)\n\n async_result = {}\n async_result.get = function(timeout){\n console.log(results)\n console.log(fargs)\n return this.results}\n async_result.results=[]\n\n var _pos=0\n\n _workers=[]\n for(var i=0; i < self.$processes; i++) {\n _workers[i] = new Worker('/src/web_workers/multiprocessing.js')\n var arg\n\n try{\n arg = $B.$getattr(fargs, '__next__')()\n }catch(err) {\n if (err.__class__ !== _b_.StopIteration){\n throw err\n }\n }\n _workers[i].postMessage({target: func+'', pos: _pos,\n args: $convert_args([arg])})\n _pos++\n\n _workers[i].addEventListener('message', function(e) {\n async_result.results[e.data.pos]=e.data.result\n //if (_results.length == args.length) return _results\n\n try {\n arg = $B.$getattr(fargs, '__next__')()\n e.currentTarget.postMessage({target: func+'', pos: _pos,\n args: $convert_args([arg])})\n _pos++\n } catch(err) {\n if (err.__class__ !== _b_.StopIteration){\n throw err\n }\n this.finished=true\n }\n }, false);\n }\n\n return async_result\n}\n\nPool.$factory = function(){\n var $ns = $B.args('Pool',1,\n {processes:null},['processes'],arguments,{},'args','kw')\n\n var processes = $ns['processes']\n\n if (processes === _b_.None) {\n // look to see if we have stored cpu_count in local storage\n // maybe we should create a brython config file with settings,etc..??\n\n // if not there use a tool such as Core Estimator to calculate number of cpu's\n // http://eligrey.com/blog/post/cpu-core-estimation-with-javascript\n }\n\n var res = {\n __class__: Pool,\n $processes: processes\n }\n return res\n}\n\n$B.set_func_names(Pool, \"multiprocessing\")\n\n$B.imported._multiprocessing = {Process, Pool}\n\n})(__BRYTHON__)\n"], "_posixsubprocess": [".js", "(function($B){\n\n $B.imported._posixsubprocess = {\n cloexec_pipe: function() {}, // fixme\n fork_exec: function(){}\n }\n})(__BRYTHON__)\n"], "_profile": [".js", "// Private interface to the profiling instrumentation implemented in py_utils.js.\n// Uses local a copy of the eval function from py_builtin_functions.js\n\nvar $module=(function($B) {\n eval($B.InjectBuiltins());\n return {\n brython:$B,\n data:$B.$profile_data,\n start:$B.$profile.start,\n stop:$B.$profile.stop,\n pause:$B.$profile.pause,\n status:$B.$profile.status,\n clear:$B.$profile.clear,\n elapsed:$B.$profile.elapsed,\n run:function(src,_globals,_locals,nruns) {\n var current_frame = $B.frames_stack[$B.frames_stack.length-1]\n if(current_frame!==undefined){\n var current_locals_id = current_frame[0].replace(/\\./,'_'),\n current_globals_id = current_frame[2].replace(/\\./,'_')\n }\n\n var is_exec = true,\n leave = false\n\n // code will be run in a specific block\n var globals_id = '$profile_'+$B.UUID(),\n locals_id\n\n if(_locals===_globals){\n locals_id = globals_id\n }else{\n locals_id = '$profile_'+$B.UUID()\n }\n // Initialise the object for block namespaces\n eval('var $locals_'+globals_id+' = {}\\nvar $locals_'+locals_id+' = {}')\n\n // Initialise block globals\n\n // A _globals dictionary is provided, set or reuse its attribute\n // globals_id\n _globals.globals_id = _globals.globals_id || globals_id\n globals_id = _globals.globals_id\n\n if(_locals === _globals || _locals === undefined){\n locals_id = globals_id\n parent_scope = $B.builtins_scope\n }else{\n // The parent block of locals must be set to globals\n parent_scope = {\n id: globals_id,\n parent_block: $B.builtins_scope,\n binding: {}\n }\n for(var attr of _b_.dict.$keys_string(_globals)){\n parent_scope.binding[attr] = true\n }\n }\n\n // Initialise block globals\n if(_globals.$jsobj){\n var items = _globals.$jsobj\n }else{\n var items = {}\n for(var key of _b_.dict.$keys_string(_globals)){\n items[key] = _b_.dict.$getitem_string(_globals, key)\n }\n }\n for(var item in items){\n item1 = to_alias(item)\n try{\n eval('$locals_' + globals_id + '[\"' + item1 +\n '\"] = items[item]')\n }catch(err){\n console.log(err)\n console.log('error setting', item)\n break\n }\n }\n\n // Initialise block locals\n var items = _b_.dict.items(_locals), item\n if(_locals.$jsobj){\n var items = _locals.$jsobj\n }else{\n var items = {}\n for(var key of _b_.dict.$keys_string(_locals)){\n items[key] = _b_.dict.$getitem_string(_locals, key)\n } }\n for(var item in items){\n item1 = to_alias(item)\n try{\n eval('$locals_' + locals_id + '[\"' + item[0] + '\"] = item[1]')\n }catch(err){\n console.log(err)\n console.log('error setting', item)\n break\n }\n }\n //var nb_modules = Object.keys(__BRYTHON__.modules).length\n //console.log('before exec', nb_modules)\n\n console.log(\"call py2js\", src, globals_id, locals_id, parent_scope)\n var root = $B.py2js(src, globals_id, locals_id, parent_scope),\n js, gns, lns\n\n try{\n\n var js = root.to_js()\n\n var i,res,gns;\n for(i=0;i>> i) & 0x1){\n sum = addition32(sum, unsigned32(n2 << i))\n }\n }\n return sum\n }\n\n /* initializes mt[N] with a seed */\n //c//void init_genrand(unsigned long s)\n function init_genrand(s) {\n //c//mt[0]= s & 0xffffffff;\n mt[0] = unsigned32(s & 0xffffffff)\n for(mti = 1; mti < N; mti++){\n mt[mti] =\n //c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);\n addition32(multiplication32(1812433253,\n unsigned32(mt[mti - 1] ^ (mt[mti - 1] >>> 30))), mti)\n /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\n /* In the previous versions, MSBs of the seed affect */\n /* only MSBs of the array mt[]. */\n /* 2002/01/09 modified by Makoto Matsumoto */\n //c//mt[mti] &= 0xffffffff;\n mt[mti] = unsigned32(mt[mti] & 0xffffffff);\n /* for >32 bit machines */\n }\n }\n\n /* initialize by an array with array-length */\n /* init_key is the array for initializing keys */\n /* key_length is its length */\n /* slight change for C++, 2004/2/26 */\n //c//void init_by_array(unsigned long init_key[], int key_length)\n function init_by_array(init_key, key_length) {\n //c//int i, j, k;\n var i, j, k\n init_genrand(19650218)\n i = 1\n j = 0\n k = (N > key_length ? N : key_length)\n for(; k; k--){\n //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))\n //c// + init_key[j] + j; /* non linear */\n mt[i] = addition32(\n addition32(unsigned32(mt[i] ^\n multiplication32(unsigned32(mt[i - 1] ^ (mt[i - 1] >>> 30)),\n 1664525)),\n init_key[j]), j)\n mt[i] =\n //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n unsigned32(mt[i] & 0xffffffff)\n i++\n j++\n if(i >= N){mt[0] = mt[N - 1]; i = 1}\n if(j >= key_length){j = 0}\n }\n for(k = N - 1; k; k--){\n //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))\n //c//- i; /* non linear */\n mt[i] = subtraction32(\n unsigned32(\n (mt[i]) ^\n multiplication32(\n unsigned32(mt[i - 1] ^ (mt[i - 1] >>> 30)),\n 1566083941)),\n i\n )\n //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n mt[i] = unsigned32(mt[i] & 0xffffffff)\n i++\n if(i >= N){mt[0] = mt[N - 1]; i = 1}\n }\n mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */\n }\n\n /* generates a random number on [0,0xffffffff]-interval */\n //c//unsigned long genrand_int32(void)\n function genrand_int32() {\n //c//unsigned long y;\n //c//static unsigned long mag01[2]={0x0UL, MATRIX_A};\n var y;\n var mag01 = [0x0, MATRIX_A];\n /* mag01[x] = x * MATRIX_A for x=0,1 */\n\n if(mti >= N){ /* generate N words at one time */\n //c//int kk;\n var kk\n\n if(mti == N + 1){ /* if init_genrand() has not been called, */\n init_genrand(Date.now()) /* a default initial seed is used */\n }\n\n for(kk = 0; kk < N - M; kk++){\n //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\n //c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[kk]&UPPER_MASK) | (mt[kk + 1]&LOWER_MASK))\n mt[kk] = unsigned32(mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1])\n }\n for(;kk < N - 1; kk++){\n //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\n //c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[kk]&UPPER_MASK) | (mt[kk + 1]&LOWER_MASK))\n mt[kk] = unsigned32(mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1])\n }\n //c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);\n //c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK))\n mt[N - 1] = unsigned32(mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1])\n mti = 0\n }\n\n y = mt[mti++]\n\n /* Tempering */\n //c//y ^= (y >> 11);\n //c//y ^= (y << 7) & 0x9d2c5680;\n //c//y ^= (y << 15) & 0xefc60000;\n //c//y ^= (y >> 18);\n y = unsigned32(y ^ (y >>> 11))\n y = unsigned32(y ^ ((y << 7) & 0x9d2c5680))\n y = unsigned32(y ^ ((y << 15) & 0xefc60000))\n y = unsigned32(y ^ (y >>> 18))\n\n return y\n }\n\n /* generates a random number on [0,0x7fffffff]-interval */\n //c//long genrand_int31(void)\n function genrand_int31(){\n //c//return (genrand_int32()>>1);\n return (genrand_int32()>>>1)\n }\n\n /* generates a random number on [0,1]-real-interval */\n //c//double genrand_real1(void)\n function genrand_real1(){\n return genrand_int32()*(1.0/4294967295.0)\n /* divided by 2^32-1 */\n }\n\n /* generates a random number on [0,1)-real-interval */\n //c//double genrand_real2(void)\n function genrand_real2(){\n return genrand_int32() * (1.0 / 4294967296.0)\n /* divided by 2^32 */\n }\n\n /* generates a random number on (0,1)-real-interval */\n //c//double genrand_real3(void)\n function genrand_real3() {\n return ((genrand_int32()) + 0.5) * (1.0 / 4294967296.0)\n /* divided by 2^32 */\n }\n\n /* generates a random number on [0,1) with 53-bit resolution*/\n //c//double genrand_res53(void)\n function genrand_res53() {\n //c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;\n var a = genrand_int32() >>> 5,\n b = genrand_int32() >>> 6\n return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0)\n }\n /* These real versions are due to Isaku Wada, 2002/01/09 added */\n\n var random = genrand_res53\n\n random.seed = function(seed){\n if(seed === undefined || $B.is_none(seed)){\n const entries = new Uint32Array(N)\n crypto.getRandomValues(entries)\n init_by_array(Array.from(entries), N)\n return\n }\n\n if(!$B.$isinstance(seed, _b_.int)){\n seed = _b_.hash(seed)\n }\n\n // Transform to long integer\n if(typeof seed == \"number\"){\n seed = BigInt(seed)\n }else if(seed.__class__ === $B.long_int){\n seed = seed.value\n }else{\n return random.seed(seed.$brython_value)\n }\n\n // Take abs(seed)\n seed = seed > 0 ? seed : -seed\n\n var keys = []\n var int32_1 = 2n ** 32n - 1n\n\n // decomposition in factors of 2 ** 32\n while(seed >= int32_1){\n var quot = seed / int32_1,\n rest = seed % int32_1\n // Rest is a JS number (< 2 ** 32)\n keys.push(Number(rest))\n // Quotient is either a JS number or a instance of long_int\n // but seed must be long_int\n seed = quot\n }\n keys.push(Number(seed))\n\n init_by_array(keys, keys.length)\n }\n\n random.seed(seed)\n\n random.int31 = genrand_int31\n random.int32 = genrand_int32\n random.real1 = genrand_real1\n random.real2 = genrand_real2\n random.real3 = genrand_real3\n random.res53 = genrand_res53\n\n // Added for compatibility with Python\n random.getstate = function(){\n return $B.fast_tuple(mt.concat([mti]))\n }\n\n random.setstate = function(state){\n mt = state.slice(0, state.length - 1)\n mti = state[state.length - 1]\n }\n\n return random\n\n}\n\nvar Random = $B.make_class(\"Random\",\n function(){\n return {\n __class__: Random,\n _random: RandomStream(Date.now())\n }\n }\n)\n\nRandom.getrandbits = function(){\n var $ = $B.args(\"getrandbits\", 2, {self: null, k:null}, [\"self\", \"k\"],\n arguments, {}, null, null),\n self = $.self,\n k = $B.$GetInt($.k)\n\n if(k < 0)\n throw _b_.ValueError.$factory('number of bits must be non-negative')\n\n if(k === 0)\n return 0\n\n const words = Math.floor((k - 1) / 32) + 1\n const wordarray = new ArrayBuffer(words * 4)\n const wordarray_view = new DataView(wordarray)\n\n /* Fill-out bits of long integer, by 32-bit words, from least significant\n to most significant. */\n for(i = 0; i < words; i++, k -= 32){\n r = self._random.int32()\n if (k < 32)\n r >>>= (32 - k) /* Drop least significant bits */\n wordarray_view.setUint32(i * 4, r, true)\n }\n\n return _b_.int.from_bytes(_b_.bytes.$factory(Array.from(new Uint8Array(wordarray))), \"little\")\n}\n\nRandom.getstate = function(){\n var $ = $B.args('getstate', 1, {self: null},\n [\"self\"], arguments, {}, null, null),\n self = $.self\n return self._random.getstate()\n}\n\nRandom.random = function(){\n var $ = $B.args('random', 1, {self: null}, [\"self\"],\n arguments, {}, null, null),\n self = $.self\n return $B.fast_float(self._random())\n}\n\nRandom.seed = function(){\n var $ = $B.args('seed', 2, {self: null, n: null}, ['self', 'n'],\n arguments, {}, null, null),\n self = $.self,\n n = $.n\n\n if (self._random === undefined){\n self._random = RandomStream(n)\n }else{\n self._random.seed(n)\n }\n}\n\nRandom.setstate = function(){\n var $ = $B.args('setstate', 2, {self: null, state:null}, ['self', 'state'],\n arguments, {}, null, null),\n self = $.self,\n state = $.state\n return self._random.setstate(state)\n}\n\n$B.set_func_names(Random, \"_random\")\n\n$B.imported._random = { Random }\n\n})(__BRYTHON__)\n"], "_sre": [".py", "\n''\n\n\n\n\n\n\n\nMAXREPEAT=2147483648\nMAXGROUPS=2147483647\n\nimport array\nimport operator,sys\nfrom sre_constants import ATCODES,OPCODES,CHCODES\nfrom sre_constants import SRE_INFO_PREFIX,SRE_INFO_LITERAL\nfrom sre_constants import SRE_FLAG_UNICODE,SRE_FLAG_LOCALE\n\n\nfrom _sre_utils import(unicode_iscased,ascii_iscased,unicode_tolower,\nascii_tolower)\n\nimport sys\n\n\n\nMAGIC=20171005\n\n\n\n\n\n\n\n\n\n\n\n\n\nCODESIZE=4\n\ncopyright=\"_sre.py 2.4c Copyright 2005 by Nik Haldimann\"\n\n\ndef getcodesize():\n return CODESIZE\n \ndef compile(pattern,flags,code,groups=0,groupindex={},indexgroup=[None]):\n ''\n \n return SRE_Pattern(pattern,flags,code,groups,groupindex,indexgroup)\n \ndef getlower(char_ord,flags):\n if(char_ord <128)or(flags&SRE_FLAG_UNICODE)\\\n or(flags&SRE_FLAG_LOCALE and char_ord <256):\n \n return ord(chr(char_ord).lower())\n else:\n return char_ord\n \n \nclass SRE_Pattern:\n\n def __init__(self,pattern,flags,code,groups=0,groupindex={},indexgroup=[None]):\n self.pattern=pattern\n self.flags=flags\n self.groups=groups\n self.groupindex=groupindex\n self._indexgroup=indexgroup\n self._code=code\n \n def match(self,string,pos=0,endpos=sys.maxsize):\n ''\n\n \n state=_State(string,pos,endpos,self.flags)\n if state.match(self._code):\n return SRE_Match(self,state)\n return None\n \n def fullmatch(self,string,pos=0,endpos=sys.maxsize):\n ''\n\n \n end=\"$\"if isinstance(string,str)else b\"$\"\n if not string.endswith(end):\n string +=end\n state=_State(string,pos,endpos,self.flags)\n if state.match(self._code):\n return SRE_Match(self,state)\n return None\n \n def search(self,string,pos=0,endpos=sys.maxsize):\n ''\n\n\n \n state=_State(string,pos,endpos,self.flags)\n if state.search(self._code):\n return SRE_Match(self,state)\n else:\n return None\n \n def findall(self,string,pos=0,endpos=sys.maxsize):\n ''\n matchlist=[]\n state=_State(string,pos,endpos,self.flags)\n while state.start <=state.end:\n state.reset()\n state.string_position=state.start\n if not state.search(self._code):\n break\n match=SRE_Match(self,state)\n if self.groups ==0 or self.groups ==1:\n item=match.group(self.groups)\n else:\n item=match.groups(\"\")\n matchlist.append(item)\n if state.string_position ==state.start:\n state.start +=1\n else:\n state.start=state.string_position\n return matchlist\n \n def _subx(self,template,string,count=0,subn=False):\n filter=template\n if not callable(template)and \"\\\\\"in template:\n \n \n \n \n import re as sre\n filter=sre._subx(self,template)\n state=_State(string,0,sys.maxsize,self.flags)\n sublist=[]\n \n n=last_pos=0\n while not count or n 0):\n \n if callable(filter):\n sublist.append(filter(SRE_Match(self,state)))\n else:\n sublist.append(filter)\n last_pos=state.string_position\n n +=1\n if state.string_position ==state.start:\n state.start +=1\n else:\n state.start=state.string_position\n \n if last_pos =0 and group <=self.re.groups:\n return group\n else:\n if group in self.re.groupindex:\n return self.re.groupindex[group]\n raise IndexError(\"no such group\")\n \n def _get_slice(self,group,default):\n group_indices=self.regs[group]\n if group_indices[0]>=0:\n return self.string[group_indices[0]:group_indices[1]]\n else:\n return default\n \n def start(self,group=0):\n ''\n\n \n return self.regs[self._get_index(group)][0]\n \n def end(self,group=0):\n ''\n\n \n return self.regs[self._get_index(group)][1]\n \n def span(self,group=0):\n ''\n return self.start(group),self.end(group)\n \n def expand(self,template):\n ''\n \n import sre\n return sre._expand(self.re,self,template)\n \n def groups(self,default=None):\n ''\n\n \n groups=[]\n for indices in self.regs[1:]:\n if indices[0]>=0:\n groups.append(self.string[indices[0]:indices[1]])\n else:\n groups.append(default)\n return tuple(groups)\n \n def groupdict(self,default=None):\n ''\n\n \n groupdict={}\n for key,value in self.re.groupindex.items():\n groupdict[key]=self._get_slice(value,default)\n return groupdict\n \n def group(self,*args):\n ''\n \n if len(args)==0:\n args=(0,)\n grouplist=[]\n for group in args:\n grouplist.append(self._get_slice(self._get_index(group),None))\n if len(grouplist)==1:\n return grouplist[0]\n else:\n return tuple(grouplist)\n \n def __copy__():\n raise TypeError(\"cannot copy this pattern object\")\n \n def __deepcopy__():\n raise TypeError(\"cannot copy this pattern object\")\n \n def __str__(self):\n start,end=self.start(0),self.end(0)\n return(f\"\")\n \nclass _State:\n\n def __init__(self,string,start,end,flags):\n if isinstance(string,bytearray):\n string=str(bytes(string),\"latin1\")\n if isinstance(string,bytes):\n string=str(string,\"latin1\")\n self.string=string\n if start <0:\n start=0\n if end >len(string):\n end=len(string)\n self.start=start\n self.string_position=self.start\n self.end=end\n self.pos=start\n self.flags=flags\n self.reset()\n \n def reset(self):\n self.marks=[]\n self.lastindex=-1\n self.marks_stack=[]\n self.context_stack=[]\n self.repeat=None\n \n def match(self,pattern_codes):\n \n \n \n \n \n \n \n \n dispatcher=_OpcodeDispatcher()\n self.context_stack.append(_MatchContext(self,pattern_codes))\n has_matched=None\n while len(self.context_stack)>0:\n context=self.context_stack[-1]\n has_matched=dispatcher.match(context)\n if has_matched is not None:\n self.context_stack.pop()\n return has_matched\n \n def search(self,pattern_codes):\n flags=0\n if OPCODES[pattern_codes[0]].name ==\"info\":\n \n \n if pattern_codes[2]&SRE_INFO_PREFIX and pattern_codes[5]>1:\n return self.fast_search(pattern_codes)\n flags=pattern_codes[2]\n pattern_codes=pattern_codes[pattern_codes[1]+1:]\n \n string_position=self.start\n if OPCODES[pattern_codes[0]].name ==\"literal\":\n \n \n character=pattern_codes[1]\n while True:\n while string_position =self.end:\n return False\n self.start=string_position\n string_position +=1\n self.string_position=string_position\n if flags&SRE_INFO_LITERAL:\n return True\n if self.match(pattern_codes[2:]):\n return True\n return False\n \n \n while string_position <=self.end:\n self.reset()\n self.start=self.string_position=string_position\n if self.match(pattern_codes):\n return True\n string_position +=1\n return False\n \n def fast_search(self,pattern_codes):\n ''\n \n \n \n flags=pattern_codes[2]\n prefix_len=pattern_codes[5]\n prefix_skip=pattern_codes[6]\n prefix=pattern_codes[7:7+prefix_len]\n overlap=pattern_codes[7+prefix_len -1:pattern_codes[1]+1]\n pattern_codes=pattern_codes[pattern_codes[1]+1:]\n i=0\n string_position=self.string_position\n while string_position =len(self.marks):\n self.marks.extend([None]*(mark_nr -len(self.marks)+1))\n self.marks[mark_nr]=position\n \n def get_marks(self,group_index):\n marks_index=2 *group_index\n if len(self.marks)>marks_index+1:\n return self.marks[marks_index],self.marks[marks_index+1]\n else:\n return None,None\n \n def marks_push(self):\n self.marks_stack.append((self.marks[:],self.lastindex))\n \n def marks_pop(self):\n self.marks,self.lastindex=self.marks_stack.pop()\n \n def marks_pop_keep(self):\n self.marks,self.lastindex=self.marks_stack[-1]\n \n def marks_pop_discard(self):\n self.marks_stack.pop()\n \n def lower(self,char_ord):\n return getlower(char_ord,self.flags)\n \n \nclass _MatchContext:\n\n def __init__(self,state,pattern_codes):\n self.state=state\n self.pattern_codes=pattern_codes\n self.string_position=state.string_position\n self.code_position=0\n self.has_matched=None\n \n def push_new_context(self,pattern_offset):\n ''\n\n \n child_context=_MatchContext(self.state,\n self.pattern_codes[self.code_position+pattern_offset:])\n \n \n \n \n self.state.context_stack.append(child_context)\n return child_context\n \n def peek_char(self,peek=0):\n return self.state.string[self.string_position+peek]\n \n def skip_char(self,skip_count):\n self.string_position +=skip_count\n \n def remaining_chars(self):\n return self.state.end -self.string_position\n \n def peek_code(self,peek=0):\n return self.pattern_codes[self.code_position+peek]\n \n def skip_code(self,skip_count):\n self.code_position +=skip_count\n \n def remaining_codes(self):\n return len(self.pattern_codes)-self.code_position\n \n def at_beginning(self):\n return self.string_position ==0\n \n def at_end(self):\n return self.string_position ==self.state.end\n \n def at_linebreak(self):\n return not self.at_end()and _is_linebreak(self.peek_char())\n \n def at_boundary(self,word_checker):\n if self.at_beginning()and self.at_end():\n return False\n that=not self.at_beginning()and word_checker(self.peek_char(-1))\n this=not self.at_end()and word_checker(self.peek_char())\n return this !=that\n \n \nclass _RepeatContext(_MatchContext):\n\n def __init__(self,context):\n _MatchContext.__init__(self,context.state,\n context.pattern_codes[context.code_position:])\n self.count=-1\n \n self.previous=context.state.repeat\n self.last_position=None\n \n \nclass _Dispatcher:\n\n DISPATCH_TABLE=None\n \n def dispatch(self,code,context):\n method=self.DISPATCH_TABLE.get(code,self.__class__.unknown)\n return method(self,context)\n \n def unknown(self,code,ctx):\n raise NotImplementedError()\n \n def build_dispatch_table(cls,items,method_prefix):\n if cls.DISPATCH_TABLE is not None:\n return\n table={}\n for item in items:\n key,value=item.name.lower(),int(item)\n if hasattr(cls,\"%s%s\"%(method_prefix,key)):\n table[value]=getattr(cls,\"%s%s\"%(method_prefix,key))\n cls.DISPATCH_TABLE=table\n \n build_dispatch_table=classmethod(build_dispatch_table)\n \n \nclass _OpcodeDispatcher(_Dispatcher):\n\n def __init__(self):\n self.executing_contexts={}\n self.at_dispatcher=_AtcodeDispatcher()\n self.ch_dispatcher=_ChcodeDispatcher()\n self.set_dispatcher=_CharsetDispatcher()\n \n def match(self,context):\n ''\n\n \n while context.remaining_codes()>0 and context.has_matched is None:\n opcode=context.peek_code()\n if not self.dispatch(opcode,context):\n return None\n if context.has_matched is None:\n context.has_matched=False\n return context.has_matched\n \n def dispatch(self,opcode,context):\n ''\n \n \n if id(context)in self.executing_contexts:\n generator=self.executing_contexts[id(context)]\n del self.executing_contexts[id(context)]\n has_finished=next(generator)\n else:\n method=self.DISPATCH_TABLE.get(opcode,_OpcodeDispatcher.unknown)\n has_finished=method(self,context)\n if hasattr(has_finished,\"__next__\"):\n generator=has_finished\n has_finished=next(generator)\n if not has_finished:\n self.executing_contexts[id(context)]=generator\n return has_finished\n \n def op_success(self,ctx):\n \n \n ctx.state.string_position=ctx.string_position\n ctx.has_matched=True\n return True\n \n def op_failure(self,ctx):\n \n \n ctx.has_matched=False\n return True\n \n def general_op_literal(self,ctx,compare,decorate=lambda x:x):\n if ctx.at_end()or not compare(decorate(ord(ctx.peek_char())),\n decorate(ctx.peek_code(1))):\n ctx.has_matched=False\n ctx.skip_code(2)\n ctx.skip_char(1)\n \n def op_literal(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.eq)\n return True\n \n def op_not_literal(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.ne)\n return True\n \n def op_literal_ignore(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.eq,ctx.state.lower)\n return True\n \n def op_literal_uni_ignore(self,ctx):\n self.general_op_literal(ctx,operator.eq,ctx.state.lower)\n return True\n \n def op_not_literal_ignore(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.ne,ctx.state.lower)\n return True\n \n def op_at(self,ctx):\n \n \n \n if not self.at_dispatcher.dispatch(ctx.peek_code(1),ctx):\n ctx.has_matched=False\n \n return True\n ctx.skip_code(2)\n return True\n \n def op_category(self,ctx):\n \n \n \n if ctx.at_end()or not self.ch_dispatcher.dispatch(ctx.peek_code(1),ctx):\n ctx.has_matched=False\n \n return True\n ctx.skip_code(2)\n ctx.skip_char(1)\n return True\n \n def op_any(self,ctx):\n \n \n \n if ctx.at_end()or ctx.at_linebreak():\n ctx.has_matched=False\n \n return True\n ctx.skip_code(1)\n ctx.skip_char(1)\n return True\n \n def op_any_all(self,ctx):\n \n \n \n if ctx.at_end():\n ctx.has_matched=False\n \n return True\n ctx.skip_code(1)\n ctx.skip_char(1)\n return True\n \n def general_op_in(self,ctx,decorate=lambda x:x):\n \n \n if ctx.at_end():\n ctx.has_matched=False\n \n return\n skip=ctx.peek_code(1)\n ctx.skip_code(2)\n \n \n if not self.check_charset(ctx,decorate(ord(ctx.peek_char()))):\n \n ctx.has_matched=False\n return\n ctx.skip_code(skip -1)\n ctx.skip_char(1)\n \n \n def op_in(self,ctx):\n \n \n \n self.general_op_in(ctx)\n return True\n \n def op_in_ignore(self,ctx):\n \n \n \n self.general_op_in(ctx,ctx.state.lower)\n return True\n \n def op_in_uni_ignore(self,ctx):\n self.general_op_in(ctx,ctx.state.lower)\n return True\n \n def op_jump(self,ctx):\n \n \n \n ctx.skip_code(ctx.peek_code(1)+1)\n return True\n \n \n \n op_info=op_jump\n \n def op_mark(self,ctx):\n \n \n \n ctx.state.set_mark(ctx.peek_code(1),ctx.string_position)\n ctx.skip_code(2)\n return True\n \n def op_branch(self,ctx):\n \n \n \n ctx.state.marks_push()\n ctx.skip_code(1)\n current_branch_length=ctx.peek_code(0)\n while current_branch_length:\n \n \n if not(OPCODES[ctx.peek_code(1)].name ==\"literal\"and\\\n (ctx.at_end()or ctx.peek_code(2)!=ord(ctx.peek_char()))):\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(1)\n \n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.state.marks_pop_keep()\n ctx.skip_code(current_branch_length)\n current_branch_length=ctx.peek_code(0)\n ctx.state.marks_pop_discard()\n ctx.has_matched=False\n \n yield True\n \n def op_repeat_one(self,ctx):\n \n \n \n \n mincount=ctx.peek_code(2)\n maxcount=ctx.peek_code(3)\n \n \n \n if ctx.remaining_chars()=mincount and\\\n (ctx.at_end()or ord(ctx.peek_char())!=char):\n ctx.skip_char(-1)\n count -=1\n if count =mincount:\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(ctx.peek_code(1)+1)\n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.skip_char(-1)\n count -=1\n ctx.state.marks_pop_keep()\n \n ctx.state.marks_pop_discard()\n ctx.has_matched=False\n \n yield True\n \n def op_min_repeat_one(self,ctx):\n \n \n mincount=ctx.peek_code(2)\n maxcount=ctx.peek_code(3)\n \n \n if ctx.remaining_chars()=maxcount and maxcount !=MAXREPEAT:\n ctx.has_matched=False\n \n yield True\n repeat.count=count\n child_context=repeat.push_new_context(4)\n yield False\n ctx.has_matched=child_context.has_matched\n if not ctx.has_matched:\n repeat.count=count -1\n ctx.state.string_position=ctx.string_position\n yield True\n \n def general_op_groupref(self,ctx,decorate=lambda x:x):\n group_start,group_end=ctx.state.get_marks(ctx.peek_code(1))\n if group_start is None or group_end is None or group_end =0:\n child_context=ctx.push_new_context(3)\n yield False\n if child_context.has_matched:\n ctx.has_matched=False\n yield True\n ctx.skip_code(ctx.peek_code(1)+1)\n yield True\n \n def unknown(self,ctx):\n \n raise RuntimeError(\"Internal re error. Unknown opcode: %s\"%ctx.peek_code())\n \n def check_charset(self,ctx,char):\n ''\n \n self.set_dispatcher.reset(char)\n save_position=ctx.code_position\n result=None\n while result is None:\n result=self.set_dispatcher.dispatch(ctx.peek_code(),ctx)\n ctx.code_position=save_position\n \n return result\n \n def count_repetitions(self,ctx,maxcount):\n ''\n\n \n count=0\n real_maxcount=ctx.state.end -ctx.string_position\n if maxcount >4)\\\n &(1 <<(char_code&15)):\n return self.ok\n ctx.skip_code(16)\n else:\n if char_code <256 and ctx.peek_code(char_code >>5)\\\n &(1 <<(char_code&31)):\n return self.ok\n ctx.skip_code(8)\n def set_range(self,ctx):\n \n if ctx.peek_code(1)<=self.char <=ctx.peek_code(2):\n return self.ok\n ctx.skip_code(3)\n def set_negate(self,ctx):\n self.ok=not self.ok\n ctx.skip_code(1)\n \n def set_bigcharset(self,ctx):\n \n char_code=self.char\n count=ctx.peek_code(1)\n ctx.skip_code(2)\n if char_code <65536:\n block_index=char_code >>8\n \n a=array.array(\"B\")\n a.fromstring(array.array(CODESIZE ==2 and \"H\"or \"I\",\n [ctx.peek_code(block_index //CODESIZE)]).tostring())\n block=a[block_index %CODESIZE]\n ctx.skip_code(256 //CODESIZE)\n block_value=ctx.peek_code(block *(32 //CODESIZE)\n +((char_code&255)>>(CODESIZE ==2 and 4 or 5)))\n if block_value&(1 <<(char_code&((8 *CODESIZE)-1))):\n return self.ok\n else:\n ctx.skip_code(256 //CODESIZE)\n ctx.skip_code(count *(32 //CODESIZE))\n \n def unknown(self,ctx):\n return False\n \n_CharsetDispatcher.build_dispatch_table(OPCODES,\"set_\")\n\n\nclass _AtcodeDispatcher(_Dispatcher):\n\n def at_beginning(self,ctx):\n return ctx.at_beginning()\n at_beginning_string=at_beginning\n def at_beginning_line(self,ctx):\n return ctx.at_beginning()or _is_linebreak(ctx.peek_char(-1))\n def at_end(self,ctx):\n return(ctx.remaining_chars()==1 and ctx.at_linebreak())or ctx.at_end()\n def at_end_line(self,ctx):\n return ctx.at_linebreak()or ctx.at_end()\n def at_end_string(self,ctx):\n return ctx.at_end()\n def at_boundary(self,ctx):\n return ctx.at_boundary(_is_word)\n def at_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_word)\n def at_loc_boundary(self,ctx):\n return ctx.at_boundary(_is_loc_word)\n def at_loc_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_loc_word)\n def at_uni_boundary(self,ctx):\n return ctx.at_boundary(_is_uni_word)\n def at_uni_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_uni_word)\n def unknown(self,ctx):\n return False\n \n_AtcodeDispatcher.build_dispatch_table(ATCODES,\"\")\n\n\nclass _ChcodeDispatcher(_Dispatcher):\n\n def category_digit(self,ctx):\n return _is_digit(ctx.peek_char())\n def category_not_digit(self,ctx):\n return not _is_digit(ctx.peek_char())\n def category_space(self,ctx):\n return _is_space(ctx.peek_char())\n def category_not_space(self,ctx):\n return not _is_space(ctx.peek_char())\n def category_word(self,ctx):\n return _is_word(ctx.peek_char())\n def category_not_word(self,ctx):\n return not _is_word(ctx.peek_char())\n def category_linebreak(self,ctx):\n return _is_linebreak(ctx.peek_char())\n def category_not_linebreak(self,ctx):\n return not _is_linebreak(ctx.peek_char())\n def category_loc_word(self,ctx):\n return _is_loc_word(ctx.peek_char())\n def category_loc_not_word(self,ctx):\n return not _is_loc_word(ctx.peek_char())\n def category_uni_digit(self,ctx):\n return ctx.peek_char().isdigit()\n def category_uni_not_digit(self,ctx):\n return not ctx.peek_char().isdigit()\n def category_uni_space(self,ctx):\n return ctx.peek_char().isspace()\n def category_uni_not_space(self,ctx):\n return not ctx.peek_char().isspace()\n def category_uni_word(self,ctx):\n return _is_uni_word(ctx.peek_char())\n def category_uni_not_word(self,ctx):\n return not _is_uni_word(ctx.peek_char())\n def category_uni_linebreak(self,ctx):\n return ord(ctx.peek_char())in _uni_linebreaks\n def category_uni_not_linebreak(self,ctx):\n return ord(ctx.peek_char())not in _uni_linebreaks\n def unknown(self,ctx):\n return False\n \n_ChcodeDispatcher.build_dispatch_table(CHCODES,\"\")\n\n\n_ascii_char_info=[0,0,0,0,0,0,0,0,0,2,6,2,\n2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,\n0,0,0,0,0,0,0,0,0,0,0,0,0,25,25,25,25,25,25,25,25,\n25,25,0,0,0,0,0,0,0,24,24,24,24,24,24,24,24,24,24,\n24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,0,0,\n0,0,16,0,24,24,24,24,24,24,24,24,24,24,24,24,24,24,\n24,24,24,24,24,24,24,24,24,24,24,24,0,0,0,0,0]\n\ndef _is_digit(char):\n code=ord(char)\n return code <128 and _ascii_char_info[code]&1\n \ndef _is_space(char):\n code=ord(char)\n return code <128 and _ascii_char_info[code]&2\n \ndef _is_word(char):\n\n code=ord(char)\n return code <128 and _ascii_char_info[code]&16\n \ndef _is_loc_word(char):\n return(not(ord(char)&~255)and char.isalnum())or char =='_'\n \ndef _is_uni_word(char):\n\n\n return chr(ord(char)).isalnum()or char =='_'\n \ndef _is_linebreak(char):\n return char ==\"\\n\"\n \n \n_uni_linebreaks=[10,13,28,29,30,133,8232,8233]\n\ndef _log(message):\n if 0:\n print(message)\n", ["_sre_utils", "array", "operator", "re", "sre", "sre_constants", "sys"]], "_sre_utils": [".js", "var $module=(function($B){\n\n function unicode_iscased(cp){\n // cp : Unicode code point\n var letter = String.fromCodePoint(cp)\n return (letter != letter.toLowerCase() ||\n letter != letter.toUpperCase())\n }\n\n function ascii_iscased(cp){\n if(cp > 255){return false}\n return unicode_iscased(cp)\n }\n\n function unicode_tolower(cp){\n var letter = String.fromCodePoint(cp),\n lower = letter.toLowerCase()\n return lower.charCodeAt(0)\n }\n\n function ascii_tolower(cp){\n return unicode_tolower(cp)\n }\n\nreturn {\n unicode_iscased: unicode_iscased,\n ascii_iscased: ascii_iscased,\n unicode_tolower: unicode_tolower,\n ascii_tolower: ascii_tolower\n}\n\n}\n\n)(__BRYTHON__)"], "_string": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nfunction parts(format_string){\n var result = [],\n _parts = $B.split_format(format_string) // defined in py_string.js\n for(var i = 0; i < _parts.length; i+= 2){\n result.push({pre: _parts[i], fmt: _parts[i + 1]})\n }\n return result\n}\n\nfunction Tuple(){\n var args = []\n for(var i=0, len=arguments.length; i < len; i++){\n args.push(arguments[i])\n }\n return _b_.tuple.$factory(args)\n}\n\n$B.imported._string = {\n\n formatter_field_name_split: function(fieldname){\n // Split the argument as a field name\n var parsed = $B.parse_format(fieldname),\n first = parsed.name,\n rest = []\n if(first.match(/\\d+/)){first = parseInt(first)}\n parsed.name_ext.forEach(function(ext){\n if(ext.startsWith(\"[\")){\n var item = ext.substr(1, ext.length - 2)\n if(item.match(/\\d+/)){\n rest.push(Tuple(false, parseInt(item)))\n }else{\n rest.push(Tuple(false, item))\n }\n }else{\n rest.push(Tuple(true, ext.substr(1)))\n }\n })\n return Tuple(first, _b_.iter(rest))\n },\n formatter_parser: function(format_string){\n // Parse the argument as a format string\n\n if(! _b_.isinstance(format_string, _b_.str)){\n throw _b_.ValueError.$factory(\"Invalid format string type: \" +\n $B.class_name(format_string))\n }\n\n var result = []\n parts(format_string).forEach(function(item){\n var pre = item.pre === undefined ? \"\" : item.pre,\n fmt = item.fmt\n if(fmt === undefined){\n result.push(Tuple(pre, _b_.None, _b_.None, _b_.None))\n }else if(fmt.string == ''){\n result.push(Tuple(pre, '', '', _b_.None))\n }else{\n result.push(Tuple(pre,\n fmt.raw_name + fmt.name_ext.join(\"\"),\n fmt.raw_spec,\n fmt.conv || _b_.None))\n }\n })\n return result\n }\n}\n})(__BRYTHON__)"], "_strptime": [".js", "\n(function($B){\n var _b_ = __BRYTHON__.builtins\n $B.imported._strptime = {\n _strptime_datetime: function(cls, s, fmt){\n var pos_s = 0,\n pos_fmt = 0,\n dt = {}\n function error(time_data, format){\n throw _b_.ValueError.$factory(\n `time data '${time_data}' does not match format '${format}'`)\n }\n\n var locale = __BRYTHON__.locale,\n shortdays = [],\n longdays = [],\n conv_func = locale == \"C\" ?\n function(d, options){\n return d.toLocaleDateString('en-EN', options)\n } :\n function(d, options){\n return d.toLocaleDateString(locale, options)\n }\n\n for(var day = 16; day < 23; day++){\n var d = new Date(Date.UTC(2012, 11, day, 3, 0, 0))\n shortdays.push(conv_func(d, {weekday: 'short'}))\n longdays.push(conv_func(d, {weekday: 'long'}))\n }\n\n var shortmonths = [],\n longmonths = []\n\n for(var month = 0; month < 12; month++){\n var d = new Date(Date.UTC(2012, month, 11, 3, 0, 0))\n shortmonths.push(conv_func(d, {month: 'short'}))\n longmonths.push(conv_func(d, {month: 'long'}))\n }\n\n var shortdays_re = new RegExp(shortdays.join(\"|\").replace(\".\", \"\\\\.\")),\n longdays_re = new RegExp(longdays.join(\"|\")),\n shortmonths_re = new RegExp(shortmonths.join(\"|\").replace(\".\", \"\\\\.\")),\n longmonths_re = new RegExp(longmonths.join(\"|\"))\n\n var regexps = {\n d: [\"day\", new RegExp(\"^[123][0-9]|0?[1-9]\")],\n f: [\"microsecond\", new RegExp(\"^\\\\d{1,6}\")],\n H: [\"hour\", new RegExp(\"^[01][0-9]|2[0-3]|\\\\d\")],\n I: [\"hour\", new RegExp(\"^1[0-2]|0?[0-9]\")],\n m: [\"month\", new RegExp(\"^1[012]|0?[1-9]\")],\n M: [\"minute\", new RegExp(\"^[1-5][0-9]|0?[0-9]\")],\n S: [\"second\", new RegExp(\"^[1-5]\\\\d|0?\\\\d\")],\n y: [\"year\", new RegExp(\"^0{0,2}\\\\d{2}\")],\n Y: [\"year\", new RegExp(\"^\\\\d{4}\")],\n z: [\"tzinfo\", new RegExp(\"Z\")]\n }\n\n for(var key in regexps){\n var re = new RegExp('%' + key, \"g\"),\n mo = fmt.match(re)\n if(mo && mo.length > 1){\n throw _b_.ValueError.$factory('strptime directive %' +\n key + ' defined more than once')\n }\n }\n\n while(pos_fmt < fmt.length){\n var car = fmt.charAt(pos_fmt)\n if(car == \"%\"){\n var spec = fmt.charAt(pos_fmt + 1),\n regexp = regexps[spec]\n if(regexp !== undefined){\n var re = regexp[1],\n attr = regexp[0],\n res = re.exec(s.substr(pos_s))\n if(res === null){\n error(s, fmt)\n }else{\n dt[attr] = parseInt(res[0])\n if(attr == \"microsecond\"){\n while(dt[attr] < 100000){\n dt[attr] *= 10\n }\n }else if(attr == \"tzinfo\"){\n // Only value supported for the moment : Z\n // (UTC)\n var dt_module = $B.imported[cls.__module__]\n dt.tzinfo = dt_module.timezone.utc\n }\n pos_fmt += 2\n pos_s += res[0].length\n }\n }else if(spec == \"a\" || spec == \"A\"){\n // Locale's abbreviated (a) or full (A) weekday name\n var attr = \"weekday\",\n re = spec == \"a\" ? shortdays_re : longdays_re,\n t = spec == \"a\" ? shortdays : longdays\n res = re.exec(s.substr(pos_s))\n if(res === null){\n console.log('error', re, 'string', s.substr(pos_s), 'fmt', fmt)\n error(s, fmt)\n }else{\n var match = res[0],\n ix = t.indexOf(match)\n }\n dt.weekday = ix\n pos_fmt += 2\n pos_s += match.length\n }else if(spec == \"b\" || spec == \"B\"){\n // Locales's abbreviated (b) or full (B) month\n var attr = \"month\",\n re = spec == \"b\" ? shortmonths_re : longmonths_re,\n t = spec == \"b\" ? shortmonths : longmonths,\n res = re.exec(s.substr(pos_s))\n if(res === null){\n error(s, fmt)\n }else{\n var match = res[0],\n ix = t.indexOf(match)\n }\n dt.month = ix + 1\n pos_fmt += 2\n pos_s += match.length\n }else if(spec == \"c\"){\n // Locale's appropriate date and time representation\n var fmt1 = fmt.substr(0, pos_fmt - 1) + _locale_c_format() +\n fmt.substr(pos_fmt + 2)\n fmt = fmt1\n }else if(spec == \"%\"){\n if(s.charAt(pos_s) == \"%\"){\n pos_fmt++\n pos_s++\n }else{\n error(s, fmt)\n }\n }else if(spec == 'p'){\n // AM or PM\n var next2 = s.substr(pos_s, 2)\n if(next2.toUpperCase() == 'AM'){\n if(dt.hasOwnProperty('hour')){\n if(dt.hour > 0 && dt.hour < 12){\n // ok\n }else if(dt.hour == 12){\n dt.hour = 0\n }else{\n error(s, fmt)\n }\n }else{\n error(s, fmt)\n }\n }else if(next2.toUpperCase() == 'PM'){\n if(dt.hasOwnProperty('hour')){\n if(dt.hour > 0 && dt.hour < 12){\n dt.hour += 12\n }else if(dt.hour == 12){\n dt.hour = 12\n }else{\n error(s, fmt)\n }\n }else{\n error(s, fmt)\n }\n }else{\n error(s, fmt)\n }\n pos_fmt += 2\n pos_s += 2\n }else{\n pos_fmt++\n }\n }else{\n if(car == s.charAt(pos_s)){\n pos_fmt++\n pos_s++\n }else{\n error(s, fmt)\n }\n }\n }\n\n if(pos_s < s.length){\n throw _b_.ValueError.$factory('unconverted data remains: ' +\n s.substr(pos_s))\n }\n\n return $B.$call(cls)(dt.year, dt.month, dt.day,\n dt.hour || 0, dt.minute || 0, dt.second || 0,\n dt.microsecond || 0, dt.tzinfo || _b_.None)\n }\n }\n})(__BRYTHON__)\n"], "_svg": [".js", "// creation of a SVG element\n(function($B){\n\nvar _b_ = $B.builtins\nvar TagSum = $B.TagSum // defined in py_dom.js\n\nvar $svgNS = \"http://www.w3.org/2000/svg\"\nvar $xlinkNS = \"http://www.w3.org/1999/xlink\"\n\nfunction makeTagDict(tagName){\n // return the dictionary for the class associated with tagName\n var dict = $B.make_class(tagName)\n\n dict.__init__ = function(){\n var $ns = $B.args('__init__', 1, {self: null}, ['self'],\n arguments, {}, 'args', 'kw'),\n self = $ns['self'],\n args = $ns['args']\n if(args.length == 1){\n var first = args[0]\n if($B.$isinstance(first, [_b_.str, _b_.int, _b_.float])){\n self.appendChild(document.createTextNode(_b_.str.$factory(first)))\n }else if(first.__class__ === TagSum){\n for(var i = 0, len = first.children.length; i < len; i++){\n self.appendChild(first.children[i].elt)\n }\n }else{ // argument is another DOMNode instance\n try{self.appendChild(first.elt)}\n catch(err){throw _b_.ValueError.$factory('wrong element ' + first)}\n }\n }\n\n // attributes\n var items = _b_.list.$factory(_b_.dict.items($ns['kw']))\n for(var item of _b_.dict.$iter_items($ns.kw)){\n // keyword arguments\n var arg = item.key,\n value = $B.py_immutable_to_js(item.value)\n if(arg.toLowerCase().substr(0,2) == \"on\"){\n // Event binding passed as argument \"onclick\", \"onfocus\"...\n // Better use method bind of DOMNode objects\n $B.DOMNode.bind(self,\n arg.toLowerCase().substr(2),\n value)\n }else if(arg.toLowerCase() == \"style\"){\n $B.DOMNode.set_style(self, value)\n }else if(arg.toLowerCase().indexOf(\"href\") !== -1){ // xlink:href\n self.setAttributeNS( \"http://www.w3.org/1999/xlink\",\n \"href\",value)\n }else{\n if(value !== false){\n // option.selected=false sets it to true :-)\n try{\n arg = arg.replace('_', '-')\n self.setAttributeNS(null, arg, value)\n }catch(err){\n throw _b_.ValueError.$factory(\"can't set attribute \" + arg)\n }\n }\n }\n }\n }\n\n dict.__mro__ = [$B.DOMNode, $B.builtins.object]\n\n dict.__new__ = function(cls){\n var res = $B.DOMNode.$factory(document.createElementNS($svgNS, tagName))\n res.__class__ = cls\n return res\n }\n\n dict.$factory = function(){\n var res = $B.DOMNode.$factory(\n document.createElementNS($svgNS, tagName))\n res.__class__ = dict\n // apply __init__\n dict.__init__(res, ...arguments)\n return res\n }\n\n $B.set_func_names(dict, \"browser.svg\")\n\n return dict\n}\n\n\n// SVG\nvar $svg_tags = ['a',\n'altGlyph',\n'altGlyphDef',\n'altGlyphItem',\n'animate',\n'animateColor',\n'animateMotion',\n'animateTransform',\n'circle',\n'clipPath',\n'color_profile', // instead of color-profile\n'cursor',\n'defs',\n'desc',\n'ellipse',\n'feBlend',\n'foreignObject', //patch to enable foreign objects\n'g',\n'image',\n'line',\n'linearGradient',\n'marker',\n'mask',\n'path',\n'pattern',\n'polygon',\n'polyline',\n'radialGradient',\n'rect',\n'set',\n'stop',\n'svg',\n'text',\n'tref',\n'tspan',\n'use']\n\n// create classes\nvar obj = new Object()\nvar dicts = {}\nfor(var i = 0, len = $svg_tags.length; i < len; i++){\n var tag = $svg_tags[i]\n obj[tag] = makeTagDict(tag)\n}\n\n$B.imported._svg = obj\n})(__BRYTHON__)\n"], "_symtable": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nvar module = $B.SYMBOL_FLAGS // in brython_builtins.js\n\nmodule.symtable = function(){\n var $ = $B.args('symtable', 3,\n {code: null, filename: null, compile_type: null},\n ['code', 'filename', 'compile_type'], arguments,\n {}, null, null)\n var ast = _b_.compile($.code, $.filename, $.compile_type,\n $B.PyCF_ONLY_AST)\n // ast is an instance of Python class\n // _Py_Symtable_Build in symtable.js uses the underlying JS object\n return $B._PySymtable_Build(ast.$js_ast, $.filename)\n}\n\n\n$B.addToImported('_symtable', module)\n\n})(__BRYTHON__)"], "_tokenize": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\n$B.$import('token')\n\nvar TokenizerIter = $B.make_class('TokenizerIter',\n function(it){\n return {\n __class__: TokenizerIter,\n it\n }\n }\n)\n\nTokenizerIter.__iter__ = function(self){\n var js_iter = function*(){\n var line_num = 0\n while(true){\n try{\n var bytes = self.it()\n }catch(err){\n if($B.is_exc(err, [_b_.StopIteration])){\n token = endmarker\n token.lineno++\n token.end_lineno++\n yield $B.fast_tuple([token.num_type, token.string,\n $B.fast_tuple([token.lineno, token.col_offset]),\n $B.fast_tuple([token.end_lineno, token.end_col_offset]),\n token.line])\n }\n throw err\n }\n line_num++\n var line = _b_.bytes.decode(bytes, 'utf-8')\n for(var token of $B.tokenizer(line, 'test')){\n if(token.num_type == $B.py_tokens.ENCODING){ // skip encoding token\n continue\n }else if(token.num_type == $B.py_tokens.ENDMARKER){\n var endmarker = token\n continue\n }\n token.type = token.num_type\n token.lineno = line_num\n token.end_lineno = line_num\n yield $B.fast_tuple([token.num_type, token.string,\n $B.fast_tuple([token.lineno, token.col_offset]),\n $B.fast_tuple([token.end_lineno, token.end_col_offset]),\n token.line])\n }\n }\n\n }\n return $B.generator.$factory(js_iter)()\n}\n\nTokenizerIter.__next__ = function*(self){\n\n}\n\n$B.set_func_names(TokenizerIter, '_tokenize')\n\n$B.addToImported('_tokenize', {TokenizerIter})\n\n\n})(__BRYTHON__)"], "_webcomponent": [".js", "// module for Web Components\n(function($B){\n\nvar _b_ = $B.builtins\n\nfunction define(tag_name, cls, options){\n var $ = $B.args(\"define\", 3, {tag_name: null, cls: null, options: null},\n [\"tag_name\", \"cls\", \"options\"], arguments, {options: _b_.None},\n null, null),\n tag_name = $.tag_name,\n cls = $.cls,\n options = $.options,\n _extends,\n extend_dom_name = 'HTMLElement'\n if(options !== _b_.None){\n if(! $B.$isinstance(options, _b_.dict)){\n throw _b_.TypeError.$factory('options can only be None or a ' +\n `dict, not '${$B.class_name(options)}'`)\n }\n try{\n _extends = _b_.dict.$getitem(options, 'extends')\n }catch(err){\n // ignore\n }\n }else{\n let stack = [...cls.__bases__];\n while(stack.length) {\n base = stack.pop();\n if(base.__module__ === 'browser.html'){\n _extends = base.__name__.toLowerCase()\n break\n }\n\n stack.push(...base.__bases__);\n }\n }\n\n if(_extends){\n if(typeof _extends != 'string'){\n throw _b_.TypeError.$factory('value for extends must be a ' +\n `string, not '${$B.class_name(_extends)}'`)\n }\n var elt = document.createElement(_extends)\n if(elt instanceof HTMLUnknownElement){\n throw _b_.ValueError.$factory(`'${_extends}' is not a valid ` +\n 'tag name')\n }\n var extend_tag = _extends.toLowerCase()\n extend_dom_name = Object.getPrototypeOf(elt).constructor.name\n }\n if(typeof tag_name != \"string\"){\n throw _b_.TypeError.$factory(\"first argument of define() \" +\n \"must be a string, not '\" + $B.class_name(tag_name) + \"'\")\n }else if(tag_name.indexOf(\"-\") == -1){\n throw _b_.ValueError.$factory(\"custom tag name must \" +\n \"contain a hyphen (-)\")\n }\n if(!$B.$isinstance(cls, _b_.type)){\n throw _b_.TypeError.$factory(\"second argument of define() \" +\n \"must be a class, not '\" + $B.class_name(tag_name) + \"'\")\n }\n cls.$webcomponent = true\n\n // Create the Javascript class used for the component. It must have\n // the same name as the Python class\n var src = String.raw`var WebComponent = class extends HTMLElement {\n constructor(){\n // Always call super first in constructor\n super()\n var html = $B.imported['browser.html']\n // Create tag in module html\n if(html['tag_name'] === undefined){\n html.maketag('tag_name', WebComponent)\n }\n var init = $B.$getattr(cls, \"__init__\", _b_.None)\n if(init !== _b_.None){\n try{\n var _self = $B.DOMNode.$factory(this),\n attrs_before_init = []\n for(var i = 0, len = _self.attributes.length; i < len; i++){\n attrs_before_init.push(_self.attributes.item(i))\n }\n _self.__class__ = cls\n _self.__dict__ = $B.empty_dict()\n $B.$call(init)(_self)\n if(WebComponent.initialized){\n // Check that init() did not introduce new attributes,\n // which is illegal\n // cf. https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-conformance\n for(var i = 0, len = _self.attributes.length; i < len; i++){\n var item = _self.attributes.item(i)\n if(attrs_before_init.indexOf(item) == -1){\n throw _b_.TypeError.$factory(\"Custom element \" +\n \"must not create attributes, found: \" +\n item.name + '=\"' + item.value + '\"')\n }\n }\n }\n }catch(err){\n $B.handle_error(err)\n }\n }\n }\n static get observedAttributes(){\n var obs_attr = $B.$getattr(cls, \"observedAttributes\", null)\n if(obs_attr === null){\n return []\n }\n if($B.$isinstance(obs_attr, _b_.property)){ // issue 2454\n obs_attr = obs_attr.fget(cls)\n }\n if(obs_attr === null){\n return []\n }else if(typeof obs_attr == \"function\"){\n var warning = _b_.DeprecationWarning.$factory(\n \"Setting observedAttributes as a method \" +\n \"is deprecated. Set it as a class attribute.\")\n // module _warning is in builtin_modules.js\n $B.imported._warnings.warn(warning)\n return $B.$call(obs_attr)(this)\n }else if(Array.isArray(obs_attr)){\n return obs_attr\n }else{\n throw _b_.TypeError.$factory(\n \"wrong type for observedAttributes: \" +\n $B.class_name(obs_attr))\n }\n }\n }\n `\n var name = cls.__name__,\n code = src.replace(/WebComponent/g, name).\n replace(/tag_name/g, tag_name).\n replace(/HTMLElement/, extend_dom_name)\n var src = eval(code)\n var webcomp = eval(name) // JS class for component\n webcomp.$cls = cls\n\n // Override __getattribute__ to handle DOMNode attributes such as\n // attachShadow\n cls.__getattribute__ = function(self, attr){\n try{\n return $B.DOMNode.__getattribute__(self, attr)\n }catch(err){\n if($B.DOMNode[attr]){\n if(typeof $B.DOMNode[attr] == 'function'){\n return function(){\n var args = [self]\n for(var i = 0, len = arguments.length; i < len; i++){\n args.push(arguments[i])\n }\n return $B.DOMNode[attr].apply(null, args)\n }\n }else{\n return $B.DOMNode[attr]\n }\n }\n throw err\n }\n }\n\n var mro = [cls].concat(cls.__mro__).reverse()\n for(var i = 0, len = mro.length; i < len; i++){\n var pcls = mro[i]\n for(var key in pcls){\n if((! webcomp.hasOwnProperty(key)) &&\n typeof pcls[key] == \"function\" &&\n // don't set $factory (would make it a class)\n key !== '$factory'\n ){\n webcomp.prototype[key] = (function(attr, klass){\n return function(){\n try{\n return $B.$call(klass[attr])($B.DOMNode.$factory(this), ...arguments)\n }catch(err){\n $B.show_error(err)\n }\n }\n })(key, pcls)\n }\n }\n }\n\n // define WebComp as the class to use for the specified tag name\n if(_extends){\n customElements.define(tag_name, webcomp, {extends: extend_tag})\n }else{\n customElements.define(tag_name, webcomp)\n }\n webcomp.initialized = true\n}\n\nfunction get(name){\n var ce = customElements.get(name)\n if(ce && ce.$cls){return ce.$cls}\n return _b_.None\n}\n\nvar module = {\n define: define,\n get: get\n}\n\n$B.addToImported('_webcomponent', module)\n\n})(__BRYTHON__)\n"], "_webworker": [".js", "// Web Worker implementation\n\n(function($B){\n\nvar _b_ = $B.builtins\n\nvar VFS = $B.brython_modules ? 'brython_modules' :\n $B.use_VFS ? 'brython_stdlib' : null\n\nfunction scripts_to_load(debug_level){\n if(debug_level > 2){\n var brython_scripts = [\n 'brython_builtins',\n\n 'py_ast_classes',\n 'stdlib_paths',\n 'unicode_data',\n 'version_info',\n\n 'py_tokens',\n 'python_tokenizer',\n 'py_ast',\n 'py2js',\n 'loaders',\n 'py_utils',\n 'py_object',\n 'py_type',\n 'py_builtin_functions',\n 'py_sort',\n 'py_exceptions',\n 'py_range_slice',\n 'py_bytes',\n 'py_set',\n 'py_import',\n 'py_string',\n 'py_int',\n 'py_long_int',\n 'py_float',\n 'py_complex',\n 'py_dict',\n 'py_list',\n 'js_objects',\n 'py_generator',\n 'py_dom',\n 'py_pattern_matching',\n 'async',\n 'py_flags',\n 'builtin_modules',\n 'ast_to_js',\n 'symtable',\n\n 'action_helpers_generated_version',\n 'string_parser',\n 'number_parser',\n 'python_parser_peg_version',\n 'pegen',\n 'gen_parse',\n 'brython_ready'\n ]\n }else{\n var brython_scripts = ['brython']\n }\n\n if(VFS !== null){\n brython_scripts.push(VFS)\n }\n return brython_scripts\n}\n\nvar wclass = $B.make_class(\"Worker\",\n function(worker){\n return {\n __class__: wclass,\n worker\n }\n }\n)\n\nwclass.send = function(){\n var $ = $B.args('send', 2, {self: null, message: null}, ['self', 'message'],\n arguments, {}, 'args', null)\n var message = $B.pyobj2structuredclone($.message)\n return $.self.worker.postMessage(message, ...$.args)\n}\n\nwclass.__mro__ = [$B.JSObj, _b_.object]\n\n$B.set_func_names(wclass, \"browser.worker\")\n\n\nvar _Worker = $B.make_class(\"Worker\", function(id, onmessage, onerror){\n $B.warn(_b_.DeprecationWarning,\n \"worker.Worker is deprecated in version 3.12. \" +\n \"Use worker.create_worker instead\")\n var $ = $B.args(\"__init__\", 3, {id: null, onmessage: null, onerror: null},\n ['id', 'onmessage', 'onerror'], arguments,\n {onmessage: _b_.None, onerror: _b_.None}, null, null),\n id = $.id,\n worker_script = $B.webworkers[id]\n\n if(worker_script === undefined){\n throw _b_.KeyError.$factory(id)\n }\n var filepath = worker_script.src ? worker_script.src : $B.script_path + \"#\" + id,\n filename = $B.strip_host(filepath),\n src = $B.file_cache[filename]\n\n var indexedDB = worker_script.attributes &&\n worker_script.attributes.getNamedItem('indexedDB')\n var script_id = \"worker\" + $B.UUID(),\n filename = $B.script_path + \"#\" + id\n $B.url2name[filename] = script_id\n\n var js = $B.py2js({src, filename}, script_id).to_js(),\n header = '';\n var brython_scripts = scripts_to_load(\n $B.get_option_from_filename('debug', filename))\n brython_scripts.forEach(function(script){\n if(script != VFS || VFS == \"brython_stdlib\"){\n var url = $B.brython_path + script + \".js\"\n }else{\n // attribute $B.brython_modules is set to the path of\n // brython_modules.js by the script itself\n var url = $B.brython_modules\n }\n if(! $B.get_option('cache')){ // cf. issue 1954\n url += '?' + (new Date()).getTime()\n }\n header += 'importScripts(\"' + url + '\")\\n'\n })\n // set __BRYTHON__.imported[script_id]\n header += `\n var $B = __BRYTHON__,\n _b_ = $B.builtins\n var module = $B.module.$factory(\"${script_id}\")\n module.__file__ = \"${filename}\"\n module.__doc__ = _b_.None\n $B.imported[\"${script_id}\"] = module\\n`\n // restore brython_path\n header += `$B.brython_path = \"${$B.brython_path}\"\\n`\n // restore path for imports (cf. issue #1305)\n header += `$B.make_import_paths(\"${filename}\")\\n`\n // Call brython() to initialize internal Brython values\n header += `brython(${JSON.stringify($B.$options)})\\n`\n js = header + js\n js = `try{${js}}catch(err){$B.handle_error(err)}`\n\n var blob = new Blob([js], {type: \"application/js\"}),\n url = URL.createObjectURL(blob),\n w = new Worker(url),\n res = wclass.$factory(w)\n return res\n})\n\nfunction create_worker(){\n var $ = $B.args(\"__init__\", 4,\n {id: null, onready: null, onmessage: null, onerror: null},\n ['id', 'onready', 'onmessage', 'onerror'], arguments,\n {onready: _b_.None, onmessage: _b_.None, onerror: _b_.None},\n null, null),\n id = $.id,\n worker_script = $B.webworkers[id],\n onready = $.onready === _b_.None ? _b_.None : $B.$call($.onready),\n onmessage = $.onmessage === _b_.None ? _b_.None : $B.$call($.onmessage),\n onerror = $.onerror === _b_.None ? _b_.None : $B.$call($.onerror)\n\n if(worker_script === undefined){\n throw _b_.RuntimeError.$factory(`No webworker with id '${id}'`)\n }\n var script_id = \"worker\" + $B.UUID(),\n filepath = worker_script.src ? worker_script.src : $B.script_path + \"#\" + id,\n filename = $B.strip_host(filepath),\n src = $B.file_cache[filename]\n $B.url2name[filename] = script_id\n\n var brython_scripts = scripts_to_load(\n $B.get_option_from_filename('debug', filename))\n\n var js = $B.py2js({src, filename}, script_id).to_js(),\n header = '';\n for(var script of brython_scripts){\n if(script != VFS || VFS == \"brython_stdlib\"){\n var url = $B.brython_path + script + \".js\"\n }else{\n // attribute $B.brython_modules is set to the path of\n // brython_modules.js by the script itself\n var url = $B.brython_modules\n }\n if(! $B.get_option('cache')){ // cf. issue 1954\n url += '?' + (new Date()).getTime()\n }\n header += 'importScripts(\"' + url + '\")\\n'\n }\n // set __BRYTHON__.imported[script_id]\n header += `\n var $B = __BRYTHON__,\n _b_ = $B.builtins\n var module = $B.module.$factory(\"${script_id}\")\n module.__file__ = \"${filename}\"\n module.__doc__ = _b_.None\n $B.script_domain = \"${$B.script_domain}\"\n $B.imported[\"${script_id}\"] = module\\n`\n\n header += '$B.file_cache[module.__file__] = `' + src + '`\\n'\n // restore brython_path\n header += `$B.brython_path = \"${$B.brython_path}\"\\n`\n // inject script attributes to get options\n header += `var script = $B.scripts[\"${filename}\"] = new $B.fakeScript()\\n`\n for(var key in $B.brython_options){\n var value = $B.brython_options[key]\n if(Array.isArray(value)){\n value = `[${value.map(x => '\"' + x + '\"')}]`\n }else{\n value = `\"${value}\"`\n }\n header += `script.options[\"${key}\"] = ${value}\\n`\n }\n\n for(var attr of worker_script.attributes){\n header += `script.options[\"${attr.name}\"] = \"${attr.value}\"\\n`\n }\n\n // restore path for imports (cf. issue #1305)\n header += `$B.make_import_paths(\"${filename}\")\\n`\n\n // Call brython() to initialize internal Brython values\n var save_option = JSON.stringify($B.brython_options)\n header += `brython(${save_option})\\n`\n\n // send dummy message to trigger resolution of Promise\n var ok_token = Math.random().toString(36).substr(2, 8),\n error_token = Math.random().toString(36).substr(2, 8)\n\n // open indexedDB cache before running worker code\n js = `$B.idb_open_promise().then(function(){\\n` +\n `try{\\n` +\n `${js}\\n` +\n `self.postMessage('${ok_token}')\\n` +\n `}catch(err){\\n` +\n `self.postMessage('${error_token}Error in worker \"${id}\"\\\\n'` +\n ` + $B.error_trace(err))\\n` +\n `}\\n})`\n js = header + js\n\n var p = new Promise(function(resolve, reject){\n try{\n var blob = new Blob([js], {type: \"application/js\"}),\n url = URL.createObjectURL(blob),\n w = new Worker(url),\n res = wclass.$factory(w)\n }catch(err){\n reject(err)\n }\n\n w.onmessage = function(ev){\n if(ev.data == ok_token){\n resolve(res)\n }else if(typeof ev.data == 'string' &&\n ev.data.startsWith(error_token)){\n reject(_b_.Exception.$factory(ev.data.substr(error_token.length)))\n }else{\n if(onmessage !== _b_.None){\n onmessage(ev)\n }\n try{\n resolve(res)\n }catch(err){\n reject(err)\n }\n }\n }\n\n return res\n })\n\n var error_func = onerror === _b_.None ? $B.handle_error : onerror\n\n if(onready !== _b_.None){\n p.then(onready).catch(error_func)\n }else{\n p.catch(error_func)\n }\n return _b_.None\n}\n\nvar module = {\n Worker: _Worker,\n create_worker\n}\n\n$B.addToImported('_webworker', module)\n\n})(__BRYTHON__)\n"], "_zlib_utils": [".js", "\n\n(function($B){\n\nfunction Text(bytes){\n this.bytes = bytes\n this.length = bytes.length\n this.hash = {} // this.hash[pos] is the hash of the 3-elt sequence at pos\n this.hash_pos = {} // maps hashes to list of positions in bytes\n this.hash_start = -1\n}\n\nText.prototype.at = function(pos){\n return this.bytes[pos]\n}\n\nText.prototype.make_hashes = function(start, end){\n // for all 3-elt sequences from start to end, store the position of the\n // hash\n for(var pos = start; pos < end; pos++){\n if(this.hash.hasOwnProperty(pos)){\n continue\n }\n var hash = this.hash[pos] = this.make_hash(pos)\n if(pos == 27){\n console.log('hash for pos', pos)\n console.log(this.hash_pos[hash])\n alert()\n }\n if(this.hash_pos.hasOwnProperty(hash)){\n var item = this.hash_pos[hash]\n while(item.next !== null){\n item = item.next\n }\n item.next = {pos, next: null}\n }else{\n this.hash_pos[hash] = {pos, next: null}\n\n }\n }\n if(end == 28){\n console.log('start', start, 'end', end)\n console.log(this.hash_pos)\n alert()\n }\n}\n\nText.prototype.make_hash = function(pos){\n return this.at(pos) +\n (this.at(pos + 1) << 8) +\n (this.at(pos + 2) << 16)\n}\n\nfunction HashChain(value, pointer){\n // points to the first position in text where hash == value\n this.pointer = pointer\n}\n\nfunction rfind1(text, start, end, seq){\n // find seq in text starting at start\n var pos = start,\n len = seq.length,\n found\n while(pos < end - len){\n if(text[pos] == seq[0]){\n found = true\n for(var i = 1; i < len; i++){\n if(text[pos + i] != seq[i]){\n found = false\n break\n }\n }\n if(found){\n return pos\n }\n }\n pos++\n }\n return -1\n}\n\nfunction rfind2(text, start, pos){\n //text.make_hashes(start, pos)\n var h = text.make_hash(pos)\n if(! text.hash_pos.hasOwnProperty(h)){\n // hash was not found\n text.hash_pos[h] = {pos, next: null}\n return -1\n }else{\n var item = text.hash_pos[h]\n // discard items before start\n while(item.pos < start){\n if(item.next !== null){\n item = item.next\n text.hash_pos[h] = item\n }else{\n // no item found after start\n text.hash_pos[h] = {pos, next: null}\n return -1\n }\n }\n var found_at = item.pos\n while(item.next !== null){\n item = item.next\n }\n item.next = {pos, next: null}\n return found_at\n }\n}\n\nfunction rfind(buf, seq){\n var buflen = buf.length,\n len = seq.length\n for(var i = buflen - len; i >= 0; i--){\n var chunk = buf.slice(i, i + len),\n found = true\n for(var j = 0; j < len; j++){\n if(chunk[j] != seq[j]){\n found = false\n break\n }\n }\n if(found){\n return i\n }\n }\n return -1\n}\n\nfunction to_str(bytes){\n return bytes.map(x => String.fromCodePoint(x)).join('')\n}\n\nfunction restore(items){\n var s = ''\n for(var item of items){\n if(typeof item == \"number\"){\n s += String.fromCodePoint(item)\n }else{\n var len = item[0],\n distance = item[1]\n s += s.substr(s.length - distance, len)\n }\n }\n return s\n}\n\nvar c;\nvar crcTable = [];\nfor(var n =0; n < 256; n++){\n c = n;\n for(var k =0; k < 8; k++){\n c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n}\n\nvar mod = {\n crc32: function(bytes, crc) {\n var crc = crc ^ (-1);\n\n for (var byte of bytes.source) {\n crc = (crc >>> 8) ^ crcTable[(crc ^ byte) & 0xFF];\n }\n\n return (crc ^ (-1)) >>> 0;\n },\n\n lz_generator: function(text, size, min_len){\n /*\n Returns a list of items based on the LZ algorithm, using the\n specified window size and a minimum match length.\n The items are a tuple (length, distance) if a match has been\n found, and a byte otherwise.\n */\n // 'text' is an instance of Python 'bytes' class, the actual\n // bytes are in text.source\n text = new Text(text.source)\n if(min_len === undefined){\n min_len = 3\n }\n var pos = 0, // position in text\n items = [], // returned items\n start\n var t0 = globalThis.performance.now()\n var nb = 1000,\n delta = 1000\n while(pos < text.length){\n if(pos > text.length - min_len){\n for(var i = pos; i < text.length; i++){\n items.push(text.at(i))\n }\n break\n }\n // Search the sequence in the 'size' previous bytes\n start = Math.max(0, pos - size)\n buf_pos = rfind2(text, start, pos)\n if(buf_pos > -1 && buf_pos < pos - min_len){\n // Match of length 3 found; search a longer one\n var len = 1\n while(len < 258 &&\n buf_pos + len < pos &&\n pos + len < text.length &&\n text.at(pos + len) == text.at(buf_pos + len)){\n len += 1\n }\n // \"Lazy matching\": search longer match starting at next\n // position\n longer_match = false\n if(pos + len < text.length - 2){\n // match2 = text.slice(pos + 1, pos + len + 2)\n var start1 = pos + 1\n end = pos + len + 2\n longer_buf_pos = rfind2(text, start1, end)\n if(longer_buf_pos > -1){\n // found longer match : emit current byte as\n // literal and move 1 byte forward\n longer_match = true\n char = text.at(pos)\n items.push(char)\n pos += 1\n }\n }\n if(! longer_match){\n // position of match start in text is buf_pos\n // distance is pos - buf_pos\n var distance = pos - buf_pos\n items.push($B.fast_tuple([len, distance]))\n if(pos + len == text.length){\n break\n }else{\n pos += len\n items.push(text.at(pos))\n pos += 1\n }\n }\n }else{\n char = text.bytes[pos]\n items.push(char)\n pos += 1\n }\n }\n return $B.$list(items)\n }\n\n}\n\n$B.addToImported('_zlib_utils', mod)\n\n})(__BRYTHON__)\n"], "crypto_js": [".py", "", [], 1], "crypto_js.rollups": [".py", "", [], 1], "crypto_js.rollups.md5": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(s,p){var m={},l=m.lib={},n=function(){},r=l.Base={extend:function(b){n.prototype=this;var h=new n;b&&h.mixIn(b);h.hasOwnProperty(\"init\")||(h.init=function(){h.$super.init.apply(this,arguments)});h.init.prototype=h;h.$super=this;return h},create:function(){var b=this.extend();b.init.apply(b,arguments);return b},init:function(){},mixIn:function(b){for(var h in b)b.hasOwnProperty(h)&&(this[h]=b[h]);b.hasOwnProperty(\"toString\")&&(this.toString=b.toString)},clone:function(){return this.init.prototype.extend(this)}},\nq=l.WordArray=r.extend({init:function(b,h){b=this.words=b||[];this.sigBytes=h!=p?h:4*b.length},toString:function(b){return(b||t).stringify(this)},concat:function(b){var h=this.words,a=b.words,j=this.sigBytes;b=b.sigBytes;this.clamp();if(j%4)for(var g=0;g>>2]|=(a[g>>>2]>>>24-8*(g%4)&255)<<24-8*((j+g)%4);else if(65535>>2]=a[g>>>2];else h.push.apply(h,a);this.sigBytes+=b;return this},clamp:function(){var b=this.words,h=this.sigBytes;b[h>>>2]&=4294967295<<\n32-8*(h%4);b.length=s.ceil(h/4)},clone:function(){var b=r.clone.call(this);b.words=this.words.slice(0);return b},random:function(b){for(var h=[],a=0;a>>2]>>>24-8*(j%4)&255;g.push((k>>>4).toString(16));g.push((k&15).toString(16))}return g.join(\"\")},parse:function(b){for(var a=b.length,g=[],j=0;j>>3]|=parseInt(b.substr(j,\n2),16)<<24-4*(j%8);return new q.init(g,a/2)}},a=v.Latin1={stringify:function(b){var a=b.words;b=b.sigBytes;for(var g=[],j=0;j>>2]>>>24-8*(j%4)&255));return g.join(\"\")},parse:function(b){for(var a=b.length,g=[],j=0;j>>2]|=(b.charCodeAt(j)&255)<<24-8*(j%4);return new q.init(g,a)}},u=v.Utf8={stringify:function(b){try{return decodeURIComponent(escape(a.stringify(b)))}catch(g){throw Error(\"Malformed UTF-8 data\");}},parse:function(b){return a.parse(unescape(encodeURIComponent(b)))}},\ng=l.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(b){\"string\"==typeof b&&(b=u.parse(b));this._data.concat(b);this._nDataBytes+=b.sigBytes},_process:function(b){var a=this._data,g=a.words,j=a.sigBytes,k=this.blockSize,m=j/(4*k),m=b?s.ceil(m):s.max((m|0)-this._minBufferSize,0);b=m*k;j=s.min(4*b,j);if(b){for(var l=0;l>>32-j)+k}function m(a,k,b,h,l,j,m){a=a+(k&h|b&~h)+l+m;return(a<>>32-j)+k}function l(a,k,b,h,l,j,m){a=a+(k^b^h)+l+m;return(a<>>32-j)+k}function n(a,k,b,h,l,j,m){a=a+(b^(k|~h))+l+m;return(a<>>32-j)+k}for(var r=CryptoJS,q=r.lib,v=q.WordArray,t=q.Hasher,q=r.algo,a=[],u=0;64>u;u++)a[u]=4294967296*s.abs(s.sin(u+1))|0;q=q.MD5=t.extend({_doReset:function(){this._hash=new v.init([1732584193,4023233417,2562383102,271733878])},\n_doProcessBlock:function(g,k){for(var b=0;16>b;b++){var h=k+b,w=g[h];g[h]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}var b=this._hash.words,h=g[k+0],w=g[k+1],j=g[k+2],q=g[k+3],r=g[k+4],s=g[k+5],t=g[k+6],u=g[k+7],v=g[k+8],x=g[k+9],y=g[k+10],z=g[k+11],A=g[k+12],B=g[k+13],C=g[k+14],D=g[k+15],c=b[0],d=b[1],e=b[2],f=b[3],c=p(c,d,e,f,h,7,a[0]),f=p(f,c,d,e,w,12,a[1]),e=p(e,f,c,d,j,17,a[2]),d=p(d,e,f,c,q,22,a[3]),c=p(c,d,e,f,r,7,a[4]),f=p(f,c,d,e,s,12,a[5]),e=p(e,f,c,d,t,17,a[6]),d=p(d,e,f,c,u,22,a[7]),\nc=p(c,d,e,f,v,7,a[8]),f=p(f,c,d,e,x,12,a[9]),e=p(e,f,c,d,y,17,a[10]),d=p(d,e,f,c,z,22,a[11]),c=p(c,d,e,f,A,7,a[12]),f=p(f,c,d,e,B,12,a[13]),e=p(e,f,c,d,C,17,a[14]),d=p(d,e,f,c,D,22,a[15]),c=m(c,d,e,f,w,5,a[16]),f=m(f,c,d,e,t,9,a[17]),e=m(e,f,c,d,z,14,a[18]),d=m(d,e,f,c,h,20,a[19]),c=m(c,d,e,f,s,5,a[20]),f=m(f,c,d,e,y,9,a[21]),e=m(e,f,c,d,D,14,a[22]),d=m(d,e,f,c,r,20,a[23]),c=m(c,d,e,f,x,5,a[24]),f=m(f,c,d,e,C,9,a[25]),e=m(e,f,c,d,q,14,a[26]),d=m(d,e,f,c,v,20,a[27]),c=m(c,d,e,f,B,5,a[28]),f=m(f,c,\nd,e,j,9,a[29]),e=m(e,f,c,d,u,14,a[30]),d=m(d,e,f,c,A,20,a[31]),c=l(c,d,e,f,s,4,a[32]),f=l(f,c,d,e,v,11,a[33]),e=l(e,f,c,d,z,16,a[34]),d=l(d,e,f,c,C,23,a[35]),c=l(c,d,e,f,w,4,a[36]),f=l(f,c,d,e,r,11,a[37]),e=l(e,f,c,d,u,16,a[38]),d=l(d,e,f,c,y,23,a[39]),c=l(c,d,e,f,B,4,a[40]),f=l(f,c,d,e,h,11,a[41]),e=l(e,f,c,d,q,16,a[42]),d=l(d,e,f,c,t,23,a[43]),c=l(c,d,e,f,x,4,a[44]),f=l(f,c,d,e,A,11,a[45]),e=l(e,f,c,d,D,16,a[46]),d=l(d,e,f,c,j,23,a[47]),c=n(c,d,e,f,h,6,a[48]),f=n(f,c,d,e,u,10,a[49]),e=n(e,f,c,d,\nC,15,a[50]),d=n(d,e,f,c,s,21,a[51]),c=n(c,d,e,f,A,6,a[52]),f=n(f,c,d,e,q,10,a[53]),e=n(e,f,c,d,y,15,a[54]),d=n(d,e,f,c,w,21,a[55]),c=n(c,d,e,f,v,6,a[56]),f=n(f,c,d,e,D,10,a[57]),e=n(e,f,c,d,t,15,a[58]),d=n(d,e,f,c,B,21,a[59]),c=n(c,d,e,f,r,6,a[60]),f=n(f,c,d,e,z,10,a[61]),e=n(e,f,c,d,j,15,a[62]),d=n(d,e,f,c,x,21,a[63]);b[0]=b[0]+c|0;b[1]=b[1]+d|0;b[2]=b[2]+e|0;b[3]=b[3]+f|0},_doFinalize:function(){var a=this._data,k=a.words,b=8*this._nDataBytes,h=8*a.sigBytes;k[h>>>5]|=128<<24-h%32;var l=s.floor(b/\n4294967296);k[(h+64>>>9<<4)+15]=(l<<8|l>>>24)&16711935|(l<<24|l>>>8)&4278255360;k[(h+64>>>9<<4)+14]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;a.sigBytes=4*(k.length+1);this._process();a=this._hash;k=a.words;for(b=0;4>b;b++)h=k[b],k[b]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360;return a},clone:function(){var a=t.clone.call(this);a._hash=this._hash.clone();return a}});r.MD5=t._createHelper(q);r.HmacMD5=t._createHmacHelper(q)})(Math);\n"], "crypto_js.rollups.sha1": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(e,m){var p={},j=p.lib={},l=function(){},f=j.Base={extend:function(a){l.prototype=this;var c=new l;a&&c.mixIn(a);c.hasOwnProperty(\"init\")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\nn=j.WordArray=f.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=m?c:4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var c=this.words,q=a.words,d=this.sigBytes;a=a.sigBytes;this.clamp();if(d%4)for(var b=0;b>>2]|=(q[b>>>2]>>>24-8*(b%4)&255)<<24-8*((d+b)%4);else if(65535>>2]=q[b>>>2];else c.push.apply(c,q);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<\n32-8*(c%4);a.length=e.ceil(c/4)},clone:function(){var a=f.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b>>2]>>>24-8*(d%4)&255;b.push((f>>>4).toString(16));b.push((f&15).toString(16))}return b.join(\"\")},parse:function(a){for(var c=a.length,b=[],d=0;d>>3]|=parseInt(a.substr(d,\n2),16)<<24-4*(d%8);return new n.init(b,c/2)}},g=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],d=0;d>>2]>>>24-8*(d%4)&255));return b.join(\"\")},parse:function(a){for(var c=a.length,b=[],d=0;d>>2]|=(a.charCodeAt(d)&255)<<24-8*(d%4);return new n.init(b,c)}},r=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(g.stringify(a)))}catch(c){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return g.parse(unescape(encodeURIComponent(a)))}},\nk=j.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new n.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=r.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,b=c.words,d=c.sigBytes,f=this.blockSize,h=d/(4*f),h=a?e.ceil(h):e.max((h|0)-this._minBufferSize,0);a=h*f;d=e.min(4*a,d);if(a){for(var g=0;ga;a++){if(16>a)l[a]=f[n+a]|0;else{var c=l[a-3]^l[a-8]^l[a-14]^l[a-16];l[a]=c<<1|c>>>31}c=(h<<5|h>>>27)+j+l[a];c=20>a?c+((g&e|~g&k)+1518500249):40>a?c+((g^e^k)+1859775393):60>a?c+((g&e|g&k|e&k)-1894007588):c+((g^e^\nk)-899497514);j=k;k=e;e=g<<30|g>>>2;g=h;h=c}b[0]=b[0]+h|0;b[1]=b[1]+g|0;b[2]=b[2]+e|0;b[3]=b[3]+k|0;b[4]=b[4]+j|0},_doFinalize:function(){var f=this._data,e=f.words,b=8*this._nDataBytes,h=8*f.sigBytes;e[h>>>5]|=128<<24-h%32;e[(h+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(h+64>>>9<<4)+15]=b;f.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=j.clone.call(this);e._hash=this._hash.clone();return e}});e.SHA1=j._createHelper(m);e.HmacSHA1=j._createHmacHelper(m)})();\n"], "crypto_js.rollups.sha224": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(g,l){var f={},k=f.lib={},h=function(){},m=k.Base={extend:function(a){h.prototype=this;var c=new h;a&&c.mixIn(a);c.hasOwnProperty(\"init\")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\nq=k.WordArray=m.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=l?c:4*a.length},toString:function(a){return(a||s).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<\n32-8*(c%4);a.length=g.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join(\"\")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b,\n2),16)<<24-4*(b%8);return new q.init(d,c/2)}},n=t.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join(\"\")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new q.init(d,c)}},j=t.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}},\nw=k.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?g.ceil(f):g.max((f|0)-this._minBufferSize,0);a=f*e;b=g.min(4*a,b);if(a){for(var u=0;un;){var j;a:{j=s;for(var w=g.sqrt(j),v=2;v<=w;v++)if(!(j%v)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=t(g.pow(s,0.5))),q[n]=t(g.pow(s,1/3)),n++);s++}var a=[],f=f.SHA256=h.extend({_doReset:function(){this._hash=new k.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],k=b[3],h=b[4],l=b[5],m=b[6],n=b[7],p=0;64>p;p++){if(16>p)a[p]=\nc[d+p]|0;else{var j=a[p-15],r=a[p-2];a[p]=((j<<25|j>>>7)^(j<<14|j>>>18)^j>>>3)+a[p-7]+((r<<15|r>>>17)^(r<<13|r>>>19)^r>>>10)+a[p-16]}j=n+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&l^~h&m)+q[p]+a[p];r=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);n=m;m=l;l=h;h=k+j|0;k=g;g=f;f=e;e=j+r|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+k|0;b[4]=b[4]+h|0;b[5]=b[5]+l|0;b[6]=b[6]+m|0;b[7]=b[7]+n|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes;\nd[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=g.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=h.clone.call(this);a._hash=this._hash.clone();return a}});l.SHA256=h._createHelper(f);l.HmacSHA256=h._createHmacHelper(f)})(Math);\n(function(){var g=CryptoJS,l=g.lib.WordArray,f=g.algo,k=f.SHA256,f=f.SHA224=k.extend({_doReset:function(){this._hash=new l.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var f=k._doFinalize.call(this);f.sigBytes-=4;return f}});g.SHA224=k._createHelper(f);g.HmacSHA224=k._createHmacHelper(f)})();\n"], "crypto_js.rollups.sha256": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(h,s){var f={},t=f.lib={},g=function(){},j=t.Base={extend:function(a){g.prototype=this;var c=new g;a&&c.mixIn(a);c.hasOwnProperty(\"init\")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\nq=t.WordArray=j.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=s?c:4*a.length},toString:function(a){return(a||u).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<\n32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=j.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join(\"\")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b,\n2),16)<<24-4*(b%8);return new q.init(d,c/2)}},k=v.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join(\"\")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new q.init(d,c)}},l=v.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch(c){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}},\nx=t.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=l.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var m=0;mk;){var l;a:{l=u;for(var x=h.sqrt(l),w=2;w<=x;w++)if(!(l%w)){l=!1;break a}l=!0}l&&(8>k&&(j[k]=v(h.pow(u,0.5))),q[k]=v(h.pow(u,1/3)),k++);u++}var a=[],f=f.SHA256=g.extend({_doReset:function(){this._hash=new t.init(j.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],m=b[2],h=b[3],p=b[4],j=b[5],k=b[6],l=b[7],n=0;64>n;n++){if(16>n)a[n]=\nc[d+n]|0;else{var r=a[n-15],g=a[n-2];a[n]=((r<<25|r>>>7)^(r<<14|r>>>18)^r>>>3)+a[n-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+a[n-16]}r=l+((p<<26|p>>>6)^(p<<21|p>>>11)^(p<<7|p>>>25))+(p&j^~p&k)+q[n]+a[n];g=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&m^f&m);l=k;k=j;j=p;p=h+r|0;h=m;m=f;f=e;e=r+g|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+m|0;b[3]=b[3]+h|0;b[4]=b[4]+p|0;b[5]=b[5]+j|0;b[6]=b[6]+k|0;b[7]=b[7]+l|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes;\nd[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=g.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=g._createHelper(f);s.HmacSHA256=g._createHmacHelper(f)})(Math);\n"], "crypto_js.rollups.sha3": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(v,p){var d={},u=d.lib={},r=function(){},f=u.Base={extend:function(a){r.prototype=this;var b=new r;a&&b.mixIn(a);b.hasOwnProperty(\"init\")||(b.init=function(){b.$super.init.apply(this,arguments)});b.init.prototype=b;b.$super=this;return b},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\ns=u.WordArray=f.extend({init:function(a,b){a=this.words=a||[];this.sigBytes=b!=p?b:4*a.length},toString:function(a){return(a||y).stringify(this)},concat:function(a){var b=this.words,c=a.words,j=this.sigBytes;a=a.sigBytes;this.clamp();if(j%4)for(var n=0;n>>2]|=(c[n>>>2]>>>24-8*(n%4)&255)<<24-8*((j+n)%4);else if(65535>>2]=c[n>>>2];else b.push.apply(b,c);this.sigBytes+=a;return this},clamp:function(){var a=this.words,b=this.sigBytes;a[b>>>2]&=4294967295<<\n32-8*(b%4);a.length=v.ceil(b/4)},clone:function(){var a=f.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var b=[],c=0;c>>2]>>>24-8*(j%4)&255;c.push((n>>>4).toString(16));c.push((n&15).toString(16))}return c.join(\"\")},parse:function(a){for(var b=a.length,c=[],j=0;j>>3]|=parseInt(a.substr(j,\n2),16)<<24-4*(j%8);return new s.init(c,b/2)}},e=x.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var c=[],j=0;j>>2]>>>24-8*(j%4)&255));return c.join(\"\")},parse:function(a){for(var b=a.length,c=[],j=0;j>>2]|=(a.charCodeAt(j)&255)<<24-8*(j%4);return new s.init(c,b)}},q=x.Utf8={stringify:function(a){try{return decodeURIComponent(escape(e.stringify(a)))}catch(b){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return e.parse(unescape(encodeURIComponent(a)))}},\nt=u.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new s.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=q.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,c=b.words,j=b.sigBytes,n=this.blockSize,e=j/(4*n),e=a?v.ceil(e):v.max((e|0)-this._minBufferSize,0);a=e*n;j=v.min(4*a,j);if(a){for(var f=0;ft;t++){s[e+5*q]=(t+1)*(t+2)/2%64;var w=(2*e+3*q)%5,e=q%5,q=w}for(e=0;5>e;e++)for(q=0;5>q;q++)x[e+5*q]=q+5*((2*e+3*q)%5);e=1;for(q=0;24>q;q++){for(var a=w=t=0;7>a;a++){if(e&1){var b=(1<b?w^=1<e;e++)c[e]=f.create();d=d.SHA3=r.extend({cfg:r.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=\n[],b=0;25>b;b++)a[b]=new f.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var e=this._state,f=this.blockSize/2,h=0;h>>24)&16711935|(l<<24|l>>>8)&4278255360,m=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360,g=e[h];g.high^=m;g.low^=l}for(f=0;24>f;f++){for(h=0;5>h;h++){for(var d=l=0,k=0;5>k;k++)g=e[h+5*k],l^=g.high,d^=g.low;g=c[h];g.high=l;g.low=d}for(h=0;5>h;h++){g=c[(h+4)%5];l=c[(h+1)%5];m=l.high;k=l.low;l=g.high^\n(m<<1|k>>>31);d=g.low^(k<<1|m>>>31);for(k=0;5>k;k++)g=e[h+5*k],g.high^=l,g.low^=d}for(m=1;25>m;m++)g=e[m],h=g.high,g=g.low,k=s[m],32>k?(l=h<>>32-k,d=g<>>32-k):(l=g<>>64-k,d=h<>>64-k),g=c[x[m]],g.high=l,g.low=d;g=c[0];h=e[0];g.high=h.high;g.low=h.low;for(h=0;5>h;h++)for(k=0;5>k;k++)m=h+5*k,g=e[m],l=c[m],m=c[(h+1)%5+5*k],d=c[(h+2)%5+5*k],g.high=l.high^~m.high&d.high,g.low=l.low^~m.low&d.low;g=e[0];h=y[f];g.high^=h.high;g.low^=h.low}},_doFinalize:function(){var a=this._data,\nb=a.words,c=8*a.sigBytes,e=32*this.blockSize;b[c>>>5]|=1<<24-c%32;b[(v.ceil((c+1)/e)*e>>>5)-1]|=128;a.sigBytes=4*b.length;this._process();for(var a=this._state,b=this.cfg.outputLength/8,c=b/8,e=[],h=0;h>>24)&16711935|(f<<24|f>>>8)&4278255360,d=(d<<8|d>>>24)&16711935|(d<<24|d>>>8)&4278255360;e.push(d);e.push(f)}return new u.init(e,b)},clone:function(){for(var a=r.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});\np.SHA3=r._createHelper(d);p.HmacSHA3=r._createHmacHelper(d)})(Math);\n"], "crypto_js.rollups.sha384": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(a,c){var d={},j=d.lib={},f=function(){},m=j.Base={extend:function(a){f.prototype=this;var b=new f;a&&b.mixIn(a);b.hasOwnProperty(\"init\")||(b.init=function(){b.$super.init.apply(this,arguments)});b.init.prototype=b;b.$super=this;return b},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\nB=j.WordArray=m.extend({init:function(a,b){a=this.words=a||[];this.sigBytes=b!=c?b:4*a.length},toString:function(a){return(a||y).stringify(this)},concat:function(a){var b=this.words,g=a.words,e=this.sigBytes;a=a.sigBytes;this.clamp();if(e%4)for(var k=0;k>>2]|=(g[k>>>2]>>>24-8*(k%4)&255)<<24-8*((e+k)%4);else if(65535>>2]=g[k>>>2];else b.push.apply(b,g);this.sigBytes+=a;return this},clamp:function(){var n=this.words,b=this.sigBytes;n[b>>>2]&=4294967295<<\n32-8*(b%4);n.length=a.ceil(b/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(n){for(var b=[],g=0;g>>2]>>>24-8*(e%4)&255;g.push((k>>>4).toString(16));g.push((k&15).toString(16))}return g.join(\"\")},parse:function(a){for(var b=a.length,g=[],e=0;e>>3]|=parseInt(a.substr(e,\n2),16)<<24-4*(e%8);return new B.init(g,b/2)}},F=v.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var g=[],e=0;e>>2]>>>24-8*(e%4)&255));return g.join(\"\")},parse:function(a){for(var b=a.length,g=[],e=0;e>>2]|=(a.charCodeAt(e)&255)<<24-8*(e%4);return new B.init(g,b)}},ha=v.Utf8={stringify:function(a){try{return decodeURIComponent(escape(F.stringify(a)))}catch(b){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return F.parse(unescape(encodeURIComponent(a)))}},\nZ=j.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new B.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=ha.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(n){var b=this._data,g=b.words,e=b.sigBytes,k=this.blockSize,m=e/(4*k),m=n?a.ceil(m):a.max((m|0)-this._minBufferSize,0);n=m*k;e=a.min(4*n,e);if(n){for(var c=0;cy;y++)v[y]=a();j=j.SHA512=d.extend({_doReset:function(){this._hash=new m.init([new f.init(1779033703,4089235720),new f.init(3144134277,2227873595),new f.init(1013904242,4271175723),new f.init(2773480762,1595750129),new f.init(1359893119,2917565137),new f.init(2600822924,725511199),new f.init(528734635,4215389547),new f.init(1541459225,327033209)])},_doProcessBlock:function(a,c){for(var d=this._hash.words,\nf=d[0],j=d[1],b=d[2],g=d[3],e=d[4],k=d[5],m=d[6],d=d[7],y=f.high,M=f.low,$=j.high,N=j.low,aa=b.high,O=b.low,ba=g.high,P=g.low,ca=e.high,Q=e.low,da=k.high,R=k.low,ea=m.high,S=m.low,fa=d.high,T=d.low,s=y,p=M,G=$,D=N,H=aa,E=O,W=ba,I=P,t=ca,q=Q,U=da,J=R,V=ea,K=S,X=fa,L=T,u=0;80>u;u++){var z=v[u];if(16>u)var r=z.high=a[c+2*u]|0,h=z.low=a[c+2*u+1]|0;else{var r=v[u-15],h=r.high,w=r.low,r=(h>>>1|w<<31)^(h>>>8|w<<24)^h>>>7,w=(w>>>1|h<<31)^(w>>>8|h<<24)^(w>>>7|h<<25),C=v[u-2],h=C.high,l=C.low,C=(h>>>19|l<<\n13)^(h<<3|l>>>29)^h>>>6,l=(l>>>19|h<<13)^(l<<3|h>>>29)^(l>>>6|h<<26),h=v[u-7],Y=h.high,A=v[u-16],x=A.high,A=A.low,h=w+h.low,r=r+Y+(h>>>0>>0?1:0),h=h+l,r=r+C+(h>>>0>>0?1:0),h=h+A,r=r+x+(h>>>0>>0?1:0);z.high=r;z.low=h}var Y=t&U^~t&V,A=q&J^~q&K,z=s&G^s&H^G&H,ja=p&D^p&E^D&E,w=(s>>>28|p<<4)^(s<<30|p>>>2)^(s<<25|p>>>7),C=(p>>>28|s<<4)^(p<<30|s>>>2)^(p<<25|s>>>7),l=B[u],ka=l.high,ga=l.low,l=L+((q>>>14|t<<18)^(q>>>18|t<<14)^(q<<23|t>>>9)),x=X+((t>>>14|q<<18)^(t>>>18|q<<14)^(t<<23|q>>>9))+(l>>>0<\nL>>>0?1:0),l=l+A,x=x+Y+(l>>>0>>0?1:0),l=l+ga,x=x+ka+(l>>>0>>0?1:0),l=l+h,x=x+r+(l>>>0>>0?1:0),h=C+ja,z=w+z+(h>>>0>>0?1:0),X=V,L=K,V=U,K=J,U=t,J=q,q=I+l|0,t=W+x+(q>>>0>>0?1:0)|0,W=H,I=E,H=G,E=D,G=s,D=p,p=l+h|0,s=x+z+(p>>>0>>0?1:0)|0}M=f.low=M+p;f.high=y+s+(M>>>0

>>0?1:0);N=j.low=N+D;j.high=$+G+(N>>>0>>0?1:0);O=b.low=O+E;b.high=aa+H+(O>>>0>>0?1:0);P=g.low=P+I;g.high=ba+W+(P>>>0>>0?1:0);Q=e.low=Q+q;e.high=ca+t+(Q>>>0>>0?1:0);R=k.low=R+J;k.high=da+U+(R>>>0>>0?1:0);\nS=m.low=S+K;m.high=ea+V+(S>>>0>>0?1:0);T=d.low=T+L;d.high=fa+X+(T>>>0>>0?1:0)},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,f=8*a.sigBytes;c[f>>>5]|=128<<24-f%32;c[(f+128>>>10<<5)+30]=Math.floor(d/4294967296);c[(f+128>>>10<<5)+31]=d;a.sigBytes=4*c.length;this._process();return this._hash.toX32()},clone:function(){var a=d.clone.call(this);a._hash=this._hash.clone();return a},blockSize:32});c.SHA512=d._createHelper(j);c.HmacSHA512=d._createHmacHelper(j)})();\n(function(){var a=CryptoJS,c=a.x64,d=c.Word,j=c.WordArray,c=a.algo,f=c.SHA512,c=c.SHA384=f.extend({_doReset:function(){this._hash=new j.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=f._doFinalize.call(this);a.sigBytes-=16;return a}});a.SHA384=\nf._createHelper(c);a.HmacSHA384=f._createHmacHelper(c)})();\n"], "crypto_js.rollups.sha512": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(a,m){var r={},f=r.lib={},g=function(){},l=f.Base={extend:function(a){g.prototype=this;var b=new g;a&&b.mixIn(a);b.hasOwnProperty(\"init\")||(b.init=function(){b.$super.init.apply(this,arguments)});b.init.prototype=b;b.$super=this;return b},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\np=f.WordArray=l.extend({init:function(a,b){a=this.words=a||[];this.sigBytes=b!=m?b:4*a.length},toString:function(a){return(a||q).stringify(this)},concat:function(a){var b=this.words,d=a.words,c=this.sigBytes;a=a.sigBytes;this.clamp();if(c%4)for(var j=0;j>>2]|=(d[j>>>2]>>>24-8*(j%4)&255)<<24-8*((c+j)%4);else if(65535>>2]=d[j>>>2];else b.push.apply(b,d);this.sigBytes+=a;return this},clamp:function(){var n=this.words,b=this.sigBytes;n[b>>>2]&=4294967295<<\n32-8*(b%4);n.length=a.ceil(b/4)},clone:function(){var a=l.clone.call(this);a.words=this.words.slice(0);return a},random:function(n){for(var b=[],d=0;d>>2]>>>24-8*(c%4)&255;d.push((j>>>4).toString(16));d.push((j&15).toString(16))}return d.join(\"\")},parse:function(a){for(var b=a.length,d=[],c=0;c>>3]|=parseInt(a.substr(c,\n2),16)<<24-4*(c%8);return new p.init(d,b/2)}},G=y.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var d=[],c=0;c>>2]>>>24-8*(c%4)&255));return d.join(\"\")},parse:function(a){for(var b=a.length,d=[],c=0;c>>2]|=(a.charCodeAt(c)&255)<<24-8*(c%4);return new p.init(d,b)}},fa=y.Utf8={stringify:function(a){try{return decodeURIComponent(escape(G.stringify(a)))}catch(b){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return G.parse(unescape(encodeURIComponent(a)))}},\nh=f.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new p.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=fa.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(n){var b=this._data,d=b.words,c=b.sigBytes,j=this.blockSize,l=c/(4*j),l=n?a.ceil(l):a.max((l|0)-this._minBufferSize,0);n=l*j;c=a.min(4*n,c);if(n){for(var h=0;hq;q++)y[q]=a();f=f.SHA512=r.extend({_doReset:function(){this._hash=new l.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,f){for(var h=this._hash.words,\ng=h[0],n=h[1],b=h[2],d=h[3],c=h[4],j=h[5],l=h[6],h=h[7],q=g.high,m=g.low,r=n.high,N=n.low,Z=b.high,O=b.low,$=d.high,P=d.low,aa=c.high,Q=c.low,ba=j.high,R=j.low,ca=l.high,S=l.low,da=h.high,T=h.low,v=q,s=m,H=r,E=N,I=Z,F=O,W=$,J=P,w=aa,t=Q,U=ba,K=R,V=ca,L=S,X=da,M=T,x=0;80>x;x++){var B=y[x];if(16>x)var u=B.high=a[f+2*x]|0,e=B.low=a[f+2*x+1]|0;else{var u=y[x-15],e=u.high,z=u.low,u=(e>>>1|z<<31)^(e>>>8|z<<24)^e>>>7,z=(z>>>1|e<<31)^(z>>>8|e<<24)^(z>>>7|e<<25),D=y[x-2],e=D.high,k=D.low,D=(e>>>19|k<<13)^\n(e<<3|k>>>29)^e>>>6,k=(k>>>19|e<<13)^(k<<3|e>>>29)^(k>>>6|e<<26),e=y[x-7],Y=e.high,C=y[x-16],A=C.high,C=C.low,e=z+e.low,u=u+Y+(e>>>0>>0?1:0),e=e+k,u=u+D+(e>>>0>>0?1:0),e=e+C,u=u+A+(e>>>0>>0?1:0);B.high=u;B.low=e}var Y=w&U^~w&V,C=t&K^~t&L,B=v&H^v&I^H&I,ha=s&E^s&F^E&F,z=(v>>>28|s<<4)^(v<<30|s>>>2)^(v<<25|s>>>7),D=(s>>>28|v<<4)^(s<<30|v>>>2)^(s<<25|v>>>7),k=p[x],ia=k.high,ea=k.low,k=M+((t>>>14|w<<18)^(t>>>18|w<<14)^(t<<23|w>>>9)),A=X+((w>>>14|t<<18)^(w>>>18|t<<14)^(w<<23|t>>>9))+(k>>>0>>\n0?1:0),k=k+C,A=A+Y+(k>>>0>>0?1:0),k=k+ea,A=A+ia+(k>>>0>>0?1:0),k=k+e,A=A+u+(k>>>0>>0?1:0),e=D+ha,B=z+B+(e>>>0>>0?1:0),X=V,M=L,V=U,L=K,U=w,K=t,t=J+k|0,w=W+A+(t>>>0>>0?1:0)|0,W=I,J=F,I=H,F=E,H=v,E=s,s=k+e|0,v=A+B+(s>>>0>>0?1:0)|0}m=g.low=m+s;g.high=q+v+(m>>>0>>0?1:0);N=n.low=N+E;n.high=r+H+(N>>>0>>0?1:0);O=b.low=O+F;b.high=Z+I+(O>>>0>>0?1:0);P=d.low=P+J;d.high=$+W+(P>>>0>>0?1:0);Q=c.low=Q+t;c.high=aa+w+(Q>>>0>>0?1:0);R=j.low=R+K;j.high=ba+U+(R>>>0>>0?1:0);S=l.low=\nS+L;l.high=ca+V+(S>>>0>>0?1:0);T=h.low=T+M;h.high=da+X+(T>>>0>>0?1:0)},_doFinalize:function(){var a=this._data,f=a.words,h=8*this._nDataBytes,g=8*a.sigBytes;f[g>>>5]|=128<<24-g%32;f[(g+128>>>10<<5)+30]=Math.floor(h/4294967296);f[(g+128>>>10<<5)+31]=h;a.sigBytes=4*f.length;this._process();return this._hash.toX32()},clone:function(){var a=r.clone.call(this);a._hash=this._hash.clone();return a},blockSize:32});m.SHA512=r._createHelper(f);m.HmacSHA512=r._createHmacHelper(f)})();\n"], "abc": [".py", "\n\n\n\"\"\"Abstract Base Classes (ABCs) according to PEP 3119.\"\"\"\n\n\ndef abstractmethod(funcobj):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n funcobj.__isabstractmethod__=True\n return funcobj\n \n \nclass abstractclassmethod(classmethod):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n def __init__(self,callable):\n callable.__isabstractmethod__=True\n super().__init__(callable)\n \n \nclass abstractstaticmethod(staticmethod):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n def __init__(self,callable):\n callable.__isabstractmethod__=True\n super().__init__(callable)\n \n \nclass abstractproperty(property):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n \ntry:\n from _abc import(get_cache_token,_abc_init,_abc_register,\n _abc_instancecheck,_abc_subclasscheck,_get_dump,\n _reset_registry,_reset_caches)\nexcept ImportError:\n from _py_abc import ABCMeta,get_cache_token\n ABCMeta.__module__='abc'\nelse:\n class ABCMeta(type):\n ''\n\n\n\n\n\n\n\n\n\n\n \n def __new__(mcls,name,bases,namespace,/,**kwargs):\n cls=super().__new__(mcls,name,bases,namespace,**kwargs)\n _abc_init(cls)\n return cls\n \n def register(cls,subclass):\n ''\n\n\n \n return _abc_register(cls,subclass)\n \n def __instancecheck__(cls,instance):\n ''\n return _abc_instancecheck(cls,instance)\n \n def __subclasscheck__(cls,subclass):\n ''\n return _abc_subclasscheck(cls,subclass)\n \n def _dump_registry(cls,file=None):\n ''\n print(f\"Class: {cls.__module__}.{cls.__qualname__}\",file=file)\n print(f\"Inv. counter: {get_cache_token()}\",file=file)\n (_abc_registry,_abc_cache,_abc_negative_cache,\n _abc_negative_cache_version)=_get_dump(cls)\n print(f\"_abc_registry: {_abc_registry !r}\",file=file)\n print(f\"_abc_cache: {_abc_cache !r}\",file=file)\n print(f\"_abc_negative_cache: {_abc_negative_cache !r}\",file=file)\n print(f\"_abc_negative_cache_version: {_abc_negative_cache_version !r}\",\n file=file)\n \n def _abc_registry_clear(cls):\n ''\n _reset_registry(cls)\n \n def _abc_caches_clear(cls):\n ''\n _reset_caches(cls)\n \n \ndef update_abstractmethods(cls):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not hasattr(cls,'__abstractmethods__'):\n \n \n \n return cls\n \n abstracts=set()\n \n \n for scls in cls.__bases__:\n for name in getattr(scls,'__abstractmethods__',()):\n value=getattr(cls,name,None)\n if getattr(value,\"__isabstractmethod__\",False):\n abstracts.add(name)\n \n for name,value in cls.__dict__.items():\n if getattr(value,\"__isabstractmethod__\",False):\n abstracts.add(name)\n cls.__abstractmethods__=frozenset(abstracts)\n return cls\n \n \nclass ABC(metaclass=ABCMeta):\n ''\n\n \n __slots__=()\n", ["_abc", "_py_abc"]], "antigravity": [".py", "\nimport webbrowser\nimport hashlib\n\nwebbrowser.open(\"https://xkcd.com/353/\")\n\ndef geohash(latitude,longitude,datedow):\n ''\n\n\n\n\n \n \n h=hashlib.md5(datedow,usedforsecurity=False).hexdigest()\n p,q=[('%f'%float.fromhex('0.'+x))for x in(h[:16],h[16:32])]\n print('%d%s %d%s'%(latitude,p[1:],longitude,q[1:]))\n", ["hashlib", "webbrowser"]], "argparse": [".py", "\n\n\n\"\"\"Command-line parsing library\n\nThis module is an optparse-inspired command-line parsing library that:\n\n - handles both optional and positional arguments\n - produces highly informative usage messages\n - supports parsers that dispatch to sub-parsers\n\nThe following is a simple usage example that sums integers from the\ncommand-line and writes the result to a file::\n\n parser = argparse.ArgumentParser(\n description='sum the integers at the command line')\n parser.add_argument(\n 'integers', metavar='int', nargs='+', type=int,\n help='an integer to be summed')\n parser.add_argument(\n '--log', default=sys.stdout, type=argparse.FileType('w'),\n help='the file where the sum should be written')\n args = parser.parse_args()\n args.log.write('%s' % sum(args.integers))\n args.log.close()\n\nThe module contains the following public classes:\n\n - ArgumentParser -- The main entry point for command-line parsing. As the\n example above shows, the add_argument() method is used to populate\n the parser with actions for optional and positional arguments. Then\n the parse_args() method is invoked to convert the args at the\n command-line into an object with attributes.\n\n - ArgumentError -- The exception raised by ArgumentParser objects when\n there are errors with the parser's actions. Errors raised while\n parsing the command-line are caught by ArgumentParser and emitted\n as command-line messages.\n\n - FileType -- A factory for defining types of files to be created. As the\n example above shows, instances of FileType are typically passed as\n the type= argument of add_argument() calls.\n\n - Action -- The base class for parser actions. Typically actions are\n selected by passing strings like 'store_true' or 'append_const' to\n the action= argument of add_argument(). However, for greater\n customization of ArgumentParser actions, subclasses of Action may\n be defined and passed as the action= argument.\n\n - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,\n ArgumentDefaultsHelpFormatter -- Formatter classes which\n may be passed as the formatter_class= argument to the\n ArgumentParser constructor. HelpFormatter is the default,\n RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser\n not to change the formatting for help text, and\n ArgumentDefaultsHelpFormatter adds information about argument defaults\n to the help.\n\nAll other classes in this module are considered implementation details.\n(Also note that HelpFormatter and RawDescriptionHelpFormatter are only\nconsidered public as object names -- the API of the formatter objects is\nstill considered an implementation detail.)\n\"\"\"\n\n__version__='1.1'\n__all__=[\n'ArgumentParser',\n'ArgumentError',\n'ArgumentTypeError',\n'BooleanOptionalAction',\n'FileType',\n'HelpFormatter',\n'ArgumentDefaultsHelpFormatter',\n'RawDescriptionHelpFormatter',\n'RawTextHelpFormatter',\n'MetavarTypeHelpFormatter',\n'Namespace',\n'Action',\n'ONE_OR_MORE',\n'OPTIONAL',\n'PARSER',\n'REMAINDER',\n'SUPPRESS',\n'ZERO_OR_MORE',\n]\n\n\nimport os as _os\nimport re as _re\nimport sys as _sys\n\nfrom gettext import gettext as _,ngettext\n\nSUPPRESS='==SUPPRESS=='\n\nOPTIONAL='?'\nZERO_OR_MORE='*'\nONE_OR_MORE='+'\nPARSER='A...'\nREMAINDER='...'\n_UNRECOGNIZED_ARGS_ATTR='_unrecognized_args'\n\n\n\n\n\nclass _AttributeHolder(object):\n ''\n\n\n\n\n\n \n \n def __repr__(self):\n type_name=type(self).__name__\n arg_strings=[]\n star_args={}\n for arg in self._get_args():\n arg_strings.append(repr(arg))\n for name,value in self._get_kwargs():\n if name.isidentifier():\n arg_strings.append('%s=%r'%(name,value))\n else:\n star_args[name]=value\n if star_args:\n arg_strings.append('**%s'%repr(star_args))\n return '%s(%s)'%(type_name,', '.join(arg_strings))\n \n def _get_kwargs(self):\n return list(self.__dict__.items())\n \n def _get_args(self):\n return[]\n \n \ndef _copy_items(items):\n if items is None:\n return[]\n \n \n \n if type(items)is list:\n return items[:]\n import copy\n return copy.copy(items)\n \n \n \n \n \n \n \nclass HelpFormatter(object):\n ''\n\n\n\n \n \n def __init__(self,\n prog,\n indent_increment=2,\n max_help_position=24,\n width=None):\n \n \n if width is None:\n import shutil\n width=shutil.get_terminal_size().columns\n width -=2\n \n self._prog=prog\n self._indent_increment=indent_increment\n self._max_help_position=min(max_help_position,\n max(width -20,indent_increment *2))\n self._width=width\n \n self._current_indent=0\n self._level=0\n self._action_max_length=0\n \n self._root_section=self._Section(self,None)\n self._current_section=self._root_section\n \n self._whitespace_matcher=_re.compile(r'\\s+',_re.ASCII)\n self._long_break_matcher=_re.compile(r'\\n\\n\\n+')\n \n \n \n \n def _indent(self):\n self._current_indent +=self._indent_increment\n self._level +=1\n \n def _dedent(self):\n self._current_indent -=self._indent_increment\n assert self._current_indent >=0,'Indent decreased below 0.'\n self._level -=1\n \n class _Section(object):\n \n def __init__(self,formatter,parent,heading=None):\n self.formatter=formatter\n self.parent=parent\n self.heading=heading\n self.items=[]\n \n def format_help(self):\n \n if self.parent is not None:\n self.formatter._indent()\n join=self.formatter._join_parts\n item_help=join([func(*args)for func,args in self.items])\n if self.parent is not None:\n self.formatter._dedent()\n \n \n if not item_help:\n return ''\n \n \n if self.heading is not SUPPRESS and self.heading is not None:\n current_indent=self.formatter._current_indent\n heading_text=_('%(heading)s:')%dict(heading=self.heading)\n heading='%*s%s\\n'%(current_indent,'',heading_text)\n else:\n heading=''\n \n \n return join(['\\n',heading,item_help,'\\n'])\n \n def _add_item(self,func,args):\n self._current_section.items.append((func,args))\n \n \n \n \n def start_section(self,heading):\n self._indent()\n section=self._Section(self,self._current_section,heading)\n self._add_item(section.format_help,[])\n self._current_section=section\n \n def end_section(self):\n self._current_section=self._current_section.parent\n self._dedent()\n \n def add_text(self,text):\n if text is not SUPPRESS and text is not None:\n self._add_item(self._format_text,[text])\n \n def add_usage(self,usage,actions,groups,prefix=None):\n if usage is not SUPPRESS:\n args=usage,actions,groups,prefix\n self._add_item(self._format_usage,args)\n \n def add_argument(self,action):\n if action.help is not SUPPRESS:\n \n \n get_invocation=self._format_action_invocation\n invocations=[get_invocation(action)]\n for subaction in self._iter_indented_subactions(action):\n invocations.append(get_invocation(subaction))\n \n \n invocation_length=max(map(len,invocations))\n action_length=invocation_length+self._current_indent\n self._action_max_length=max(self._action_max_length,\n action_length)\n \n \n self._add_item(self._format_action,[action])\n \n def add_arguments(self,actions):\n for action in actions:\n self.add_argument(action)\n \n \n \n \n def format_help(self):\n help=self._root_section.format_help()\n if help:\n help=self._long_break_matcher.sub('\\n\\n',help)\n help=help.strip('\\n')+'\\n'\n return help\n \n def _join_parts(self,part_strings):\n return ''.join([part\n for part in part_strings\n if part and part is not SUPPRESS])\n \n def _format_usage(self,usage,actions,groups,prefix):\n if prefix is None:\n prefix=_('usage: ')\n \n \n if usage is not None:\n usage=usage %dict(prog=self._prog)\n \n \n elif usage is None and not actions:\n usage='%(prog)s'%dict(prog=self._prog)\n \n \n elif usage is None:\n prog='%(prog)s'%dict(prog=self._prog)\n \n \n optionals=[]\n positionals=[]\n for action in actions:\n if action.option_strings:\n optionals.append(action)\n else:\n positionals.append(action)\n \n \n format=self._format_actions_usage\n action_usage=format(optionals+positionals,groups)\n usage=' '.join([s for s in[prog,action_usage]if s])\n \n \n text_width=self._width -self._current_indent\n if len(prefix)+len(usage)>text_width:\n \n \n opt_parts=self._get_actions_usage_parts(optionals,groups)\n pos_parts=self._get_actions_usage_parts(positionals,groups)\n \n \n def get_lines(parts,indent,prefix=None):\n lines=[]\n line=[]\n indent_length=len(indent)\n if prefix is not None:\n line_len=len(prefix)-1\n else:\n line_len=indent_length -1\n for part in parts:\n if line_len+1+len(part)>text_width and line:\n lines.append(indent+' '.join(line))\n line=[]\n line_len=indent_length -1\n line.append(part)\n line_len +=len(part)+1\n if line:\n lines.append(indent+' '.join(line))\n if prefix is not None:\n lines[0]=lines[0][indent_length:]\n return lines\n \n \n if len(prefix)+len(prog)<=0.75 *text_width:\n indent=' '*(len(prefix)+len(prog)+1)\n if opt_parts:\n lines=get_lines([prog]+opt_parts,indent,prefix)\n lines.extend(get_lines(pos_parts,indent))\n elif pos_parts:\n lines=get_lines([prog]+pos_parts,indent,prefix)\n else:\n lines=[prog]\n \n \n else:\n indent=' '*len(prefix)\n parts=opt_parts+pos_parts\n lines=get_lines(parts,indent)\n if len(lines)>1:\n lines=[]\n lines.extend(get_lines(opt_parts,indent))\n lines.extend(get_lines(pos_parts,indent))\n lines=[prog]+lines\n \n \n usage='\\n'.join(lines)\n \n \n return '%s%s\\n\\n'%(prefix,usage)\n \n def _format_actions_usage(self,actions,groups):\n return ' '.join(self._get_actions_usage_parts(actions,groups))\n \n def _get_actions_usage_parts(self,actions,groups):\n \n group_actions=set()\n inserts={}\n for group in groups:\n if not group._group_actions:\n raise ValueError(f'empty group {group}')\n \n if all(action.help is SUPPRESS for action in group._group_actions):\n continue\n \n try:\n start=actions.index(group._group_actions[0])\n except ValueError:\n continue\n else:\n end=start+len(group._group_actions)\n if actions[start:end]==group._group_actions:\n group_actions.update(group._group_actions)\n inserts[start,end]=group\n \n \n parts=[]\n for action in actions:\n \n \n if action.help is SUPPRESS:\n part=None\n \n \n elif not action.option_strings:\n default=self._get_default_metavar_for_positional(action)\n part=self._format_args(action,default)\n \n \n if action in group_actions:\n if part[0]=='['and part[-1]==']':\n part=part[1:-1]\n \n \n else:\n option_string=action.option_strings[0]\n \n \n \n if action.nargs ==0:\n part=action.format_usage()\n \n \n \n else:\n default=self._get_default_metavar_for_optional(action)\n args_string=self._format_args(action,default)\n part='%s %s'%(option_string,args_string)\n \n \n if not action.required and action not in group_actions:\n part='[%s]'%part\n \n \n parts.append(part)\n \n \n for start,end in sorted(inserts,reverse=True):\n group=inserts[start,end]\n group_parts=[item for item in parts[start:end]if item is not None]\n if group.required:\n open,close=\"()\"if len(group_parts)>1 else(\"\",\"\")\n else:\n open,close=\"[]\"\n parts[start]=open+\" | \".join(group_parts)+close\n for i in range(start+1,end):\n parts[i]=None\n \n \n return[item for item in parts if item is not None]\n \n def _format_text(self,text):\n if '%(prog)'in text:\n text=text %dict(prog=self._prog)\n text_width=max(self._width -self._current_indent,11)\n indent=' '*self._current_indent\n return self._fill_text(text,text_width,indent)+'\\n\\n'\n \n def _format_action(self,action):\n \n help_position=min(self._action_max_length+2,\n self._max_help_position)\n help_width=max(self._width -help_position,11)\n action_width=help_position -self._current_indent -2\n action_header=self._format_action_invocation(action)\n \n \n if not action.help:\n tup=self._current_indent,'',action_header\n action_header='%*s%s\\n'%tup\n \n \n elif len(action_header)<=action_width:\n tup=self._current_indent,'',action_width,action_header\n action_header='%*s%-*s '%tup\n indent_first=0\n \n \n else:\n tup=self._current_indent,'',action_header\n action_header='%*s%s\\n'%tup\n indent_first=help_position\n \n \n parts=[action_header]\n \n \n if action.help and action.help.strip():\n help_text=self._expand_help(action)\n if help_text:\n help_lines=self._split_lines(help_text,help_width)\n parts.append('%*s%s\\n'%(indent_first,'',help_lines[0]))\n for line in help_lines[1:]:\n parts.append('%*s%s\\n'%(help_position,'',line))\n \n \n elif not action_header.endswith('\\n'):\n parts.append('\\n')\n \n \n for subaction in self._iter_indented_subactions(action):\n parts.append(self._format_action(subaction))\n \n \n return self._join_parts(parts)\n \n def _format_action_invocation(self,action):\n if not action.option_strings:\n default=self._get_default_metavar_for_positional(action)\n metavar,=self._metavar_formatter(action,default)(1)\n return metavar\n \n else:\n \n \n \n if action.nargs ==0:\n return ', '.join(action.option_strings)\n \n \n \n else:\n default=self._get_default_metavar_for_optional(action)\n args_string=self._format_args(action,default)\n return ', '.join(action.option_strings)+' '+args_string\n \n def _metavar_formatter(self,action,default_metavar):\n if action.metavar is not None:\n result=action.metavar\n elif action.choices is not None:\n choice_strs=[str(choice)for choice in action.choices]\n result='{%s}'%','.join(choice_strs)\n else:\n result=default_metavar\n \n def format(tuple_size):\n if isinstance(result,tuple):\n return result\n else:\n return(result,)*tuple_size\n return format\n \n def _format_args(self,action,default_metavar):\n get_metavar=self._metavar_formatter(action,default_metavar)\n if action.nargs is None:\n result='%s'%get_metavar(1)\n elif action.nargs ==OPTIONAL:\n result='[%s]'%get_metavar(1)\n elif action.nargs ==ZERO_OR_MORE:\n metavar=get_metavar(1)\n if len(metavar)==2:\n result='[%s [%s ...]]'%metavar\n else:\n result='[%s ...]'%metavar\n elif action.nargs ==ONE_OR_MORE:\n result='%s [%s ...]'%get_metavar(2)\n elif action.nargs ==REMAINDER:\n result='...'\n elif action.nargs ==PARSER:\n result='%s ...'%get_metavar(1)\n elif action.nargs ==SUPPRESS:\n result=''\n else:\n try:\n formats=['%s'for _ in range(action.nargs)]\n except TypeError:\n raise ValueError(\"invalid nargs value\")from None\n result=' '.join(formats)%get_metavar(action.nargs)\n return result\n \n def _expand_help(self,action):\n params=dict(vars(action),prog=self._prog)\n for name in list(params):\n if params[name]is SUPPRESS:\n del params[name]\n for name in list(params):\n if hasattr(params[name],'__name__'):\n params[name]=params[name].__name__\n if params.get('choices')is not None:\n choices_str=', '.join([str(c)for c in params['choices']])\n params['choices']=choices_str\n return self._get_help_string(action)%params\n \n def _iter_indented_subactions(self,action):\n try:\n get_subactions=action._get_subactions\n except AttributeError:\n pass\n else:\n self._indent()\n yield from get_subactions()\n self._dedent()\n \n def _split_lines(self,text,width):\n text=self._whitespace_matcher.sub(' ',text).strip()\n \n \n import textwrap\n return textwrap.wrap(text,width)\n \n def _fill_text(self,text,width,indent):\n text=self._whitespace_matcher.sub(' ',text).strip()\n import textwrap\n return textwrap.fill(text,width,\n initial_indent=indent,\n subsequent_indent=indent)\n \n def _get_help_string(self,action):\n return action.help\n \n def _get_default_metavar_for_optional(self,action):\n return action.dest.upper()\n \n def _get_default_metavar_for_positional(self,action):\n return action.dest\n \n \nclass RawDescriptionHelpFormatter(HelpFormatter):\n ''\n\n\n\n \n \n def _fill_text(self,text,width,indent):\n return ''.join(indent+line for line in text.splitlines(keepends=True))\n \n \nclass RawTextHelpFormatter(RawDescriptionHelpFormatter):\n ''\n\n\n\n \n \n def _split_lines(self,text,width):\n return text.splitlines()\n \n \nclass ArgumentDefaultsHelpFormatter(HelpFormatter):\n ''\n\n\n\n \n \n def _get_help_string(self,action):\n help=action.help\n if help is None:\n help=''\n \n if '%(default)'not in help:\n if action.default is not SUPPRESS:\n defaulting_nargs=[OPTIONAL,ZERO_OR_MORE]\n if action.option_strings or action.nargs in defaulting_nargs:\n help +=_(' (default: %(default)s)')\n return help\n \n \n \nclass MetavarTypeHelpFormatter(HelpFormatter):\n ''\n\n\n\n\n \n \n def _get_default_metavar_for_optional(self,action):\n return action.type.__name__\n \n def _get_default_metavar_for_positional(self,action):\n return action.type.__name__\n \n \n \n \n \n \ndef _get_action_name(argument):\n if argument is None:\n return None\n elif argument.option_strings:\n return '/'.join(argument.option_strings)\n elif argument.metavar not in(None,SUPPRESS):\n return argument.metavar\n elif argument.dest not in(None,SUPPRESS):\n return argument.dest\n elif argument.choices:\n return '{'+','.join(argument.choices)+'}'\n else:\n return None\n \n \nclass ArgumentError(Exception):\n ''\n\n\n\n \n \n def __init__(self,argument,message):\n self.argument_name=_get_action_name(argument)\n self.message=message\n \n def __str__(self):\n if self.argument_name is None:\n format='%(message)s'\n else:\n format=_('argument %(argument_name)s: %(message)s')\n return format %dict(message=self.message,\n argument_name=self.argument_name)\n \n \nclass ArgumentTypeError(Exception):\n ''\n pass\n \n \n \n \n \n \nclass Action(_AttributeHolder):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,\n option_strings,\n dest,\n nargs=None,\n const=None,\n default=None,\n type=None,\n choices=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n self.option_strings=option_strings\n self.dest=dest\n self.nargs=nargs\n self.const=const\n self.default=default\n self.type=type\n self.choices=choices\n self.required=required\n self.help=help\n self.metavar=metavar\n self.deprecated=deprecated\n \n def _get_kwargs(self):\n names=[\n 'option_strings',\n 'dest',\n 'nargs',\n 'const',\n 'default',\n 'type',\n 'choices',\n 'required',\n 'help',\n 'metavar',\n 'deprecated',\n ]\n return[(name,getattr(self,name))for name in names]\n \n def format_usage(self):\n return self.option_strings[0]\n \n def __call__(self,parser,namespace,values,option_string=None):\n raise NotImplementedError(_('.__call__() not defined'))\n \n \n \n_deprecated_default=object()\n\nclass BooleanOptionalAction(Action):\n def __init__(self,\n option_strings,\n dest,\n default=None,\n type=_deprecated_default,\n choices=_deprecated_default,\n required=False,\n help=None,\n metavar=_deprecated_default,\n deprecated=False):\n \n _option_strings=[]\n for option_string in option_strings:\n _option_strings.append(option_string)\n \n if option_string.startswith('--'):\n option_string='--no-'+option_string[2:]\n _option_strings.append(option_string)\n \n \n \n \n for field_name in('type','choices','metavar'):\n if locals()[field_name]is not _deprecated_default:\n import warnings\n warnings._deprecated(\n field_name,\n \"{name!r} is deprecated as of Python 3.12 and will be \"\n \"removed in Python {remove}.\",\n remove=(3,14))\n \n if type is _deprecated_default:\n type=None\n if choices is _deprecated_default:\n choices=None\n if metavar is _deprecated_default:\n metavar=None\n \n super().__init__(\n option_strings=_option_strings,\n dest=dest,\n nargs=0,\n default=default,\n type=type,\n choices=choices,\n required=required,\n help=help,\n metavar=metavar,\n deprecated=deprecated)\n \n \n def __call__(self,parser,namespace,values,option_string=None):\n if option_string in self.option_strings:\n setattr(namespace,self.dest,not option_string.startswith('--no-'))\n \n def format_usage(self):\n return ' | '.join(self.option_strings)\n \n \nclass _StoreAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n nargs=None,\n const=None,\n default=None,\n type=None,\n choices=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n if nargs ==0:\n raise ValueError('nargs for store actions must be != 0; if you '\n 'have nothing to store, actions such as store '\n 'true or store const may be more appropriate')\n if const is not None and nargs !=OPTIONAL:\n raise ValueError('nargs must be %r to supply const'%OPTIONAL)\n super(_StoreAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=nargs,\n const=const,\n default=default,\n type=type,\n choices=choices,\n required=required,\n help=help,\n metavar=metavar,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n setattr(namespace,self.dest,values)\n \n \nclass _StoreConstAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n const=None,\n default=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n super(_StoreConstAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n const=const,\n default=default,\n required=required,\n help=help,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n setattr(namespace,self.dest,self.const)\n \n \nclass _StoreTrueAction(_StoreConstAction):\n\n def __init__(self,\n option_strings,\n dest,\n default=False,\n required=False,\n help=None,\n deprecated=False):\n super(_StoreTrueAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=True,\n deprecated=deprecated,\n required=required,\n help=help,\n default=default)\n \n \nclass _StoreFalseAction(_StoreConstAction):\n\n def __init__(self,\n option_strings,\n dest,\n default=True,\n required=False,\n help=None,\n deprecated=False):\n super(_StoreFalseAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=False,\n default=default,\n required=required,\n help=help,\n deprecated=deprecated)\n \n \nclass _AppendAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n nargs=None,\n const=None,\n default=None,\n type=None,\n choices=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n if nargs ==0:\n raise ValueError('nargs for append actions must be != 0; if arg '\n 'strings are not supplying the value to append, '\n 'the append const action may be more appropriate')\n if const is not None and nargs !=OPTIONAL:\n raise ValueError('nargs must be %r to supply const'%OPTIONAL)\n super(_AppendAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=nargs,\n const=const,\n default=default,\n type=type,\n choices=choices,\n required=required,\n help=help,\n metavar=metavar,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n items=getattr(namespace,self.dest,None)\n items=_copy_items(items)\n items.append(values)\n setattr(namespace,self.dest,items)\n \n \nclass _AppendConstAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n const=None,\n default=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n super(_AppendConstAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n const=const,\n default=default,\n required=required,\n help=help,\n metavar=metavar,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n items=getattr(namespace,self.dest,None)\n items=_copy_items(items)\n items.append(self.const)\n setattr(namespace,self.dest,items)\n \n \nclass _CountAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n default=None,\n required=False,\n help=None,\n deprecated=False):\n super(_CountAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n default=default,\n required=required,\n help=help,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n count=getattr(namespace,self.dest,None)\n if count is None:\n count=0\n setattr(namespace,self.dest,count+1)\n \n \nclass _HelpAction(Action):\n\n def __init__(self,\n option_strings,\n dest=SUPPRESS,\n default=SUPPRESS,\n help=None,\n deprecated=False):\n super(_HelpAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n default=default,\n nargs=0,\n help=help,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n parser.print_help()\n parser.exit()\n \n \nclass _VersionAction(Action):\n\n def __init__(self,\n option_strings,\n version=None,\n dest=SUPPRESS,\n default=SUPPRESS,\n help=None,\n deprecated=False):\n if help is None:\n help=_(\"show program's version number and exit\")\n super(_VersionAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n default=default,\n nargs=0,\n help=help)\n self.version=version\n \n def __call__(self,parser,namespace,values,option_string=None):\n version=self.version\n if version is None:\n version=parser.version\n formatter=parser._get_formatter()\n formatter.add_text(version)\n parser._print_message(formatter.format_help(),_sys.stdout)\n parser.exit()\n \n \nclass _SubParsersAction(Action):\n\n class _ChoicesPseudoAction(Action):\n \n def __init__(self,name,aliases,help):\n metavar=dest=name\n if aliases:\n metavar +=' (%s)'%', '.join(aliases)\n sup=super(_SubParsersAction._ChoicesPseudoAction,self)\n sup.__init__(option_strings=[],dest=dest,help=help,\n metavar=metavar)\n \n def __init__(self,\n option_strings,\n prog,\n parser_class,\n dest=SUPPRESS,\n required=False,\n help=None,\n metavar=None):\n \n self._prog_prefix=prog\n self._parser_class=parser_class\n self._name_parser_map={}\n self._choices_actions=[]\n self._deprecated=set()\n \n super(_SubParsersAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=PARSER,\n choices=self._name_parser_map,\n required=required,\n help=help,\n metavar=metavar)\n \n def add_parser(self,name,*,deprecated=False,**kwargs):\n \n if kwargs.get('prog')is None:\n kwargs['prog']='%s %s'%(self._prog_prefix,name)\n \n aliases=kwargs.pop('aliases',())\n \n if name in self._name_parser_map:\n raise ArgumentError(self,_('conflicting subparser: %s')%name)\n for alias in aliases:\n if alias in self._name_parser_map:\n raise ArgumentError(\n self,_('conflicting subparser alias: %s')%alias)\n \n \n if 'help'in kwargs:\n help=kwargs.pop('help')\n choice_action=self._ChoicesPseudoAction(name,aliases,help)\n self._choices_actions.append(choice_action)\n \n \n parser=self._parser_class(**kwargs)\n self._name_parser_map[name]=parser\n \n \n for alias in aliases:\n self._name_parser_map[alias]=parser\n \n if deprecated:\n self._deprecated.add(name)\n self._deprecated.update(aliases)\n \n return parser\n \n def _get_subactions(self):\n return self._choices_actions\n \n def __call__(self,parser,namespace,values,option_string=None):\n parser_name=values[0]\n arg_strings=values[1:]\n \n \n if self.dest is not SUPPRESS:\n setattr(namespace,self.dest,parser_name)\n \n \n try:\n subparser=self._name_parser_map[parser_name]\n except KeyError:\n args={'parser_name':parser_name,\n 'choices':', '.join(self._name_parser_map)}\n msg=_('unknown parser %(parser_name)r (choices: %(choices)s)')%args\n raise ArgumentError(self,msg)\n \n if parser_name in self._deprecated:\n parser._warning(_(\"command '%(parser_name)s' is deprecated\")%\n {'parser_name':parser_name})\n \n \n \n \n \n \n \n \n subnamespace,arg_strings=subparser.parse_known_args(arg_strings,None)\n for key,value in vars(subnamespace).items():\n setattr(namespace,key,value)\n \n if arg_strings:\n vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR,[])\n getattr(namespace,_UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)\n \nclass _ExtendAction(_AppendAction):\n def __call__(self,parser,namespace,values,option_string=None):\n items=getattr(namespace,self.dest,None)\n items=_copy_items(items)\n items.extend(values)\n setattr(namespace,self.dest,items)\n \n \n \n \n \nclass FileType(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,mode='r',bufsize=-1,encoding=None,errors=None):\n self._mode=mode\n self._bufsize=bufsize\n self._encoding=encoding\n self._errors=errors\n \n def __call__(self,string):\n \n if string =='-':\n if 'r'in self._mode:\n return _sys.stdin.buffer if 'b'in self._mode else _sys.stdin\n elif any(c in self._mode for c in 'wax'):\n return _sys.stdout.buffer if 'b'in self._mode else _sys.stdout\n else:\n msg=_('argument \"-\" with mode %r')%self._mode\n raise ValueError(msg)\n \n \n try:\n return open(string,self._mode,self._bufsize,self._encoding,\n self._errors)\n except OSError as e:\n args={'filename':string,'error':e}\n message=_(\"can't open '%(filename)s': %(error)s\")\n raise ArgumentTypeError(message %args)\n \n def __repr__(self):\n args=self._mode,self._bufsize\n kwargs=[('encoding',self._encoding),('errors',self._errors)]\n args_str=', '.join([repr(arg)for arg in args if arg !=-1]+\n ['%s=%r'%(kw,arg)for kw,arg in kwargs\n if arg is not None])\n return '%s(%s)'%(type(self).__name__,args_str)\n \n \n \n \n \nclass Namespace(_AttributeHolder):\n ''\n\n\n\n \n \n def __init__(self,**kwargs):\n for name in kwargs:\n setattr(self,name,kwargs[name])\n \n def __eq__(self,other):\n if not isinstance(other,Namespace):\n return NotImplemented\n return vars(self)==vars(other)\n \n def __contains__(self,key):\n return key in self.__dict__\n \n \nclass _ActionsContainer(object):\n\n def __init__(self,\n description,\n prefix_chars,\n argument_default,\n conflict_handler):\n super(_ActionsContainer,self).__init__()\n \n self.description=description\n self.argument_default=argument_default\n self.prefix_chars=prefix_chars\n self.conflict_handler=conflict_handler\n \n \n self._registries={}\n \n \n self.register('action',None,_StoreAction)\n self.register('action','store',_StoreAction)\n self.register('action','store_const',_StoreConstAction)\n self.register('action','store_true',_StoreTrueAction)\n self.register('action','store_false',_StoreFalseAction)\n self.register('action','append',_AppendAction)\n self.register('action','append_const',_AppendConstAction)\n self.register('action','count',_CountAction)\n self.register('action','help',_HelpAction)\n self.register('action','version',_VersionAction)\n self.register('action','parsers',_SubParsersAction)\n self.register('action','extend',_ExtendAction)\n \n \n self._get_handler()\n \n \n self._actions=[]\n self._option_string_actions={}\n \n \n self._action_groups=[]\n self._mutually_exclusive_groups=[]\n \n \n self._defaults={}\n \n \n self._negative_number_matcher=_re.compile(r'^-\\d+$|^-\\d*\\.\\d+$')\n \n \n \n self._has_negative_number_optionals=[]\n \n \n \n \n def register(self,registry_name,value,object):\n registry=self._registries.setdefault(registry_name,{})\n registry[value]=object\n \n def _registry_get(self,registry_name,value,default=None):\n return self._registries[registry_name].get(value,default)\n \n \n \n \n def set_defaults(self,**kwargs):\n self._defaults.update(kwargs)\n \n \n \n for action in self._actions:\n if action.dest in kwargs:\n action.default=kwargs[action.dest]\n \n def get_default(self,dest):\n for action in self._actions:\n if action.dest ==dest and action.default is not None:\n return action.default\n return self._defaults.get(dest,None)\n \n \n \n \n \n def add_argument(self,*args,**kwargs):\n ''\n\n\n \n \n \n \n \n chars=self.prefix_chars\n if not args or len(args)==1 and args[0][0]not in chars:\n if args and 'dest'in kwargs:\n raise ValueError('dest supplied twice for positional argument')\n kwargs=self._get_positional_kwargs(*args,**kwargs)\n \n \n else:\n kwargs=self._get_optional_kwargs(*args,**kwargs)\n \n \n if 'default'not in kwargs:\n dest=kwargs['dest']\n if dest in self._defaults:\n kwargs['default']=self._defaults[dest]\n elif self.argument_default is not None:\n kwargs['default']=self.argument_default\n \n \n action_class=self._pop_action_class(kwargs)\n if not callable(action_class):\n raise ValueError('unknown action \"%s\"'%(action_class,))\n action=action_class(**kwargs)\n \n \n type_func=self._registry_get('type',action.type,action.type)\n if not callable(type_func):\n raise ValueError('%r is not callable'%(type_func,))\n \n if type_func is FileType:\n raise ValueError('%r is a FileType class object, instance of it'\n ' must be passed'%(type_func,))\n \n \n if hasattr(self,\"_get_formatter\"):\n try:\n self._get_formatter()._format_args(action,None)\n except TypeError:\n raise ValueError(\"length of metavar tuple does not match nargs\")\n \n return self._add_action(action)\n \n def add_argument_group(self,*args,**kwargs):\n group=_ArgumentGroup(self,*args,**kwargs)\n self._action_groups.append(group)\n return group\n \n def add_mutually_exclusive_group(self,**kwargs):\n group=_MutuallyExclusiveGroup(self,**kwargs)\n self._mutually_exclusive_groups.append(group)\n return group\n \n def _add_action(self,action):\n \n self._check_conflict(action)\n \n \n self._actions.append(action)\n action.container=self\n \n \n for option_string in action.option_strings:\n self._option_string_actions[option_string]=action\n \n \n for option_string in action.option_strings:\n if self._negative_number_matcher.match(option_string):\n if not self._has_negative_number_optionals:\n self._has_negative_number_optionals.append(True)\n \n \n return action\n \n def _remove_action(self,action):\n self._actions.remove(action)\n \n def _add_container_actions(self,container):\n \n title_group_map={}\n for group in self._action_groups:\n if group.title in title_group_map:\n \n \n msg=_('cannot merge actions - two groups are named %r')\n raise ValueError(msg %(group.title))\n title_group_map[group.title]=group\n \n \n group_map={}\n for group in container._action_groups:\n \n \n \n if group.title not in title_group_map:\n title_group_map[group.title]=self.add_argument_group(\n title=group.title,\n description=group.description,\n conflict_handler=group.conflict_handler)\n \n \n for action in group._group_actions:\n group_map[action]=title_group_map[group.title]\n \n \n \n \n for group in container._mutually_exclusive_groups:\n mutex_group=self.add_mutually_exclusive_group(\n required=group.required)\n \n \n for action in group._group_actions:\n group_map[action]=mutex_group\n \n \n for action in container._actions:\n group_map.get(action,self)._add_action(action)\n \n def _get_positional_kwargs(self,dest,**kwargs):\n \n if 'required'in kwargs:\n msg=_(\"'required' is an invalid argument for positionals\")\n raise TypeError(msg)\n \n \n \n if kwargs.get('nargs')not in[OPTIONAL,ZERO_OR_MORE]:\n kwargs['required']=True\n if kwargs.get('nargs')==ZERO_OR_MORE and 'default'not in kwargs:\n kwargs['required']=True\n \n \n return dict(kwargs,dest=dest,option_strings=[])\n \n def _get_optional_kwargs(self,*args,**kwargs):\n \n option_strings=[]\n long_option_strings=[]\n for option_string in args:\n \n if not option_string[0]in self.prefix_chars:\n args={'option':option_string,\n 'prefix_chars':self.prefix_chars}\n msg=_('invalid option string %(option)r: '\n 'must start with a character %(prefix_chars)r')\n raise ValueError(msg %args)\n \n \n option_strings.append(option_string)\n if len(option_string)>1 and option_string[1]in self.prefix_chars:\n long_option_strings.append(option_string)\n \n \n dest=kwargs.pop('dest',None)\n if dest is None:\n if long_option_strings:\n dest_option_string=long_option_strings[0]\n else:\n dest_option_string=option_strings[0]\n dest=dest_option_string.lstrip(self.prefix_chars)\n if not dest:\n msg=_('dest= is required for options like %r')\n raise ValueError(msg %option_string)\n dest=dest.replace('-','_')\n \n \n return dict(kwargs,dest=dest,option_strings=option_strings)\n \n def _pop_action_class(self,kwargs,default=None):\n action=kwargs.pop('action',default)\n return self._registry_get('action',action,action)\n \n def _get_handler(self):\n \n handler_func_name='_handle_conflict_%s'%self.conflict_handler\n try:\n return getattr(self,handler_func_name)\n except AttributeError:\n msg=_('invalid conflict_resolution value: %r')\n raise ValueError(msg %self.conflict_handler)\n \n def _check_conflict(self,action):\n \n \n confl_optionals=[]\n for option_string in action.option_strings:\n if option_string in self._option_string_actions:\n confl_optional=self._option_string_actions[option_string]\n confl_optionals.append((option_string,confl_optional))\n \n \n if confl_optionals:\n conflict_handler=self._get_handler()\n conflict_handler(action,confl_optionals)\n \n def _handle_conflict_error(self,action,conflicting_actions):\n message=ngettext('conflicting option string: %s',\n 'conflicting option strings: %s',\n len(conflicting_actions))\n conflict_string=', '.join([option_string\n for option_string,action\n in conflicting_actions])\n raise ArgumentError(action,message %conflict_string)\n \n def _handle_conflict_resolve(self,action,conflicting_actions):\n \n \n for option_string,action in conflicting_actions:\n \n \n action.option_strings.remove(option_string)\n self._option_string_actions.pop(option_string,None)\n \n \n \n if not action.option_strings:\n action.container._remove_action(action)\n \n \nclass _ArgumentGroup(_ActionsContainer):\n\n def __init__(self,container,title=None,description=None,**kwargs):\n \n update=kwargs.setdefault\n update('conflict_handler',container.conflict_handler)\n update('prefix_chars',container.prefix_chars)\n update('argument_default',container.argument_default)\n super_init=super(_ArgumentGroup,self).__init__\n super_init(description=description,**kwargs)\n \n \n self.title=title\n self._group_actions=[]\n \n \n self._registries=container._registries\n self._actions=container._actions\n self._option_string_actions=container._option_string_actions\n self._defaults=container._defaults\n self._has_negative_number_optionals=\\\n container._has_negative_number_optionals\n self._mutually_exclusive_groups=container._mutually_exclusive_groups\n \n def _add_action(self,action):\n action=super(_ArgumentGroup,self)._add_action(action)\n self._group_actions.append(action)\n return action\n \n def _remove_action(self,action):\n super(_ArgumentGroup,self)._remove_action(action)\n self._group_actions.remove(action)\n \n def add_argument_group(self,*args,**kwargs):\n import warnings\n warnings.warn(\n \"Nesting argument groups is deprecated.\",\n category=DeprecationWarning,\n stacklevel=2\n )\n return super().add_argument_group(*args,**kwargs)\n \n \nclass _MutuallyExclusiveGroup(_ArgumentGroup):\n\n def __init__(self,container,required=False):\n super(_MutuallyExclusiveGroup,self).__init__(container)\n self.required=required\n self._container=container\n \n def _add_action(self,action):\n if action.required:\n msg=_('mutually exclusive arguments must be optional')\n raise ValueError(msg)\n action=self._container._add_action(action)\n self._group_actions.append(action)\n return action\n \n def _remove_action(self,action):\n self._container._remove_action(action)\n self._group_actions.remove(action)\n \n def add_mutually_exclusive_group(self,*args,**kwargs):\n import warnings\n warnings.warn(\n \"Nesting mutually exclusive groups is deprecated.\",\n category=DeprecationWarning,\n stacklevel=2\n )\n return super().add_mutually_exclusive_group(*args,**kwargs)\n \n \nclass ArgumentParser(_AttributeHolder,_ActionsContainer):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,\n prog=None,\n usage=None,\n description=None,\n epilog=None,\n parents=[],\n formatter_class=HelpFormatter,\n prefix_chars='-',\n fromfile_prefix_chars=None,\n argument_default=None,\n conflict_handler='error',\n add_help=True,\n allow_abbrev=True,\n exit_on_error=True):\n \n superinit=super(ArgumentParser,self).__init__\n superinit(description=description,\n prefix_chars=prefix_chars,\n argument_default=argument_default,\n conflict_handler=conflict_handler)\n \n \n if prog is None:\n prog=_os.path.basename(_sys.argv[0])\n \n self.prog=prog\n self.usage=usage\n self.epilog=epilog\n self.formatter_class=formatter_class\n self.fromfile_prefix_chars=fromfile_prefix_chars\n self.add_help=add_help\n self.allow_abbrev=allow_abbrev\n self.exit_on_error=exit_on_error\n \n add_group=self.add_argument_group\n self._positionals=add_group(_('positional arguments'))\n self._optionals=add_group(_('options'))\n self._subparsers=None\n \n \n def identity(string):\n return string\n self.register('type',None,identity)\n \n \n \n default_prefix='-'if '-'in prefix_chars else prefix_chars[0]\n if self.add_help:\n self.add_argument(\n default_prefix+'h',default_prefix *2+'help',\n action='help',default=SUPPRESS,\n help=_('show this help message and exit'))\n \n \n for parent in parents:\n if not isinstance(parent,ArgumentParser):\n raise TypeError('parents must be a list of ArgumentParser')\n self._add_container_actions(parent)\n defaults=parent._defaults\n self._defaults.update(defaults)\n \n \n \n \n def _get_kwargs(self):\n names=[\n 'prog',\n 'usage',\n 'description',\n 'formatter_class',\n 'conflict_handler',\n 'add_help',\n ]\n return[(name,getattr(self,name))for name in names]\n \n \n \n \n def add_subparsers(self,**kwargs):\n if self._subparsers is not None:\n raise ArgumentError(None,_('cannot have multiple subparser arguments'))\n \n \n kwargs.setdefault('parser_class',type(self))\n \n if 'title'in kwargs or 'description'in kwargs:\n title=_(kwargs.pop('title','subcommands'))\n description=_(kwargs.pop('description',None))\n self._subparsers=self.add_argument_group(title,description)\n else:\n self._subparsers=self._positionals\n \n \n \n if kwargs.get('prog')is None:\n formatter=self._get_formatter()\n positionals=self._get_positional_actions()\n groups=self._mutually_exclusive_groups\n formatter.add_usage(self.usage,positionals,groups,'')\n kwargs['prog']=formatter.format_help().strip()\n \n \n parsers_class=self._pop_action_class(kwargs,'parsers')\n action=parsers_class(option_strings=[],**kwargs)\n self._subparsers._add_action(action)\n \n \n return action\n \n def _add_action(self,action):\n if action.option_strings:\n self._optionals._add_action(action)\n else:\n self._positionals._add_action(action)\n return action\n \n def _get_optional_actions(self):\n return[action\n for action in self._actions\n if action.option_strings]\n \n def _get_positional_actions(self):\n return[action\n for action in self._actions\n if not action.option_strings]\n \n \n \n \n def parse_args(self,args=None,namespace=None):\n args,argv=self.parse_known_args(args,namespace)\n if argv:\n msg=_('unrecognized arguments: %s')%' '.join(argv)\n if self.exit_on_error:\n self.error(msg)\n else:\n raise ArgumentError(None,msg)\n return args\n \n def parse_known_args(self,args=None,namespace=None):\n if args is None:\n \n args=_sys.argv[1:]\n else:\n \n args=list(args)\n \n \n if namespace is None:\n namespace=Namespace()\n \n \n for action in self._actions:\n if action.dest is not SUPPRESS:\n if not hasattr(namespace,action.dest):\n if action.default is not SUPPRESS:\n setattr(namespace,action.dest,action.default)\n \n \n for dest in self._defaults:\n if not hasattr(namespace,dest):\n setattr(namespace,dest,self._defaults[dest])\n \n \n if self.exit_on_error:\n try:\n namespace,args=self._parse_known_args(args,namespace)\n except ArgumentError as err:\n self.error(str(err))\n else:\n namespace,args=self._parse_known_args(args,namespace)\n \n if hasattr(namespace,_UNRECOGNIZED_ARGS_ATTR):\n args.extend(getattr(namespace,_UNRECOGNIZED_ARGS_ATTR))\n delattr(namespace,_UNRECOGNIZED_ARGS_ATTR)\n return namespace,args\n \n def _parse_known_args(self,arg_strings,namespace):\n \n if self.fromfile_prefix_chars is not None:\n arg_strings=self._read_args_from_files(arg_strings)\n \n \n \n action_conflicts={}\n for mutex_group in self._mutually_exclusive_groups:\n group_actions=mutex_group._group_actions\n for i,mutex_action in enumerate(mutex_group._group_actions):\n conflicts=action_conflicts.setdefault(mutex_action,[])\n conflicts.extend(group_actions[:i])\n conflicts.extend(group_actions[i+1:])\n \n \n \n \n option_string_indices={}\n arg_string_pattern_parts=[]\n arg_strings_iter=iter(arg_strings)\n for i,arg_string in enumerate(arg_strings_iter):\n \n \n if arg_string =='--':\n arg_string_pattern_parts.append('-')\n for arg_string in arg_strings_iter:\n arg_string_pattern_parts.append('A')\n \n \n \n else:\n option_tuple=self._parse_optional(arg_string)\n if option_tuple is None:\n pattern='A'\n else:\n option_string_indices[i]=option_tuple\n pattern='O'\n arg_string_pattern_parts.append(pattern)\n \n \n arg_strings_pattern=''.join(arg_string_pattern_parts)\n \n \n seen_actions=set()\n seen_non_default_actions=set()\n warned=set()\n \n def take_action(action,argument_strings,option_string=None):\n seen_actions.add(action)\n argument_values=self._get_values(action,argument_strings)\n \n \n \n \n if argument_values is not action.default:\n seen_non_default_actions.add(action)\n for conflict_action in action_conflicts.get(action,[]):\n if conflict_action in seen_non_default_actions:\n msg=_('not allowed with argument %s')\n action_name=_get_action_name(conflict_action)\n raise ArgumentError(action,msg %action_name)\n \n \n \n if argument_values is not SUPPRESS:\n action(self,namespace,argument_values,option_string)\n \n \n def consume_optional(start_index):\n \n \n option_tuple=option_string_indices[start_index]\n action,option_string,sep,explicit_arg=option_tuple\n \n \n \n match_argument=self._match_argument\n action_tuples=[]\n while True:\n \n \n if action is None:\n extras.append(arg_strings[start_index])\n return start_index+1\n \n \n \n if explicit_arg is not None:\n arg_count=match_argument(action,'A')\n \n \n \n \n chars=self.prefix_chars\n if(\n arg_count ==0\n and option_string[1]not in chars\n and explicit_arg !=''\n ):\n if sep or explicit_arg[0]in chars:\n msg=_('ignored explicit argument %r')\n raise ArgumentError(action,msg %explicit_arg)\n action_tuples.append((action,[],option_string))\n char=option_string[0]\n option_string=char+explicit_arg[0]\n optionals_map=self._option_string_actions\n if option_string in optionals_map:\n action=optionals_map[option_string]\n explicit_arg=explicit_arg[1:]\n if not explicit_arg:\n sep=explicit_arg=None\n elif explicit_arg[0]=='=':\n sep='='\n explicit_arg=explicit_arg[1:]\n else:\n sep=''\n else:\n extras.append(char+explicit_arg)\n stop=start_index+1\n break\n \n \n elif arg_count ==1:\n stop=start_index+1\n args=[explicit_arg]\n action_tuples.append((action,args,option_string))\n break\n \n \n \n else:\n msg=_('ignored explicit argument %r')\n raise ArgumentError(action,msg %explicit_arg)\n \n \n \n \n else:\n start=start_index+1\n selected_patterns=arg_strings_pattern[start:]\n arg_count=match_argument(action,selected_patterns)\n stop=start+arg_count\n args=arg_strings[start:stop]\n action_tuples.append((action,args,option_string))\n break\n \n \n \n assert action_tuples\n for action,args,option_string in action_tuples:\n if action.deprecated and option_string not in warned:\n self._warning(_(\"option '%(option)s' is deprecated\")%\n {'option':option_string})\n warned.add(option_string)\n take_action(action,args,option_string)\n return stop\n \n \n \n positionals=self._get_positional_actions()\n \n \n def consume_positionals(start_index):\n \n match_partial=self._match_arguments_partial\n selected_pattern=arg_strings_pattern[start_index:]\n arg_counts=match_partial(positionals,selected_pattern)\n \n \n \n for action,arg_count in zip(positionals,arg_counts):\n args=arg_strings[start_index:start_index+arg_count]\n start_index +=arg_count\n if args and action.deprecated and action.dest not in warned:\n self._warning(_(\"argument '%(argument_name)s' is deprecated\")%\n {'argument_name':action.dest})\n warned.add(action.dest)\n take_action(action,args)\n \n \n \n positionals[:]=positionals[len(arg_counts):]\n return start_index\n \n \n \n extras=[]\n start_index=0\n if option_string_indices:\n max_option_string_index=max(option_string_indices)\n else:\n max_option_string_index=-1\n while start_index <=max_option_string_index:\n \n \n next_option_string_index=start_index\n while next_option_string_index <=max_option_string_index:\n if next_option_string_index in option_string_indices:\n break\n next_option_string_index +=1\n if start_index !=next_option_string_index:\n positionals_end_index=consume_positionals(start_index)\n \n \n \n if positionals_end_index >start_index:\n start_index=positionals_end_index\n continue\n else:\n start_index=positionals_end_index\n \n \n \n if start_index not in option_string_indices:\n strings=arg_strings[start_index:next_option_string_index]\n extras.extend(strings)\n start_index=next_option_string_index\n \n \n start_index=consume_optional(start_index)\n \n \n stop_index=consume_positionals(start_index)\n \n \n extras.extend(arg_strings[stop_index:])\n \n \n \n required_actions=[]\n for action in self._actions:\n if action not in seen_actions:\n if action.required:\n required_actions.append(_get_action_name(action))\n else:\n \n \n \n \n if(action.default is not None and\n isinstance(action.default,str)and\n hasattr(namespace,action.dest)and\n action.default is getattr(namespace,action.dest)):\n setattr(namespace,action.dest,\n self._get_value(action,action.default))\n \n if required_actions:\n raise ArgumentError(None,_('the following arguments are required: %s')%\n ', '.join(required_actions))\n \n \n for group in self._mutually_exclusive_groups:\n if group.required:\n for action in group._group_actions:\n if action in seen_non_default_actions:\n break\n \n \n else:\n names=[_get_action_name(action)\n for action in group._group_actions\n if action.help is not SUPPRESS]\n msg=_('one of the arguments %s is required')\n raise ArgumentError(None,msg %' '.join(names))\n \n \n return namespace,extras\n \n def _read_args_from_files(self,arg_strings):\n \n new_arg_strings=[]\n for arg_string in arg_strings:\n \n \n if not arg_string or arg_string[0]not in self.fromfile_prefix_chars:\n new_arg_strings.append(arg_string)\n \n \n else:\n try:\n with open(arg_string[1:],\n encoding=_sys.getfilesystemencoding(),\n errors=_sys.getfilesystemencodeerrors())as args_file:\n arg_strings=[]\n for arg_line in args_file.read().splitlines():\n for arg in self.convert_arg_line_to_args(arg_line):\n arg_strings.append(arg)\n arg_strings=self._read_args_from_files(arg_strings)\n new_arg_strings.extend(arg_strings)\n except OSError as err:\n raise ArgumentError(None,str(err))\n \n \n return new_arg_strings\n \n def convert_arg_line_to_args(self,arg_line):\n return[arg_line]\n \n def _match_argument(self,action,arg_strings_pattern):\n \n nargs_pattern=self._get_nargs_pattern(action)\n match=_re.match(nargs_pattern,arg_strings_pattern)\n \n \n if match is None:\n nargs_errors={\n None:_('expected one argument'),\n OPTIONAL:_('expected at most one argument'),\n ONE_OR_MORE:_('expected at least one argument'),\n }\n msg=nargs_errors.get(action.nargs)\n if msg is None:\n msg=ngettext('expected %s argument',\n 'expected %s arguments',\n action.nargs)%action.nargs\n raise ArgumentError(action,msg)\n \n \n return len(match.group(1))\n \n def _match_arguments_partial(self,actions,arg_strings_pattern):\n \n \n result=[]\n for i in range(len(actions),0,-1):\n actions_slice=actions[:i]\n pattern=''.join([self._get_nargs_pattern(action)\n for action in actions_slice])\n match=_re.match(pattern,arg_strings_pattern)\n if match is not None:\n result.extend([len(string)for string in match.groups()])\n break\n \n \n return result\n \n def _parse_optional(self,arg_string):\n \n if not arg_string:\n return None\n \n \n if not arg_string[0]in self.prefix_chars:\n return None\n \n \n if arg_string in self._option_string_actions:\n action=self._option_string_actions[arg_string]\n return action,arg_string,None,None\n \n \n if len(arg_string)==1:\n return None\n \n \n option_string,sep,explicit_arg=arg_string.partition('=')\n if sep and option_string in self._option_string_actions:\n action=self._option_string_actions[option_string]\n return action,option_string,sep,explicit_arg\n \n \n \n option_tuples=self._get_option_tuples(arg_string)\n \n \n if len(option_tuples)>1:\n options=', '.join([option_string\n for action,option_string,sep,explicit_arg in option_tuples])\n args={'option':arg_string,'matches':options}\n msg=_('ambiguous option: %(option)s could match %(matches)s')\n raise ArgumentError(None,msg %args)\n \n \n \n elif len(option_tuples)==1:\n option_tuple,=option_tuples\n return option_tuple\n \n \n \n \n if self._negative_number_matcher.match(arg_string):\n if not self._has_negative_number_optionals:\n return None\n \n \n if ' 'in arg_string:\n return None\n \n \n \n return None,arg_string,None,None\n \n def _get_option_tuples(self,option_string):\n result=[]\n \n \n \n chars=self.prefix_chars\n if option_string[0]in chars and option_string[1]in chars:\n if self.allow_abbrev:\n option_prefix,sep,explicit_arg=option_string.partition('=')\n if not sep:\n sep=explicit_arg=None\n for option_string in self._option_string_actions:\n if option_string.startswith(option_prefix):\n action=self._option_string_actions[option_string]\n tup=action,option_string,sep,explicit_arg\n result.append(tup)\n \n \n \n \n elif option_string[0]in chars and option_string[1]not in chars:\n option_prefix=option_string\n short_option_prefix=option_string[:2]\n short_explicit_arg=option_string[2:]\n \n for option_string in self._option_string_actions:\n if option_string ==short_option_prefix:\n action=self._option_string_actions[option_string]\n tup=action,option_string,'',short_explicit_arg\n result.append(tup)\n elif option_string.startswith(option_prefix):\n action=self._option_string_actions[option_string]\n tup=action,option_string,None,None\n result.append(tup)\n \n \n else:\n raise ArgumentError(None,_('unexpected option string: %s')%option_string)\n \n \n return result\n \n def _get_nargs_pattern(self,action):\n \n \n nargs=action.nargs\n \n \n if nargs is None:\n nargs_pattern='(-*A-*)'\n \n \n elif nargs ==OPTIONAL:\n nargs_pattern='(-*A?-*)'\n \n \n elif nargs ==ZERO_OR_MORE:\n nargs_pattern='(-*[A-]*)'\n \n \n elif nargs ==ONE_OR_MORE:\n nargs_pattern='(-*A[A-]*)'\n \n \n elif nargs ==REMAINDER:\n nargs_pattern='([-AO]*)'\n \n \n elif nargs ==PARSER:\n nargs_pattern='(-*A[-AO]*)'\n \n \n elif nargs ==SUPPRESS:\n nargs_pattern='(-*-*)'\n \n \n else:\n nargs_pattern='(-*%s-*)'%'-*'.join('A'*nargs)\n \n \n if action.option_strings:\n nargs_pattern=nargs_pattern.replace('-*','')\n nargs_pattern=nargs_pattern.replace('-','')\n \n \n return nargs_pattern\n \n \n \n \n \n def parse_intermixed_args(self,args=None,namespace=None):\n args,argv=self.parse_known_intermixed_args(args,namespace)\n if argv:\n msg=_('unrecognized arguments: %s')%' '.join(argv)\n if self.exit_on_error:\n self.error(msg)\n else:\n raise ArgumentError(None,msg)\n return args\n \n def parse_known_intermixed_args(self,args=None,namespace=None):\n \n \n \n \n \n \n \n \n \n \n \n \n positionals=self._get_positional_actions()\n a=[action for action in positionals\n if action.nargs in[PARSER,REMAINDER]]\n if a:\n raise TypeError('parse_intermixed_args: positional arg'\n ' with nargs=%s'%a[0].nargs)\n \n if[action.dest for group in self._mutually_exclusive_groups\n for action in group._group_actions if action in positionals]:\n raise TypeError('parse_intermixed_args: positional in'\n ' mutuallyExclusiveGroup')\n \n try:\n save_usage=self.usage\n try:\n if self.usage is None:\n \n self.usage=self.format_usage()[7:]\n for action in positionals:\n \n action.save_nargs=action.nargs\n \n action.nargs=SUPPRESS\n action.save_default=action.default\n action.default=SUPPRESS\n namespace,remaining_args=self.parse_known_args(args,\n namespace)\n for action in positionals:\n \n if(hasattr(namespace,action.dest)\n and getattr(namespace,action.dest)==[]):\n from warnings import warn\n warn('Do not expect %s in %s'%(action.dest,namespace))\n delattr(namespace,action.dest)\n finally:\n \n for action in positionals:\n action.nargs=action.save_nargs\n action.default=action.save_default\n optionals=self._get_optional_actions()\n try:\n \n \n for action in optionals:\n action.save_required=action.required\n action.required=False\n for group in self._mutually_exclusive_groups:\n group.save_required=group.required\n group.required=False\n namespace,extras=self.parse_known_args(remaining_args,\n namespace)\n finally:\n \n for action in optionals:\n action.required=action.save_required\n for group in self._mutually_exclusive_groups:\n group.required=group.save_required\n finally:\n self.usage=save_usage\n return namespace,extras\n \n \n \n \n def _get_values(self,action,arg_strings):\n \n if not action.option_strings and action.nargs not in[PARSER,REMAINDER]:\n try:\n arg_strings.remove('--')\n except ValueError:\n pass\n \n \n if not arg_strings and action.nargs ==OPTIONAL:\n if action.option_strings:\n value=action.const\n else:\n value=action.default\n if isinstance(value,str):\n value=self._get_value(action,value)\n self._check_value(action,value)\n \n \n \n elif(not arg_strings and action.nargs ==ZERO_OR_MORE and\n not action.option_strings):\n if action.default is not None:\n value=action.default\n self._check_value(action,value)\n else:\n \n \n value=arg_strings\n \n \n elif len(arg_strings)==1 and action.nargs in[None,OPTIONAL]:\n arg_string,=arg_strings\n value=self._get_value(action,arg_string)\n self._check_value(action,value)\n \n \n elif action.nargs ==REMAINDER:\n value=[self._get_value(action,v)for v in arg_strings]\n \n \n elif action.nargs ==PARSER:\n value=[self._get_value(action,v)for v in arg_strings]\n self._check_value(action,value[0])\n \n \n elif action.nargs ==SUPPRESS:\n value=SUPPRESS\n \n \n else:\n value=[self._get_value(action,v)for v in arg_strings]\n for v in value:\n self._check_value(action,v)\n \n \n return value\n \n def _get_value(self,action,arg_string):\n type_func=self._registry_get('type',action.type,action.type)\n if not callable(type_func):\n msg=_('%r is not callable')\n raise ArgumentError(action,msg %type_func)\n \n \n try:\n result=type_func(arg_string)\n \n \n except ArgumentTypeError as err:\n msg=str(err)\n raise ArgumentError(action,msg)\n \n \n except(TypeError,ValueError):\n name=getattr(action.type,'__name__',repr(action.type))\n args={'type':name,'value':arg_string}\n msg=_('invalid %(type)s value: %(value)r')\n raise ArgumentError(action,msg %args)\n \n \n return result\n \n def _check_value(self,action,value):\n \n if action.choices is not None and value not in action.choices:\n args={'value':value,\n 'choices':', '.join(map(repr,action.choices))}\n msg=_('invalid choice: %(value)r (choose from %(choices)s)')\n raise ArgumentError(action,msg %args)\n \n \n \n \n def format_usage(self):\n formatter=self._get_formatter()\n formatter.add_usage(self.usage,self._actions,\n self._mutually_exclusive_groups)\n return formatter.format_help()\n \n def format_help(self):\n formatter=self._get_formatter()\n \n \n formatter.add_usage(self.usage,self._actions,\n self._mutually_exclusive_groups)\n \n \n formatter.add_text(self.description)\n \n \n for action_group in self._action_groups:\n formatter.start_section(action_group.title)\n formatter.add_text(action_group.description)\n formatter.add_arguments(action_group._group_actions)\n formatter.end_section()\n \n \n formatter.add_text(self.epilog)\n \n \n return formatter.format_help()\n \n def _get_formatter(self):\n return self.formatter_class(prog=self.prog)\n \n \n \n \n def print_usage(self,file=None):\n if file is None:\n file=_sys.stdout\n self._print_message(self.format_usage(),file)\n \n def print_help(self,file=None):\n if file is None:\n file=_sys.stdout\n self._print_message(self.format_help(),file)\n \n def _print_message(self,message,file=None):\n if message:\n file=file or _sys.stderr\n try:\n file.write(message)\n except(AttributeError,OSError):\n pass\n \n \n \n \n def exit(self,status=0,message=None):\n if message:\n self._print_message(message,_sys.stderr)\n _sys.exit(status)\n \n def error(self,message):\n ''\n\n\n\n\n\n\n \n self.print_usage(_sys.stderr)\n args={'prog':self.prog,'message':message}\n self.exit(2,_('%(prog)s: error: %(message)s\\n')%args)\n \n def _warning(self,message):\n args={'prog':self.prog,'message':message}\n self._print_message(_('%(prog)s: warning: %(message)s\\n')%args,_sys.stderr)\n", ["copy", "gettext", "os", "re", "shutil", "sys", "textwrap", "warnings"]], "ast": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport re\nfrom _ast import *\nfrom contextlib import contextmanager,nullcontext\nfrom enum import IntEnum,auto,_simple_enum\n\n\ndef parse(source,filename='',mode='exec',*,\ntype_comments=False,feature_version=None,optimize=-1):\n ''\n\n\n\n \n flags=PyCF_ONLY_AST\n if optimize >0:\n flags |=PyCF_OPTIMIZED_AST\n if type_comments:\n flags |=PyCF_TYPE_COMMENTS\n if feature_version is None:\n feature_version=-1\n elif isinstance(feature_version,tuple):\n major,minor=feature_version\n if major !=3:\n raise ValueError(f\"Unsupported major version: {major}\")\n feature_version=minor\n \n return compile(source,filename,mode,flags,\n _feature_version=feature_version,optimize=optimize)\n \n \ndef literal_eval(node_or_string):\n ''\n\n\n\n\n\n\n \n if isinstance(node_or_string,str):\n node_or_string=parse(node_or_string.lstrip(\" \\t\"),mode='eval')\n if isinstance(node_or_string,Expression):\n node_or_string=node_or_string.body\n def _raise_malformed_node(node):\n msg=\"malformed node or string\"\n if lno :=getattr(node,'lineno',None):\n msg +=f' on line {lno}'\n raise ValueError(msg+f': {node !r}')\n def _convert_num(node):\n if not isinstance(node,Constant)or type(node.value)not in(int,float,complex):\n _raise_malformed_node(node)\n return node.value\n def _convert_signed_num(node):\n if isinstance(node,UnaryOp)and isinstance(node.op,(UAdd,USub)):\n operand=_convert_num(node.operand)\n if isinstance(node.op,UAdd):\n return+operand\n else:\n return -operand\n return _convert_num(node)\n def _convert(node):\n if isinstance(node,Constant):\n return node.value\n elif isinstance(node,Tuple):\n return tuple(map(_convert,node.elts))\n elif isinstance(node,List):\n return list(map(_convert,node.elts))\n elif isinstance(node,Set):\n return set(map(_convert,node.elts))\n elif(isinstance(node,Call)and isinstance(node.func,Name)and\n node.func.id =='set'and node.args ==node.keywords ==[]):\n return set()\n elif isinstance(node,Dict):\n if len(node.keys)!=len(node.values):\n _raise_malformed_node(node)\n return dict(zip(map(_convert,node.keys),\n map(_convert,node.values)))\n elif isinstance(node,BinOp)and isinstance(node.op,(Add,Sub)):\n left=_convert_signed_num(node.left)\n right=_convert_num(node.right)\n if isinstance(left,(int,float))and isinstance(right,complex):\n if isinstance(node.op,Add):\n return left+right\n else:\n return left -right\n return _convert_signed_num(node)\n return _convert(node_or_string)\n \n \ndef dump(\nnode,annotate_fields=True,include_attributes=False,\n*,\nindent=None,show_empty=False,\n):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n def _format(node,level=0):\n if indent is not None:\n level +=1\n prefix='\\n'+indent *level\n sep=',\\n'+indent *level\n else:\n prefix=''\n sep=', '\n if isinstance(node,AST):\n cls=type(node)\n args=[]\n args_buffer=[]\n allsimple=True\n keywords=annotate_fields\n for name in node._fields:\n try:\n value=getattr(node,name)\n except AttributeError:\n keywords=True\n continue\n if value is None and getattr(cls,name,...)is None:\n keywords=True\n continue\n if(\n not show_empty\n and(value is None or value ==[])\n \n \n and not isinstance(node,(Constant,MatchSingleton))\n ):\n args_buffer.append(repr(value))\n continue\n elif not keywords:\n args.extend(args_buffer)\n args_buffer=[]\n value,simple=_format(value,level)\n allsimple=allsimple and simple\n if keywords:\n args.append('%s=%s'%(name,value))\n else:\n args.append(value)\n if include_attributes and node._attributes:\n for name in node._attributes:\n try:\n value=getattr(node,name)\n except AttributeError:\n continue\n if value is None and getattr(cls,name,...)is None:\n continue\n value,simple=_format(value,level)\n allsimple=allsimple and simple\n args.append('%s=%s'%(name,value))\n if allsimple and len(args)<=3:\n return '%s(%s)'%(node.__class__.__name__,', '.join(args)),not args\n return '%s(%s%s)'%(node.__class__.__name__,prefix,sep.join(args)),False\n elif isinstance(node,list):\n if not node:\n return '[]',True\n return '[%s%s]'%(prefix,sep.join(_format(x,level)[0]for x in node)),False\n return repr(node),True\n \n if not isinstance(node,AST):\n raise TypeError('expected AST, got %r'%node.__class__.__name__)\n if indent is not None and not isinstance(indent,str):\n indent=' '*indent\n return _format(node)[0]\n \n \ndef copy_location(new_node,old_node):\n ''\n\n\n \n for attr in 'lineno','col_offset','end_lineno','end_col_offset':\n if attr in old_node._attributes and attr in new_node._attributes:\n value=getattr(old_node,attr,None)\n \n \n if value is not None or(\n hasattr(old_node,attr)and attr.startswith(\"end_\")\n ):\n setattr(new_node,attr,value)\n return new_node\n \n \ndef fix_missing_locations(node):\n ''\n\n\n\n\n\n \n def _fix(node,lineno,col_offset,end_lineno,end_col_offset):\n if 'lineno'in node._attributes:\n if not hasattr(node,'lineno'):\n node.lineno=lineno\n else:\n lineno=node.lineno\n if 'end_lineno'in node._attributes:\n if getattr(node,'end_lineno',None)is None:\n node.end_lineno=end_lineno\n else:\n end_lineno=node.end_lineno\n if 'col_offset'in node._attributes:\n if not hasattr(node,'col_offset'):\n node.col_offset=col_offset\n else:\n col_offset=node.col_offset\n if 'end_col_offset'in node._attributes:\n if getattr(node,'end_col_offset',None)is None:\n node.end_col_offset=end_col_offset\n else:\n end_col_offset=node.end_col_offset\n for child in iter_child_nodes(node):\n _fix(child,lineno,col_offset,end_lineno,end_col_offset)\n _fix(node,1,0,1,0)\n return node\n \n \ndef increment_lineno(node,n=1):\n ''\n\n\n\n \n for child in walk(node):\n \n \n if isinstance(child,TypeIgnore):\n child.lineno=getattr(child,'lineno',0)+n\n continue\n \n if 'lineno'in child._attributes:\n child.lineno=getattr(child,'lineno',0)+n\n if(\n \"end_lineno\"in child._attributes\n and(end_lineno :=getattr(child,\"end_lineno\",0))is not None\n ):\n child.end_lineno=end_lineno+n\n return node\n \n \ndef iter_fields(node):\n ''\n\n\n \n for field in node._fields:\n try:\n yield field,getattr(node,field)\n except AttributeError:\n pass\n \n \ndef iter_child_nodes(node):\n ''\n\n\n \n for name,field in iter_fields(node):\n if isinstance(field,AST):\n yield field\n elif isinstance(field,list):\n for item in field:\n if isinstance(item,AST):\n yield item\n \n \ndef get_docstring(node,clean=True):\n ''\n\n\n\n\n\n\n \n if not isinstance(node,(AsyncFunctionDef,FunctionDef,ClassDef,Module)):\n raise TypeError(\"%r can't have docstrings\"%node.__class__.__name__)\n if not(node.body and isinstance(node.body[0],Expr)):\n return None\n node=node.body[0].value\n if isinstance(node,Constant)and isinstance(node.value,str):\n text=node.value\n else:\n return None\n if clean:\n import inspect\n text=inspect.cleandoc(text)\n return text\n \n \n_line_pattern=re.compile(r\"(.*?(?:\\r\\n|\\n|\\r|$))\")\ndef _splitlines_no_ff(source,maxlines=None):\n ''\n\n\n \n lines=[]\n for lineno,match in enumerate(_line_pattern.finditer(source),1):\n if maxlines is not None and lineno >maxlines:\n break\n lines.append(match[0])\n return lines\n \n \ndef _pad_whitespace(source):\n ''\n result=''\n for c in source:\n if c in '\\f\\t':\n result +=c\n else:\n result +=' '\n return result\n \n \ndef get_source_segment(source,node,*,padded=False):\n ''\n\n\n\n\n\n\n \n try:\n if node.end_lineno is None or node.end_col_offset is None:\n return None\n lineno=node.lineno -1\n end_lineno=node.end_lineno -1\n col_offset=node.col_offset\n end_col_offset=node.end_col_offset\n except AttributeError:\n return None\n \n lines=_splitlines_no_ff(source,maxlines=end_lineno+1)\n if end_lineno ==lineno:\n return lines[lineno].encode()[col_offset:end_col_offset].decode()\n \n if padded:\n padding=_pad_whitespace(lines[lineno].encode()[:col_offset].decode())\n else:\n padding=''\n \n first=padding+lines[lineno].encode()[col_offset:].decode()\n last=lines[end_lineno].encode()[:end_col_offset].decode()\n lines=lines[lineno+1:end_lineno]\n \n lines.insert(0,first)\n lines.append(last)\n return ''.join(lines)\n \n \ndef walk(node):\n ''\n\n\n\n \n from collections import deque\n todo=deque([node])\n while todo:\n node=todo.popleft()\n todo.extend(iter_child_nodes(node))\n yield node\n \n \nclass NodeVisitor(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def visit(self,node):\n ''\n method='visit_'+node.__class__.__name__\n visitor=getattr(self,method,self.generic_visit)\n return visitor(node)\n \n def generic_visit(self,node):\n ''\n for field,value in iter_fields(node):\n if isinstance(value,list):\n for item in value:\n if isinstance(item,AST):\n self.visit(item)\n elif isinstance(value,AST):\n self.visit(value)\n \n def visit_Constant(self,node):\n value=node.value\n type_name=_const_node_type_names.get(type(value))\n if type_name is None:\n for cls,name in _const_node_type_names.items():\n if isinstance(value,cls):\n type_name=name\n break\n if type_name is not None:\n method='visit_'+type_name\n try:\n visitor=getattr(self,method)\n except AttributeError:\n pass\n else:\n import warnings\n warnings.warn(f\"{method} is deprecated; add visit_Constant\",\n DeprecationWarning,2)\n return visitor(node)\n return self.generic_visit(node)\n \n \nclass NodeTransformer(NodeVisitor):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def generic_visit(self,node):\n for field,old_value in iter_fields(node):\n if isinstance(old_value,list):\n new_values=[]\n for value in old_value:\n if isinstance(value,AST):\n value=self.visit(value)\n if value is None:\n continue\n elif not isinstance(value,AST):\n new_values.extend(value)\n continue\n new_values.append(value)\n old_value[:]=new_values\n elif isinstance(old_value,AST):\n new_node=self.visit(old_value)\n if new_node is None:\n delattr(node,field)\n else:\n setattr(node,field,new_node)\n return node\n \n \n_DEPRECATED_VALUE_ALIAS_MESSAGE=(\n\"{name} is deprecated and will be removed in Python {remove}; use value instead\"\n)\n_DEPRECATED_CLASS_MESSAGE=(\n\"{name} is deprecated and will be removed in Python {remove}; \"\n\"use ast.Constant instead\"\n)\n\n\n\nif not hasattr(Constant,'n'):\n\n\n\n def _n_getter(self):\n ''\n import warnings\n warnings._deprecated(\n \"Attribute n\",message=_DEPRECATED_VALUE_ALIAS_MESSAGE,remove=(3,14)\n )\n return self.value\n \n def _n_setter(self,value):\n import warnings\n warnings._deprecated(\n \"Attribute n\",message=_DEPRECATED_VALUE_ALIAS_MESSAGE,remove=(3,14)\n )\n self.value=value\n \n def _s_getter(self):\n ''\n import warnings\n warnings._deprecated(\n \"Attribute s\",message=_DEPRECATED_VALUE_ALIAS_MESSAGE,remove=(3,14)\n )\n return self.value\n \n def _s_setter(self,value):\n import warnings\n warnings._deprecated(\n \"Attribute s\",message=_DEPRECATED_VALUE_ALIAS_MESSAGE,remove=(3,14)\n )\n self.value=value\n \n Constant.n=property(_n_getter,_n_setter)\n Constant.s=property(_s_getter,_s_setter)\n \nclass _ABC(type):\n\n def __init__(cls,*args):\n cls.__doc__=\"\"\"Deprecated AST node class. Use ast.Constant instead\"\"\"\n \n def __instancecheck__(cls,inst):\n if cls in _const_types:\n import warnings\n warnings._deprecated(\n f\"ast.{cls.__qualname__}\",\n message=_DEPRECATED_CLASS_MESSAGE,\n remove=(3,14)\n )\n if not isinstance(inst,Constant):\n return False\n if cls in _const_types:\n try:\n value=inst.value\n except AttributeError:\n return False\n else:\n return(\n isinstance(value,_const_types[cls])and\n not isinstance(value,_const_types_not.get(cls,()))\n )\n return type.__instancecheck__(cls,inst)\n \ndef _new(cls,*args,**kwargs):\n for key in kwargs:\n if key not in cls._fields:\n \n continue\n pos=cls._fields.index(key)\n if pos precedence)\n \n def get_precedence(self,node):\n return self._precedences.get(node,_Precedence.TEST)\n \n def set_precedence(self,precedence,*nodes):\n for node in nodes:\n self._precedences[node]=precedence\n \n def get_raw_docstring(self,node):\n ''\n\n\n \n if not isinstance(\n node,(AsyncFunctionDef,FunctionDef,ClassDef,Module)\n )or len(node.body)<1:\n return None\n node=node.body[0]\n if not isinstance(node,Expr):\n return None\n node=node.value\n if isinstance(node,Constant)and isinstance(node.value,str):\n return node\n \n def get_type_comment(self,node):\n comment=self._type_ignores.get(node.lineno)or node.type_comment\n if comment is not None:\n return f\" # type: {comment}\"\n \n def traverse(self,node):\n if isinstance(node,list):\n for item in node:\n self.traverse(item)\n else:\n super().visit(node)\n \n \n \n \n def visit(self,node):\n ''\n \n self._source=[]\n self.traverse(node)\n return \"\".join(self._source)\n \n def _write_docstring_and_traverse_body(self,node):\n if(docstring :=self.get_raw_docstring(node)):\n self._write_docstring(docstring)\n self.traverse(node.body[1:])\n else:\n self.traverse(node.body)\n \n def visit_Module(self,node):\n self._type_ignores={\n ignore.lineno:f\"ignore{ignore.tag}\"\n for ignore in node.type_ignores\n }\n self._write_docstring_and_traverse_body(node)\n self._type_ignores.clear()\n \n def visit_FunctionType(self,node):\n with self.delimit(\"(\",\")\"):\n self.interleave(\n lambda:self.write(\", \"),self.traverse,node.argtypes\n )\n \n self.write(\" -> \")\n self.traverse(node.returns)\n \n def visit_Expr(self,node):\n self.fill()\n self.set_precedence(_Precedence.YIELD,node.value)\n self.traverse(node.value)\n \n def visit_NamedExpr(self,node):\n with self.require_parens(_Precedence.NAMED_EXPR,node):\n self.set_precedence(_Precedence.ATOM,node.target,node.value)\n self.traverse(node.target)\n self.write(\" := \")\n self.traverse(node.value)\n \n def visit_Import(self,node):\n self.fill(\"import \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.names)\n \n def visit_ImportFrom(self,node):\n self.fill(\"from \")\n self.write(\".\"*(node.level or 0))\n if node.module:\n self.write(node.module)\n self.write(\" import \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.names)\n \n def visit_Assign(self,node):\n self.fill()\n for target in node.targets:\n self.set_precedence(_Precedence.TUPLE,target)\n self.traverse(target)\n self.write(\" = \")\n self.traverse(node.value)\n if type_comment :=self.get_type_comment(node):\n self.write(type_comment)\n \n def visit_AugAssign(self,node):\n self.fill()\n self.traverse(node.target)\n self.write(\" \"+self.binop[node.op.__class__.__name__]+\"= \")\n self.traverse(node.value)\n \n def visit_AnnAssign(self,node):\n self.fill()\n with self.delimit_if(\"(\",\")\",not node.simple and isinstance(node.target,Name)):\n self.traverse(node.target)\n self.write(\": \")\n self.traverse(node.annotation)\n if node.value:\n self.write(\" = \")\n self.traverse(node.value)\n \n def visit_Return(self,node):\n self.fill(\"return\")\n if node.value:\n self.write(\" \")\n self.traverse(node.value)\n \n def visit_Pass(self,node):\n self.fill(\"pass\")\n \n def visit_Break(self,node):\n self.fill(\"break\")\n \n def visit_Continue(self,node):\n self.fill(\"continue\")\n \n def visit_Delete(self,node):\n self.fill(\"del \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.targets)\n \n def visit_Assert(self,node):\n self.fill(\"assert \")\n self.traverse(node.test)\n if node.msg:\n self.write(\", \")\n self.traverse(node.msg)\n \n def visit_Global(self,node):\n self.fill(\"global \")\n self.interleave(lambda:self.write(\", \"),self.write,node.names)\n \n def visit_Nonlocal(self,node):\n self.fill(\"nonlocal \")\n self.interleave(lambda:self.write(\", \"),self.write,node.names)\n \n def visit_Await(self,node):\n with self.require_parens(_Precedence.AWAIT,node):\n self.write(\"await\")\n if node.value:\n self.write(\" \")\n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n \n def visit_Yield(self,node):\n with self.require_parens(_Precedence.YIELD,node):\n self.write(\"yield\")\n if node.value:\n self.write(\" \")\n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n \n def visit_YieldFrom(self,node):\n with self.require_parens(_Precedence.YIELD,node):\n self.write(\"yield from \")\n if not node.value:\n raise ValueError(\"Node can't be used without a value attribute.\")\n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n \n def visit_Raise(self,node):\n self.fill(\"raise\")\n if not node.exc:\n if node.cause:\n raise ValueError(f\"Node can't use cause without an exception.\")\n return\n self.write(\" \")\n self.traverse(node.exc)\n if node.cause:\n self.write(\" from \")\n self.traverse(node.cause)\n \n def do_visit_try(self,node):\n self.fill(\"try\")\n with self.block():\n self.traverse(node.body)\n for ex in node.handlers:\n self.traverse(ex)\n if node.orelse:\n self.fill(\"else\")\n with self.block():\n self.traverse(node.orelse)\n if node.finalbody:\n self.fill(\"finally\")\n with self.block():\n self.traverse(node.finalbody)\n \n def visit_Try(self,node):\n prev_in_try_star=self._in_try_star\n try:\n self._in_try_star=False\n self.do_visit_try(node)\n finally:\n self._in_try_star=prev_in_try_star\n \n def visit_TryStar(self,node):\n prev_in_try_star=self._in_try_star\n try:\n self._in_try_star=True\n self.do_visit_try(node)\n finally:\n self._in_try_star=prev_in_try_star\n \n def visit_ExceptHandler(self,node):\n self.fill(\"except*\"if self._in_try_star else \"except\")\n if node.type:\n self.write(\" \")\n self.traverse(node.type)\n if node.name:\n self.write(\" as \")\n self.write(node.name)\n with self.block():\n self.traverse(node.body)\n \n def visit_ClassDef(self,node):\n self.maybe_newline()\n for deco in node.decorator_list:\n self.fill(\"@\")\n self.traverse(deco)\n self.fill(\"class \"+node.name)\n if hasattr(node,\"type_params\"):\n self._type_params_helper(node.type_params)\n with self.delimit_if(\"(\",\")\",condition=node.bases or node.keywords):\n comma=False\n for e in node.bases:\n if comma:\n self.write(\", \")\n else:\n comma=True\n self.traverse(e)\n for e in node.keywords:\n if comma:\n self.write(\", \")\n else:\n comma=True\n self.traverse(e)\n \n with self.block():\n self._write_docstring_and_traverse_body(node)\n \n def visit_FunctionDef(self,node):\n self._function_helper(node,\"def\")\n \n def visit_AsyncFunctionDef(self,node):\n self._function_helper(node,\"async def\")\n \n def _function_helper(self,node,fill_suffix):\n self.maybe_newline()\n for deco in node.decorator_list:\n self.fill(\"@\")\n self.traverse(deco)\n def_str=fill_suffix+\" \"+node.name\n self.fill(def_str)\n if hasattr(node,\"type_params\"):\n self._type_params_helper(node.type_params)\n with self.delimit(\"(\",\")\"):\n self.traverse(node.args)\n if node.returns:\n self.write(\" -> \")\n self.traverse(node.returns)\n with self.block(extra=self.get_type_comment(node)):\n self._write_docstring_and_traverse_body(node)\n \n def _type_params_helper(self,type_params):\n if type_params is not None and len(type_params)>0:\n with self.delimit(\"[\",\"]\"):\n self.interleave(lambda:self.write(\", \"),self.traverse,type_params)\n \n def visit_TypeVar(self,node):\n self.write(node.name)\n if node.bound:\n self.write(\": \")\n self.traverse(node.bound)\n if node.default_value:\n self.write(\" = \")\n self.traverse(node.default_value)\n \n def visit_TypeVarTuple(self,node):\n self.write(\"*\"+node.name)\n if node.default_value:\n self.write(\" = \")\n self.traverse(node.default_value)\n \n def visit_ParamSpec(self,node):\n self.write(\"**\"+node.name)\n if node.default_value:\n self.write(\" = \")\n self.traverse(node.default_value)\n \n def visit_TypeAlias(self,node):\n self.fill(\"type \")\n self.traverse(node.name)\n self._type_params_helper(node.type_params)\n self.write(\" = \")\n self.traverse(node.value)\n \n def visit_For(self,node):\n self._for_helper(\"for \",node)\n \n def visit_AsyncFor(self,node):\n self._for_helper(\"async for \",node)\n \n def _for_helper(self,fill,node):\n self.fill(fill)\n self.set_precedence(_Precedence.TUPLE,node.target)\n self.traverse(node.target)\n self.write(\" in \")\n self.traverse(node.iter)\n with self.block(extra=self.get_type_comment(node)):\n self.traverse(node.body)\n if node.orelse:\n self.fill(\"else\")\n with self.block():\n self.traverse(node.orelse)\n \n def visit_If(self,node):\n self.fill(\"if \")\n self.traverse(node.test)\n with self.block():\n self.traverse(node.body)\n \n while node.orelse and len(node.orelse)==1 and isinstance(node.orelse[0],If):\n node=node.orelse[0]\n self.fill(\"elif \")\n self.traverse(node.test)\n with self.block():\n self.traverse(node.body)\n \n if node.orelse:\n self.fill(\"else\")\n with self.block():\n self.traverse(node.orelse)\n \n def visit_While(self,node):\n self.fill(\"while \")\n self.traverse(node.test)\n with self.block():\n self.traverse(node.body)\n if node.orelse:\n self.fill(\"else\")\n with self.block():\n self.traverse(node.orelse)\n \n def visit_With(self,node):\n self.fill(\"with \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.items)\n with self.block(extra=self.get_type_comment(node)):\n self.traverse(node.body)\n \n def visit_AsyncWith(self,node):\n self.fill(\"async with \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.items)\n with self.block(extra=self.get_type_comment(node)):\n self.traverse(node.body)\n \n def _str_literal_helper(\n self,string,*,quote_types=_ALL_QUOTES,escape_special_whitespace=False\n ):\n ''\n\n \n def escape_char(c):\n \n \n if not escape_special_whitespace and c in \"\\n\\t\":\n return c\n \n if c ==\"\\\\\"or not c.isprintable():\n return c.encode(\"unicode_escape\").decode(\"ascii\")\n return c\n \n escaped_string=\"\".join(map(escape_char,string))\n possible_quotes=quote_types\n if \"\\n\"in escaped_string:\n possible_quotes=[q for q in possible_quotes if q in _MULTI_QUOTES]\n possible_quotes=[q for q in possible_quotes if q not in escaped_string]\n if not possible_quotes:\n \n \n \n string=repr(string)\n quote=next((q for q in quote_types if string[0]in q),string[0])\n return string[1:-1],[quote]\n if escaped_string:\n \n possible_quotes.sort(key=lambda q:q[0]==escaped_string[-1])\n \n \n if possible_quotes[0][0]==escaped_string[-1]:\n assert len(possible_quotes[0])==3\n escaped_string=escaped_string[:-1]+\"\\\\\"+escaped_string[-1]\n return escaped_string,possible_quotes\n \n def _write_str_avoiding_backslashes(self,string,*,quote_types=_ALL_QUOTES):\n ''\n string,quote_types=self._str_literal_helper(string,quote_types=quote_types)\n quote_type=quote_types[0]\n self.write(f\"{quote_type}{string}{quote_type}\")\n \n def visit_JoinedStr(self,node):\n self.write(\"f\")\n \n fstring_parts=[]\n for value in node.values:\n with self.buffered()as buffer:\n self._write_fstring_inner(value)\n fstring_parts.append(\n (\"\".join(buffer),isinstance(value,Constant))\n )\n \n new_fstring_parts=[]\n quote_types=list(_ALL_QUOTES)\n fallback_to_repr=False\n for value,is_constant in fstring_parts:\n if is_constant:\n value,new_quote_types=self._str_literal_helper(\n value,\n quote_types=quote_types,\n escape_special_whitespace=True,\n )\n if set(new_quote_types).isdisjoint(quote_types):\n fallback_to_repr=True\n break\n quote_types=new_quote_types\n elif \"\\n\"in value:\n quote_types=[q for q in quote_types if q in _MULTI_QUOTES]\n assert quote_types\n new_fstring_parts.append(value)\n \n if fallback_to_repr:\n \n \n quote_types=[\"'''\"]\n new_fstring_parts.clear()\n for value,is_constant in fstring_parts:\n if is_constant:\n value=repr('\"'+value)\n expected_prefix=\"'\\\"\"\n assert value.startswith(expected_prefix),repr(value)\n value=value[len(expected_prefix):-1]\n new_fstring_parts.append(value)\n \n value=\"\".join(new_fstring_parts)\n quote_type=quote_types[0]\n self.write(f\"{quote_type}{value}{quote_type}\")\n \n def _write_fstring_inner(self,node,is_format_spec=False):\n if isinstance(node,JoinedStr):\n \n for value in node.values:\n self._write_fstring_inner(value,is_format_spec=is_format_spec)\n elif isinstance(node,Constant)and isinstance(node.value,str):\n value=node.value.replace(\"{\",\"{{\").replace(\"}\",\"}}\")\n \n if is_format_spec:\n value=value.replace(\"\\\\\",\"\\\\\\\\\")\n value=value.replace(\"'\",\"\\\\'\")\n value=value.replace('\"','\\\\\"')\n value=value.replace(\"\\n\",\"\\\\n\")\n self.write(value)\n elif isinstance(node,FormattedValue):\n self.visit_FormattedValue(node)\n else:\n raise ValueError(f\"Unexpected node inside JoinedStr, {node !r}\")\n \n def visit_FormattedValue(self,node):\n def unparse_inner(inner):\n unparser=type(self)()\n unparser.set_precedence(_Precedence.TEST.next(),inner)\n return unparser.visit(inner)\n \n with self.delimit(\"{\",\"}\"):\n expr=unparse_inner(node.value)\n if expr.startswith(\"{\"):\n \n self.write(\" \")\n self.write(expr)\n if node.conversion !=-1:\n self.write(f\"!{chr(node.conversion)}\")\n if node.format_spec:\n self.write(\":\")\n self._write_fstring_inner(node.format_spec,is_format_spec=True)\n \n def visit_Name(self,node):\n self.write(node.id)\n \n def _write_docstring(self,node):\n self.fill()\n if node.kind ==\"u\":\n self.write(\"u\")\n self._write_str_avoiding_backslashes(node.value,quote_types=_MULTI_QUOTES)\n \n def _write_constant(self,value):\n if isinstance(value,(float,complex)):\n \n \n self.write(\n repr(value)\n .replace(\"inf\",_INFSTR)\n .replace(\"nan\",f\"({_INFSTR}-{_INFSTR})\")\n )\n else:\n self.write(repr(value))\n \n def visit_Constant(self,node):\n value=node.value\n if isinstance(value,tuple):\n with self.delimit(\"(\",\")\"):\n self.items_view(self._write_constant,value)\n elif value is ...:\n self.write(\"...\")\n else:\n if node.kind ==\"u\":\n self.write(\"u\")\n self._write_constant(node.value)\n \n def visit_List(self,node):\n with self.delimit(\"[\",\"]\"):\n self.interleave(lambda:self.write(\", \"),self.traverse,node.elts)\n \n def visit_ListComp(self,node):\n with self.delimit(\"[\",\"]\"):\n self.traverse(node.elt)\n for gen in node.generators:\n self.traverse(gen)\n \n def visit_GeneratorExp(self,node):\n with self.delimit(\"(\",\")\"):\n self.traverse(node.elt)\n for gen in node.generators:\n self.traverse(gen)\n \n def visit_SetComp(self,node):\n with self.delimit(\"{\",\"}\"):\n self.traverse(node.elt)\n for gen in node.generators:\n self.traverse(gen)\n \n def visit_DictComp(self,node):\n with self.delimit(\"{\",\"}\"):\n self.traverse(node.key)\n self.write(\": \")\n self.traverse(node.value)\n for gen in node.generators:\n self.traverse(gen)\n \n def visit_comprehension(self,node):\n if node.is_async:\n self.write(\" async for \")\n else:\n self.write(\" for \")\n self.set_precedence(_Precedence.TUPLE,node.target)\n self.traverse(node.target)\n self.write(\" in \")\n self.set_precedence(_Precedence.TEST.next(),node.iter,*node.ifs)\n self.traverse(node.iter)\n for if_clause in node.ifs:\n self.write(\" if \")\n self.traverse(if_clause)\n \n def visit_IfExp(self,node):\n with self.require_parens(_Precedence.TEST,node):\n self.set_precedence(_Precedence.TEST.next(),node.body,node.test)\n self.traverse(node.body)\n self.write(\" if \")\n self.traverse(node.test)\n self.write(\" else \")\n self.set_precedence(_Precedence.TEST,node.orelse)\n self.traverse(node.orelse)\n \n def visit_Set(self,node):\n if node.elts:\n with self.delimit(\"{\",\"}\"):\n self.interleave(lambda:self.write(\", \"),self.traverse,node.elts)\n else:\n \n \n self.write('{*()}')\n \n def visit_Dict(self,node):\n def write_key_value_pair(k,v):\n self.traverse(k)\n self.write(\": \")\n self.traverse(v)\n \n def write_item(item):\n k,v=item\n if k is None:\n \n \n self.write(\"**\")\n self.set_precedence(_Precedence.EXPR,v)\n self.traverse(v)\n else:\n write_key_value_pair(k,v)\n \n with self.delimit(\"{\",\"}\"):\n self.interleave(\n lambda:self.write(\", \"),write_item,zip(node.keys,node.values)\n )\n \n def visit_Tuple(self,node):\n with self.delimit_if(\n \"(\",\n \")\",\n len(node.elts)==0 or self.get_precedence(node)>_Precedence.TUPLE\n ):\n self.items_view(self.traverse,node.elts)\n \n unop={\"Invert\":\"~\",\"Not\":\"not\",\"UAdd\":\"+\",\"USub\":\"-\"}\n unop_precedence={\n \"not\":_Precedence.NOT,\n \"~\":_Precedence.FACTOR,\n \"+\":_Precedence.FACTOR,\n \"-\":_Precedence.FACTOR,\n }\n \n def visit_UnaryOp(self,node):\n operator=self.unop[node.op.__class__.__name__]\n operator_precedence=self.unop_precedence[operator]\n with self.require_parens(operator_precedence,node):\n self.write(operator)\n \n \n if operator_precedence is not _Precedence.FACTOR:\n self.write(\" \")\n self.set_precedence(operator_precedence,node.operand)\n self.traverse(node.operand)\n \n binop={\n \"Add\":\"+\",\n \"Sub\":\"-\",\n \"Mult\":\"*\",\n \"MatMult\":\"@\",\n \"Div\":\"/\",\n \"Mod\":\"%\",\n \"LShift\":\"<<\",\n \"RShift\":\">>\",\n \"BitOr\":\"|\",\n \"BitXor\":\"^\",\n \"BitAnd\":\"&\",\n \"FloorDiv\":\"//\",\n \"Pow\":\"**\",\n }\n \n binop_precedence={\n \"+\":_Precedence.ARITH,\n \"-\":_Precedence.ARITH,\n \"*\":_Precedence.TERM,\n \"@\":_Precedence.TERM,\n \"/\":_Precedence.TERM,\n \"%\":_Precedence.TERM,\n \"<<\":_Precedence.SHIFT,\n \">>\":_Precedence.SHIFT,\n \"|\":_Precedence.BOR,\n \"^\":_Precedence.BXOR,\n \"&\":_Precedence.BAND,\n \"//\":_Precedence.TERM,\n \"**\":_Precedence.POWER,\n }\n \n binop_rassoc=frozenset((\"**\",))\n def visit_BinOp(self,node):\n operator=self.binop[node.op.__class__.__name__]\n operator_precedence=self.binop_precedence[operator]\n with self.require_parens(operator_precedence,node):\n if operator in self.binop_rassoc:\n left_precedence=operator_precedence.next()\n right_precedence=operator_precedence\n else:\n left_precedence=operator_precedence\n right_precedence=operator_precedence.next()\n \n self.set_precedence(left_precedence,node.left)\n self.traverse(node.left)\n self.write(f\" {operator} \")\n self.set_precedence(right_precedence,node.right)\n self.traverse(node.right)\n \n cmpops={\n \"Eq\":\"==\",\n \"NotEq\":\"!=\",\n \"Lt\":\"<\",\n \"LtE\":\"<=\",\n \"Gt\":\">\",\n \"GtE\":\">=\",\n \"Is\":\"is\",\n \"IsNot\":\"is not\",\n \"In\":\"in\",\n \"NotIn\":\"not in\",\n }\n \n def visit_Compare(self,node):\n with self.require_parens(_Precedence.CMP,node):\n self.set_precedence(_Precedence.CMP.next(),node.left,*node.comparators)\n self.traverse(node.left)\n for o,e in zip(node.ops,node.comparators):\n self.write(\" \"+self.cmpops[o.__class__.__name__]+\" \")\n self.traverse(e)\n \n boolops={\"And\":\"and\",\"Or\":\"or\"}\n boolop_precedence={\"and\":_Precedence.AND,\"or\":_Precedence.OR}\n \n def visit_BoolOp(self,node):\n operator=self.boolops[node.op.__class__.__name__]\n operator_precedence=self.boolop_precedence[operator]\n \n def increasing_level_traverse(node):\n nonlocal operator_precedence\n operator_precedence=operator_precedence.next()\n self.set_precedence(operator_precedence,node)\n self.traverse(node)\n \n with self.require_parens(operator_precedence,node):\n s=f\" {operator} \"\n self.interleave(lambda:self.write(s),increasing_level_traverse,node.values)\n \n def visit_Attribute(self,node):\n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n \n \n \n if isinstance(node.value,Constant)and isinstance(node.value.value,int):\n self.write(\" \")\n self.write(\".\")\n self.write(node.attr)\n \n def visit_Call(self,node):\n self.set_precedence(_Precedence.ATOM,node.func)\n self.traverse(node.func)\n with self.delimit(\"(\",\")\"):\n comma=False\n for e in node.args:\n if comma:\n self.write(\", \")\n else:\n comma=True\n self.traverse(e)\n for e in node.keywords:\n if comma:\n self.write(\", \")\n else:\n comma=True\n self.traverse(e)\n \n def visit_Subscript(self,node):\n def is_non_empty_tuple(slice_value):\n return(\n isinstance(slice_value,Tuple)\n and slice_value.elts\n )\n \n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n with self.delimit(\"[\",\"]\"):\n if is_non_empty_tuple(node.slice):\n \n self.items_view(self.traverse,node.slice.elts)\n else:\n self.traverse(node.slice)\n \n def visit_Starred(self,node):\n self.write(\"*\")\n self.set_precedence(_Precedence.EXPR,node.value)\n self.traverse(node.value)\n \n def visit_Ellipsis(self,node):\n self.write(\"...\")\n \n def visit_Slice(self,node):\n if node.lower:\n self.traverse(node.lower)\n self.write(\":\")\n if node.upper:\n self.traverse(node.upper)\n if node.step:\n self.write(\":\")\n self.traverse(node.step)\n \n def visit_Match(self,node):\n self.fill(\"match \")\n self.traverse(node.subject)\n with self.block():\n for case in node.cases:\n self.traverse(case)\n \n def visit_arg(self,node):\n self.write(node.arg)\n if node.annotation:\n self.write(\": \")\n self.traverse(node.annotation)\n \n def visit_arguments(self,node):\n first=True\n \n all_args=node.posonlyargs+node.args\n defaults=[None]*(len(all_args)-len(node.defaults))+node.defaults\n for index,elements in enumerate(zip(all_args,defaults),1):\n a,d=elements\n if first:\n first=False\n else:\n self.write(\", \")\n self.traverse(a)\n if d:\n self.write(\"=\")\n self.traverse(d)\n if index ==len(node.posonlyargs):\n self.write(\", /\")\n \n \n if node.vararg or node.kwonlyargs:\n if first:\n first=False\n else:\n self.write(\", \")\n self.write(\"*\")\n if node.vararg:\n self.write(node.vararg.arg)\n if node.vararg.annotation:\n self.write(\": \")\n self.traverse(node.vararg.annotation)\n \n \n if node.kwonlyargs:\n for a,d in zip(node.kwonlyargs,node.kw_defaults):\n self.write(\", \")\n self.traverse(a)\n if d:\n self.write(\"=\")\n self.traverse(d)\n \n \n if node.kwarg:\n if first:\n first=False\n else:\n self.write(\", \")\n self.write(\"**\"+node.kwarg.arg)\n if node.kwarg.annotation:\n self.write(\": \")\n self.traverse(node.kwarg.annotation)\n \n def visit_keyword(self,node):\n if node.arg is None:\n self.write(\"**\")\n else:\n self.write(node.arg)\n self.write(\"=\")\n self.traverse(node.value)\n \n def visit_Lambda(self,node):\n with self.require_parens(_Precedence.TEST,node):\n self.write(\"lambda\")\n with self.buffered()as buffer:\n self.traverse(node.args)\n if buffer:\n self.write(\" \",*buffer)\n self.write(\": \")\n self.set_precedence(_Precedence.TEST,node.body)\n self.traverse(node.body)\n \n def visit_alias(self,node):\n self.write(node.name)\n if node.asname:\n self.write(\" as \"+node.asname)\n \n def visit_withitem(self,node):\n self.traverse(node.context_expr)\n if node.optional_vars:\n self.write(\" as \")\n self.traverse(node.optional_vars)\n \n def visit_match_case(self,node):\n self.fill(\"case \")\n self.traverse(node.pattern)\n if node.guard:\n self.write(\" if \")\n self.traverse(node.guard)\n with self.block():\n self.traverse(node.body)\n \n def visit_MatchValue(self,node):\n self.traverse(node.value)\n \n def visit_MatchSingleton(self,node):\n self._write_constant(node.value)\n \n def visit_MatchSequence(self,node):\n with self.delimit(\"[\",\"]\"):\n self.interleave(\n lambda:self.write(\", \"),self.traverse,node.patterns\n )\n \n def visit_MatchStar(self,node):\n name=node.name\n if name is None:\n name=\"_\"\n self.write(f\"*{name}\")\n \n def visit_MatchMapping(self,node):\n def write_key_pattern_pair(pair):\n k,p=pair\n self.traverse(k)\n self.write(\": \")\n self.traverse(p)\n \n with self.delimit(\"{\",\"}\"):\n keys=node.keys\n self.interleave(\n lambda:self.write(\", \"),\n write_key_pattern_pair,\n zip(keys,node.patterns,strict=True),\n )\n rest=node.rest\n if rest is not None:\n if keys:\n self.write(\", \")\n self.write(f\"**{rest}\")\n \n def visit_MatchClass(self,node):\n self.set_precedence(_Precedence.ATOM,node.cls)\n self.traverse(node.cls)\n with self.delimit(\"(\",\")\"):\n patterns=node.patterns\n self.interleave(\n lambda:self.write(\", \"),self.traverse,patterns\n )\n attrs=node.kwd_attrs\n if attrs:\n def write_attr_pattern(pair):\n attr,pattern=pair\n self.write(f\"{attr}=\")\n self.traverse(pattern)\n \n if patterns:\n self.write(\", \")\n self.interleave(\n lambda:self.write(\", \"),\n write_attr_pattern,\n zip(attrs,node.kwd_patterns,strict=True),\n )\n \n def visit_MatchAs(self,node):\n name=node.name\n pattern=node.pattern\n if name is None:\n self.write(\"_\")\n elif pattern is None:\n self.write(node.name)\n else:\n with self.require_parens(_Precedence.TEST,node):\n self.set_precedence(_Precedence.BOR,node.pattern)\n self.traverse(node.pattern)\n self.write(f\" as {node.name}\")\n \n def visit_MatchOr(self,node):\n with self.require_parens(_Precedence.BOR,node):\n self.set_precedence(_Precedence.BOR.next(),*node.patterns)\n self.interleave(lambda:self.write(\" | \"),self.traverse,node.patterns)\n \ndef unparse(ast_obj):\n unparser=_Unparser()\n return unparser.visit(ast_obj)\n \n \n_deprecated_globals={\nname:globals().pop(name)\nfor name in('Num','Str','Bytes','NameConstant','Ellipsis')\n}\n\ndef __getattr__(name):\n if name in _deprecated_globals:\n globals()[name]=value=_deprecated_globals[name]\n import warnings\n warnings._deprecated(\n f\"ast.{name}\",message=_DEPRECATED_CLASS_MESSAGE,remove=(3,14)\n )\n return value\n raise AttributeError(f\"module 'ast' has no attribute '{name}'\")\n \n \ndef main():\n import argparse\n \n parser=argparse.ArgumentParser(prog='python -m ast')\n parser.add_argument('infile',nargs='?',default='-',\n help='the file to parse; defaults to stdin')\n parser.add_argument('-m','--mode',default='exec',\n choices=('exec','single','eval','func_type'),\n help='specify what kind of code must be parsed')\n parser.add_argument('--no-type-comments',default=True,action='store_false',\n help=\"don't add information about type comments\")\n parser.add_argument('-a','--include-attributes',action='store_true',\n help='include attributes such as line numbers and '\n 'column offsets')\n parser.add_argument('-i','--indent',type=int,default=3,\n help='indentation of nodes (number of spaces)')\n args=parser.parse_args()\n \n if args.infile =='-':\n name=''\n source=sys.stdin.buffer.read()\n else:\n name=args.infile\n with open(args.infile,'rb')as infile:\n source=infile.read()\n tree=parse(source,name,args.mode,type_comments=args.no_type_comments)\n print(dump(tree,include_attributes=args.include_attributes,indent=args.indent))\n \nif __name__ =='__main__':\n main()\n", ["_ast", "argparse", "collections", "contextlib", "enum", "inspect", "re", "sys", "warnings"]], "asyncio": [".py", "print('Brython implementation of asyncio is present to avoid ImportError '+\n'in some modules, but does not implement the asyncio features '+\n'because of browser limitations.\\nFor asynchronous programming, use '+\n'browser.aio instead')\n\nALL_COMPLETED=\"\"\"ALL_COMPLETED\"\"\"\n\n\nclass AbstractEventLoop:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n \nclass AbstractEventLoopPolicy:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n def get_child_watcher(*args,**kw):\n pass\n \n def get_event_loop(*args,**kw):\n pass\n \n def new_event_loop(*args,**kw):\n pass\n \n def set_child_watcher(*args,**kw):\n pass\n \n def set_event_loop(*args,**kw):\n pass\n \nclass AbstractServer:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n def close(*args,**kw):\n pass\n \n def get_loop(*args,**kw):\n pass\n \n def is_serving(*args,**kw):\n pass\n \n def serve_forever(*args,**kw):\n pass\n \n def start_serving(*args,**kw):\n pass\n \n def wait_closed(*args,**kw):\n pass\n \nclass Barrier:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _block(*args,**kw):\n pass\n \n def _exit(*args,**kw):\n pass\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def _release(*args,**kw):\n pass\n \n def _wait(*args,**kw):\n pass\n \n def abort(*args,**kw):\n pass\n \n broken=\"\"\n \n n_waiting=\"\"\n \n parties=\"\"\n \n def reset(*args,**kw):\n pass\n \n def wait(*args,**kw):\n pass\n \nclass BaseEventLoop:\n\n __module__=\"\"\"asyncio.base_events\"\"\"\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n \nclass BaseProtocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass BaseTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \nclass BoundedSemaphore:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def _wake_up_next(*args,**kw):\n pass\n \n def acquire(*args,**kw):\n pass\n \n def locked(*args,**kw):\n pass\n \n def release(*args,**kw):\n pass\n \nclass BrokenBarrierError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass BufferedProtocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def buffer_updated(*args,**kw):\n pass\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def eof_received(*args,**kw):\n pass\n \n def get_buffer(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass CancelledError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass Condition:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def notify(*args,**kw):\n pass\n \n def notify_all(*args,**kw):\n pass\n \n def wait(*args,**kw):\n pass\n \n def wait_for(*args,**kw):\n pass\n \nclass DatagramProtocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def datagram_received(*args,**kw):\n pass\n \n def error_received(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass DatagramTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def abort(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def sendto(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \nclass DefaultEventLoopPolicy:\n\n\n class _Local:\n \n __module__=\"\"\"asyncio.events\"\"\"\n \n _loop=None\n \n _set_called=False\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n \n class _loop_factory:\n \n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _loop_self_reading(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_duplex_pipe_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_accept_futures(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_pipe_connection(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_serving_pipe(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n def get_child_watcher(*args,**kw):\n pass\n \n def get_event_loop(*args,**kw):\n pass\n \n def new_event_loop(*args,**kw):\n pass\n \n def set_child_watcher(*args,**kw):\n pass\n \n def set_event_loop(*args,**kw):\n pass\n \nclass Event:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def clear(*args,**kw):\n pass\n \n def is_set(*args,**kw):\n pass\n \n def set(*args,**kw):\n pass\n \n def wait(*args,**kw):\n pass\nFIRST_COMPLETED=\"\"\"FIRST_COMPLETED\"\"\"\n\nFIRST_EXCEPTION=\"\"\"FIRST_EXCEPTION\"\"\"\n\n\nclass Future:\n\n _asyncio_future_blocking=\"\"\n \n _callbacks=\"\"\n \n _cancel_message=\"\"\n \n _exception=\"\"\n \n _log_traceback=\"\"\n \n _loop=\"\"\n \n _make_cancelled_error=\"\"\n \n _result=\"\"\n \n _source_traceback=\"\"\n \n _state=\"\"\n \n add_done_callback=\"\"\n \n cancel=\"\"\n \n cancelled=\"\"\n \n done=\"\"\n \n exception=\"\"\n \n get_loop=\"\"\n \n remove_done_callback=\"\"\n \n result=\"\"\n \n set_exception=\"\"\n \n set_result=\"\"\n \nclass Handle:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n _args=\"\"\n \n _callback=\"\"\n \n _cancelled=\"\"\n \n _context=\"\"\n \n _loop=\"\"\n \n _repr=\"\"\n \n def _repr_info(*args,**kw):\n pass\n \n def _run(*args,**kw):\n pass\n \n _source_traceback=\"\"\n \n def cancel(*args,**kw):\n pass\n \n def cancelled(*args,**kw):\n pass\n \nclass IncompleteReadError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass InvalidStateError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass IocpProactor:\n\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _check_closed(*args,**kw):\n pass\n \n def _get_accept_socket(*args,**kw):\n pass\n \n def _poll(*args,**kw):\n pass\n \n def _register(*args,**kw):\n pass\n \n def _register_with_iocp(*args,**kw):\n pass\n \n def _result(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _unregister(*args,**kw):\n pass\n \n def _wait_cancel(*args,**kw):\n pass\n \n def _wait_for_handle(*args,**kw):\n pass\n \n def accept(*args,**kw):\n pass\n \n def accept_pipe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect(*args,**kw):\n pass\n \n def connect_pipe(*args,**kw):\n pass\n \n def recv(*args,**kw):\n pass\n \n def recv_into(*args,**kw):\n pass\n \n def recvfrom(*args,**kw):\n pass\n \n def recvfrom_into(*args,**kw):\n pass\n \n def select(*args,**kw):\n pass\n \n def send(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def sendto(*args,**kw):\n pass\n \n def set_loop(*args,**kw):\n pass\n \n def wait_for_handle(*args,**kw):\n pass\n \nclass LifoQueue:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n def _format(*args,**kw):\n pass\n \n def _get(*args,**kw):\n pass\n \n def _get_loop(*args,**kw):\n pass\n \n def _init(*args,**kw):\n pass\n \n _loop=None\n \n def _put(*args,**kw):\n pass\n \n def _wakeup_next(*args,**kw):\n pass\n \n def empty(*args,**kw):\n pass\n \n def full(*args,**kw):\n pass\n \n def get(*args,**kw):\n pass\n \n def get_nowait(*args,**kw):\n pass\n \n def join(*args,**kw):\n pass\n \n maxsize=\"\"\n \n def put(*args,**kw):\n pass\n \n def put_nowait(*args,**kw):\n pass\n \n def qsize(*args,**kw):\n pass\n \n def task_done(*args,**kw):\n pass\n \nclass LimitOverrunError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass Lock:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def _wake_up_first(*args,**kw):\n pass\n \n def acquire(*args,**kw):\n pass\n \n def locked(*args,**kw):\n pass\n \n def release(*args,**kw):\n pass\n \nclass PriorityQueue:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n def _format(*args,**kw):\n pass\n \n def _get(*args,**kw):\n pass\n \n def _get_loop(*args,**kw):\n pass\n \n def _init(*args,**kw):\n pass\n \n _loop=None\n \n def _put(*args,**kw):\n pass\n \n def _wakeup_next(*args,**kw):\n pass\n \n def empty(*args,**kw):\n pass\n \n def full(*args,**kw):\n pass\n \n def get(*args,**kw):\n pass\n \n def get_nowait(*args,**kw):\n pass\n \n def join(*args,**kw):\n pass\n \n maxsize=\"\"\n \n def put(*args,**kw):\n pass\n \n def put_nowait(*args,**kw):\n pass\n \n def qsize(*args,**kw):\n pass\n \n def task_done(*args,**kw):\n pass\n \nclass ProactorEventLoop:\n\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _loop_self_reading(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_duplex_pipe_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_accept_futures(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_pipe_connection(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_serving_pipe(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n \nclass Protocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def data_received(*args,**kw):\n pass\n \n def eof_received(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass Queue:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n def _format(*args,**kw):\n pass\n \n def _get(*args,**kw):\n pass\n \n def _get_loop(*args,**kw):\n pass\n \n def _init(*args,**kw):\n pass\n \n _loop=None\n \n def _put(*args,**kw):\n pass\n \n def _wakeup_next(*args,**kw):\n pass\n \n def empty(*args,**kw):\n pass\n \n def full(*args,**kw):\n pass\n \n def get(*args,**kw):\n pass\n \n def get_nowait(*args,**kw):\n pass\n \n def join(*args,**kw):\n pass\n \n maxsize=\"\"\n \n def put(*args,**kw):\n pass\n \n def put_nowait(*args,**kw):\n pass\n \n def qsize(*args,**kw):\n pass\n \n def task_done(*args,**kw):\n pass\n \nclass QueueEmpty:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass QueueFull:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass ReadTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def is_reading(*args,**kw):\n pass\n \n def pause_reading(*args,**kw):\n pass\n \n def resume_reading(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \nclass Runner:\n\n __module__=\"\"\"asyncio.runners\"\"\"\n \n def _lazy_init(*args,**kw):\n pass\n \n def _on_sigint(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_loop(*args,**kw):\n pass\n \n def run(*args,**kw):\n pass\n \nclass SelectorEventLoop:\n\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _accept_connection(*args,**kw):\n pass\n \n def _accept_connection2(*args,**kw):\n pass\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _add_reader(*args,**kw):\n pass\n \n def _add_writer(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_fd_no_transport(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _process_self_data(*args,**kw):\n pass\n \n def _read_from_self(*args,**kw):\n pass\n \n def _remove_reader(*args,**kw):\n pass\n \n def _remove_writer(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_accept(*args,**kw):\n pass\n \n def _sock_connect(*args,**kw):\n pass\n \n def _sock_connect_cb(*args,**kw):\n pass\n \n def _sock_read_done(*args,**kw):\n pass\n \n def _sock_recv(*args,**kw):\n pass\n \n def _sock_recv_into(*args,**kw):\n pass\n \n def _sock_recvfrom(*args,**kw):\n pass\n \n def _sock_recvfrom_into(*args,**kw):\n pass\n \n def _sock_sendall(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _sock_sendto(*args,**kw):\n pass\n \n def _sock_write_done(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n \nclass Semaphore:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def _wake_up_next(*args,**kw):\n pass\n \n def acquire(*args,**kw):\n pass\n \n def locked(*args,**kw):\n pass\n \n def release(*args,**kw):\n pass\n \nclass SendfileNotAvailableError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass Server:\n\n __module__=\"\"\"asyncio.base_events\"\"\"\n \n def _attach(*args,**kw):\n pass\n \n def _detach(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _wakeup(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_loop(*args,**kw):\n pass\n \n def is_serving(*args,**kw):\n pass\n \n def serve_forever(*args,**kw):\n pass\n \n sockets=\"\"\n \n def start_serving(*args,**kw):\n pass\n \n def wait_closed(*args,**kw):\n pass\n \nclass StreamReader:\n\n __module__=\"\"\"asyncio.streams\"\"\"\n \n def _maybe_resume_transport(*args,**kw):\n pass\n \n _source_traceback=None\n \n def _wait_for_data(*args,**kw):\n pass\n \n def _wakeup_waiter(*args,**kw):\n pass\n \n def at_eof(*args,**kw):\n pass\n \n def exception(*args,**kw):\n pass\n \n def feed_data(*args,**kw):\n pass\n \n def feed_eof(*args,**kw):\n pass\n \n def read(*args,**kw):\n pass\n \n def readexactly(*args,**kw):\n pass\n \n def readline(*args,**kw):\n pass\n \n def readuntil(*args,**kw):\n pass\n \n def set_exception(*args,**kw):\n pass\n \n def set_transport(*args,**kw):\n pass\n \nclass StreamReaderProtocol:\n\n __module__=\"\"\"asyncio.streams\"\"\"\n \n def _drain_helper(*args,**kw):\n pass\n \n def _get_close_waiter(*args,**kw):\n pass\n \n def _replace_writer(*args,**kw):\n pass\n \n _source_traceback=None\n \n _stream_reader=\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def data_received(*args,**kw):\n pass\n \n def eof_received(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass StreamWriter:\n\n __module__=\"\"\"asyncio.streams\"\"\"\n \n def can_write_eof(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def drain(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n transport=\"\"\n \n def wait_closed(*args,**kw):\n pass\n \n def write(*args,**kw):\n pass\n \n def write_eof(*args,**kw):\n pass\n \n def writelines(*args,**kw):\n pass\n \nclass SubprocessProtocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def pipe_connection_lost(*args,**kw):\n pass\n \n def pipe_data_received(*args,**kw):\n pass\n \n def process_exited(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass SubprocessTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_pid(*args,**kw):\n pass\n \n def get_pipe_transport(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def get_returncode(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def kill(*args,**kw):\n pass\n \n def send_signal(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \n def terminate(*args,**kw):\n pass\n \nclass Task:\n\n _asyncio_future_blocking=\"\"\n \n _callbacks=\"\"\n \n _cancel_message=\"\"\n \n _check_future=\"\"\n \n _coro=\"\"\n \n _exception=\"\"\n \n _fut_waiter=\"\"\n \n _log_destroy_pending=\"\"\n \n _log_traceback=\"\"\n \n _loop=\"\"\n \n _make_cancelled_error=\"\"\n \n _must_cancel=\"\"\n \n _result=\"\"\n \n _source_traceback=\"\"\n \n _state=\"\"\n \n add_done_callback=\"\"\n \n cancel=\"\"\n \n cancelled=\"\"\n \n cancelling=\"\"\n \n done=\"\"\n \n exception=\"\"\n \n get_coro=\"\"\n \n get_loop=\"\"\n \n get_name=\"\"\n \n get_stack=\"\"\n \n print_stack=\"\"\n \n remove_done_callback=\"\"\n \n result=\"\"\n \n set_exception=\"\"\n \n set_name=\"\"\n \n set_result=\"\"\n \n uncancel=\"\"\n \nclass TaskGroup:\n\n __module__=\"\"\"asyncio.taskgroups\"\"\"\n \n def _abort(*args,**kw):\n pass\n \n def _is_base_error(*args,**kw):\n pass\n \n def _on_task_done(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \nclass Timeout:\n\n __module__=\"\"\"asyncio.timeouts\"\"\"\n \n def _on_timeout(*args,**kw):\n pass\n \n def expired(*args,**kw):\n pass\n \n def reschedule(*args,**kw):\n pass\n \n def when(*args,**kw):\n pass\n \nclass TimeoutError:\n\n add_note=\"\"\n \n args=\"\"\n \n characters_written=\"\"\n \n errno=\"\"\n \n filename=\"\"\n \n filename2=\"\"\n \n strerror=\"\"\n \n winerror=\"\"\n \n with_traceback=\"\"\n \nclass TimerHandle:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n _args=\"\"\n \n _callback=\"\"\n \n _cancelled=\"\"\n \n _context=\"\"\n \n _loop=\"\"\n \n _repr=\"\"\n \n def _repr_info(*args,**kw):\n pass\n \n def _run(*args,**kw):\n pass\n \n _scheduled=\"\"\n \n _source_traceback=\"\"\n \n _when=\"\"\n \n def cancel(*args,**kw):\n pass\n \n def cancelled(*args,**kw):\n pass\n \n def when(*args,**kw):\n pass\n \nclass Transport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def abort(*args,**kw):\n pass\n \n def can_write_eof(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def get_write_buffer_limits(*args,**kw):\n pass\n \n def get_write_buffer_size(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def is_reading(*args,**kw):\n pass\n \n def pause_reading(*args,**kw):\n pass\n \n def resume_reading(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \n def set_write_buffer_limits(*args,**kw):\n pass\n \n def write(*args,**kw):\n pass\n \n def write_eof(*args,**kw):\n pass\n \n def writelines(*args,**kw):\n pass\n \nclass WindowsProactorEventLoopPolicy:\n\n\n class _Local:\n \n __module__=\"\"\"asyncio.events\"\"\"\n \n _loop=None\n \n _set_called=False\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n \n class _loop_factory:\n \n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _loop_self_reading(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_duplex_pipe_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_accept_futures(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_pipe_connection(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_serving_pipe(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n def get_child_watcher(*args,**kw):\n pass\n \n def get_event_loop(*args,**kw):\n pass\n \n def new_event_loop(*args,**kw):\n pass\n \n def set_child_watcher(*args,**kw):\n pass\n \n def set_event_loop(*args,**kw):\n pass\n \nclass WindowsSelectorEventLoopPolicy:\n\n\n class _Local:\n \n __module__=\"\"\"asyncio.events\"\"\"\n \n _loop=None\n \n _set_called=False\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n \n class _loop_factory:\n \n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _accept_connection(*args,**kw):\n pass\n \n def _accept_connection2(*args,**kw):\n pass\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _add_reader(*args,**kw):\n pass\n \n def _add_writer(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_fd_no_transport(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _process_self_data(*args,**kw):\n pass\n \n def _read_from_self(*args,**kw):\n pass\n \n def _remove_reader(*args,**kw):\n pass\n \n def _remove_writer(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_accept(*args,**kw):\n pass\n \n def _sock_connect(*args,**kw):\n pass\n \n def _sock_connect_cb(*args,**kw):\n pass\n \n def _sock_read_done(*args,**kw):\n pass\n \n def _sock_recv(*args,**kw):\n pass\n \n def _sock_recv_into(*args,**kw):\n pass\n \n def _sock_recvfrom(*args,**kw):\n pass\n \n def _sock_recvfrom_into(*args,**kw):\n pass\n \n def _sock_sendall(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _sock_sendto(*args,**kw):\n pass\n \n def _sock_write_done(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n def get_child_watcher(*args,**kw):\n pass\n \n def get_event_loop(*args,**kw):\n pass\n \n def new_event_loop(*args,**kw):\n pass\n \n def set_child_watcher(*args,**kw):\n pass\n \n def set_event_loop(*args,**kw):\n pass\n \nclass WriteTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def abort(*args,**kw):\n pass\n \n def can_write_eof(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def get_write_buffer_limits(*args,**kw):\n pass\n \n def get_write_buffer_size(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \n def set_write_buffer_limits(*args,**kw):\n pass\n \n def write(*args,**kw):\n pass\n \n def write_eof(*args,**kw):\n pass\n \n def writelines(*args,**kw):\n pass\ndef _enter_task(*args,**kw):\n pass\n \ndef _get_running_loop(*args,**kw):\n pass\n \ndef _leave_task(*args,**kw):\n pass\n \ndef _register_task(*args,**kw):\n pass\n \ndef _set_running_loop(*args,**kw):\n pass\n \ndef _unregister_task(*args,**kw):\n pass\n \ndef all_tasks(*args,**kw):\n pass\n \ndef as_completed(*args,**kw):\n pass\n \nbase_events=\"\"\n\nbase_futures=\"\"\n\nbase_subprocess=\"\"\n\nbase_tasks=\"\"\n\nconstants=\"\"\n\ncoroutines=\"\"\n\ndef create_subprocess_exec(*args,**kw):\n pass\n \ndef create_subprocess_shell(*args,**kw):\n pass\n \ndef create_task(*args,**kw):\n pass\n \ndef current_task(*args,**kw):\n pass\n \ndef ensure_future(*args,**kw):\n pass\n \nevents=\"\"\n\nexceptions=\"\"\n\nformat_helpers=\"\"\n\nfutures=\"\"\n\ndef gather(*args,**kw):\n pass\n \ndef get_child_watcher(*args,**kw):\n pass\n \ndef get_event_loop(*args,**kw):\n pass\n \ndef get_event_loop_policy(*args,**kw):\n pass\n \ndef get_running_loop(*args,**kw):\n pass\n \ndef iscoroutine(*args,**kw):\n pass\n \ndef iscoroutinefunction(*args,**kw):\n pass\n \ndef isfuture(*args,**kw):\n pass\n \nlocks=\"\"\n\nlog=\"\"\n\nmixins=\"\"\n\ndef new_event_loop(*args,**kw):\n pass\n \ndef open_connection(*args,**kw):\n pass\n \nproactor_events=\"\"\n\nprotocols=\"\"\n\nqueues=\"\"\n\ndef run(*args,**kw):\n pass\n \ndef run_coroutine_threadsafe(*args,**kw):\n pass\n \nrunners=\"\"\n\nselector_events=\"\"\n\ndef set_child_watcher(*args,**kw):\n pass\n \ndef set_event_loop(*args,**kw):\n pass\n \ndef set_event_loop_policy(*args,**kw):\n pass\n \ndef shield(*args,**kw):\n pass\n \ndef sleep(*args,**kw):\n pass\n \nsslproto=\"\"\n\nstaggered=\"\"\n\ndef start_server(*args,**kw):\n pass\n \nstreams=\"\"\n\nsubprocess=\"\"\n\nsys=\"\"\n\ntaskgroups=\"\"\n\ntasks=\"\"\n\nthreads=\"\"\n\ndef timeout(*args,**kw):\n pass\n \ndef timeout_at(*args,**kw):\n pass\n \ntimeouts=\"\"\n\ndef to_thread(*args,**kw):\n pass\n \ntransports=\"\"\n\ntrsock=\"\"\n\ndef wait(*args,**kw):\n pass\n \ndef wait_for(*args,**kw):\n pass\n \nwindows_events=\"\"\n\nwindows_utils=\"\"\n\ndef wrap_future(*args,**kw):\n pass\n \n", []], "atexit": [".py", "''\n\n\n\n\n\nclass __loader__(object):\n pass\n \ndef _clear(*args,**kw):\n ''\n \n pass\n \ndef _run_exitfuncs(*args,**kw):\n ''\n \n pass\n \ndef register(*args,**kw):\n ''\n\n\n\n\n\n\n \n pass\n \ndef unregister(*args,**kw):\n ''\n\n\n\n \n pass\n", []], "base64": [".py", "#! /usr/bin/env python3\n\n\"\"\"Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings\"\"\"\n\n\n\n\n\nimport re\nimport struct\nimport binascii\n\n\n__all__=[\n\n'encode','decode','encodebytes','decodebytes',\n\n'b64encode','b64decode','b32encode','b32decode',\n'b32hexencode','b32hexdecode','b16encode','b16decode',\n\n'b85encode','b85decode','a85encode','a85decode','z85encode','z85decode',\n\n'standard_b64encode','standard_b64decode',\n\n\n\n\n'urlsafe_b64encode','urlsafe_b64decode',\n]\n\n\nbytes_types=(bytes,bytearray)\n\ndef _bytes_from_decode_data(s):\n if isinstance(s,str):\n try:\n return s.encode('ascii')\n except UnicodeEncodeError:\n raise ValueError('string argument should contain only ASCII characters')\n if isinstance(s,bytes_types):\n return s\n try:\n return memoryview(s).tobytes()\n except TypeError:\n raise TypeError(\"argument should be a bytes-like object or ASCII \"\n \"string, not %r\"%s.__class__.__name__)from None\n \n \n \n \ndef b64encode(s,altchars=None):\n ''\n\n\n\n\n \n encoded=binascii.b2a_base64(s,newline=False)\n if altchars is not None:\n assert len(altchars)==2,repr(altchars)\n return encoded.translate(bytes.maketrans(b'+/',altchars))\n return encoded\n \n \ndef b64decode(s,altchars=None,validate=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n if altchars is not None:\n altchars=_bytes_from_decode_data(altchars)\n assert len(altchars)==2,repr(altchars)\n s=s.translate(bytes.maketrans(altchars,b'+/'))\n return binascii.a2b_base64(s,strict_mode=validate)\n \n \ndef standard_b64encode(s):\n ''\n\n\n \n return b64encode(s)\n \ndef standard_b64decode(s):\n ''\n\n\n\n\n\n \n return b64decode(s)\n \n \n_urlsafe_encode_translation=bytes.maketrans(b'+/',b'-_')\n_urlsafe_decode_translation=bytes.maketrans(b'-_',b'+/')\n\ndef urlsafe_b64encode(s):\n ''\n\n\n\n\n \n return b64encode(s).translate(_urlsafe_encode_translation)\n \ndef urlsafe_b64decode(s):\n ''\n\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n s=s.translate(_urlsafe_decode_translation)\n return b64decode(s)\n \n \n \n \n_B32_ENCODE_DOCSTRING='''\nEncode the bytes-like objects using {encoding} and return a bytes object.\n'''\n_B32_DECODE_DOCSTRING='''\nDecode the {encoding} encoded bytes-like object or ASCII string s.\n\nOptional casefold is a flag specifying whether a lowercase alphabet is\nacceptable as input. For security purposes, the default is False.\n{extra_args}\nThe result is returned as a bytes object. A binascii.Error is raised if\nthe input is incorrectly padded or if there are non-alphabet\ncharacters present in the input.\n'''\n_B32_DECODE_MAP01_DOCSTRING='''\nRFC 3548 allows for optional mapping of the digit 0 (zero) to the\nletter O (oh), and for optional mapping of the digit 1 (one) to\neither the letter I (eye) or letter L (el). The optional argument\nmap01 when not None, specifies which letter the digit 1 should be\nmapped to (when map01 is not None, the digit 0 is always mapped to\nthe letter O). For security purposes the default is None, so that\n0 and 1 are not allowed in the input.\n'''\n_b32alphabet=b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\n_b32hexalphabet=b'0123456789ABCDEFGHIJKLMNOPQRSTUV'\n_b32tab2={}\n_b32rev={}\n\ndef _b32encode(alphabet,s):\n\n\n if alphabet not in _b32tab2:\n b32tab=[bytes((i,))for i in alphabet]\n _b32tab2[alphabet]=[a+b for a in b32tab for b in b32tab]\n b32tab=None\n \n if not isinstance(s,bytes_types):\n s=memoryview(s).tobytes()\n leftover=len(s)%5\n \n if leftover:\n s=s+b'\\0'*(5 -leftover)\n encoded=bytearray()\n from_bytes=int.from_bytes\n b32tab2=_b32tab2[alphabet]\n for i in range(0,len(s),5):\n c=from_bytes(s[i:i+5])\n encoded +=(b32tab2[c >>30]+\n b32tab2[(c >>20)&0x3ff]+\n b32tab2[(c >>10)&0x3ff]+\n b32tab2[c&0x3ff]\n )\n \n if leftover ==1:\n encoded[-6:]=b'======'\n elif leftover ==2:\n encoded[-4:]=b'===='\n elif leftover ==3:\n encoded[-3:]=b'==='\n elif leftover ==4:\n encoded[-1:]=b'='\n return bytes(encoded)\n \ndef _b32decode(alphabet,s,casefold=False,map01=None):\n\n\n if alphabet not in _b32rev:\n _b32rev[alphabet]={v:k for k,v in enumerate(alphabet)}\n s=_bytes_from_decode_data(s)\n if len(s)%8:\n raise binascii.Error('Incorrect padding')\n \n \n \n if map01 is not None:\n map01=_bytes_from_decode_data(map01)\n assert len(map01)==1,repr(map01)\n s=s.translate(bytes.maketrans(b'01',b'O'+map01))\n if casefold:\n s=s.upper()\n \n \n \n l=len(s)\n s=s.rstrip(b'=')\n padchars=l -len(s)\n \n decoded=bytearray()\n b32rev=_b32rev[alphabet]\n for i in range(0,len(s),8):\n quanta=s[i:i+8]\n acc=0\n try:\n for c in quanta:\n acc=(acc <<5)+b32rev[c]\n except KeyError:\n raise binascii.Error('Non-base32 digit found')from None\n decoded +=acc.to_bytes(5)\n \n if l %8 or padchars not in{0,1,3,4,6}:\n raise binascii.Error('Incorrect padding')\n if padchars and decoded:\n acc <<=5 *padchars\n last=acc.to_bytes(5)\n leftover=(43 -5 *padchars)//8\n decoded[-5:]=last[:leftover]\n return bytes(decoded)\n \n \ndef b32encode(s):\n return _b32encode(_b32alphabet,s)\nb32encode.__doc__=_B32_ENCODE_DOCSTRING.format(encoding='base32')\n\ndef b32decode(s,casefold=False,map01=None):\n return _b32decode(_b32alphabet,s,casefold,map01)\nb32decode.__doc__=_B32_DECODE_DOCSTRING.format(encoding='base32',\nextra_args=_B32_DECODE_MAP01_DOCSTRING)\n\ndef b32hexencode(s):\n return _b32encode(_b32hexalphabet,s)\nb32hexencode.__doc__=_B32_ENCODE_DOCSTRING.format(encoding='base32hex')\n\ndef b32hexdecode(s,casefold=False):\n\n return _b32decode(_b32hexalphabet,s,casefold)\nb32hexdecode.__doc__=_B32_DECODE_DOCSTRING.format(encoding='base32hex',\nextra_args='')\n\n\n\n\n\ndef b16encode(s):\n ''\n \n return binascii.hexlify(s).upper()\n \n \ndef b16decode(s,casefold=False):\n ''\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n if casefold:\n s=s.upper()\n if re.search(b'[^0-9A-F]',s):\n raise binascii.Error('Non-base16 digit found')\n return binascii.unhexlify(s)\n \n \n \n \n \n_a85chars=None\n_a85chars2=None\n_A85START=b\"<~\"\n_A85END=b\"~>\"\n\ndef _85encode(b,chars,chars2,pad=False,foldnuls=False,foldspaces=False):\n\n if not isinstance(b,bytes_types):\n b=memoryview(b).tobytes()\n \n padding=(-len(b))%4\n if padding:\n b=b+b'\\0'*padding\n words=struct.Struct('!%dI'%(len(b)//4)).unpack(b)\n \n chunks=[b'z'if foldnuls and not word else\n b'y'if foldspaces and word ==0x20202020 else\n (chars2[word //614125]+\n chars2[word //85 %7225]+\n chars[word %85])\n for word in words]\n \n if padding and not pad:\n if chunks[-1]==b'z':\n chunks[-1]=chars[0]*5\n chunks[-1]=chunks[-1][:-padding]\n \n return b''.join(chunks)\n \ndef a85encode(b,*,foldspaces=False,wrapcol=0,pad=False,adobe=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _a85chars,_a85chars2\n \n \n if _a85chars2 is None:\n _a85chars=[bytes((i,))for i in range(33,118)]\n _a85chars2=[(a+b)for a in _a85chars for b in _a85chars]\n \n result=_85encode(b,_a85chars,_a85chars2,pad,True,foldspaces)\n \n if adobe:\n result=_A85START+result\n if wrapcol:\n wrapcol=max(2 if adobe else 1,wrapcol)\n chunks=[result[i:i+wrapcol]\n for i in range(0,len(result),wrapcol)]\n if adobe:\n if len(chunks[-1])+2 >wrapcol:\n chunks.append(b'')\n result=b'\\n'.join(chunks)\n if adobe:\n result +=_A85END\n \n return result\n \ndef a85decode(b,*,foldspaces=False,adobe=False,ignorechars=b' \\t\\n\\r\\v'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n b=_bytes_from_decode_data(b)\n if adobe:\n if not b.endswith(_A85END):\n raise ValueError(\n \"Ascii85 encoded byte sequences must end \"\n \"with {!r}\".format(_A85END)\n )\n if b.startswith(_A85START):\n b=b[2:-2]\n else:\n b=b[:-2]\n \n \n \n \n packI=struct.Struct('!I').pack\n decoded=[]\n decoded_append=decoded.append\n curr=[]\n curr_append=curr.append\n curr_clear=curr.clear\n for x in b+b'u'*4:\n if b'!'[0]<=x <=b'u'[0]:\n curr_append(x)\n if len(curr)==5:\n acc=0\n for x in curr:\n acc=85 *acc+(x -33)\n try:\n decoded_append(packI(acc))\n except struct.error:\n raise ValueError('Ascii85 overflow')from None\n curr_clear()\n elif x ==b'z'[0]:\n if curr:\n raise ValueError('z inside Ascii85 5-tuple')\n decoded_append(b'\\0\\0\\0\\0')\n elif foldspaces and x ==b'y'[0]:\n if curr:\n raise ValueError('y inside Ascii85 5-tuple')\n decoded_append(b'\\x20\\x20\\x20\\x20')\n elif x in ignorechars:\n \n continue\n else:\n raise ValueError('Non-Ascii85 digit found: %c'%x)\n \n result=b''.join(decoded)\n padding=4 -len(curr)\n if padding:\n \n result=result[:-padding]\n return result\n \n \n \n_b85alphabet=(b\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nb\"abcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~\")\n_b85chars=None\n_b85chars2=None\n_b85dec=None\n\ndef b85encode(b,pad=False):\n ''\n\n\n\n \n global _b85chars,_b85chars2\n \n \n if _b85chars2 is None:\n _b85chars=[bytes((i,))for i in _b85alphabet]\n _b85chars2=[(a+b)for a in _b85chars for b in _b85chars]\n return _85encode(b,_b85chars,_b85chars2,pad)\n \ndef b85decode(b):\n ''\n\n\n \n global _b85dec\n \n \n if _b85dec is None:\n _b85dec=[None]*256\n for i,c in enumerate(_b85alphabet):\n _b85dec[c]=i\n \n b=_bytes_from_decode_data(b)\n padding=(-len(b))%5\n b=b+b'~'*padding\n out=[]\n packI=struct.Struct('!I').pack\n for i in range(0,len(b),5):\n chunk=b[i:i+5]\n acc=0\n try:\n for c in chunk:\n acc=acc *85+_b85dec[c]\n except TypeError:\n for j,c in enumerate(chunk):\n if _b85dec[c]is None:\n raise ValueError('bad base85 character at position %d'\n %(i+j))from None\n raise\n try:\n out.append(packI(acc))\n except struct.error:\n raise ValueError('base85 overflow in hunk starting at byte %d'\n %i)from None\n \n result=b''.join(out)\n if padding:\n result=result[:-padding]\n return result\n \n_z85alphabet=(b'0123456789abcdefghijklmnopqrstuvwxyz'\nb'ABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#')\n\n\n_z85_b85_decode_diff=b';_`|~'\n_z85_decode_translation=bytes.maketrans(\n_z85alphabet+_z85_b85_decode_diff,\n_b85alphabet+b'\\x00'*len(_z85_b85_decode_diff)\n)\n_z85_encode_translation=bytes.maketrans(_b85alphabet,_z85alphabet)\n\ndef z85encode(s):\n ''\n return b85encode(s).translate(_z85_encode_translation)\n \ndef z85decode(s):\n ''\n\n\n \n s=_bytes_from_decode_data(s)\n s=s.translate(_z85_decode_translation)\n try:\n return b85decode(s)\n except ValueError as e:\n raise ValueError(e.args[0].replace('base85','z85'))from None\n \n \n \n \n \nMAXLINESIZE=76\nMAXBINSIZE=(MAXLINESIZE //4)*3\n\ndef encode(input,output):\n ''\n while s :=input.read(MAXBINSIZE):\n while len(s)\":\n return filename\n canonic=self.fncache.get(filename)\n if not canonic:\n canonic=os.path.abspath(filename)\n canonic=os.path.normcase(canonic)\n self.fncache[filename]=canonic\n return canonic\n \n def reset(self):\n ''\n import linecache\n linecache.checkcache()\n self.botframe=None\n self._set_stopinfo(None,None)\n \n def trace_dispatch(self,frame,event,arg):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.enterframe=frame\n \n if self.quitting:\n return\n if event =='line':\n return self.dispatch_line(frame)\n if event =='call':\n return self.dispatch_call(frame,arg)\n if event =='return':\n return self.dispatch_return(frame,arg)\n if event =='exception':\n return self.dispatch_exception(frame,arg)\n if event =='c_call':\n return self.trace_dispatch\n if event =='c_exception':\n return self.trace_dispatch\n if event =='c_return':\n return self.trace_dispatch\n if event =='opcode':\n return self.dispatch_opcode(frame,arg)\n print('bdb.Bdb.dispatch: unknown debugging event:',repr(event))\n return self.trace_dispatch\n \n def dispatch_line(self,frame):\n ''\n\n\n\n\n \n if self.stop_here(frame)or self.break_here(frame):\n self.user_line(frame)\n if self.quitting:raise BdbQuit\n return self.trace_dispatch\n \n def dispatch_call(self,frame,arg):\n ''\n\n\n\n\n \n \n if self.botframe is None:\n \n self.botframe=frame.f_back\n return self.trace_dispatch\n if not(self.stop_here(frame)or self.break_anywhere(frame)):\n \n return\n \n if self.stopframe and frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n return self.trace_dispatch\n self.user_call(frame,arg)\n if self.quitting:raise BdbQuit\n return self.trace_dispatch\n \n def dispatch_return(self,frame,arg):\n ''\n\n\n\n\n \n if self.stop_here(frame)or frame ==self.returnframe:\n \n if self.stopframe and frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n return self.trace_dispatch\n try:\n self.frame_returning=frame\n self.user_return(frame,arg)\n finally:\n self.frame_returning=None\n if self.quitting:raise BdbQuit\n \n if self.stopframe is frame and self.stoplineno !=-1:\n self._set_stopinfo(None,None)\n \n \n \n if self.stoplineno !=-1:\n self._set_caller_tracefunc(frame)\n return self.trace_dispatch\n \n def dispatch_exception(self,frame,arg):\n ''\n\n\n\n\n \n if self.stop_here(frame):\n \n \n \n if not(frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS\n and arg[0]is StopIteration and arg[2]is None):\n self.user_exception(frame,arg)\n if self.quitting:raise BdbQuit\n \n \n \n \n elif(self.stopframe and frame is not self.stopframe\n and self.stopframe.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS\n and arg[0]in(StopIteration,GeneratorExit)):\n self.user_exception(frame,arg)\n if self.quitting:raise BdbQuit\n \n return self.trace_dispatch\n \n def dispatch_opcode(self,frame,arg):\n ''\n\n\n\n \n if self.stop_here(frame)or self.break_here(frame):\n self.user_opcode(frame)\n if self.quitting:raise BdbQuit\n return self.trace_dispatch\n \n \n \n \n \n def is_skipped_module(self,module_name):\n ''\n if module_name is None:\n return False\n for pattern in self.skip:\n if fnmatch.fnmatch(module_name,pattern):\n return True\n return False\n \n def stop_here(self,frame):\n ''\n \n \n if self.skip and\\\n self.is_skipped_module(frame.f_globals.get('__name__')):\n return False\n if frame is self.stopframe:\n if self.stoplineno ==-1:\n return False\n return frame.f_lineno >=self.stoplineno\n if not self.stopframe:\n return True\n return False\n \n def break_here(self,frame):\n ''\n\n\n\n \n filename=self.canonic(frame.f_code.co_filename)\n if filename not in self.breaks:\n return False\n lineno=frame.f_lineno\n if lineno not in self.breaks[filename]:\n \n \n lineno=frame.f_code.co_firstlineno\n if lineno not in self.breaks[filename]:\n return False\n \n \n (bp,flag)=effective(filename,lineno,frame)\n if bp:\n self.currentbp=bp.number\n if(flag and bp.temporary):\n self.do_clear(str(bp.number))\n return True\n else:\n return False\n \n def do_clear(self,arg):\n ''\n\n\n \n raise NotImplementedError(\"subclass of bdb must implement do_clear()\")\n \n def break_anywhere(self,frame):\n ''\n \n return self.canonic(frame.f_code.co_filename)in self.breaks\n \n \n \n \n def user_call(self,frame,argument_list):\n ''\n pass\n \n def user_line(self,frame):\n ''\n pass\n \n def user_return(self,frame,return_value):\n ''\n pass\n \n def user_exception(self,frame,exc_info):\n ''\n pass\n \n def user_opcode(self,frame):\n ''\n pass\n \n def _set_trace_opcodes(self,trace_opcodes):\n if trace_opcodes !=self.trace_opcodes:\n self.trace_opcodes=trace_opcodes\n frame=self.enterframe\n while frame is not None:\n frame.f_trace_opcodes=trace_opcodes\n if frame is self.botframe:\n break\n frame=frame.f_back\n \n def _set_stopinfo(self,stopframe,returnframe,stoplineno=0,opcode=False):\n ''\n\n\n\n\n \n self.stopframe=stopframe\n self.returnframe=returnframe\n self.quitting=False\n \n \n self.stoplineno=stoplineno\n self._set_trace_opcodes(opcode)\n \n def _set_caller_tracefunc(self,current_frame):\n \n \n \n \n caller_frame=current_frame.f_back\n if caller_frame and not caller_frame.f_trace:\n caller_frame.f_trace=self.trace_dispatch\n \n \n \n \n def set_until(self,frame,lineno=None):\n ''\n \n \n if lineno is None:\n lineno=frame.f_lineno+1\n self._set_stopinfo(frame,frame,lineno)\n \n def set_step(self):\n ''\n self._set_stopinfo(None,None)\n \n def set_stepinstr(self):\n ''\n self._set_stopinfo(None,None,opcode=True)\n \n def set_next(self,frame):\n ''\n self._set_stopinfo(frame,None)\n \n def set_return(self,frame):\n ''\n if frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n self._set_stopinfo(frame,None,-1)\n else:\n self._set_stopinfo(frame.f_back,frame)\n \n def set_trace(self,frame=None):\n ''\n\n\n \n if frame is None:\n frame=sys._getframe().f_back\n self.reset()\n self.enterframe=frame\n while frame:\n frame.f_trace=self.trace_dispatch\n self.botframe=frame\n self.frame_trace_lines_opcodes[frame]=(frame.f_trace_lines,frame.f_trace_opcodes)\n \n frame.f_trace_lines=True\n frame=frame.f_back\n self.set_stepinstr()\n sys.settrace(self.trace_dispatch)\n \n def set_continue(self):\n ''\n\n\n \n \n self._set_stopinfo(self.botframe,None,-1)\n if not self.breaks:\n \n sys.settrace(None)\n frame=sys._getframe().f_back\n while frame and frame is not self.botframe:\n del frame.f_trace\n frame=frame.f_back\n for frame,(trace_lines,trace_opcodes)in self.frame_trace_lines_opcodes.items():\n frame.f_trace_lines,frame.f_trace_opcodes=trace_lines,trace_opcodes\n self.frame_trace_lines_opcodes={}\n \n def set_quit(self):\n ''\n\n\n \n self.stopframe=self.botframe\n self.returnframe=None\n self.quitting=True\n sys.settrace(None)\n \n \n \n \n \n \n \n \n def _add_to_breaks(self,filename,lineno):\n ''\n bp_linenos=self.breaks.setdefault(filename,[])\n if lineno not in bp_linenos:\n bp_linenos.append(lineno)\n \n def set_break(self,filename,lineno,temporary=False,cond=None,\n funcname=None):\n ''\n\n\n\n \n filename=self.canonic(filename)\n import linecache\n line=linecache.getline(filename,lineno)\n if not line:\n return 'Line %s:%d does not exist'%(filename,lineno)\n self._add_to_breaks(filename,lineno)\n bp=Breakpoint(filename,lineno,temporary,cond,funcname)\n return None\n \n def _load_breaks(self):\n ''\n\n\n\n\n\n \n for(filename,lineno)in Breakpoint.bplist.keys():\n self._add_to_breaks(filename,lineno)\n \n def _prune_breaks(self,filename,lineno):\n ''\n\n\n\n\n\n \n if(filename,lineno)not in Breakpoint.bplist:\n self.breaks[filename].remove(lineno)\n if not self.breaks[filename]:\n del self.breaks[filename]\n \n def clear_break(self,filename,lineno):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename not in self.breaks:\n return 'There are no breakpoints in %s'%filename\n if lineno not in self.breaks[filename]:\n return 'There is no breakpoint at %s:%d'%(filename,lineno)\n \n \n for bp in Breakpoint.bplist[filename,lineno][:]:\n bp.deleteMe()\n self._prune_breaks(filename,lineno)\n return None\n \n def clear_bpbynumber(self,arg):\n ''\n\n\n \n try:\n bp=self.get_bpbynumber(arg)\n except ValueError as err:\n return str(err)\n bp.deleteMe()\n self._prune_breaks(bp.file,bp.line)\n return None\n \n def clear_all_file_breaks(self,filename):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename not in self.breaks:\n return 'There are no breakpoints in %s'%filename\n for line in self.breaks[filename]:\n blist=Breakpoint.bplist[filename,line]\n for bp in blist:\n bp.deleteMe()\n del self.breaks[filename]\n return None\n \n def clear_all_breaks(self):\n ''\n\n\n \n if not self.breaks:\n return 'There are no breakpoints'\n for bp in Breakpoint.bpbynumber:\n if bp:\n bp.deleteMe()\n self.breaks={}\n return None\n \n def get_bpbynumber(self,arg):\n ''\n\n\n\n \n if not arg:\n raise ValueError('Breakpoint number expected')\n try:\n number=int(arg)\n except ValueError:\n raise ValueError('Non-numeric breakpoint number %s'%arg)from None\n try:\n bp=Breakpoint.bpbynumber[number]\n except IndexError:\n raise ValueError('Breakpoint number %d out of range'%number)from None\n if bp is None:\n raise ValueError('Breakpoint %d already deleted'%number)\n return bp\n \n def get_break(self,filename,lineno):\n ''\n filename=self.canonic(filename)\n return filename in self.breaks and\\\n lineno in self.breaks[filename]\n \n def get_breaks(self,filename,lineno):\n ''\n\n\n \n filename=self.canonic(filename)\n return filename in self.breaks and\\\n lineno in self.breaks[filename]and\\\n Breakpoint.bplist[filename,lineno]or[]\n \n def get_file_breaks(self,filename):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename in self.breaks:\n return self.breaks[filename]\n else:\n return[]\n \n def get_all_breaks(self):\n ''\n return self.breaks\n \n \n \n \n def get_stack(self,f,t):\n ''\n\n\n\n \n stack=[]\n if t and t.tb_frame is f:\n t=t.tb_next\n while f is not None:\n stack.append((f,f.f_lineno))\n if f is self.botframe:\n break\n f=f.f_back\n stack.reverse()\n i=max(0,len(stack)-1)\n while t is not None:\n stack.append((t.tb_frame,t.tb_lineno))\n t=t.tb_next\n if f is None:\n i=max(0,len(stack)-1)\n return stack,i\n \n def format_stack_entry(self,frame_lineno,lprefix=': '):\n ''\n\n\n\n\n\n\n \n import linecache,reprlib\n frame,lineno=frame_lineno\n filename=self.canonic(frame.f_code.co_filename)\n s='%s(%r)'%(filename,lineno)\n if frame.f_code.co_name:\n s +=frame.f_code.co_name\n else:\n s +=\"\"\n s +='()'\n if '__return__'in frame.f_locals:\n rv=frame.f_locals['__return__']\n s +='->'\n s +=reprlib.repr(rv)\n if lineno is not None:\n line=linecache.getline(filename,lineno,frame.f_globals)\n if line:\n s +=lprefix+line.strip()\n else:\n s +=f'{lprefix}Warning: lineno is None'\n return s\n \n \n \n \n \n def run(self,cmd,globals=None,locals=None):\n ''\n\n\n \n if globals is None:\n import __main__\n globals=__main__.__dict__\n if locals is None:\n locals=globals\n self.reset()\n if isinstance(cmd,str):\n cmd=compile(cmd,\"\",\"exec\")\n sys.settrace(self.trace_dispatch)\n try:\n exec(cmd,globals,locals)\n except BdbQuit:\n pass\n finally:\n self.quitting=True\n sys.settrace(None)\n \n def runeval(self,expr,globals=None,locals=None):\n ''\n\n\n \n if globals is None:\n import __main__\n globals=__main__.__dict__\n if locals is None:\n locals=globals\n self.reset()\n sys.settrace(self.trace_dispatch)\n try:\n return eval(expr,globals,locals)\n except BdbQuit:\n pass\n finally:\n self.quitting=True\n sys.settrace(None)\n \n def runctx(self,cmd,globals,locals):\n ''\n \n self.run(cmd,globals,locals)\n \n \n \n def runcall(self,func,/,*args,**kwds):\n ''\n\n\n \n self.reset()\n sys.settrace(self.trace_dispatch)\n res=None\n try:\n res=func(*args,**kwds)\n except BdbQuit:\n pass\n finally:\n self.quitting=True\n sys.settrace(None)\n return res\n \n \ndef set_trace():\n ''\n Bdb().set_trace()\n \n \nclass Breakpoint:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n next=1\n bplist={}\n bpbynumber=[None]\n \n \n \n def __init__(self,file,line,temporary=False,cond=None,funcname=None):\n self.funcname=funcname\n \n self.func_first_executable_line=None\n self.file=file\n self.line=line\n self.temporary=temporary\n self.cond=cond\n self.enabled=True\n self.ignore=0\n self.hits=0\n self.number=Breakpoint.next\n Breakpoint.next +=1\n \n self.bpbynumber.append(self)\n if(file,line)in self.bplist:\n self.bplist[file,line].append(self)\n else:\n self.bplist[file,line]=[self]\n \n @staticmethod\n def clearBreakpoints():\n Breakpoint.next=1\n Breakpoint.bplist={}\n Breakpoint.bpbynumber=[None]\n \n def deleteMe(self):\n ''\n\n\n\n \n \n index=(self.file,self.line)\n self.bpbynumber[self.number]=None\n self.bplist[index].remove(self)\n if not self.bplist[index]:\n \n del self.bplist[index]\n \n def enable(self):\n ''\n self.enabled=True\n \n def disable(self):\n ''\n self.enabled=False\n \n def bpprint(self,out=None):\n ''\n\n\n\n \n if out is None:\n out=sys.stdout\n print(self.bpformat(),file=out)\n \n def bpformat(self):\n ''\n\n\n\n\n\n \n if self.temporary:\n disp='del '\n else:\n disp='keep '\n if self.enabled:\n disp=disp+'yes '\n else:\n disp=disp+'no '\n ret='%-4dbreakpoint %s at %s:%d'%(self.number,disp,\n self.file,self.line)\n if self.cond:\n ret +='\\n\\tstop only if %s'%(self.cond,)\n if self.ignore:\n ret +='\\n\\tignore next %d hits'%(self.ignore,)\n if self.hits:\n if self.hits >1:\n ss='s'\n else:\n ss=''\n ret +='\\n\\tbreakpoint already hit %d time%s'%(self.hits,ss)\n return ret\n \n def __str__(self):\n ''\n return 'breakpoint %s at %s:%s'%(self.number,self.file,self.line)\n \n \n \n \ndef checkfuncname(b,frame):\n ''\n\n\n\n\n\n \n if not b.funcname:\n \n if b.line !=frame.f_lineno:\n \n \n return False\n return True\n \n \n if frame.f_code.co_name !=b.funcname:\n \n return False\n \n \n if not b.func_first_executable_line:\n \n b.func_first_executable_line=frame.f_lineno\n \n if b.func_first_executable_line !=frame.f_lineno:\n \n return False\n return True\n \n \ndef effective(file,line,frame):\n ''\n\n\n\n\n\n\n\n\n\n\n \n possibles=Breakpoint.bplist[file,line]\n for b in possibles:\n if not b.enabled:\n continue\n if not checkfuncname(b,frame):\n continue\n \n b.hits +=1\n if not b.cond:\n \n if b.ignore >0:\n b.ignore -=1\n continue\n else:\n \n return(b,True)\n else:\n \n \n \n try:\n val=eval(b.cond,frame.f_globals,frame.f_locals)\n if val:\n if b.ignore >0:\n b.ignore -=1\n \n else:\n return(b,True)\n \n \n except:\n \n \n \n return(b,False)\n return(None,None)\n \n \n \n \nclass Tdb(Bdb):\n def user_call(self,frame,args):\n name=frame.f_code.co_name\n if not name:name='???'\n print('+++ call',name,args)\n def user_line(self,frame):\n import linecache\n name=frame.f_code.co_name\n if not name:name='???'\n fn=self.canonic(frame.f_code.co_filename)\n line=linecache.getline(fn,frame.f_lineno,frame.f_globals)\n print('+++',fn,frame.f_lineno,name,':',line.strip())\n def user_return(self,frame,retval):\n print('+++ return',retval)\n def user_exception(self,frame,exc_stuff):\n print('+++ exception',exc_stuff)\n self.set_continue()\n \ndef foo(n):\n print('foo(',n,')')\n x=bar(n *10)\n print('bar returned',x)\n \ndef bar(a):\n print('bar(',a,')')\n return a /2\n \ndef test():\n t=Tdb()\n t.run('import bdb; bdb.foo(10)')\n", ["__main__", "fnmatch", "inspect", "linecache", "os", "reprlib", "sys"]], "binascii": [".py", "''\n\n\n\n\n\n\n\nimport _base64\n\nfrom _binascii import *\n\nclass Error(ValueError):\n def __init__(self,msg=''):\n self._msg=msg\n \n def __str__(self):\n return \" binascii.Error: \"+self._msg\n \n \nclass Done(Exception):\n pass\n \nclass Incomplete(Error):\n pass\n \ndef a2b_uu(s):\n if not s:\n return ''\n \n length=(ord(s[0])-0x20)%64\n \n def quadruplets_gen(s):\n while s:\n try:\n yield ord(s[0]),ord(s[1]),ord(s[2]),ord(s[3])\n except IndexError:\n s +=' '\n yield ord(s[0]),ord(s[1]),ord(s[2]),ord(s[3])\n return\n s=s[4:]\n \n try:\n result=[''.join(\n [chr((A -0x20)<<2 |(((B -0x20)>>4)&0x3)),\n chr(((B -0x20)&0xf)<<4 |(((C -0x20)>>2)&0xf)),\n chr(((C -0x20)&0x3)<<6 |((D -0x20)&0x3f))\n ])for A,B,C,D in quadruplets_gen(s[1:].rstrip())]\n except ValueError:\n raise Error('Illegal char')\n result=''.join(result)\n trailingdata=result[length:]\n if trailingdata.strip('\\x00'):\n raise Error('Trailing garbage')\n result=result[:length]\n if len(result)>2)&0x3F],\n table_b2a_base64[((A <<4)|((B >>4)&0xF))&0x3F],\n table_b2a_base64[((B <<2)|((C >>6)&0x3))&0x3F],\n table_b2a_base64[(C)&0x3F]])\n for A,B,C in a]\n \n final=s[length -final_length:]\n if final_length ==0:\n snippet=''\n elif final_length ==1:\n a=final[0]\n snippet=table_b2a_base64[(a >>2)&0x3F]+\\\n table_b2a_base64[(a <<4)&0x3F]+'=='\n else:\n a=final[0]\n b=final[1]\n snippet=table_b2a_base64[(a >>2)&0x3F]+\\\n table_b2a_base64[((a <<4)|(b >>4)&0xF)&0x3F]+\\\n table_b2a_base64[(b <<2)&0x3F]+'='\n \n result=''.join(result)+snippet\n if newline:\n result +='\\n'\n return bytes(result,__BRYTHON__.charset)\n \ndef a2b_qp(s,header=False):\n inp=0\n odata=[]\n while inp =len(s):\n break\n \n if(s[inp]=='\\n')or(s[inp]=='\\r'):\n if s[inp]!='\\n':\n while inp 0 and data[lf -1]=='\\r'\n \n inp=0\n linelen=0\n odata=[]\n while inp '~'or\n c =='='or\n (header and c =='_')or\n (c =='.'and linelen ==0 and(inp+1 ==len(data)or\n data[inp+1]=='\\n'or\n data[inp+1]=='\\r'))or\n (not istext and(c =='\\r'or c =='\\n'))or\n ((c =='\\t'or c ==' ')and(inp+1 ==len(data)))or\n (c <=' 'and c !='\\r'and c !='\\n'and\n (quotetabs or(not quotetabs and(c !='\\t'and c !=' '))))):\n linelen +=3\n if linelen >=MAXLINESIZE:\n odata.append('=')\n if crlf:odata.append('\\r')\n odata.append('\\n')\n linelen=3\n odata.append('='+two_hex_digits(ord(c)))\n inp +=1\n else:\n if(istext and\n (c =='\\n'or(inp+1 0 and\n (odata[-1]==' 'or odata[-1]=='\\t')):\n ch=ord(odata[-1])\n odata[-1]='='\n odata.append(two_hex_digits(ch))\n \n if crlf:odata.append('\\r')\n odata.append('\\n')\n if c =='\\r':\n inp +=2\n else:\n inp +=1\n else:\n if(inp+1 =MAXLINESIZE):\n odata.append('=')\n if crlf:odata.append('\\r')\n odata.append('\\n')\n linelen=0\n \n linelen +=1\n if header and c ==' ':\n c='_'\n odata.append(c)\n inp +=1\n return ''.join(odata)\n \nhex_numbers='0123456789ABCDEF'\ndef hex(n):\n if n ==0:\n return '0'\n \n if n <0:\n n=-n\n sign='-'\n else:\n sign=''\n arr=[]\n \n def hex_gen(n):\n ''\n while n:\n yield n %0x10\n n=n /0x10\n \n for nibble in hex_gen(n):\n arr=[hex_numbers[nibble]]+arr\n return sign+''.join(arr)\n \ndef two_hex_digits(n):\n return hex_numbers[n /0x10]+hex_numbers[n %0x10]\n \n \ndef strhex_to_int(s):\n i=0\n for c in s:\n i=i *0x10+hex_numbers.index(c)\n return i\n \nhqx_encoding='!\"#$%&\\'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr'\n\nDONE=0x7f\nSKIP=0x7e\nFAIL=0x7d\n\ntable_a2b_hqx=[\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,SKIP,FAIL,FAIL,SKIP,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,0x00,0x01,0x02,0x03,0x04,0x05,0x06,\n\n0x07,0x08,0x09,0x0A,0x0B,0x0C,FAIL,FAIL,\n\n0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,FAIL,\n\n0x14,0x15,DONE,FAIL,FAIL,FAIL,FAIL,FAIL,\n\n0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,\n\n0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,FAIL,\n\n0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,FAIL,\n\n0x2C,0x2D,0x2E,0x2F,FAIL,FAIL,FAIL,FAIL,\n\n0x30,0x31,0x32,0x33,0x34,0x35,0x36,FAIL,\n\n0x37,0x38,0x39,0x3A,0x3B,0x3C,FAIL,FAIL,\n\n0x3D,0x3E,0x3F,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n]\n\ndef a2b_hqx(s):\n result=[]\n \n def quadruples_gen(s):\n t=[]\n for c in s:\n res=table_a2b_hqx[ord(c)]\n if res ==SKIP:\n continue\n elif res ==FAIL:\n raise Error('Illegal character')\n elif res ==DONE:\n yield t\n raise Done\n else:\n t.append(res)\n if len(t)==4:\n yield t\n t=[]\n yield t\n \n done=0\n try:\n for snippet in quadruples_gen(s):\n length=len(snippet)\n if length ==4:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n result.append(chr(((snippet[1]&0x0f)<<4)|(snippet[2]>>2)))\n result.append(chr(((snippet[2]&0x03)<<6)|(snippet[3])))\n elif length ==3:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n result.append(chr(((snippet[1]&0x0f)<<4)|(snippet[2]>>2)))\n elif length ==2:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n except Done:\n done=1\n except Error:\n raise\n return(''.join(result),done)\n \n \n \ndef b2a_hqx(s):\n result=[]\n \n def triples_gen(s):\n while s:\n try:\n yield ord(s[0]),ord(s[1]),ord(s[2])\n except IndexError:\n yield tuple([ord(c)for c in s])\n s=s[3:]\n \n for snippet in triples_gen(s):\n length=len(snippet)\n if length ==3:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)|((snippet[1]&0xf0)>>4)])\n result.append(hqx_encoding[\n (snippet[1]&0x0f)<<2 |((snippet[2]&0xc0)>>6)])\n result.append(hqx_encoding[snippet[2]&0x3f])\n elif length ==2:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)|((snippet[1]&0xf0)>>4)])\n result.append(hqx_encoding[\n (snippet[1]&0x0f)<<2])\n elif length ==1:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)])\n return ''.join(result)\n \ncrctab_hqx=[\n0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,\n0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,\n0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,\n0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,\n0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,\n0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,\n0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,\n0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,\n0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,\n0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,\n0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,\n0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,\n0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,\n0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,\n0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,\n0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,\n0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,\n0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,\n0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,\n0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,\n0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,\n0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,\n0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,\n0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,\n0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,\n0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,\n0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,\n0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,\n0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,\n0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,\n0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,\n0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0,\n]\n\ndef crc_hqx(s,crc):\n for c in s:\n crc=((crc <<8)&0xff00)^crctab_hqx[((crc >>8)&0xff)^ord(c)]\n \n return crc\n \ndef rlecode_hqx(s):\n ''\n\n\n\n \n if not s:\n return ''\n result=[]\n prev=s[0]\n count=1\n \n \n \n \n if s[-1]=='!':\n s=s[1:]+'?'\n else:\n s=s[1:]+'!'\n \n for c in s:\n if c ==prev and count <255:\n count +=1\n else:\n if count ==1:\n if prev !='\\x90':\n result.append(prev)\n else:\n result.extend(['\\x90','\\x00'])\n elif count <4:\n if prev !='\\x90':\n result.extend([prev]*count)\n else:\n result.extend(['\\x90','\\x00']*count)\n else:\n if prev !='\\x90':\n result.extend([prev,'\\x90',chr(count)])\n else:\n result.extend(['\\x90','\\x00','\\x90',chr(count)])\n count=1\n prev=c\n \n return ''.join(result)\n \ndef rledecode_hqx(s):\n s=s.split('\\x90')\n result=[s[0]]\n prev=s[0]\n for snippet in s[1:]:\n count=ord(snippet[0])\n if count >0:\n result.append(prev[-1]*(count -1))\n prev=snippet\n else:\n result.append('\\x90')\n prev='\\x90'\n result.append(snippet[1:])\n \n return ''.join(result)\n \ncrc_32_tab=[\n0x00000000,0x77073096,0xee0e612c,0x990951ba,0x076dc419,\n0x706af48f,0xe963a535,0x9e6495a3,0x0edb8832,0x79dcb8a4,\n0xe0d5e91e,0x97d2d988,0x09b64c2b,0x7eb17cbd,0xe7b82d07,\n0x90bf1d91,0x1db71064,0x6ab020f2,0xf3b97148,0x84be41de,\n0x1adad47d,0x6ddde4eb,0xf4d4b551,0x83d385c7,0x136c9856,\n0x646ba8c0,0xfd62f97a,0x8a65c9ec,0x14015c4f,0x63066cd9,\n0xfa0f3d63,0x8d080df5,0x3b6e20c8,0x4c69105e,0xd56041e4,\n0xa2677172,0x3c03e4d1,0x4b04d447,0xd20d85fd,0xa50ab56b,\n0x35b5a8fa,0x42b2986c,0xdbbbc9d6,0xacbcf940,0x32d86ce3,\n0x45df5c75,0xdcd60dcf,0xabd13d59,0x26d930ac,0x51de003a,\n0xc8d75180,0xbfd06116,0x21b4f4b5,0x56b3c423,0xcfba9599,\n0xb8bda50f,0x2802b89e,0x5f058808,0xc60cd9b2,0xb10be924,\n0x2f6f7c87,0x58684c11,0xc1611dab,0xb6662d3d,0x76dc4190,\n0x01db7106,0x98d220bc,0xefd5102a,0x71b18589,0x06b6b51f,\n0x9fbfe4a5,0xe8b8d433,0x7807c9a2,0x0f00f934,0x9609a88e,\n0xe10e9818,0x7f6a0dbb,0x086d3d2d,0x91646c97,0xe6635c01,\n0x6b6b51f4,0x1c6c6162,0x856530d8,0xf262004e,0x6c0695ed,\n0x1b01a57b,0x8208f4c1,0xf50fc457,0x65b0d9c6,0x12b7e950,\n0x8bbeb8ea,0xfcb9887c,0x62dd1ddf,0x15da2d49,0x8cd37cf3,\n0xfbd44c65,0x4db26158,0x3ab551ce,0xa3bc0074,0xd4bb30e2,\n0x4adfa541,0x3dd895d7,0xa4d1c46d,0xd3d6f4fb,0x4369e96a,\n0x346ed9fc,0xad678846,0xda60b8d0,0x44042d73,0x33031de5,\n0xaa0a4c5f,0xdd0d7cc9,0x5005713c,0x270241aa,0xbe0b1010,\n0xc90c2086,0x5768b525,0x206f85b3,0xb966d409,0xce61e49f,\n0x5edef90e,0x29d9c998,0xb0d09822,0xc7d7a8b4,0x59b33d17,\n0x2eb40d81,0xb7bd5c3b,0xc0ba6cad,0xedb88320,0x9abfb3b6,\n0x03b6e20c,0x74b1d29a,0xead54739,0x9dd277af,0x04db2615,\n0x73dc1683,0xe3630b12,0x94643b84,0x0d6d6a3e,0x7a6a5aa8,\n0xe40ecf0b,0x9309ff9d,0x0a00ae27,0x7d079eb1,0xf00f9344,\n0x8708a3d2,0x1e01f268,0x6906c2fe,0xf762575d,0x806567cb,\n0x196c3671,0x6e6b06e7,0xfed41b76,0x89d32be0,0x10da7a5a,\n0x67dd4acc,0xf9b9df6f,0x8ebeeff9,0x17b7be43,0x60b08ed5,\n0xd6d6a3e8,0xa1d1937e,0x38d8c2c4,0x4fdff252,0xd1bb67f1,\n0xa6bc5767,0x3fb506dd,0x48b2364b,0xd80d2bda,0xaf0a1b4c,\n0x36034af6,0x41047a60,0xdf60efc3,0xa867df55,0x316e8eef,\n0x4669be79,0xcb61b38c,0xbc66831a,0x256fd2a0,0x5268e236,\n0xcc0c7795,0xbb0b4703,0x220216b9,0x5505262f,0xc5ba3bbe,\n0xb2bd0b28,0x2bb45a92,0x5cb36a04,0xc2d7ffa7,0xb5d0cf31,\n0x2cd99e8b,0x5bdeae1d,0x9b64c2b0,0xec63f226,0x756aa39c,\n0x026d930a,0x9c0906a9,0xeb0e363f,0x72076785,0x05005713,\n0x95bf4a82,0xe2b87a14,0x7bb12bae,0x0cb61b38,0x92d28e9b,\n0xe5d5be0d,0x7cdcefb7,0x0bdbdf21,0x86d3d2d4,0xf1d4e242,\n0x68ddb3f8,0x1fda836e,0x81be16cd,0xf6b9265b,0x6fb077e1,\n0x18b74777,0x88085ae6,0xff0f6a70,0x66063bca,0x11010b5c,\n0x8f659eff,0xf862ae69,0x616bffd3,0x166ccf45,0xa00ae278,\n0xd70dd2ee,0x4e048354,0x3903b3c2,0xa7672661,0xd06016f7,\n0x4969474d,0x3e6e77db,0xaed16a4a,0xd9d65adc,0x40df0b66,\n0x37d83bf0,0xa9bcae53,0xdebb9ec5,0x47b2cf7f,0x30b5ffe9,\n0xbdbdf21c,0xcabac28a,0x53b39330,0x24b4a3a6,0xbad03605,\n0xcdd70693,0x54de5729,0x23d967bf,0xb3667a2e,0xc4614ab8,\n0x5d681b02,0x2a6f2b94,0xb40bbe37,0xc30c8ea1,0x5a05df1b,\n0x2d02ef8d\n]\n\ndef crc32(s,crc=0):\n result=0\n crc=~int(crc)&0xffffffff\n \n for c in s:\n crc=crc_32_tab[(crc ^int(ord(c)))&0xff]^(crc >>8)\n \n \n \n result=crc ^0xffffffff\n \n if result >2 **31:\n result=((result+2 **31)%2 **32)-2 **31\n \n return result\n", ["_base64", "_binascii"]], "bisect": [".py", "''\n\n\ndef insort_right(a,x,lo=0,hi=None,*,key=None):\n ''\n\n\n\n\n\n\n\n \n if key is None:\n lo=bisect_right(a,x,lo,hi)\n else:\n lo=bisect_right(a,key(x),lo,hi,key=key)\n a.insert(lo,x)\n \n \ndef bisect_right(a,x,lo=0,hi=None,*,key=None):\n ''\n\n\n\n\n\n\n\n\n\n \n \n if lo <0:\n raise ValueError('lo must be non-negative')\n if hi is None:\n hi=len(a)\n \n \n if key is None:\n while lo =9:\n names=day_name\n else:\n names=day_abbr\n return names[day][:width].center(width)\n \n def formatweekheader(self,width):\n ''\n\n \n return ' '.join(self.formatweekday(i,width)for i in self.iterweekdays())\n \n def formatmonthname(self,theyear,themonth,width,withyear=True):\n ''\n\n \n s=month_name[themonth]\n if withyear:\n s=\"%s %r\"%(s,theyear)\n return s.center(width)\n \n def prmonth(self,theyear,themonth,w=0,l=0):\n ''\n\n \n print(self.formatmonth(theyear,themonth,w,l),end='')\n \n def formatmonth(self,theyear,themonth,w=0,l=0):\n ''\n\n \n w=max(2,w)\n l=max(1,l)\n s=self.formatmonthname(theyear,themonth,7 *(w+1)-1)\n s=s.rstrip()\n s +='\\n'*l\n s +=self.formatweekheader(w).rstrip()\n s +='\\n'*l\n for week in self.monthdays2calendar(theyear,themonth):\n s +=self.formatweek(week,w).rstrip()\n s +='\\n'*l\n return s\n \n def formatyear(self,theyear,w=2,l=1,c=6,m=3):\n ''\n\n \n w=max(2,w)\n l=max(1,l)\n c=max(2,c)\n colwidth=(w+1)*7 -1\n v=[]\n a=v.append\n a(repr(theyear).center(colwidth *m+c *(m -1)).rstrip())\n a('\\n'*l)\n header=self.formatweekheader(w)\n for(i,row)in enumerate(self.yeardays2calendar(theyear,m)):\n \n months=range(m *i+1,min(m *(i+1)+1,13))\n a('\\n'*l)\n names=(self.formatmonthname(theyear,k,colwidth,False)\n for k in months)\n a(formatstring(names,colwidth,c).rstrip())\n a('\\n'*l)\n headers=(header for k in months)\n a(formatstring(headers,colwidth,c).rstrip())\n a('\\n'*l)\n \n height=max(len(cal)for cal in row)\n for j in range(height):\n weeks=[]\n for cal in row:\n if j >=len(cal):\n weeks.append('')\n else:\n weeks.append(self.formatweek(cal[j],w))\n a(formatstring(weeks,colwidth,c).rstrip())\n a('\\n'*l)\n return ''.join(v)\n \n def pryear(self,theyear,w=0,l=0,c=6,m=3):\n ''\n print(self.formatyear(theyear,w,l,c,m),end='')\n \n \nclass HTMLCalendar(Calendar):\n ''\n\n \n \n \n cssclasses=[\"mon\",\"tue\",\"wed\",\"thu\",\"fri\",\"sat\",\"sun\"]\n \n \n cssclasses_weekday_head=cssclasses\n \n \n cssclass_noday=\"noday\"\n \n \n cssclass_month_head=\"month\"\n \n \n cssclass_month=\"month\"\n \n \n cssclass_year_head=\"year\"\n \n \n cssclass_year=\"year\"\n \n def formatday(self,day,weekday):\n ''\n\n \n if day ==0:\n \n return ' '%self.cssclass_noday\n else:\n return '%d'%(self.cssclasses[weekday],day)\n \n def formatweek(self,theweek):\n ''\n\n \n s=''.join(self.formatday(d,wd)for(d,wd)in theweek)\n return '%s'%s\n \n def formatweekday(self,day):\n ''\n\n \n return '%s'%(\n self.cssclasses_weekday_head[day],day_abbr[day])\n \n def formatweekheader(self):\n ''\n\n \n s=''.join(self.formatweekday(i)for i in self.iterweekdays())\n return '%s'%s\n \n def formatmonthname(self,theyear,themonth,withyear=True):\n ''\n\n \n if withyear:\n s='%s %s'%(month_name[themonth],theyear)\n else:\n s='%s'%month_name[themonth]\n return '%s'%(\n self.cssclass_month_head,s)\n \n def formatmonth(self,theyear,themonth,withyear=True):\n ''\n\n \n v=[]\n a=v.append\n a(''%(\n self.cssclass_month))\n a('\\n')\n a(self.formatmonthname(theyear,themonth,withyear=withyear))\n a('\\n')\n a(self.formatweekheader())\n a('\\n')\n for week in self.monthdays2calendar(theyear,themonth):\n a(self.formatweek(week))\n a('\\n')\n a('
')\n a('\\n')\n return ''.join(v)\n \n def formatyear(self,theyear,width=3):\n ''\n\n \n v=[]\n a=v.append\n width=max(width,1)\n a(''%\n self.cssclass_year)\n a('\\n')\n a(''%(\n width,self.cssclass_year_head,theyear))\n for i in range(JANUARY,JANUARY+12,width):\n \n months=range(i,min(i+width,13))\n a('')\n for m in months:\n a('')\n a('')\n a('
%s
')\n a(self.formatmonth(theyear,m,withyear=False))\n a('
')\n return ''.join(v)\n \n def formatyearpage(self,theyear,width=3,css='calendar.css',encoding=None):\n ''\n\n \n if encoding is None:\n encoding=sys.getdefaultencoding()\n v=[]\n a=v.append\n a('\\n'%encoding)\n a('\\n')\n a('\\n')\n a('\\n')\n a('\\n'%encoding)\n if css is not None:\n a('\\n'%css)\n a('Calendar for %d\\n'%theyear)\n a('\\n')\n a('\\n')\n a(self.formatyear(theyear,width))\n a('\\n')\n a('\\n')\n return ''.join(v).encode(encoding,\"xmlcharrefreplace\")\n \n \nclass different_locale:\n def __init__(self,locale):\n self.locale=locale\n self.oldlocale=None\n \n def __enter__(self):\n self.oldlocale=_locale.setlocale(_locale.LC_TIME,None)\n _locale.setlocale(_locale.LC_TIME,self.locale)\n \n def __exit__(self,*args):\n _locale.setlocale(_locale.LC_TIME,self.oldlocale)\n \n \ndef _get_default_locale():\n locale=_locale.setlocale(_locale.LC_TIME,None)\n if locale ==\"C\":\n with different_locale(\"\"):\n \n \n locale=_locale.setlocale(_locale.LC_TIME,None)\n return locale\n \n \nclass LocaleTextCalendar(TextCalendar):\n ''\n\n\n \n \n def __init__(self,firstweekday=0,locale=None):\n TextCalendar.__init__(self,firstweekday)\n if locale is None:\n locale=_get_default_locale()\n self.locale=locale\n \n def formatweekday(self,day,width):\n with different_locale(self.locale):\n return super().formatweekday(day,width)\n \n def formatmonthname(self,theyear,themonth,width,withyear=True):\n with different_locale(self.locale):\n return super().formatmonthname(theyear,themonth,width,withyear)\n \n \nclass LocaleHTMLCalendar(HTMLCalendar):\n ''\n\n\n \n def __init__(self,firstweekday=0,locale=None):\n HTMLCalendar.__init__(self,firstweekday)\n if locale is None:\n locale=_get_default_locale()\n self.locale=locale\n \n def formatweekday(self,day):\n with different_locale(self.locale):\n return super().formatweekday(day)\n \n def formatmonthname(self,theyear,themonth,withyear=True):\n with different_locale(self.locale):\n return super().formatmonthname(theyear,themonth,withyear)\n \n \nc=TextCalendar()\n\nfirstweekday=c.getfirstweekday\n\ndef setfirstweekday(firstweekday):\n if not MONDAY <=firstweekday <=SUNDAY:\n raise IllegalWeekdayError(firstweekday)\n c.firstweekday=firstweekday\n \nmonthcalendar=c.monthdayscalendar\nprweek=c.prweek\nweek=c.formatweek\nweekheader=c.formatweekheader\nprmonth=c.prmonth\nmonth=c.formatmonth\ncalendar=c.formatyear\nprcal=c.pryear\n\n\n\n_colwidth=7 *3 -1\n_spacing=6\n\n\ndef format(cols,colwidth=_colwidth,spacing=_spacing):\n ''\n print(formatstring(cols,colwidth,spacing))\n \n \ndef formatstring(cols,colwidth=_colwidth,spacing=_spacing):\n ''\n spacing *=' '\n return spacing.join(c.center(colwidth)for c in cols)\n \n \nEPOCH=1970\n_EPOCH_ORD=datetime.date(EPOCH,1,1).toordinal()\n\n\ndef timegm(tuple):\n ''\n year,month,day,hour,minute,second=tuple[:6]\n days=datetime.date(year,month,1).toordinal()-_EPOCH_ORD+day -1\n hours=days *24+hour\n minutes=hours *60+minute\n seconds=minutes *60+second\n return seconds\n \n \ndef main(args=None):\n import argparse\n parser=argparse.ArgumentParser()\n textgroup=parser.add_argument_group('text only arguments')\n htmlgroup=parser.add_argument_group('html only arguments')\n textgroup.add_argument(\n \"-w\",\"--width\",\n type=int,default=2,\n help=\"width of date column (default 2)\"\n )\n textgroup.add_argument(\n \"-l\",\"--lines\",\n type=int,default=1,\n help=\"number of lines for each week (default 1)\"\n )\n textgroup.add_argument(\n \"-s\",\"--spacing\",\n type=int,default=6,\n help=\"spacing between months (default 6)\"\n )\n textgroup.add_argument(\n \"-m\",\"--months\",\n type=int,default=3,\n help=\"months per row (default 3)\"\n )\n htmlgroup.add_argument(\n \"-c\",\"--css\",\n default=\"calendar.css\",\n help=\"CSS to use for page\"\n )\n parser.add_argument(\n \"-L\",\"--locale\",\n default=None,\n help=\"locale to use for month and weekday names\"\n )\n parser.add_argument(\n \"-e\",\"--encoding\",\n default=None,\n help=\"encoding to use for output\"\n )\n parser.add_argument(\n \"-t\",\"--type\",\n default=\"text\",\n choices=(\"text\",\"html\"),\n help=\"output type (text or html)\"\n )\n parser.add_argument(\n \"-f\",\"--first-weekday\",\n type=int,default=0,\n help=\"weekday (0 is Monday, 6 is Sunday) to start each week (default 0)\"\n )\n parser.add_argument(\n \"year\",\n nargs='?',type=int,\n help=\"year number\"\n )\n parser.add_argument(\n \"month\",\n nargs='?',type=int,\n help=\"month number (1-12, text only)\"\n )\n \n options=parser.parse_args(args)\n \n if options.locale and not options.encoding:\n parser.error(\"if --locale is specified --encoding is required\")\n sys.exit(1)\n \n locale=options.locale,options.encoding\n \n if options.type ==\"html\":\n if options.month:\n parser.error(\"incorrect number of arguments\")\n sys.exit(1)\n if options.locale:\n cal=LocaleHTMLCalendar(locale=locale)\n else:\n cal=HTMLCalendar()\n cal.setfirstweekday(options.first_weekday)\n encoding=options.encoding\n if encoding is None:\n encoding=sys.getdefaultencoding()\n optdict=dict(encoding=encoding,css=options.css)\n write=sys.stdout.buffer.write\n if options.year is None:\n write(cal.formatyearpage(datetime.date.today().year,**optdict))\n else:\n write(cal.formatyearpage(options.year,**optdict))\n else:\n if options.locale:\n cal=LocaleTextCalendar(locale=locale)\n else:\n cal=TextCalendar()\n cal.setfirstweekday(options.first_weekday)\n optdict=dict(w=options.width,l=options.lines)\n if options.month is None:\n optdict[\"c\"]=options.spacing\n optdict[\"m\"]=options.months\n if options.year is None:\n result=cal.formatyear(datetime.date.today().year,**optdict)\n elif options.month is None:\n result=cal.formatyear(options.year,**optdict)\n else:\n result=cal.formatmonth(options.year,options.month,**optdict)\n write=sys.stdout.write\n if options.encoding:\n result=result.encode(options.encoding)\n write=sys.stdout.buffer.write\n write(result)\n \n \nif __name__ ==\"__main__\":\n main()\n", ["argparse", "datetime", "enum", "itertools", "locale", "sys", "warnings"]], "cmath": [".py", "\n\n\n\n\n\n\n\n\n\nimport math\nimport sys\n\ndef _takes_complex(func):\n def decorated(x):\n if isinstance(x,complex):\n return func(x)\n elif type(x)in[int,float]:\n return func(complex(x))\n elif hasattr(x,'__complex__'):\n c=x.__complex__()\n if not isinstance(c,complex):\n raise TypeError(\"A complex number is required\")\n else:\n return func(c)\n elif hasattr(x,'__float__'):\n try:\n c=complex(x.__float__(),0)\n except:\n raise TypeError(\"A complex number is required\")\n return func(c)\n elif hasattr(x,'__index__'):\n try:\n c=complex(x.__index__(),0)\n except:\n raise TypeError(\"A complex number is required\")\n return func(c)\n else:\n raise TypeError(\"A complex number is required\")\n if hasattr(func,'__doc__'):\n decorated.__doc__=func.__doc__\n if hasattr(func,'__name__'):\n decorated.__name__=func.__name__\n return decorated\n \n@_takes_complex\ndef isfinite(x):\n return math.isfinite(x.imag)and math.isfinite(x.real)\n \n@_takes_complex\ndef phase(x):\n ''\n return math.atan2(x.imag,x.real)\n \n@_takes_complex\ndef polar(x):\n ''\n\n\n\n\n \n phi=math.atan2(x.imag,x.real)\n if math.isnan(x.imag):\n if math.isinf(x.real):\n return abs(x.real),nan\n return nan,nan\n elif math.isinf(x.imag):\n r=inf\n elif math.isinf(x.real):\n r=inf\n else:\n r=math.sqrt(x.real **2+x.imag **2)\n if math.isinf(r):\n raise OverflowError(\"math range error\")\n return r,phi\n \ndef rect(r,phi):\n ''\n\n \n if math.isnan(r):\n if not math.isnan(phi)and not phi:\n return complex(nan,0)\n return complex(nan,nan)\n elif math.isnan(phi):\n if not r:\n return complex(0,0)\n elif math.isinf(r):\n return complex(inf,nan)\n return complex(nan,nan)\n if math.isinf(r)or math.isinf(phi):\n \n \n if math.isinf(phi)and r !=.0 and not math.isnan(r):\n raise ValueError(\"math domain error\")\n \n \n \n \n if -inf 0:\n _real=math.copysign(inf,math.cos(phi))\n _imag=math.copysign(inf,math.sin(phi))\n else:\n _real=-math.copysign(inf,math.cos(phi));\n _imag=-math.copysign(inf,math.sin(phi));\n return complex(_real,_imag)\n return _SPECIAL_VALUE(complex(r,phi),_rect_special_values)\n \n else:\n if phi ==.0:\n \n \n \n return complex(r,phi *r)\n else:\n return complex(r *math.cos(phi),r *math.sin(phi))\n \n@_takes_complex\ndef sqrt(x):\n ''\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n s,d,ax,ay=.0,.0,math.fabs(x.real),math.fabs(x.imag)\n \n ret=_SPECIAL_VALUE(x,_sqrt_special_values)\n if ret is not None:\n return ret\n \n if math.isinf(x.imag):\n return complex(inf,x.imag)\n \n if x.real ==.0 and x.imag ==.0:\n _real=.0\n _imag=x.imag\n return complex(_real,_imag)\n \n if ay ==0:\n s=math.sqrt(ax)\n d=0\n elif ax 0. or ay >0.):\n \n AX=math.ldexp(ax,_CM_SCALE_UP)\n AY=math.ldexp(ay,_CM_SCALE_UP)\n S=math.sqrt((AX+math.hypot(AX,AY))/2.0)\n D=AY /(2 *S)\n s=math.ldexp(S,_CM_SCALE_DOWN)\n d=math.ldexp(D,_CM_SCALE_DOWN)\n else:\n ax /=8.0 ;\n s=2.0 *math.sqrt(ax+math.hypot(ax,ay /8.0));\n d=ay /(2.0 *s)\n \n if x.real >=.0:\n _real=s ;\n _imag=math.copysign(d,x.imag)\n else:\n _real=d ;\n _imag=math.copysign(s,x.imag)\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef acos(x):\n ''\n\n\n\n\n \n \n ret=_SPECIAL_VALUE(x,_acos_special_values)\n if ret is not None:\n if isinstance(ret,Exception):\n raise ret\n return ret\n \n if math.fabs(x.real)>_CM_LARGE_DOUBLE or math.fabs(x.imag)>_CM_LARGE_DOUBLE:\n \n _real=math.atan2(math.fabs(x.imag),x.real)\n \n \n \n if x.real <0:\n _imag=-math.copysign(math.log(math.hypot(x.real /2.,x.imag /2.))+_M_LN2 *2.,x.imag);\n else:\n _imag=math.copysign(math.log(math.hypot(x.real /2.,x.imag /2.))+_M_LN2 *2.,-x.imag);\n elif math.isnan(x.real):\n return complex(nan,nan)\n elif math.isnan(x.imag):\n if x.real ==0:\n return complex(pi /2,nan)\n return complex(nan,nan)\n else:\n s1=complex(float(1 -x.real),-x.imag)\n s1=sqrt(s1)\n s2=complex(1.0+x.real,x.imag)\n s2=sqrt(s2)\n _real=2.0 *math.atan2(s1.real,s2.real)\n _imag=math.asinh(s2.real *s1.imag -s2.imag *s1.real)\n if not x.imag:\n if x.real >1:\n _real=0\n elif x.real <-1:\n _real=math.pi\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef acosh(x):\n ''\n\n\n\n \n ret=_SPECIAL_VALUE(x,_acosh_special_values)\n if ret is not None:\n return ret\n \n if math.fabs(x.real)>_CM_LARGE_DOUBLE or math.fabs(x.imag)>_CM_LARGE_DOUBLE:\n \n _real=math.log(math.hypot(x.real /2.0,x.imag /2.0))+_M_LN2 *2.0\n _imag=math.atan2(x.imag,x.real);\n else:\n s1=sqrt(complex(x.real -1.0,x.imag))\n s2=sqrt(complex(x.real+1.0,x.imag))\n _real=math.asinh(s1.real *s2.real+s1.imag *s2.imag)\n _imag=2. *math.atan2(s1.imag,s2.real)\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef asin(x):\n ''\n\n\n\n \n \n s=complex(-x.imag,x.real)\n s=asinh(s)\n return complex(s.imag,-s.real)\n \n@_takes_complex\ndef asinh(x):\n ''\n\n\n\n\n \n ret=_SPECIAL_VALUE(x,_asinh_special_values)\n if ret is not None:\n return ret\n \n if math.fabs(x.real)>_CM_LARGE_DOUBLE or math.fabs(x.imag)>_CM_LARGE_DOUBLE:\n if x.imag >=.0:\n _real=math.copysign(math.log(math.hypot(x.real /2.,x.imag /2.))+_M_LN2 *2.,x.real)\n else:\n _real=-math.copysign(math.log(math.hypot(x.real /2.,x.imag /2.))+_M_LN2 *2.,-x.real)\n _imag=math.atan2(x.imag,math.fabs(x.real))\n else:\n s1=sqrt(complex(1.0+x.imag,-x.real))\n s2=sqrt(complex(1.0 -x.imag,x.real))\n _real=math.asinh(s1.real *s2.imag -s2.real *s1.imag)\n _imag=math.atan2(x.imag,s1.real *s2.real -s1.imag *s2.imag)\n return complex(_real,_imag)\n \n@_takes_complex\ndef atan(x):\n ''\n\n\n\n\n \n ret=_SPECIAL_VALUE(x,_atan_special_values)\n if ret is not None:\n return ret\n \n if isinf(x):\n return complex(math.copysign(1,x.real)*pi /2,\n math.copysign(0,x.imag))\n s=atanh(complex(-x.imag,x.real))\n return complex(s.imag,-s.real)\n \n@_takes_complex\ndef atanh(x):\n ''\n\n\n\n\n \n \n ret=_SPECIAL_VALUE(x,_atanh_special_values)\n if ret is not None:\n return ret\n \n if isinf(x):\n return complex(math.copysign(0,x.real),\n math.copysign(1,x.imag)*pi /2)\n \n \n if x.real <.0:\n return -(atanh(-x))\n \n ay=math.fabs(x.imag)\n \n if x.real >_CM_SQRT_LARGE_DOUBLE or ay >_CM_SQRT_LARGE_DOUBLE:\n \n \n \n \n \n h=math.hypot(x.real /2.,x.imag /2.)\n _real=x.real /4. /h /h\n \n \n \n \n \n \n _imag=-math.copysign(math.pi /2.,-x.imag)\n \n elif x.real ==1.0 and ay <_CM_SQRT_DBL_MIN:\n \n \n if(ay ==.0):\n raise ValueError(\"math domain error\")\n else:\n _real=-math.log(math.sqrt(ay)/math.sqrt(math.hypot(ay,2.)))\n _imag=math.copysign(math.atan2(2.0,-ay)/2,x.imag)\n \n else:\n \n _real=math.log1p(4. *x.real /((1 -x.real)*(1 -x.real)+ay *ay))/4.\n _imag=-math.atan2(-2. *x.imag,(1 -x.real)*(1+x.real)-ay *ay)/2.\n errno=0\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef cos(x):\n ''\n return cosh(complex(-x.imag,x.real))\n \n@_takes_complex\ndef cosh(x):\n ''\n \n ret=_SPECIAL_VALUE(x,_cosh_special_values)\n if ret is not None:\n if isinstance(ret,Exception):\n raise ret\n return ret\n \n if not math.isinf(x.real)and math.fabs(x.real)>_CM_LOG_LARGE_DOUBLE:\n \n \n x_minus_one=x.real -math.copysign(1.0,x.real)\n _real=cos(x.imag)*math.cosh(x_minus_one)*math.e\n _imag=sin(x.imag)*math.sinh(x_minus_one)*math.e\n elif math.isinf(x.real)and x.imag ==0:\n if x.real >0:\n return x\n else:\n return complex(inf,-x.imag)\n elif math.isinf(x.imag):\n raise ValueError(\"math domain error\")\n else:\n _real=math.cos(x.imag)*math.cosh(x.real)\n _imag=math.sin(x.imag)*math.sinh(x.real)\n \n ret=complex(_real,_imag)\n return ret\n \n@_takes_complex\ndef exp(x):\n ''\n if math.isinf(x.real)or math.isinf(x.imag):\n \n if math.isinf(x.imag)and(-inf 0):\n raise ValueError(\"math domain error\")\n \n if math.isinf(x.real)and -inf 0:\n _real=math.copysign(inf,math.cos(x.imag))\n _imag=math.copysign(inf,math.sin(x.imag))\n else:\n _real=math.copysign(.0,math.cos(x.imag))\n _imag=math.copysign(.0,math.sin(x.imag))\n return complex(_real,_imag)\n \n return _SPECIAL_VALUE(x,_exp_special_values)\n \n if math.isnan(x.real)and x.imag ==0:\n return x\n \n if x.real >_CM_LOG_LARGE_DOUBLE:\n l=math.exp(x.real -1.);\n _real=l *math.cos(x.imag)*math.e\n _imag=l *math.sin(x.imag)*math.e\n else:\n l=math.exp(x.real);\n _real=l *math.cos(x.imag)\n _imag=l *math.sin(x.imag)\n \n if math.isinf(_real)or math.isinf(_imag):\n raise OverflowError()\n \n return complex(_real,_imag)\n \ndef isclose(x,y,*,rel_tol=1e-09,abs_tol=0.0):\n try:\n complex(x)\n except ValueError:\n raise TypeError(f\"must be a number, not {x.__class__.__name__}\")\n try:\n complex(y)\n except ValueError:\n raise TypeError(f\"must be a number, not {y.__class__.__name__}\")\n rel_tol=float(rel_tol)\n abs_tol=float(abs_tol)\n if rel_tol <0.0 or abs_tol <0.0:\n raise ValueError('tolerances must be non-negative')\n if x is inf or x is _NINF or y is inf or y is _NINF:\n return y is x\n if x is nan or y is nan:\n return False\n return abs(x -y)<=max(rel_tol *float(max(abs(x),abs(y))),abs_tol)\n \n@_takes_complex\ndef isinf(x):\n ''\n return math.isinf(x.real)or math.isinf(x.imag)\n \n@_takes_complex\ndef isnan(x):\n ''\n return math.isnan(x.real)or math.isnan(x.imag)\n \n \n@_takes_complex\ndef _to_complex(x):\n return x\n \ndef log(x,base=None):\n ''\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n x=_to_complex(x)\n \n \n \n \n \n \n denom=1 if base is None else log(base)\n ''\n\n\n\n \n \n ret=_SPECIAL_VALUE(x,_log_special_values)\n if ret is not None:\n return ret\n \n if math.isnan(x.real):\n return complex(inf if math.isinf(x.imag)else nan,nan)\n elif math.isnan(x.imag):\n return complex(inf if math.isinf(x.real)else nan,nan)\n \n ax=math.fabs(x.real)\n ay=math.fabs(x.imag)\n \n if ax >_CM_LARGE_DOUBLE or ay >_CM_LARGE_DOUBLE:\n _real=math.log(math.hypot(ax /2.0,ay /2.0))+_M_LN2\n elif ax .0 or ay >.0:\n \n _real=math.log(math.hypot(math.ldexp(ax,sys.float_info.mant_dig),math.ldexp(ay,sys.float_info.mant_dig)))-sys.float_info.mant_dig *_M_LN2\n else:\n \n raise ValueError(\"math domain error\")\n _real=-inf\n _imag=math.atan2(x.imag,x.real)\n else:\n h=math.hypot(ax,ay)\n _real=math.log(h)/denom\n if not ay:\n if type(_real)==complex:\n return _real\n if x.real <0:\n return complex(_real,math.copysign(math.pi,x.imag))\n return complex(_real,x.imag)\n _imag=math.atan2(x.imag,x.real)\n return complex(_real,_imag)\n \n@_takes_complex\ndef log10(x):\n ''\n\n\n\n \n ret=log(x)\n _real=ret.real /_M_LN10\n _imag=ret.imag /_M_LN10\n return complex(_real,_imag)\n \n@_takes_complex\ndef sin(x):\n ''\n \n s=complex(-x.imag,x.real)\n s=sinh(s)\n return complex(s.imag,-s.real)\n \n@_takes_complex\ndef sinh(x):\n ''\n \n ret=_SPECIAL_VALUE(x,_sinh_special_values)\n if ret is not None:\n if isinstance(ret,Exception):\n raise ret\n return ret\n \n if math.isinf(x.real)or math.isinf(x.imag):\n \n \n if math.isinf(x.imag)and not math.isnan(x.real):\n raise ValueError(\"math domain error\")\n \n if math.isinf(x.real)and -inf 0:\n _real=math.copysign(inf,math.cos(x.imag))\n _imag=math.copysign(inf,math.sin(x.imag))\n else:\n _real=-math.copysign(inf,math.cos(x.imag))\n _imag=math.copysign(inf,math.sin(x.imag))\n return complex(_real,_imag)\n \n return _SPECIAL_VALUE(x,_sinh_special_values)\n \n if math.fabs(x.real)>_CM_LOG_LARGE_DOUBLE:\n x_minus_one=x.real -math.copysign(1.0,x.real)\n z=complex(x_minus_one,x.imag)\n _real=math.cos(z.imag)*math.sinh(z.real)*math.e\n _imag=math.sin(z.imag)*math.cosh(z.real)*math.e\n else:\n _real=math.cos(x.imag)*math.sinh(x.real)\n _imag=math.sin(x.imag)*math.cosh(x.real)\n \n if math.isinf(_real)or math.isinf(_imag):\n raise OverflowError()\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef tan(x):\n ''\n if math.isnan(x.real):\n if math.isinf(x.imag):\n return complex(0,math.copysign(1,x.imag))\n return complex(nan,nan)\n elif math.isnan(x.imag):\n if not x.real:\n return complex(math.copysign(0,x.real),nan)\n return complex(nan,nan)\n s=tanh(complex(-x.imag,x.real))\n return complex(s.imag,-s.real)\n \n@_takes_complex\ndef tanh(x):\n ''\n ''\n\n\n \n \n \n \n \n \n \n \n \n \n if math.isnan(x.real):\n if x.imag ==0:\n return complex(nan,math.copysign(0,x.imag))\n return complex(nan,nan)\n elif math.isnan(x.imag):\n if math.isinf(x.real):\n return complex(math.copysign(1,x.real),0)\n return complex(nan,nan)\n \n if isinf(x):\n if math.isinf(x.imag)and -inf 0:\n _real=1.0\n _imag=math.copysign(.0,2.0 *math.sin(x.imag)*math.cos(x.imag))\n else:\n _real=-1.0\n _imag=math.copysign(.0,2. *math.sin(x.imag)*math.cos(x.imag))\n return complex(_real,_imag)\n return _SPECIAL_VALUE(x,_tanh_special_values)\n \n \n if math.fabs(x.real)>_CM_LOG_LARGE_DOUBLE:\n _real=math.copysign(1.,x.real)\n _imag=4. *math.sin(x.imag)*math.cos(x.imag)*math.exp(-2. *math.fabs(x.real))\n else:\n tx=math.tanh(x.real)\n ty=math.tan(x.imag)\n cx=1.0 /math.cosh(x.real)\n txty=tx *ty\n denom=1.+txty *txty\n _real=tx *(1.+ty *ty)/denom\n _imag=((ty /denom)*cx)*cx\n return complex(_real,_imag)\n \n \nFunctionType=type(_takes_complex)\nlocs=locals()\nkeys=list(locs.keys())\nfor f in keys:\n if type(locs[f])is FunctionType and not f.startswith(\"_\"):\n locals()[f]=type(abs)(locals()[f])\n \npi=math.pi\ne=math.e\ntau=math.tau\n\n_CM_LARGE_DOUBLE=sys.float_info.max /4\n_CM_SQRT_LARGE_DOUBLE=math.sqrt(_CM_LARGE_DOUBLE)\n_CM_LOG_LARGE_DOUBLE=math.log(_CM_LARGE_DOUBLE)\n_CM_SQRT_DBL_MIN=math.sqrt(sys.float_info.min)\n_M_LN2=0.6931471805599453094\n_M_LN10=2.302585092994045684\n\nif sys.float_info.radix ==2:\n _CM_SCALE_UP=int((2 *(sys.float_info.mant_dig /2)+1))\nelif sys.float_info.radix ==16:\n _CM_SCALE_UP=int((4 *sys.float_info.mant_dig+1))\nelse:\n raise(\"cmath implementation expects the float base to be either 2 or 16, got \"+str(sys.float_info.radix)+\" instead.\")\n_CM_SCALE_DOWN=int((-(_CM_SCALE_UP+1)/2))\n\ninf=float('inf')\ninfj=complex(0.0,inf)\n_NINF=float('-inf')\nnan=float('nan')\nnanj=complex(0.0,float('nan'))\n\n_P14=0.25 *pi\n_P12=0.5 *pi\n_P34=0.75 *pi\n_U=-9.5426319407711027e33\n\n\n_ST_NINF=0\n_ST_NEG=1\n_ST_NZERO=2\n_ST_PZERO=3\n_ST_POS=4\n_ST_PINF=5\n_ST_NAN=6\n\n\ndef _SPECIAL_VALUE(z,table):\n if not math.isfinite(z.real)or not math.isfinite(z.imag):\n return table[_special_type(z.real)][_special_type(z.imag)]\n else:\n return None\n \ndef _special_type(x):\n if -inf ):\"\n misc_header=\"Miscellaneous help topics:\"\n undoc_header=\"Undocumented commands:\"\n nohelp=\"*** No help on %s\"\n use_rawinput=1\n \n def __init__(self,completekey='tab',stdin=None,stdout=None):\n ''\n\n\n\n\n\n\n\n\n \n if stdin is not None:\n self.stdin=stdin\n else:\n self.stdin=sys.stdin\n if stdout is not None:\n self.stdout=stdout\n else:\n self.stdout=sys.stdout\n self.cmdqueue=[]\n self.completekey=completekey\n \n def cmdloop(self,intro=None):\n ''\n\n\n\n \n \n self.preloop()\n if self.use_rawinput and self.completekey:\n try:\n import readline\n self.old_completer=readline.get_completer()\n readline.set_completer(self.complete)\n if readline.backend ==\"editline\":\n if self.completekey =='tab':\n \n command_string=\"bind ^I rl_complete\"\n else:\n command_string=f\"bind {self.completekey} rl_complete\"\n else:\n command_string=f\"{self.completekey}: complete\"\n readline.parse_and_bind(command_string)\n except ImportError:\n pass\n try:\n if intro is not None:\n self.intro=intro\n if self.intro:\n self.stdout.write(str(self.intro)+\"\\n\")\n stop=None\n while not stop:\n if self.cmdqueue:\n line=self.cmdqueue.pop(0)\n else:\n if self.use_rawinput:\n try:\n line=input(self.prompt)\n except EOFError:\n line='EOF'\n else:\n self.stdout.write(self.prompt)\n self.stdout.flush()\n line=self.stdin.readline()\n if not len(line):\n line='EOF'\n else:\n line=line.rstrip('\\r\\n')\n line=self.precmd(line)\n stop=self.onecmd(line)\n stop=self.postcmd(stop,line)\n self.postloop()\n finally:\n if self.use_rawinput and self.completekey:\n try:\n import readline\n readline.set_completer(self.old_completer)\n except ImportError:\n pass\n \n \n def precmd(self,line):\n ''\n\n\n \n return line\n \n def postcmd(self,stop,line):\n ''\n return stop\n \n def preloop(self):\n ''\n pass\n \n def postloop(self):\n ''\n\n\n \n pass\n \n def parseline(self,line):\n ''\n\n\n \n line=line.strip()\n if not line:\n return None,None,line\n elif line[0]=='?':\n line='help '+line[1:]\n elif line[0]=='!':\n if hasattr(self,'do_shell'):\n line='shell '+line[1:]\n else:\n return None,None,line\n i,n=0,len(line)\n while i 0:\n cmd,args,foo=self.parseline(line)\n if cmd =='':\n compfunc=self.completedefault\n else:\n try:\n compfunc=getattr(self,'complete_'+cmd)\n except AttributeError:\n compfunc=self.completedefault\n else:\n compfunc=self.completenames\n self.completion_matches=compfunc(text,line,begidx,endidx)\n try:\n return self.completion_matches[state]\n except IndexError:\n return None\n \n def get_names(self):\n \n \n return dir(self.__class__)\n \n def complete_help(self,*args):\n commands=set(self.completenames(*args))\n topics=set(a[5:]for a in self.get_names()\n if a.startswith('help_'+args[0]))\n return list(commands |topics)\n \n def do_help(self,arg):\n ''\n if arg:\n \n try:\n func=getattr(self,'help_'+arg)\n except AttributeError:\n try:\n doc=getattr(self,'do_'+arg).__doc__\n doc=inspect.cleandoc(doc)\n if doc:\n self.stdout.write(\"%s\\n\"%str(doc))\n return\n except AttributeError:\n pass\n self.stdout.write(\"%s\\n\"%str(self.nohelp %(arg,)))\n return\n func()\n else:\n names=self.get_names()\n cmds_doc=[]\n cmds_undoc=[]\n topics=set()\n for name in names:\n if name[:5]=='help_':\n topics.add(name[5:])\n names.sort()\n \n prevname=''\n for name in names:\n if name[:3]=='do_':\n if name ==prevname:\n continue\n prevname=name\n cmd=name[3:]\n if cmd in topics:\n cmds_doc.append(cmd)\n topics.remove(cmd)\n elif getattr(self,name).__doc__:\n cmds_doc.append(cmd)\n else:\n cmds_undoc.append(cmd)\n self.stdout.write(\"%s\\n\"%str(self.doc_leader))\n self.print_topics(self.doc_header,cmds_doc,15,80)\n self.print_topics(self.misc_header,sorted(topics),15,80)\n self.print_topics(self.undoc_header,cmds_undoc,15,80)\n \n def print_topics(self,header,cmds,cmdlen,maxcol):\n if cmds:\n self.stdout.write(\"%s\\n\"%str(header))\n if self.ruler:\n self.stdout.write(\"%s\\n\"%str(self.ruler *len(header)))\n self.columnize(cmds,maxcol -1)\n self.stdout.write(\"\\n\")\n \n def columnize(self,list,displaywidth=80):\n ''\n\n\n\n \n if not list:\n self.stdout.write(\"\\n\")\n return\n \n nonstrings=[i for i in range(len(list))\n if not isinstance(list[i],str)]\n if nonstrings:\n raise TypeError(\"list[i] not a string for i in %s\"\n %\", \".join(map(str,nonstrings)))\n size=len(list)\n if size ==1:\n self.stdout.write('%s\\n'%str(list[0]))\n return\n \n for nrows in range(1,len(list)):\n ncols=(size+nrows -1)//nrows\n colwidths=[]\n totwidth=-2\n for col in range(ncols):\n colwidth=0\n for row in range(nrows):\n i=row+nrows *col\n if i >=size:\n break\n x=list[i]\n colwidth=max(colwidth,len(x))\n colwidths.append(colwidth)\n totwidth +=colwidth+2\n if totwidth >displaywidth:\n break\n if totwidth <=displaywidth:\n break\n else:\n nrows=len(list)\n ncols=1\n colwidths=[0]\n for row in range(nrows):\n texts=[]\n for col in range(ncols):\n i=row+nrows *col\n if i >=size:\n x=\"\"\n else:\n x=list[i]\n texts.append(x)\n while texts and not texts[-1]:\n del texts[-1]\n for col in range(len(texts)):\n texts[col]=texts[col].ljust(colwidths[col])\n self.stdout.write(\"%s\\n\"%str(\" \".join(texts)))\n", ["inspect", "readline", "string", "sys"]], "code": [".py", "''\n\n\n\n\n\n\nimport builtins\nimport sys\nimport traceback\nfrom codeop import CommandCompiler,compile_command\n\n__all__=[\"InteractiveInterpreter\",\"InteractiveConsole\",\"interact\",\n\"compile_command\"]\n\nclass InteractiveInterpreter:\n ''\n\n\n\n\n\n \n \n def __init__(self,locals=None):\n ''\n\n\n\n\n\n\n \n if locals is None:\n locals={\"__name__\":\"__console__\",\"__doc__\":None}\n self.locals=locals\n self.compile=CommandCompiler()\n \n def runsource(self,source,filename=\"\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n code=self.compile(source,filename,symbol)\n except(OverflowError,SyntaxError,ValueError):\n \n self.showsyntaxerror(filename)\n return False\n \n if code is None:\n \n return True\n \n \n self.runcode(code)\n return False\n \n def runcode(self,code):\n ''\n\n\n\n\n\n\n\n\n\n \n try:\n exec(code,self.locals)\n except SystemExit:\n raise\n except:\n self.showtraceback()\n \n def showsyntaxerror(self,filename=None,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.pop('colorize',False)\n type,value,tb=sys.exc_info()\n sys.last_exc=value\n sys.last_type=type\n sys.last_value=value\n sys.last_traceback=tb\n if filename and type is SyntaxError:\n \n try:\n msg,(dummy_filename,lineno,offset,line)=value.args\n except ValueError:\n \n pass\n else:\n \n value=SyntaxError(msg,(filename,lineno,offset,line))\n sys.last_exc=sys.last_value=value\n if sys.excepthook is sys.__excepthook__:\n lines=traceback.format_exception_only(type,value,colorize=colorize)\n self.write(''.join(lines))\n else:\n \n \n sys.excepthook(type,value,tb)\n \n def showtraceback(self,**kwargs):\n ''\n\n\n\n\n\n \n colorize=kwargs.pop('colorize',False)\n sys.last_type,sys.last_value,last_tb=ei=sys.exc_info()\n sys.last_traceback=last_tb\n sys.last_exc=ei[1]\n try:\n lines=traceback.format_exception(ei[0],ei[1],last_tb.tb_next,colorize=colorize)\n if sys.excepthook is sys.__excepthook__:\n self.write(''.join(lines))\n else:\n \n \n sys.excepthook(ei[0],ei[1],last_tb)\n finally:\n last_tb=ei=None\n \n def write(self,data):\n ''\n\n\n\n\n \n sys.stderr.write(data)\n \n \nclass InteractiveConsole(InteractiveInterpreter):\n ''\n\n\n\n\n \n \n def __init__(self,locals=None,filename=\"\",*,local_exit=False):\n ''\n\n\n\n\n\n\n\n \n InteractiveInterpreter.__init__(self,locals)\n self.filename=filename\n self.local_exit=local_exit\n self.resetbuffer()\n \n def resetbuffer(self):\n ''\n self.buffer=[]\n \n def interact(self,banner=None,exitmsg=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n sys.ps1\n except AttributeError:\n sys.ps1=\">>> \"\n try:\n sys.ps2\n except AttributeError:\n sys.ps2=\"... \"\n cprt='Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.'\n if banner is None:\n self.write(\"Python %s on %s\\n%s\\n(%s)\\n\"%\n (sys.version,sys.platform,cprt,\n self.__class__.__name__))\n elif banner:\n self.write(\"%s\\n\"%str(banner))\n more=0\n \n \n \n \n \n \n \n \n \n \n _exit=None\n _quit=None\n \n if self.local_exit:\n if hasattr(builtins,\"exit\"):\n _exit=builtins.exit\n builtins.exit=Quitter(\"exit\")\n \n if hasattr(builtins,\"quit\"):\n _quit=builtins.quit\n builtins.quit=Quitter(\"quit\")\n \n try:\n while True:\n try:\n if more:\n prompt=sys.ps2\n else:\n prompt=sys.ps1\n try:\n line=self.raw_input(prompt)\n except EOFError:\n self.write(\"\\n\")\n break\n else:\n more=self.push(line)\n except KeyboardInterrupt:\n self.write(\"\\nKeyboardInterrupt\\n\")\n self.resetbuffer()\n more=0\n except SystemExit as e:\n if self.local_exit:\n self.write(\"\\n\")\n break\n else:\n raise e\n finally:\n \n if _exit is not None:\n builtins.exit=_exit\n \n if _quit is not None:\n builtins.quit=_quit\n \n if exitmsg is None:\n self.write('now exiting %s...\\n'%self.__class__.__name__)\n elif exitmsg !='':\n self.write('%s\\n'%exitmsg)\n \n def push(self,line,filename=None,_symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self.buffer.append(line)\n source=\"\\n\".join(self.buffer)\n if filename is None:\n filename=self.filename\n more=self.runsource(source,filename,symbol=_symbol)\n if not more:\n self.resetbuffer()\n return more\n \n def raw_input(self,prompt=\"\"):\n ''\n\n\n\n\n\n\n\n\n \n return input(prompt)\n \n \nclass Quitter:\n def __init__(self,name):\n self.name=name\n if sys.platform ==\"win32\":\n self.eof='Ctrl-Z plus Return'\n else:\n self.eof='Ctrl-D (i.e. EOF)'\n \n def __repr__(self):\n return f'Use {self.name} or {self.eof} to exit'\n \n def __call__(self,code=None):\n raise SystemExit(code)\n \n \ndef interact(banner=None,readfunc=None,local=None,exitmsg=None,local_exit=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n console=InteractiveConsole(local,local_exit=local_exit)\n if readfunc is not None:\n console.raw_input=readfunc\n else:\n try:\n import readline\n except ImportError:\n pass\n console.interact(banner,exitmsg)\n \n \nif __name__ ==\"__main__\":\n import argparse\n \n parser=argparse.ArgumentParser()\n parser.add_argument('-q',action='store_true',\n help=\"don't print version and copyright messages\")\n args=parser.parse_args()\n if args.q or sys.flags.quiet:\n banner=''\n else:\n banner=None\n interact(banner)\n", ["argparse", "builtins", "codeop", "readline", "sys", "traceback"]], "codecs": [".py", "''\n\n\n\n\n\n\n\n\nimport builtins\nimport sys\n\n\n\ntry:\n from _codecs import *\nexcept ImportError as why:\n raise SystemError('Failed to load the builtin codecs: %s'%why)\n \n__all__=[\"register\",\"lookup\",\"open\",\"EncodedFile\",\"BOM\",\"BOM_BE\",\n\"BOM_LE\",\"BOM32_BE\",\"BOM32_LE\",\"BOM64_BE\",\"BOM64_LE\",\n\"BOM_UTF8\",\"BOM_UTF16\",\"BOM_UTF16_LE\",\"BOM_UTF16_BE\",\n\"BOM_UTF32\",\"BOM_UTF32_LE\",\"BOM_UTF32_BE\",\n\"CodecInfo\",\"Codec\",\"IncrementalEncoder\",\"IncrementalDecoder\",\n\"StreamReader\",\"StreamWriter\",\n\"StreamReaderWriter\",\"StreamRecoder\",\n\"getencoder\",\"getdecoder\",\"getincrementalencoder\",\n\"getincrementaldecoder\",\"getreader\",\"getwriter\",\n\"encode\",\"decode\",\"iterencode\",\"iterdecode\",\n\"strict_errors\",\"ignore_errors\",\"replace_errors\",\n\"xmlcharrefreplace_errors\",\n\"backslashreplace_errors\",\"namereplace_errors\",\n\"register_error\",\"lookup_error\"]\n\n\n\n\n\n\n\n\n\n\nBOM_UTF8=b'\\xef\\xbb\\xbf'\n\n\nBOM_LE=BOM_UTF16_LE=b'\\xff\\xfe'\n\n\nBOM_BE=BOM_UTF16_BE=b'\\xfe\\xff'\n\n\nBOM_UTF32_LE=b'\\xff\\xfe\\x00\\x00'\n\n\nBOM_UTF32_BE=b'\\x00\\x00\\xfe\\xff'\n\nif sys.byteorder =='little':\n\n\n BOM=BOM_UTF16=BOM_UTF16_LE\n \n \n BOM_UTF32=BOM_UTF32_LE\n \nelse:\n\n\n BOM=BOM_UTF16=BOM_UTF16_BE\n \n \n BOM_UTF32=BOM_UTF32_BE\n \n \nBOM32_LE=BOM_UTF16_LE\nBOM32_BE=BOM_UTF16_BE\nBOM64_LE=BOM_UTF32_LE\nBOM64_BE=BOM_UTF32_BE\n\n\n\n\nclass CodecInfo(tuple):\n ''\n \n \n \n \n \n \n \n _is_text_encoding=True\n \n def __new__(cls,encode,decode,streamreader=None,streamwriter=None,\n incrementalencoder=None,incrementaldecoder=None,name=None,\n *,_is_text_encoding=None):\n self=tuple.__new__(cls,(encode,decode,streamreader,streamwriter))\n self.name=name\n self.encode=encode\n self.decode=decode\n self.incrementalencoder=incrementalencoder\n self.incrementaldecoder=incrementaldecoder\n self.streamwriter=streamwriter\n self.streamreader=streamreader\n if _is_text_encoding is not None:\n self._is_text_encoding=_is_text_encoding\n return self\n \n def __repr__(self):\n return \"<%s.%s object for encoding %s at %#x>\"%\\\n (self.__class__.__module__,self.__class__.__qualname__,\n self.name,id(self))\n \n def __getnewargs__(self):\n return tuple(self)\n \nclass Codec:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def encode(self,input,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def decode(self,input,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \nclass IncrementalEncoder(object):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n ''\n\n\n\n\n\n \n self.errors=errors\n self.buffer=\"\"\n \n def encode(self,input,final=False):\n ''\n\n \n raise NotImplementedError\n \n def reset(self):\n ''\n\n \n \n def getstate(self):\n ''\n\n \n return 0\n \n def setstate(self,state):\n ''\n\n\n \n \nclass BufferedIncrementalEncoder(IncrementalEncoder):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n IncrementalEncoder.__init__(self,errors)\n \n self.buffer=\"\"\n \n def _buffer_encode(self,input,errors,final):\n \n \n raise NotImplementedError\n \n def encode(self,input,final=False):\n \n data=self.buffer+input\n (result,consumed)=self._buffer_encode(data,self.errors,final)\n \n self.buffer=data[consumed:]\n return result\n \n def reset(self):\n IncrementalEncoder.reset(self)\n self.buffer=\"\"\n \n def getstate(self):\n return self.buffer or 0\n \n def setstate(self,state):\n self.buffer=state or \"\"\n \nclass IncrementalDecoder(object):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n ''\n\n\n\n\n\n \n self.errors=errors\n \n def decode(self,input,final=False):\n ''\n\n \n raise NotImplementedError\n \n def reset(self):\n ''\n\n \n \n def getstate(self):\n ''\n\n\n\n\n\n\n\n\n\n \n return(b\"\",0)\n \n def setstate(self,state):\n ''\n\n\n\n\n \n \nclass BufferedIncrementalDecoder(IncrementalDecoder):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n IncrementalDecoder.__init__(self,errors)\n \n self.buffer=b\"\"\n \n def _buffer_decode(self,input,errors,final):\n \n \n raise NotImplementedError\n \n def decode(self,input,final=False):\n \n data=self.buffer+input\n (result,consumed)=self._buffer_decode(data,self.errors,final)\n \n self.buffer=data[consumed:]\n return result\n \n def reset(self):\n IncrementalDecoder.reset(self)\n self.buffer=b\"\"\n \n def getstate(self):\n \n return(self.buffer,0)\n \n def setstate(self,state):\n \n self.buffer=state[0]\n \n \n \n \n \n \n \n \nclass StreamWriter(Codec):\n\n def __init__(self,stream,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.errors=errors\n \n def write(self,object):\n \n ''\n \n data,consumed=self.encode(object,self.errors)\n self.stream.write(data)\n \n def writelines(self,list):\n \n ''\n\n \n self.write(''.join(list))\n \n def reset(self):\n \n ''\n\n\n\n\n\n\n \n pass\n \n def seek(self,offset,whence=0):\n self.stream.seek(offset,whence)\n if whence ==0 and offset ==0:\n self.reset()\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n def __reduce_ex__(self,proto):\n raise TypeError(\"can't serialize %s\"%self.__class__.__name__)\n \n \n \nclass StreamReader(Codec):\n\n charbuffertype=str\n \n def __init__(self,stream,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.errors=errors\n self.bytebuffer=b\"\"\n self._empty_charbuffer=self.charbuffertype()\n self.charbuffer=self._empty_charbuffer\n self.linebuffer=None\n \n def decode(self,input,errors='strict'):\n raise NotImplementedError\n \n def read(self,size=-1,chars=-1,firstline=False):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if self.linebuffer:\n self.charbuffer=self._empty_charbuffer.join(self.linebuffer)\n self.linebuffer=None\n \n if chars <0:\n \n \n chars=size\n \n \n while True:\n \n if chars >=0:\n if len(self.charbuffer)>=chars:\n break\n \n if size <0:\n newdata=self.stream.read()\n else:\n newdata=self.stream.read(size)\n \n data=self.bytebuffer+newdata\n if not data:\n break\n try:\n newchars,decodedbytes=self.decode(data,self.errors)\n except UnicodeDecodeError as exc:\n if firstline:\n newchars,decodedbytes=\\\n self.decode(data[:exc.start],self.errors)\n lines=newchars.splitlines(keepends=True)\n if len(lines)<=1:\n raise\n else:\n raise\n \n self.bytebuffer=data[decodedbytes:]\n \n self.charbuffer +=newchars\n \n if not newdata:\n break\n if chars <0:\n \n result=self.charbuffer\n self.charbuffer=self._empty_charbuffer\n else:\n \n result=self.charbuffer[:chars]\n self.charbuffer=self.charbuffer[chars:]\n return result\n \n def readline(self,size=None,keepends=True):\n \n ''\n\n\n\n\n\n \n \n \n if self.linebuffer:\n line=self.linebuffer[0]\n del self.linebuffer[0]\n if len(self.linebuffer)==1:\n \n \n self.charbuffer=self.linebuffer[0]\n self.linebuffer=None\n if not keepends:\n line=line.splitlines(keepends=False)[0]\n return line\n \n readsize=size or 72\n line=self._empty_charbuffer\n \n while True:\n data=self.read(readsize,firstline=True)\n if data:\n \n \n \n if(isinstance(data,str)and data.endswith(\"\\r\"))or\\\n (isinstance(data,bytes)and data.endswith(b\"\\r\")):\n data +=self.read(size=1,chars=1)\n \n line +=data\n lines=line.splitlines(keepends=True)\n if lines:\n if len(lines)>1:\n \n \n line=lines[0]\n del lines[0]\n if len(lines)>1:\n \n lines[-1]+=self.charbuffer\n self.linebuffer=lines\n self.charbuffer=None\n else:\n \n self.charbuffer=lines[0]+self.charbuffer\n if not keepends:\n line=line.splitlines(keepends=False)[0]\n break\n line0withend=lines[0]\n line0withoutend=lines[0].splitlines(keepends=False)[0]\n if line0withend !=line0withoutend:\n \n self.charbuffer=self._empty_charbuffer.join(lines[1:])+\\\n self.charbuffer\n if keepends:\n line=line0withend\n else:\n line=line0withoutend\n break\n \n if not data or size is not None:\n if line and not keepends:\n line=line.splitlines(keepends=False)[0]\n break\n if readsize <8000:\n readsize *=2\n return line\n \n def readlines(self,sizehint=None,keepends=True):\n \n ''\n\n\n\n\n\n\n\n\n \n data=self.read()\n return data.splitlines(keepends)\n \n def reset(self):\n \n ''\n\n\n\n\n\n \n self.bytebuffer=b\"\"\n self.charbuffer=self._empty_charbuffer\n self.linebuffer=None\n \n def seek(self,offset,whence=0):\n ''\n\n\n \n self.stream.seek(offset,whence)\n self.reset()\n \n def __next__(self):\n \n ''\n line=self.readline()\n if line:\n return line\n raise StopIteration\n \n def __iter__(self):\n return self\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n def __reduce_ex__(self,proto):\n raise TypeError(\"can't serialize %s\"%self.__class__.__name__)\n \n \n \nclass StreamReaderWriter:\n\n ''\n\n\n\n\n\n\n \n \n encoding='unknown'\n \n def __init__(self,stream,Reader,Writer,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.reader=Reader(stream,errors)\n self.writer=Writer(stream,errors)\n self.errors=errors\n \n def read(self,size=-1):\n \n return self.reader.read(size)\n \n def readline(self,size=None):\n \n return self.reader.readline(size)\n \n def readlines(self,sizehint=None):\n \n return self.reader.readlines(sizehint)\n \n def __next__(self):\n \n ''\n return next(self.reader)\n \n def __iter__(self):\n return self\n \n def write(self,data):\n \n return self.writer.write(data)\n \n def writelines(self,list):\n \n return self.writer.writelines(list)\n \n def reset(self):\n \n self.reader.reset()\n self.writer.reset()\n \n def seek(self,offset,whence=0):\n self.stream.seek(offset,whence)\n self.reader.reset()\n if whence ==0 and offset ==0:\n self.writer.reset()\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n \n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n def __reduce_ex__(self,proto):\n raise TypeError(\"can't serialize %s\"%self.__class__.__name__)\n \n \n \nclass StreamRecoder:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n data_encoding='unknown'\n file_encoding='unknown'\n \n def __init__(self,stream,encode,decode,Reader,Writer,\n errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.encode=encode\n self.decode=decode\n self.reader=Reader(stream,errors)\n self.writer=Writer(stream,errors)\n self.errors=errors\n \n def read(self,size=-1):\n \n data=self.reader.read(size)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def readline(self,size=None):\n \n if size is None:\n data=self.reader.readline()\n else:\n data=self.reader.readline(size)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def readlines(self,sizehint=None):\n \n data=self.reader.read()\n data,bytesencoded=self.encode(data,self.errors)\n return data.splitlines(keepends=True)\n \n def __next__(self):\n \n ''\n data=next(self.reader)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def __iter__(self):\n return self\n \n def write(self,data):\n \n data,bytesdecoded=self.decode(data,self.errors)\n return self.writer.write(data)\n \n def writelines(self,list):\n \n data=b''.join(list)\n data,bytesdecoded=self.decode(data,self.errors)\n return self.writer.write(data)\n \n def reset(self):\n \n self.reader.reset()\n self.writer.reset()\n \n def seek(self,offset,whence=0):\n \n \n self.reader.seek(offset,whence)\n self.writer.seek(offset,whence)\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n def __reduce_ex__(self,proto):\n raise TypeError(\"can't serialize %s\"%self.__class__.__name__)\n \n \n \ndef open(filename,mode='r',encoding=None,errors='strict',buffering=-1):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if encoding is not None and\\\n 'b'not in mode:\n \n mode=mode+'b'\n file=builtins.open(filename,mode,buffering)\n if encoding is None:\n return file\n \n try:\n info=lookup(encoding)\n srw=StreamReaderWriter(file,info.streamreader,info.streamwriter,errors)\n \n srw.encoding=encoding\n return srw\n except:\n file.close()\n raise\n \ndef EncodedFile(file,data_encoding,file_encoding=None,errors='strict'):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if file_encoding is None:\n file_encoding=data_encoding\n data_info=lookup(data_encoding)\n file_info=lookup(file_encoding)\n sr=StreamRecoder(file,data_info.encode,data_info.decode,\n file_info.streamreader,file_info.streamwriter,errors)\n \n sr.data_encoding=data_encoding\n sr.file_encoding=file_encoding\n return sr\n \n \n \ndef getencoder(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).encode\n \ndef getdecoder(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).decode\n \ndef getincrementalencoder(encoding):\n\n ''\n\n\n\n\n\n \n encoder=lookup(encoding).incrementalencoder\n if encoder is None:\n raise LookupError(encoding)\n return encoder\n \ndef getincrementaldecoder(encoding):\n\n ''\n\n\n\n\n\n \n decoder=lookup(encoding).incrementaldecoder\n if decoder is None:\n raise LookupError(encoding)\n return decoder\n \ndef getreader(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).streamreader\n \ndef getwriter(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).streamwriter\n \ndef iterencode(iterator,encoding,errors='strict',**kwargs):\n ''\n\n\n\n\n\n\n \n encoder=getincrementalencoder(encoding)(errors,**kwargs)\n for input in iterator:\n output=encoder.encode(input)\n if output:\n yield output\n output=encoder.encode(\"\",True)\n if output:\n yield output\n \ndef iterdecode(iterator,encoding,errors='strict',**kwargs):\n ''\n\n\n\n\n\n\n \n decoder=getincrementaldecoder(encoding)(errors,**kwargs)\n for input in iterator:\n output=decoder.decode(input)\n if output:\n yield output\n output=decoder.decode(b\"\",True)\n if output:\n yield output\n \n \n \ndef make_identity_dict(rng):\n\n ''\n\n\n\n\n \n return{i:i for i in rng}\n \ndef make_encoding_map(decoding_map):\n\n ''\n\n\n\n\n\n\n\n\n\n \n m={}\n for k,v in decoding_map.items():\n if not v in m:\n m[v]=k\n else:\n m[v]=None\n return m\n \n \n \ntry:\n strict_errors=lookup_error(\"strict\")\n ignore_errors=lookup_error(\"ignore\")\n replace_errors=lookup_error(\"replace\")\n xmlcharrefreplace_errors=lookup_error(\"xmlcharrefreplace\")\n backslashreplace_errors=lookup_error(\"backslashreplace\")\n namereplace_errors=lookup_error(\"namereplace\")\nexcept LookupError:\n\n strict_errors=None\n ignore_errors=None\n replace_errors=None\n xmlcharrefreplace_errors=None\n backslashreplace_errors=None\n namereplace_errors=None\n \n \n \n_false=0\nif _false:\n import encodings\n", ["_codecs", "builtins", "encodings", "sys"]], "codeop": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport __future__\nimport warnings\n\n_features=[getattr(__future__,fname)\nfor fname in __future__.all_feature_names]\n\n__all__=[\"compile_command\",\"Compile\",\"CommandCompiler\"]\n\n\n\n\nPyCF_DONT_IMPLY_DEDENT=0x200\nPyCF_ALLOW_INCOMPLETE_INPUT=0x4000\n\ndef _maybe_compile(compiler,source,filename,symbol):\n\n for line in source.split(\"\\n\"):\n line=line.strip()\n if line and line[0]!='#':\n break\n else:\n if symbol !=\"eval\":\n source=\"pass\"\n \n \n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\",(SyntaxWarning,DeprecationWarning))\n try:\n compiler(source,filename,symbol)\n except SyntaxError:\n try:\n compiler(source+\"\\n\",filename,symbol)\n return None\n except _IncompleteInputError as e:\n return None\n except SyntaxError as e:\n pass\n \n \n return compiler(source,filename,symbol,incomplete_input=False)\n \ndef _compile(source,filename,symbol,incomplete_input=True):\n flags=0\n if incomplete_input:\n flags |=PyCF_ALLOW_INCOMPLETE_INPUT\n flags |=PyCF_DONT_IMPLY_DEDENT\n return compile(source,filename,symbol,flags)\n \ndef compile_command(source,filename=\"\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _maybe_compile(_compile,source,filename,symbol)\n \nclass Compile:\n ''\n\n\n \n def __init__(self):\n self.flags=PyCF_DONT_IMPLY_DEDENT |PyCF_ALLOW_INCOMPLETE_INPUT\n \n def __call__(self,source,filename,symbol,**kwargs):\n flags=self.flags\n if kwargs.get('incomplete_input',True)is False:\n flags &=~PyCF_DONT_IMPLY_DEDENT\n flags &=~PyCF_ALLOW_INCOMPLETE_INPUT\n codeob=compile(source,filename,symbol,flags,True)\n for feature in _features:\n if codeob.co_flags&feature.compiler_flag:\n self.flags |=feature.compiler_flag\n return codeob\n \nclass CommandCompiler:\n ''\n\n\n\n \n \n def __init__(self,):\n self.compiler=Compile()\n \n def __call__(self,source,filename=\"\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _maybe_compile(self.compiler,source,filename,symbol)\n", ["__future__", "warnings"]], "colorsys": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\"rgb_to_yiq\",\"yiq_to_rgb\",\"rgb_to_hls\",\"hls_to_rgb\",\n\"rgb_to_hsv\",\"hsv_to_rgb\"]\n\n\n\nONE_THIRD=1.0 /3.0\nONE_SIXTH=1.0 /6.0\nTWO_THIRD=2.0 /3.0\n\n\n\n\n\n\n\n\ndef rgb_to_yiq(r,g,b):\n y=0.30 *r+0.59 *g+0.11 *b\n i=0.74 *(r -y)-0.27 *(b -y)\n q=0.48 *(r -y)+0.41 *(b -y)\n return(y,i,q)\n \ndef yiq_to_rgb(y,i,q):\n\n\n\n\n r=y+0.9468822170900693 *i+0.6235565819861433 *q\n g=y -0.27478764629897834 *i -0.6356910791873801 *q\n b=y -1.1085450346420322 *i+1.7090069284064666 *q\n \n if r <0.0:\n r=0.0\n if g <0.0:\n g=0.0\n if b <0.0:\n b=0.0\n if r >1.0:\n r=1.0\n if g >1.0:\n g=1.0\n if b >1.0:\n b=1.0\n return(r,g,b)\n \n \n \n \n \n \n \ndef rgb_to_hls(r,g,b):\n maxc=max(r,g,b)\n minc=min(r,g,b)\n sumc=(maxc+minc)\n rangec=(maxc -minc)\n l=sumc /2.0\n if minc ==maxc:\n return 0.0,l,0.0\n if l <=0.5:\n s=rangec /sumc\n else:\n s=rangec /(2.0 -maxc -minc)\n rc=(maxc -r)/rangec\n gc=(maxc -g)/rangec\n bc=(maxc -b)/rangec\n if r ==maxc:\n h=bc -gc\n elif g ==maxc:\n h=2.0+rc -bc\n else:\n h=4.0+gc -rc\n h=(h /6.0)%1.0\n return h,l,s\n \ndef hls_to_rgb(h,l,s):\n if s ==0.0:\n return l,l,l\n if l <=0.5:\n m2=l *(1.0+s)\n else:\n m2=l+s -(l *s)\n m1=2.0 *l -m2\n return(_v(m1,m2,h+ONE_THIRD),_v(m1,m2,h),_v(m1,m2,h -ONE_THIRD))\n \ndef _v(m1,m2,hue):\n hue=hue %1.0\n if hue \"\n \n \nUNNAMED_SECTION=_UnnamedSection()\n\n\n\n\n\n_UNSET=object()\n\n\nclass Interpolation:\n ''\n \n def before_get(self,parser,section,option,value,defaults):\n return value\n \n def before_set(self,parser,section,option,value):\n return value\n \n def before_read(self,parser,section,option,value):\n return value\n \n def before_write(self,parser,section,option,value):\n return value\n \n \nclass BasicInterpolation(Interpolation):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n _KEYCRE=re.compile(r\"%\\(([^)]+)\\)s\")\n \n def before_get(self,parser,section,option,value,defaults):\n L=[]\n self._interpolate_some(parser,option,L,value,section,defaults,1)\n return ''.join(L)\n \n def before_set(self,parser,section,option,value):\n tmp_value=value.replace('%%','')\n tmp_value=self._KEYCRE.sub('',tmp_value)\n if '%'in tmp_value:\n raise ValueError(\"invalid interpolation syntax in %r at \"\n \"position %d\"%(value,tmp_value.find('%')))\n return value\n \n def _interpolate_some(self,parser,option,accum,rest,section,map,\n depth):\n rawval=parser.get(section,option,raw=True,fallback=rest)\n if depth >MAX_INTERPOLATION_DEPTH:\n raise InterpolationDepthError(option,section,rawval)\n while rest:\n p=rest.find(\"%\")\n if p <0:\n accum.append(rest)\n return\n if p >0:\n accum.append(rest[:p])\n rest=rest[p:]\n \n c=rest[1:2]\n if c ==\"%\":\n accum.append(\"%\")\n rest=rest[2:]\n elif c ==\"(\":\n m=self._KEYCRE.match(rest)\n if m is None:\n raise InterpolationSyntaxError(option,section,\n \"bad interpolation variable reference %r\"%rest)\n var=parser.optionxform(m.group(1))\n rest=rest[m.end():]\n try:\n v=map[var]\n except KeyError:\n raise InterpolationMissingOptionError(\n option,section,rawval,var)from None\n if \"%\"in v:\n self._interpolate_some(parser,option,accum,v,\n section,map,depth+1)\n else:\n accum.append(v)\n else:\n raise InterpolationSyntaxError(\n option,section,\n \"'%%' must be followed by '%%' or '(', \"\n \"found: %r\"%(rest,))\n \n \nclass ExtendedInterpolation(Interpolation):\n ''\n \n \n _KEYCRE=re.compile(r\"\\$\\{([^}]+)\\}\")\n \n def before_get(self,parser,section,option,value,defaults):\n L=[]\n self._interpolate_some(parser,option,L,value,section,defaults,1)\n return ''.join(L)\n \n def before_set(self,parser,section,option,value):\n tmp_value=value.replace('$$','')\n tmp_value=self._KEYCRE.sub('',tmp_value)\n if '$'in tmp_value:\n raise ValueError(\"invalid interpolation syntax in %r at \"\n \"position %d\"%(value,tmp_value.find('$')))\n return value\n \n def _interpolate_some(self,parser,option,accum,rest,section,map,\n depth):\n rawval=parser.get(section,option,raw=True,fallback=rest)\n if depth >MAX_INTERPOLATION_DEPTH:\n raise InterpolationDepthError(option,section,rawval)\n while rest:\n p=rest.find(\"$\")\n if p <0:\n accum.append(rest)\n return\n if p >0:\n accum.append(rest[:p])\n rest=rest[p:]\n \n c=rest[1:2]\n if c ==\"$\":\n accum.append(\"$\")\n rest=rest[2:]\n elif c ==\"{\":\n m=self._KEYCRE.match(rest)\n if m is None:\n raise InterpolationSyntaxError(option,section,\n \"bad interpolation variable reference %r\"%rest)\n path=m.group(1).split(':')\n rest=rest[m.end():]\n sect=section\n opt=option\n try:\n if len(path)==1:\n opt=parser.optionxform(path[0])\n v=map[opt]\n elif len(path)==2:\n sect=path[0]\n opt=parser.optionxform(path[1])\n v=parser.get(sect,opt,raw=True)\n else:\n raise InterpolationSyntaxError(\n option,section,\n \"More than one ':' found: %r\"%(rest,))\n except(KeyError,NoSectionError,NoOptionError):\n raise InterpolationMissingOptionError(\n option,section,rawval,\":\".join(path))from None\n if \"$\"in v:\n self._interpolate_some(parser,opt,accum,v,sect,\n dict(parser.items(sect,raw=True)),\n depth+1)\n else:\n accum.append(v)\n else:\n raise InterpolationSyntaxError(\n option,section,\n \"'$' must be followed by '$' or '{', \"\n \"found: %r\"%(rest,))\n \n \nclass _ReadState:\n elements_added:set[str]\n cursect:dict[str,str]|None=None\n sectname:str |None=None\n optname:str |None=None\n lineno:int=0\n indent_level:int=0\n errors:list[ParsingError]\n \n def __init__(self):\n self.elements_added=set()\n self.errors=list()\n \n \nclass _Line(str):\n\n def __new__(cls,val,*args,**kwargs):\n return super().__new__(cls,val)\n \n def __init__(self,val,prefixes):\n self.prefixes=prefixes\n \n @functools.cached_property\n def clean(self):\n return self._strip_full()and self._strip_inline()\n \n @property\n def has_comments(self):\n return self.strip()!=self.clean\n \n def _strip_inline(self):\n ''\n\n \n matcher=re.compile(\n '|'.join(fr'(^|\\s)({re.escape(prefix)})'for prefix in self.prefixes.inline)\n \n or '(?!)'\n )\n match=matcher.search(self)\n return self[:match.start()if match else None].strip()\n \n def _strip_full(self):\n return ''if any(map(self.strip().startswith,self.prefixes.full))else True\n \n \nclass RawConfigParser(MutableMapping):\n ''\n \n \n _SECT_TMPL=r\"\"\"\n \\[ # [\n (?P

.+) # very permissive!\n \\] # ]\n \"\"\"\n _OPT_TMPL=r\"\"\"\n (?Pn'%(\n toprefix,num_chg)\n else:\n in_change=False\n \n if not flaglist:\n flaglist=[False]\n next_id=['']\n next_href=['']\n last=0\n if context:\n fromlist=[' No Differences Found ']\n tolist=fromlist\n else:\n fromlist=tolist=[' Empty File ']\n \n if not flaglist[0]:\n next_href[0]='f'%toprefix\n \n next_href[last]='t'%(toprefix)\n \n return fromlist,tolist,flaglist,next_href,next_id\n \n def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,\n numlines=5):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n self._make_prefix()\n \n \n \n fromlines,tolines=self._tab_newline_replace(fromlines,tolines)\n \n \n if context:\n context_lines=numlines\n else:\n context_lines=None\n diffs=_mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,\n charjunk=self._charjunk)\n \n \n if self._wrapcolumn:\n diffs=self._line_wrapper(diffs)\n \n \n fromlist,tolist,flaglist=self._collect_lines(diffs)\n \n \n fromlist,tolist,flaglist,next_href,next_id=self._convert_flags(\n fromlist,tolist,flaglist,context,numlines)\n \n s=[]\n fmt=' %s%s'+\\\n '%s%s\\n'\n for i in range(len(flaglist)):\n if flaglist[i]is None:\n \n \n if i >0:\n s.append(' \\n \\n')\n else:\n s.append(fmt %(next_id[i],next_href[i],fromlist[i],\n next_href[i],tolist[i]))\n if fromdesc or todesc:\n header_row='%s%s%s%s'%(\n '
',\n '%s'%fromdesc,\n '
',\n '%s'%todesc)\n else:\n header_row=''\n \n table=self._table_template %dict(\n data_rows=''.join(s),\n header_row=header_row,\n prefix=self._prefix[1])\n \n return table.replace('\\0+','').\\\n replace('\\0-','').\\\n replace('\\0^','').\\\n replace('\\1','').\\\n replace('\\t',' ')\n \ndel re\n\ndef restore(delta,which):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n tag={1:\"- \",2:\"+ \"}[int(which)]\n except KeyError:\n raise ValueError('unknown delta choice (must be 1 or 2): %r'\n %which)from None\n prefixes=(\" \",tag)\n for line in delta:\n if line[:2]in prefixes:\n yield line[2:]\n \ndef _test():\n import doctest,difflib\n return doctest.testmod(difflib)\n \nif __name__ ==\"__main__\":\n _test()\n", ["collections", "difflib", "doctest", "heapq", "re", "types"]], "doctest": [".py", "\n\n\n\n\n\n\n\nr\"\"\"Module doctest -- a framework for running examples in docstrings.\n\nIn simplest use, end each module M to be tested with:\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n _test()\n\nThen running the module as a script will cause the examples in the\ndocstrings to get executed and verified:\n\npython M.py\n\nThis won't display anything unless an example fails, in which case the\nfailing example(s) and the cause(s) of the failure(s) are printed to stdout\n(why not stderr? because stderr is a lame hack <0.2 wink>), and the final\nline of output is \"Test failed.\".\n\nRun it with the -v switch instead:\n\npython M.py -v\n\nand a detailed report of all examples tried is printed to stdout, along\nwith assorted summaries at the end.\n\nYou can force verbose mode by passing \"verbose=True\" to testmod, or prohibit\nit by passing \"verbose=False\". In either of those cases, sys.argv is not\nexamined by testmod.\n\nThere are a variety of other ways to run doctests, including integration\nwith the unittest framework, and support for running non-Python text\nfiles containing doctests. There are also many ways to override parts\nof doctest's default behaviors. See the Library Reference Manual for\ndetails.\n\"\"\"\n\n__docformat__='reStructuredText en'\n\n__all__=[\n\n'register_optionflag',\n'DONT_ACCEPT_TRUE_FOR_1',\n'DONT_ACCEPT_BLANKLINE',\n'NORMALIZE_WHITESPACE',\n'ELLIPSIS',\n'SKIP',\n'IGNORE_EXCEPTION_DETAIL',\n'COMPARISON_FLAGS',\n'REPORT_UDIFF',\n'REPORT_CDIFF',\n'REPORT_NDIFF',\n'REPORT_ONLY_FIRST_FAILURE',\n'REPORTING_FLAGS',\n'FAIL_FAST',\n\n\n'Example',\n'DocTest',\n\n'DocTestParser',\n\n'DocTestFinder',\n\n'DocTestRunner',\n'OutputChecker',\n'DocTestFailure',\n'UnexpectedException',\n'DebugRunner',\n\n'testmod',\n'testfile',\n'run_docstring_examples',\n\n'DocTestSuite',\n'DocFileSuite',\n'set_unittest_reportflags',\n\n'script_from_examples',\n'testsource',\n'debug_src',\n'debug',\n]\n\nimport __future__\nimport difflib\nimport inspect\nimport linecache\nimport os\nimport pdb\nimport re\nimport sys\nimport traceback\nimport unittest\nfrom io import StringIO,IncrementalNewlineDecoder\nfrom collections import namedtuple\nimport _colorize\nfrom _colorize import ANSIColors,can_colorize\n\n\nclass TestResults(namedtuple('TestResults','failed attempted')):\n def __new__(cls,failed,attempted,*,skipped=0):\n results=super().__new__(cls,failed,attempted)\n results.skipped=skipped\n return results\n \n def __repr__(self):\n if self.skipped:\n return(f'TestResults(failed={self.failed}, '\n f'attempted={self.attempted}, '\n f'skipped={self.skipped})')\n else:\n \n \n return super().__repr__()\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nOPTIONFLAGS_BY_NAME={}\ndef register_optionflag(name):\n\n return OPTIONFLAGS_BY_NAME.setdefault(name,1 <=2\n \n \n startpos,endpos=0,len(got)\n w=ws[0]\n if w:\n if got.startswith(w):\n startpos=len(w)\n del ws[0]\n else:\n return False\n w=ws[-1]\n if w:\n if got.endswith(w):\n endpos -=len(w)\n del ws[-1]\n else:\n return False\n \n if startpos >endpos:\n \n \n return False\n \n \n \n \n for w in ws:\n \n \n \n startpos=got.find(w,startpos,endpos)\n if startpos <0:\n return False\n startpos +=len(w)\n \n return True\n \ndef _comment_line(line):\n ''\n line=line.rstrip()\n if line:\n return '# '+line\n else:\n return '#'\n \ndef _strip_exception_details(msg):\n\n\n\n\n\n\n\n\n\n\n start,end=0,len(msg)\n \n i=msg.find(\"\\n\")\n if i >=0:\n end=i\n \n i=msg.find(':',0,end)\n if i >=0:\n end=i\n \n i=msg.rfind('.',0,end)\n if i >=0:\n start=i+1\n return msg[start:end]\n \nclass _OutputRedirectingPdb(pdb.Pdb):\n ''\n\n\n\n \n def __init__(self,out):\n self.__out=out\n self.__debugger_used=False\n \n pdb.Pdb.__init__(self,stdout=out,nosigint=True)\n \n self.use_rawinput=1\n \n def set_trace(self,frame=None):\n self.__debugger_used=True\n if frame is None:\n frame=sys._getframe().f_back\n pdb.Pdb.set_trace(self,frame)\n \n def set_continue(self):\n \n \n if self.__debugger_used:\n pdb.Pdb.set_continue(self)\n \n def trace_dispatch(self,*args):\n \n save_stdout=sys.stdout\n sys.stdout=self.__out\n \n try:\n return pdb.Pdb.trace_dispatch(self,*args)\n finally:\n sys.stdout=save_stdout\n \n \ndef _module_relative_path(module,test_path):\n if not inspect.ismodule(module):\n raise TypeError('Expected a module: %r'%module)\n if test_path.startswith('/'):\n raise ValueError('Module-relative files may not have absolute paths')\n \n \n test_path=os.path.join(*(test_path.split('/')))\n \n \n if hasattr(module,'__file__'):\n \n basedir=os.path.split(module.__file__)[0]\n elif module.__name__ =='__main__':\n \n if len(sys.argv)>0 and sys.argv[0]!='':\n basedir=os.path.split(sys.argv[0])[0]\n else:\n basedir=os.curdir\n else:\n if hasattr(module,'__path__'):\n for directory in module.__path__:\n fullpath=os.path.join(directory,test_path)\n if os.path.exists(fullpath):\n return fullpath\n \n \n raise ValueError(\"Can't resolve paths relative to the module \"\n \"%r (it has no __file__)\"\n %module.__name__)\n \n \n return os.path.join(basedir,test_path)\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass Example:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,source,want,exc_msg=None,lineno=0,indent=0,\n options=None):\n \n if not source.endswith('\\n'):\n source +='\\n'\n if want and not want.endswith('\\n'):\n want +='\\n'\n if exc_msg is not None and not exc_msg.endswith('\\n'):\n exc_msg +='\\n'\n \n self.source=source\n self.want=want\n self.lineno=lineno\n self.indent=indent\n if options is None:options={}\n self.options=options\n self.exc_msg=exc_msg\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self.source ==other.source and\\\n self.want ==other.want and\\\n self.lineno ==other.lineno and\\\n self.indent ==other.indent and\\\n self.options ==other.options and\\\n self.exc_msg ==other.exc_msg\n \n def __hash__(self):\n return hash((self.source,self.want,self.lineno,self.indent,\n self.exc_msg))\n \nclass DocTest:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,examples,globs,name,filename,lineno,docstring):\n ''\n\n\n \n assert not isinstance(examples,str),\\\n \"DocTest no longer accepts str; use DocTestParser instead\"\n self.examples=examples\n self.docstring=docstring\n self.globs=globs.copy()\n self.name=name\n self.filename=filename\n self.lineno=lineno\n \n def __repr__(self):\n if len(self.examples)==0:\n examples='no examples'\n elif len(self.examples)==1:\n examples='1 example'\n else:\n examples='%d examples'%len(self.examples)\n return('<%s %s from %s:%s (%s)>'%\n (self.__class__.__name__,\n self.name,self.filename,self.lineno,examples))\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self.examples ==other.examples and\\\n self.docstring ==other.docstring and\\\n self.globs ==other.globs and\\\n self.name ==other.name and\\\n self.filename ==other.filename and\\\n self.lineno ==other.lineno\n \n def __hash__(self):\n return hash((self.docstring,self.name,self.filename,self.lineno))\n \n \n def __lt__(self,other):\n if not isinstance(other,DocTest):\n return NotImplemented\n self_lno=self.lineno if self.lineno is not None else -1\n other_lno=other.lineno if other.lineno is not None else -1\n return((self.name,self.filename,self_lno,id(self))\n <\n (other.name,other.filename,other_lno,id(other)))\n \n \n \n \n \nclass DocTestParser:\n ''\n\n \n \n \n \n \n \n _EXAMPLE_RE=re.compile(r'''\n # Source consists of a PS1 line followed by zero or more PS2 lines.\n (?P\n (?:^(?P [ ]*) >>> .*) # PS1 line\n (?:\\n [ ]* \\.\\.\\. .*)*) # PS2 lines\n \\n?\n # Want consists of any non-blank lines that do not start with PS1.\n (?P (?:(?![ ]*$) # Not a blank line\n (?![ ]*>>>) # Not a line starting with PS1\n .+$\\n? # But any other line\n )*)\n ''',re.MULTILINE |re.VERBOSE)\n \n \n \n \n \n \n \n \n \n \n _EXCEPTION_RE=re.compile(r\"\"\"\n # Grab the traceback header. Different versions of Python have\n # said different things on the first traceback line.\n ^(?P Traceback\\ \\(\n (?: most\\ recent\\ call\\ last\n | innermost\\ last\n ) \\) :\n )\n \\s* $ # toss trailing whitespace on the header.\n (?P .*?) # don't blink: absorb stuff until...\n ^ (?P \\w+ .*) # a line *starts* with alphanum.\n \"\"\",re.VERBOSE |re.MULTILINE |re.DOTALL)\n \n \n \n _IS_BLANK_OR_COMMENT=re.compile(r'^[ ]*(#.*)?$').match\n \n def parse(self,string,name=''):\n ''\n\n\n\n\n\n \n string=string.expandtabs()\n \n min_indent=self._min_indent(string)\n if min_indent >0:\n string='\\n'.join([l[min_indent:]for l in string.split('\\n')])\n \n output=[]\n charno,lineno=0,0\n \n for m in self._EXAMPLE_RE.finditer(string):\n \n output.append(string[charno:m.start()])\n \n lineno +=string.count('\\n',charno,m.start())\n \n (source,options,want,exc_msg)=\\\n self._parse_example(m,name,lineno)\n \n if not self._IS_BLANK_OR_COMMENT(source):\n output.append(Example(source,want,exc_msg,\n lineno=lineno,\n indent=min_indent+len(m.group('indent')),\n options=options))\n \n lineno +=string.count('\\n',m.start(),m.end())\n \n charno=m.end()\n \n output.append(string[charno:])\n return output\n \n def get_doctest(self,string,globs,name,filename,lineno):\n ''\n\n\n\n\n\n\n \n return DocTest(self.get_examples(string,name),globs,\n name,filename,lineno,string)\n \n def get_examples(self,string,name=''):\n ''\n\n\n\n\n\n\n\n\n \n return[x for x in self.parse(string,name)\n if isinstance(x,Example)]\n \n def _parse_example(self,m,name,lineno):\n ''\n\n\n\n\n\n\n\n\n \n \n indent=len(m.group('indent'))\n \n \n \n source_lines=m.group('source').split('\\n')\n self._check_prompt_blank(source_lines,indent,name,lineno)\n self._check_prefix(source_lines[1:],' '*indent+'.',name,lineno)\n source='\\n'.join([sl[indent+4:]for sl in source_lines])\n \n \n \n \n want=m.group('want')\n want_lines=want.split('\\n')\n if len(want_lines)>1 and re.match(r' *$',want_lines[-1]):\n del want_lines[-1]\n self._check_prefix(want_lines,' '*indent,name,\n lineno+len(source_lines))\n want='\\n'.join([wl[indent:]for wl in want_lines])\n \n \n m=self._EXCEPTION_RE.match(want)\n if m:\n exc_msg=m.group('msg')\n else:\n exc_msg=None\n \n \n options=self._find_options(source,name,lineno)\n \n return source,options,want,exc_msg\n \n \n \n \n \n \n \n \n _OPTION_DIRECTIVE_RE=re.compile(r'#\\s*doctest:\\s*([^\\n\\'\"]*)$',\n re.MULTILINE)\n \n def _find_options(self,source,name,lineno):\n ''\n\n\n\n\n\n \n options={}\n \n for m in self._OPTION_DIRECTIVE_RE.finditer(source):\n option_strings=m.group(1).replace(',',' ').split()\n for option in option_strings:\n if(option[0]not in '+-'or\n option[1:]not in OPTIONFLAGS_BY_NAME):\n raise ValueError('line %r of the doctest for %s '\n 'has an invalid option: %r'%\n (lineno+1,name,option))\n flag=OPTIONFLAGS_BY_NAME[option[1:]]\n options[flag]=(option[0]=='+')\n if options and self._IS_BLANK_OR_COMMENT(source):\n raise ValueError('line %r of the doctest for %s has an option '\n 'directive on a line with no example: %r'%\n (lineno,name,source))\n return options\n \n \n \n _INDENT_RE=re.compile(r'^([ ]*)(?=\\S)',re.MULTILINE)\n \n def _min_indent(self,s):\n ''\n indents=[len(indent)for indent in self._INDENT_RE.findall(s)]\n if len(indents)>0:\n return min(indents)\n else:\n return 0\n \n def _check_prompt_blank(self,lines,indent,name,lineno):\n ''\n\n\n\n\n \n for i,line in enumerate(lines):\n if len(line)>=indent+4 and line[indent+3]!=' ':\n raise ValueError('line %r of the docstring for %s '\n 'lacks blank after %s: %r'%\n (lineno+i+1,name,\n line[indent:indent+3],line))\n \n def _check_prefix(self,lines,prefix,name,lineno):\n ''\n\n\n \n for i,line in enumerate(lines):\n if line and not line.startswith(prefix):\n raise ValueError('line %r of the docstring for %s has '\n 'inconsistent leading whitespace: %r'%\n (lineno+i+1,name,line))\n \n \n \n \n \n \nclass DocTestFinder:\n ''\n\n\n\n\n\n \n \n def __init__(self,verbose=False,parser=DocTestParser(),\n recurse=True,exclude_empty=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._parser=parser\n self._verbose=verbose\n self._recurse=recurse\n self._exclude_empty=exclude_empty\n \n def find(self,obj,name=None,module=None,globs=None,extraglobs=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if name is None:\n name=getattr(obj,'__name__',None)\n if name is None:\n raise ValueError(\"DocTestFinder.find: name must be given \"\n \"when obj.__name__ doesn't exist: %r\"%\n (type(obj),))\n \n \n \n \n if module is False:\n module=None\n elif module is None:\n module=inspect.getmodule(obj)\n \n \n \n \n try:\n file=inspect.getsourcefile(obj)\n except TypeError:\n source_lines=None\n else:\n if not file:\n \n \n file=inspect.getfile(obj)\n if not file[0]+file[-2:]=='<]>':file=None\n if file is None:\n source_lines=None\n else:\n if module is not None:\n \n \n \n source_lines=linecache.getlines(file,module.__dict__)\n else:\n \n \n source_lines=linecache.getlines(file)\n if not source_lines:\n source_lines=None\n \n \n if globs is None:\n if module is None:\n globs={}\n else:\n globs=module.__dict__.copy()\n else:\n globs=globs.copy()\n if extraglobs is not None:\n globs.update(extraglobs)\n if '__name__'not in globs:\n globs['__name__']='__main__'\n \n \n tests=[]\n self._find(tests,obj,name,module,source_lines,globs,{})\n \n \n \n \n tests.sort()\n return tests\n \n def _from_module(self,module,object):\n ''\n\n\n \n if module is None:\n return True\n elif inspect.getmodule(object)is not None:\n return module is inspect.getmodule(object)\n elif inspect.isfunction(object):\n return module.__dict__ is object.__globals__\n elif(inspect.ismethoddescriptor(object)or\n inspect.ismethodwrapper(object)):\n if hasattr(object,'__objclass__'):\n obj_mod=object.__objclass__.__module__\n elif hasattr(object,'__module__'):\n obj_mod=object.__module__\n else:\n return True\n return module.__name__ ==obj_mod\n elif inspect.isclass(object):\n return module.__name__ ==object.__module__\n elif hasattr(object,'__module__'):\n return module.__name__ ==object.__module__\n elif isinstance(object,property):\n return True\n else:\n raise ValueError(\"object must be a class or function\")\n \n def _is_routine(self,obj):\n ''\n\n \n maybe_routine=obj\n try:\n maybe_routine=inspect.unwrap(maybe_routine)\n except ValueError:\n pass\n return inspect.isroutine(maybe_routine)\n \n def _find(self,tests,obj,name,module,source_lines,globs,seen):\n ''\n\n\n \n if self._verbose:\n print('Finding tests in %s'%name)\n \n \n if id(obj)in seen:\n return\n seen[id(obj)]=1\n \n \n test=self._get_test(obj,name,module,globs,source_lines)\n if test is not None:\n tests.append(test)\n \n \n if inspect.ismodule(obj)and self._recurse:\n for valname,val in obj.__dict__.items():\n valname='%s.%s'%(name,valname)\n \n \n if((self._is_routine(val)or inspect.isclass(val))and\n self._from_module(module,val)):\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n \n if inspect.ismodule(obj)and self._recurse:\n for valname,val in getattr(obj,'__test__',{}).items():\n if not isinstance(valname,str):\n raise ValueError(\"DocTestFinder.find: __test__ keys \"\n \"must be strings: %r\"%\n (type(valname),))\n if not(inspect.isroutine(val)or inspect.isclass(val)or\n inspect.ismodule(val)or isinstance(val,str)):\n raise ValueError(\"DocTestFinder.find: __test__ values \"\n \"must be strings, functions, methods, \"\n \"classes, or modules: %r\"%\n (type(val),))\n valname='%s.__test__.%s'%(name,valname)\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n \n if inspect.isclass(obj)and self._recurse:\n for valname,val in obj.__dict__.items():\n \n if isinstance(val,(staticmethod,classmethod)):\n val=val.__func__\n \n \n if((inspect.isroutine(val)or inspect.isclass(val)or\n isinstance(val,property))and\n self._from_module(module,val)):\n valname='%s.%s'%(name,valname)\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n def _get_test(self,obj,name,module,globs,source_lines):\n ''\n\n\n \n \n \n if isinstance(obj,str):\n docstring=obj\n else:\n try:\n if obj.__doc__ is None:\n docstring=''\n else:\n docstring=obj.__doc__\n if not isinstance(docstring,str):\n docstring=str(docstring)\n except(TypeError,AttributeError):\n docstring=''\n \n \n lineno=self._find_lineno(obj,source_lines)\n \n \n if self._exclude_empty and not docstring:\n return None\n \n \n if module is None:\n filename=None\n else:\n \n filename=getattr(module,'__file__',None)or module.__name__\n if filename[-4:]==\".pyc\":\n filename=filename[:-1]\n return self._parser.get_doctest(docstring,globs,name,\n filename,lineno)\n \n def _find_lineno(self,obj,source_lines):\n ''\n\n\n\n \n lineno=None\n docstring=getattr(obj,'__doc__',None)\n \n \n if inspect.ismodule(obj)and docstring is not None:\n lineno=0\n \n \n \n \n if inspect.isclass(obj)and docstring is not None:\n if source_lines is None:\n return None\n pat=re.compile(r'^\\s*class\\s*%s\\b'%\n re.escape(getattr(obj,'__name__','-')))\n for i,line in enumerate(source_lines):\n if pat.match(line):\n lineno=i\n break\n \n \n if inspect.ismethod(obj):obj=obj.__func__\n if isinstance(obj,property):\n obj=obj.fget\n if inspect.isfunction(obj)and getattr(obj,'__doc__',None):\n \n obj=inspect.unwrap(obj)\n try:\n obj=obj.__code__\n except AttributeError:\n \n \n \n return None\n if inspect.istraceback(obj):obj=obj.tb_frame\n if inspect.isframe(obj):obj=obj.f_code\n if inspect.iscode(obj):\n lineno=obj.co_firstlineno -1\n \n \n \n \n \n \n if lineno is not None:\n if source_lines is None:\n return lineno+1\n pat=re.compile(r'(^|.*:)\\s*\\w*(\"|\\')')\n for lineno in range(lineno,len(source_lines)):\n if pat.match(source_lines[lineno]):\n return lineno\n \n \n return None\n \n \n \n \n \nclass DocTestRunner:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n DIVIDER=\"*\"*70\n \n def __init__(self,checker=None,verbose=None,optionflags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._checker=checker or OutputChecker()\n if verbose is None:\n verbose='-v'in sys.argv\n self._verbose=verbose\n self.optionflags=optionflags\n self.original_optionflags=optionflags\n \n \n self.tries=0\n self.failures=0\n self.skips=0\n self._stats={}\n \n \n self._fakeout=_SpoofOut()\n \n \n \n \n \n def report_start(self,out,test,example):\n ''\n\n\n \n if self._verbose:\n if example.want:\n out('Trying:\\n'+_indent(example.source)+\n 'Expecting:\\n'+_indent(example.want))\n else:\n out('Trying:\\n'+_indent(example.source)+\n 'Expecting nothing\\n')\n \n def report_success(self,out,test,example,got):\n ''\n\n\n \n if self._verbose:\n out(\"ok\\n\")\n \n def report_failure(self,out,test,example,got):\n ''\n\n \n out(self._failure_header(test,example)+\n self._checker.output_difference(example,got,self.optionflags))\n \n def report_unexpected_exception(self,out,test,example,exc_info):\n ''\n\n \n out(self._failure_header(test,example)+\n 'Exception raised:\\n'+_indent(_exception_traceback(exc_info)))\n \n def _failure_header(self,test,example):\n red,reset=(\n (ANSIColors.RED,ANSIColors.RESET)if can_colorize()else(\"\",\"\")\n )\n out=[f\"{red}{self.DIVIDER}{reset}\"]\n if test.filename:\n if test.lineno is not None and example.lineno is not None:\n lineno=test.lineno+example.lineno+1\n else:\n lineno='?'\n out.append('File \"%s\", line %s, in %s'%\n (test.filename,lineno,test.name))\n else:\n out.append('Line %s, in %s'%(example.lineno+1,test.name))\n out.append('Failed example:')\n source=example.source\n out.append(_indent(source))\n return '\\n'.join(out)\n \n \n \n \n \n def __run(self,test,compileflags,out):\n ''\n\n\n\n\n\n \n \n failures=attempted=skips=0\n \n \n \n original_optionflags=self.optionflags\n \n SUCCESS,FAILURE,BOOM=range(3)\n \n check=self._checker.check_output\n \n \n for examplenum,example in enumerate(test.examples):\n attempted +=1\n \n \n \n quiet=(self.optionflags&REPORT_ONLY_FIRST_FAILURE and\n failures >0)\n \n \n self.optionflags=original_optionflags\n if example.options:\n for(optionflag,val)in example.options.items():\n if val:\n self.optionflags |=optionflag\n else:\n self.optionflags &=~optionflag\n \n \n if self.optionflags&SKIP:\n skips +=1\n continue\n \n \n if not quiet:\n self.report_start(out,test,example)\n \n \n \n \n filename=''%(test.name,examplenum)\n \n \n \n \n try:\n \n exec(compile(example.source,filename,\"single\",\n compileflags,True),test.globs)\n self.debugger.set_continue()\n exception=None\n except KeyboardInterrupt:\n raise\n except:\n exception=sys.exc_info()\n self.debugger.set_continue()\n \n got=self._fakeout.getvalue()\n self._fakeout.truncate(0)\n outcome=FAILURE\n \n \n \n if exception is None:\n if check(example.want,got,self.optionflags):\n outcome=SUCCESS\n \n \n else:\n formatted_ex=traceback.format_exception_only(*exception[:2])\n if issubclass(exception[0],SyntaxError):\n \n \n \n \n exception_line_prefixes=(\n f\"{exception[0].__qualname__}:\",\n f\"{exception[0].__module__}.{exception[0].__qualname__}:\",\n )\n exc_msg_index=next(\n index\n for index,line in enumerate(formatted_ex)\n if line.startswith(exception_line_prefixes)\n )\n formatted_ex=formatted_ex[exc_msg_index:]\n \n exc_msg=\"\".join(formatted_ex)\n if not quiet:\n got +=_exception_traceback(exception)\n \n \n \n if example.exc_msg is None:\n outcome=BOOM\n \n \n elif check(example.exc_msg,exc_msg,self.optionflags):\n outcome=SUCCESS\n \n \n elif self.optionflags&IGNORE_EXCEPTION_DETAIL:\n if check(_strip_exception_details(example.exc_msg),\n _strip_exception_details(exc_msg),\n self.optionflags):\n outcome=SUCCESS\n \n \n if outcome is SUCCESS:\n if not quiet:\n self.report_success(out,test,example,got)\n elif outcome is FAILURE:\n if not quiet:\n self.report_failure(out,test,example,got)\n failures +=1\n elif outcome is BOOM:\n if not quiet:\n self.report_unexpected_exception(out,test,example,\n exception)\n failures +=1\n else:\n assert False,(\"unknown outcome\",outcome)\n \n if failures and self.optionflags&FAIL_FAST:\n break\n \n \n self.optionflags=original_optionflags\n \n \n self.__record_outcome(test,failures,attempted,skips)\n return TestResults(failures,attempted,skipped=skips)\n \n def __record_outcome(self,test,failures,tries,skips):\n ''\n\n\n \n failures2,tries2,skips2=self._stats.get(test.name,(0,0,0))\n self._stats[test.name]=(failures+failures2,\n tries+tries2,\n skips+skips2)\n self.failures +=failures\n self.tries +=tries\n self.skips +=skips\n \n __LINECACHE_FILENAME_RE=re.compile(r'.+)'\n r'\\[(?P\\d+)\\]>$')\n def __patched_linecache_getlines(self,filename,module_globals=None):\n m=self.__LINECACHE_FILENAME_RE.match(filename)\n if m and m.group('name')==self.test.name:\n example=self.test.examples[int(m.group('examplenum'))]\n return example.source.splitlines(keepends=True)\n else:\n return self.save_linecache_getlines(filename,module_globals)\n \n def run(self,test,compileflags=None,out=None,clear_globs=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.test=test\n \n if compileflags is None:\n compileflags=_extract_future_flags(test.globs)\n \n save_stdout=sys.stdout\n if out is None:\n encoding=save_stdout.encoding\n if encoding is None or encoding.lower()=='utf-8':\n out=save_stdout.write\n else:\n \n def out(s):\n s=str(s.encode(encoding,'backslashreplace'),encoding)\n save_stdout.write(s)\n sys.stdout=self._fakeout\n \n \n \n \n \n \n save_trace=sys.gettrace()\n save_set_trace=pdb.set_trace\n self.debugger=_OutputRedirectingPdb(save_stdout)\n self.debugger.reset()\n pdb.set_trace=self.debugger.set_trace\n \n \n \n self.save_linecache_getlines=linecache.getlines\n linecache.getlines=self.__patched_linecache_getlines\n \n \n save_displayhook=sys.displayhook\n sys.displayhook=sys.__displayhook__\n saved_can_colorize=_colorize.can_colorize\n _colorize.can_colorize=lambda:False\n color_variables={\"PYTHON_COLORS\":None,\"FORCE_COLOR\":None}\n for key in color_variables:\n color_variables[key]=os.environ.pop(key,None)\n try:\n return self.__run(test,compileflags,out)\n finally:\n sys.stdout=save_stdout\n pdb.set_trace=save_set_trace\n sys.settrace(save_trace)\n linecache.getlines=self.save_linecache_getlines\n sys.displayhook=save_displayhook\n _colorize.can_colorize=saved_can_colorize\n for key,value in color_variables.items():\n if value is not None:\n os.environ[key]=value\n if clear_globs:\n test.globs.clear()\n import builtins\n builtins._=None\n \n \n \n \n def summarize(self,verbose=None):\n ''\n\n\n\n\n\n\n \n if verbose is None:\n verbose=self._verbose\n \n notests,passed,failed=[],[],[]\n total_tries=total_failures=total_skips=0\n \n for name,(failures,tries,skips)in self._stats.items():\n assert failures <=tries\n total_tries +=tries\n total_failures +=failures\n total_skips +=skips\n \n if tries ==0:\n notests.append(name)\n elif failures ==0:\n passed.append((name,tries))\n else:\n failed.append((name,(failures,tries,skips)))\n \n ansi=_colorize.get_colors()\n bold_green=ansi.BOLD_GREEN\n bold_red=ansi.BOLD_RED\n green=ansi.GREEN\n red=ansi.RED\n reset=ansi.RESET\n yellow=ansi.YELLOW\n \n if verbose:\n if notests:\n print(f\"{_n_items(notests)} had no tests:\")\n notests.sort()\n for name in notests:\n print(f\" {name}\")\n \n if passed:\n print(f\"{green}{_n_items(passed)} passed all tests:{reset}\")\n for name,count in sorted(passed):\n s=\"\"if count ==1 else \"s\"\n print(f\" {green}{count:3d} test{s} in {name}{reset}\")\n \n if failed:\n print(f\"{red}{self.DIVIDER}{reset}\")\n print(f\"{_n_items(failed)} had failures:\")\n for name,(failures,tries,skips)in sorted(failed):\n print(f\" {failures:3d} of {tries:3d} in {name}\")\n \n if verbose:\n s=\"\"if total_tries ==1 else \"s\"\n print(f\"{total_tries} test{s} in {_n_items(self._stats)}.\")\n \n and_f=(\n f\" and {red}{total_failures} failed{reset}\"\n if total_failures else \"\"\n )\n print(f\"{green}{total_tries -total_failures} passed{reset}{and_f}.\")\n \n if total_failures:\n s=\"\"if total_failures ==1 else \"s\"\n msg=f\"{bold_red}***Test Failed*** {total_failures} failure{s}{reset}\"\n if total_skips:\n s=\"\"if total_skips ==1 else \"s\"\n msg=f\"{msg} and {yellow}{total_skips} skipped test{s}{reset}\"\n print(f\"{msg}.\")\n elif verbose:\n print(f\"{bold_green}Test passed.{reset}\")\n \n return TestResults(total_failures,total_tries,skipped=total_skips)\n \n \n \n \n def merge(self,other):\n d=self._stats\n for name,(failures,tries,skips)in other._stats.items():\n if name in d:\n failures2,tries2,skips2=d[name]\n failures=failures+failures2\n tries=tries+tries2\n skips=skips+skips2\n d[name]=(failures,tries,skips)\n \n \ndef _n_items(items:list |dict)->str:\n ''\n\n \n n=len(items)\n s=\"\"if n ==1 else \"s\"\n return f\"{n} item{s}\"\n \n \nclass OutputChecker:\n ''\n\n\n\n\n\n \n def _toAscii(self,s):\n ''\n\n \n return str(s.encode('ASCII','backslashreplace'),\"ASCII\")\n \n def check_output(self,want,got,optionflags):\n ''\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n got=self._toAscii(got)\n want=self._toAscii(want)\n \n \n \n if got ==want:\n return True\n \n \n \n if not(optionflags&DONT_ACCEPT_TRUE_FOR_1):\n if(got,want)==(\"True\\n\",\"1\\n\"):\n return True\n if(got,want)==(\"False\\n\",\"0\\n\"):\n return True\n \n \n \n if not(optionflags&DONT_ACCEPT_BLANKLINE):\n \n want=re.sub(r'(?m)^%s\\s*?$'%re.escape(BLANKLINE_MARKER),\n '',want)\n \n \n got=re.sub(r'(?m)^[^\\S\\n]+$','',got)\n if got ==want:\n return True\n \n \n \n \n if optionflags&NORMALIZE_WHITESPACE:\n got=' '.join(got.split())\n want=' '.join(want.split())\n if got ==want:\n return True\n \n \n \n if optionflags&ELLIPSIS:\n if _ellipsis_match(want,got):\n return True\n \n \n return False\n \n \n def _do_a_fancy_diff(self,want,got,optionflags):\n \n if not optionflags&(REPORT_UDIFF |\n REPORT_CDIFF |\n REPORT_NDIFF):\n return False\n \n \n \n \n \n \n \n \n \n \n \n if optionflags&REPORT_NDIFF:\n return True\n \n \n return want.count('\\n')>2 and got.count('\\n')>2\n \n def output_difference(self,example,got,optionflags):\n ''\n\n\n\n\n \n want=example.want\n \n \n if not(optionflags&DONT_ACCEPT_BLANKLINE):\n got=re.sub('(?m)^[ ]*(?=\\n)',BLANKLINE_MARKER,got)\n \n \n if self._do_a_fancy_diff(want,got,optionflags):\n \n want_lines=want.splitlines(keepends=True)\n got_lines=got.splitlines(keepends=True)\n \n if optionflags&REPORT_UDIFF:\n diff=difflib.unified_diff(want_lines,got_lines,n=2)\n diff=list(diff)[2:]\n kind='unified diff with -expected +actual'\n elif optionflags&REPORT_CDIFF:\n diff=difflib.context_diff(want_lines,got_lines,n=2)\n diff=list(diff)[2:]\n kind='context diff with expected followed by actual'\n elif optionflags&REPORT_NDIFF:\n engine=difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)\n diff=list(engine.compare(want_lines,got_lines))\n kind='ndiff with -expected +actual'\n else:\n assert 0,'Bad diff option'\n return 'Differences (%s):\\n'%kind+_indent(''.join(diff))\n \n \n \n if want and got:\n return 'Expected:\\n%sGot:\\n%s'%(_indent(want),_indent(got))\n elif want:\n return 'Expected:\\n%sGot nothing\\n'%_indent(want)\n elif got:\n return 'Expected nothing\\nGot:\\n%s'%_indent(got)\n else:\n return 'Expected nothing\\nGot nothing\\n'\n \nclass DocTestFailure(Exception):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,test,example,got):\n self.test=test\n self.example=example\n self.got=got\n \n def __str__(self):\n return str(self.test)\n \nclass UnexpectedException(Exception):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,test,example,exc_info):\n self.test=test\n self.example=example\n self.exc_info=exc_info\n \n def __str__(self):\n return str(self.test)\n \nclass DebugRunner(DocTestRunner):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def run(self,test,compileflags=None,out=None,clear_globs=True):\n r=DocTestRunner.run(self,test,compileflags,out,False)\n if clear_globs:\n test.globs.clear()\n return r\n \n def report_unexpected_exception(self,out,test,example,exc_info):\n raise UnexpectedException(test,example,exc_info)\n \n def report_failure(self,out,test,example,got):\n raise DocTestFailure(test,example,got)\n \n \n \n \n \n \n \n \nmaster=None\n\ndef testmod(m=None,name=None,globs=None,verbose=None,\nreport=True,optionflags=0,extraglobs=None,\nraise_on_error=False,exclude_empty=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global master\n \n \n if m is None:\n \n \n \n m=sys.modules.get('__main__')\n \n \n if not inspect.ismodule(m):\n raise TypeError(\"testmod: module required; %r\"%(m,))\n \n \n if name is None:\n name=m.__name__\n \n \n finder=DocTestFinder(exclude_empty=exclude_empty)\n \n if raise_on_error:\n runner=DebugRunner(verbose=verbose,optionflags=optionflags)\n else:\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n \n for test in finder.find(m,name,globs=globs,extraglobs=extraglobs):\n runner.run(test)\n \n if report:\n runner.summarize()\n \n if master is None:\n master=runner\n else:\n master.merge(runner)\n \n return TestResults(runner.failures,runner.tries,skipped=runner.skips)\n \n \ndef testfile(filename,module_relative=True,name=None,package=None,\nglobs=None,verbose=None,report=True,optionflags=0,\nextraglobs=None,raise_on_error=False,parser=DocTestParser(),\nencoding=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global master\n \n if package and not module_relative:\n raise ValueError(\"Package may only be specified for module-\"\n \"relative paths.\")\n \n \n text,filename=_load_testfile(filename,package,module_relative,\n encoding or \"utf-8\")\n \n \n if name is None:\n name=os.path.basename(filename)\n \n \n if globs is None:\n globs={}\n else:\n globs=globs.copy()\n if extraglobs is not None:\n globs.update(extraglobs)\n if '__name__'not in globs:\n globs['__name__']='__main__'\n \n if raise_on_error:\n runner=DebugRunner(verbose=verbose,optionflags=optionflags)\n else:\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n \n \n test=parser.get_doctest(text,globs,name,filename,0)\n runner.run(test)\n \n if report:\n runner.summarize()\n \n if master is None:\n master=runner\n else:\n master.merge(runner)\n \n return TestResults(runner.failures,runner.tries,skipped=runner.skips)\n \n \ndef run_docstring_examples(f,globs,verbose=False,name=\"NoName\",\ncompileflags=None,optionflags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n finder=DocTestFinder(verbose=verbose,recurse=False)\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n for test in finder.find(f,name,globs=globs):\n runner.run(test,compileflags=compileflags)\n \n \n \n \n \n_unittest_reportflags=0\n\ndef set_unittest_reportflags(flags):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _unittest_reportflags\n \n if(flags&REPORTING_FLAGS)!=flags:\n raise ValueError(\"Only reporting flags allowed\",flags)\n old=_unittest_reportflags\n _unittest_reportflags=flags\n return old\n \n \nclass DocTestCase(unittest.TestCase):\n\n def __init__(self,test,optionflags=0,setUp=None,tearDown=None,\n checker=None):\n \n unittest.TestCase.__init__(self)\n self._dt_optionflags=optionflags\n self._dt_checker=checker\n self._dt_test=test\n self._dt_setUp=setUp\n self._dt_tearDown=tearDown\n \n def setUp(self):\n test=self._dt_test\n self._dt_globs=test.globs.copy()\n \n if self._dt_setUp is not None:\n self._dt_setUp(test)\n \n def tearDown(self):\n test=self._dt_test\n \n if self._dt_tearDown is not None:\n self._dt_tearDown(test)\n \n \n test.globs.clear()\n test.globs.update(self._dt_globs)\n \n def runTest(self):\n test=self._dt_test\n old=sys.stdout\n new=StringIO()\n optionflags=self._dt_optionflags\n \n if not(optionflags&REPORTING_FLAGS):\n \n \n optionflags |=_unittest_reportflags\n \n runner=DocTestRunner(optionflags=optionflags,\n checker=self._dt_checker,verbose=False)\n \n try:\n runner.DIVIDER=\"-\"*70\n results=runner.run(test,out=new.write,clear_globs=False)\n if results.skipped ==results.attempted:\n raise unittest.SkipTest(\"all examples were skipped\")\n finally:\n sys.stdout=old\n \n if results.failed:\n raise self.failureException(self.format_failure(new.getvalue()))\n \n def format_failure(self,err):\n test=self._dt_test\n if test.lineno is None:\n lineno='unknown line number'\n else:\n lineno='%s'%test.lineno\n lname='.'.join(test.name.split('.')[-1:])\n return('Failed doctest test for %s\\n'\n ' File \"%s\", line %s, in %s\\n\\n%s'\n %(test.name,test.filename,lineno,lname,err)\n )\n \n def debug(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.setUp()\n runner=DebugRunner(optionflags=self._dt_optionflags,\n checker=self._dt_checker,verbose=False)\n runner.run(self._dt_test,clear_globs=False)\n self.tearDown()\n \n def id(self):\n return self._dt_test.name\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self._dt_test ==other._dt_test and\\\n self._dt_optionflags ==other._dt_optionflags and\\\n self._dt_setUp ==other._dt_setUp and\\\n self._dt_tearDown ==other._dt_tearDown and\\\n self._dt_checker ==other._dt_checker\n \n def __hash__(self):\n return hash((self._dt_optionflags,self._dt_setUp,self._dt_tearDown,\n self._dt_checker))\n \n def __repr__(self):\n name=self._dt_test.name.split('.')\n return \"%s (%s)\"%(name[-1],'.'.join(name[:-1]))\n \n __str__=object.__str__\n \n def shortDescription(self):\n return \"Doctest: \"+self._dt_test.name\n \nclass SkipDocTestCase(DocTestCase):\n def __init__(self,module):\n self.module=module\n DocTestCase.__init__(self,None)\n \n def setUp(self):\n self.skipTest(\"DocTestSuite will not work with -O2 and above\")\n \n def test_skip(self):\n pass\n \n def shortDescription(self):\n return \"Skipping tests from %s\"%self.module.__name__\n \n __str__=shortDescription\n \n \nclass _DocTestSuite(unittest.TestSuite):\n\n def _removeTestAtIndex(self,index):\n pass\n \n \ndef DocTestSuite(module=None,globs=None,extraglobs=None,test_finder=None,\n**options):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if test_finder is None:\n test_finder=DocTestFinder()\n \n module=_normalize_module(module)\n tests=test_finder.find(module,globs=globs,extraglobs=extraglobs)\n \n if not tests and sys.flags.optimize >=2:\n \n suite=_DocTestSuite()\n suite.addTest(SkipDocTestCase(module))\n return suite\n \n tests.sort()\n suite=_DocTestSuite()\n \n for test in tests:\n if len(test.examples)==0:\n continue\n if not test.filename:\n filename=module.__file__\n if filename[-4:]==\".pyc\":\n filename=filename[:-1]\n test.filename=filename\n suite.addTest(DocTestCase(test,**options))\n \n return suite\n \nclass DocFileCase(DocTestCase):\n\n def id(self):\n return '_'.join(self._dt_test.name.split('.'))\n \n def __repr__(self):\n return self._dt_test.filename\n \n def format_failure(self,err):\n return('Failed doctest test for %s\\n File \"%s\", line 0\\n\\n%s'\n %(self._dt_test.name,self._dt_test.filename,err)\n )\n \ndef DocFileTest(path,module_relative=True,package=None,\nglobs=None,parser=DocTestParser(),\nencoding=None,**options):\n if globs is None:\n globs={}\n else:\n globs=globs.copy()\n \n if package and not module_relative:\n raise ValueError(\"Package may only be specified for module-\"\n \"relative paths.\")\n \n \n doc,path=_load_testfile(path,package,module_relative,\n encoding or \"utf-8\")\n \n if \"__file__\"not in globs:\n globs[\"__file__\"]=path\n \n \n name=os.path.basename(path)\n \n \n test=parser.get_doctest(doc,globs,name,path,0)\n return DocFileCase(test,**options)\n \ndef DocFileSuite(*paths,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n suite=_DocTestSuite()\n \n \n \n \n if kw.get('module_relative',True):\n kw['package']=_normalize_module(kw.get('package'))\n \n for path in paths:\n suite.addTest(DocFileTest(path,**kw))\n \n return suite\n \n \n \n \n \ndef script_from_examples(s):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n output=[]\n for piece in DocTestParser().parse(s):\n if isinstance(piece,Example):\n \n output.append(piece.source[:-1])\n \n want=piece.want\n if want:\n output.append('# Expected:')\n output +=['## '+l for l in want.split('\\n')[:-1]]\n else:\n \n output +=[_comment_line(l)\n for l in piece.split('\\n')[:-1]]\n \n \n while output and output[-1]=='#':\n output.pop()\n while output and output[0]=='#':\n output.pop(0)\n \n \n return '\\n'.join(output)+'\\n'\n \ndef testsource(module,name):\n ''\n\n\n\n\n \n module=_normalize_module(module)\n tests=DocTestFinder().find(module)\n test=[t for t in tests if t.name ==name]\n if not test:\n raise ValueError(name,\"not found in tests\")\n test=test[0]\n testsrc=script_from_examples(test.docstring)\n return testsrc\n \ndef debug_src(src,pm=False,globs=None):\n ''\n testsrc=script_from_examples(src)\n debug_script(testsrc,pm,globs)\n \ndef debug_script(src,pm=False,globs=None):\n ''\n import pdb\n \n if globs:\n globs=globs.copy()\n else:\n globs={}\n \n if pm:\n try:\n exec(src,globs,globs)\n except:\n print(sys.exc_info()[1])\n p=pdb.Pdb(nosigint=True)\n p.reset()\n p.interaction(None,sys.exc_info()[2])\n else:\n pdb.Pdb(nosigint=True).run(\"exec(%r)\"%src,globs,globs)\n \ndef debug(module,name,pm=False):\n ''\n\n\n\n\n \n module=_normalize_module(module)\n testsrc=testsource(module,name)\n debug_script(testsrc,pm,module.__dict__)\n \n \n \n \nclass _TestClass:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,val):\n ''\n\n\n\n\n \n \n self.val=val\n \n def square(self):\n ''\n\n\n\n \n \n self.val=self.val **2\n return self\n \n def get(self):\n ''\n\n\n\n\n \n \n return self.val\n \n__test__={\"_TestClass\":_TestClass,\n\"string\":r\"\"\"\n Example of a string object, searched as-is.\n >>> x = 1; y = 2\n >>> x + y, x * y\n (3, 2)\n \"\"\",\n\n\"bool-int equivalence\":r\"\"\"\n In 2.2, boolean expressions displayed\n 0 or 1. By default, we still accept\n them. This can be disabled by passing\n DONT_ACCEPT_TRUE_FOR_1 to the new\n optionflags argument.\n >>> 4 == 4\n 1\n >>> 4 == 4\n True\n >>> 4 > 4\n 0\n >>> 4 > 4\n False\n \"\"\",\n\n\"blank lines\":r\"\"\"\n Blank lines can be marked with :\n >>> print('foo\\n\\nbar\\n')\n foo\n \n bar\n \n \"\"\",\n\n\"ellipsis\":r\"\"\"\n If the ellipsis flag is used, then '...' can be used to\n elide substrings in the desired output:\n >>> print(list(range(1000))) #doctest: +ELLIPSIS\n [0, 1, 2, ..., 999]\n \"\"\",\n\n\"whitespace normalization\":r\"\"\"\n If the whitespace normalization flag is used, then\n differences in whitespace are ignored.\n >>> print(list(range(30))) #doctest: +NORMALIZE_WHITESPACE\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n 27, 28, 29]\n \"\"\",\n}\n\n\ndef _test():\n import argparse\n \n parser=argparse.ArgumentParser(description=\"doctest runner\")\n parser.add_argument('-v','--verbose',action='store_true',default=False,\n help='print very verbose output for all tests')\n parser.add_argument('-o','--option',action='append',\n choices=OPTIONFLAGS_BY_NAME.keys(),default=[],\n help=('specify a doctest option flag to apply'\n ' to the test run; may be specified more'\n ' than once to apply multiple options'))\n parser.add_argument('-f','--fail-fast',action='store_true',\n help=('stop running tests after first failure (this'\n ' is a shorthand for -o FAIL_FAST, and is'\n ' in addition to any other -o options)'))\n parser.add_argument('file',nargs='+',\n help='file containing the tests to run')\n args=parser.parse_args()\n testfiles=args.file\n \n \n verbose=args.verbose\n options=0\n for option in args.option:\n options |=OPTIONFLAGS_BY_NAME[option]\n if args.fail_fast:\n options |=FAIL_FAST\n for filename in testfiles:\n if filename.endswith(\".py\"):\n \n \n \n dirname,filename=os.path.split(filename)\n sys.path.insert(0,dirname)\n m=__import__(filename[:-3])\n del sys.path[0]\n failures,_=testmod(m,verbose=verbose,optionflags=options)\n else:\n failures,_=testfile(filename,module_relative=False,\n verbose=verbose,optionflags=options)\n if failures:\n return 1\n return 0\n \n \nif __name__ ==\"__main__\":\n sys.exit(_test())\n", ["__future__", "_colorize", "argparse", "builtins", "collections", "difflib", "inspect", "io", "linecache", "os", "pdb", "re", "sys", "traceback", "unittest"]], "enum": [".py", "import sys\nimport builtins as bltns\nfrom types import MappingProxyType,DynamicClassAttribute\n\n\n__all__=[\n'EnumType','EnumMeta','EnumDict',\n'Enum','IntEnum','StrEnum','Flag','IntFlag','ReprEnum',\n'auto','unique','property','verify','member','nonmember',\n'FlagBoundary','STRICT','CONFORM','EJECT','KEEP',\n'global_flag_repr','global_enum_repr','global_str','global_enum',\n'EnumCheck','CONTINUOUS','NAMED_FLAGS','UNIQUE',\n'pickle_by_global_name','pickle_by_enum_name',\n]\n\n\n\n\n\nEnum=Flag=EJECT=_stdlib_enums=ReprEnum=None\n\nclass nonmember(object):\n ''\n\n \n def __init__(self,value):\n self.value=value\n \nclass member(object):\n ''\n\n \n def __init__(self,value):\n self.value=value\n \ndef _is_descriptor(obj):\n ''\n\n \n return(\n hasattr(obj,'__get__')or\n hasattr(obj,'__set__')or\n hasattr(obj,'__delete__')\n )\n \ndef _is_dunder(name):\n ''\n\n \n return(\n len(name)>4 and\n name[:2]==name[-2:]=='__'and\n name[2]!='_'and\n name[-3]!='_'\n )\n \ndef _is_sunder(name):\n ''\n\n \n return(\n len(name)>2 and\n name[0]==name[-1]=='_'and\n name[1]!='_'and\n name[-2]!='_'\n )\n \ndef _is_internal_class(cls_name,obj):\n\n if not isinstance(obj,type):\n return False\n qualname=getattr(obj,'__qualname__','')\n s_pattern=cls_name+'.'+getattr(obj,'__name__','')\n e_pattern='.'+s_pattern\n return qualname ==s_pattern or qualname.endswith(e_pattern)\n \ndef _is_private(cls_name,name):\n\n pattern='_%s__'%(cls_name,)\n pat_len=len(pattern)\n if(\n len(name)>pat_len\n and name.startswith(pattern)\n and(name[-1]!='_'or name[-2]!='_')\n ):\n return True\n else:\n return False\n \ndef _is_single_bit(num):\n ''\n\n \n if num ==0:\n return False\n num &=num -1\n return num ==0\n \ndef _make_class_unpicklable(obj):\n ''\n\n\n\n \n def _break_on_call_reduce(self,proto):\n raise TypeError('%r cannot be pickled'%self)\n if isinstance(obj,dict):\n obj['__reduce_ex__']=_break_on_call_reduce\n obj['__module__']=''\n else:\n setattr(obj,'__reduce_ex__',_break_on_call_reduce)\n setattr(obj,'__module__','')\n \ndef _iter_bits_lsb(num):\n\n original=num\n if isinstance(num,Enum):\n num=num.value\n if num <0:\n raise ValueError('%r is not a positive integer'%original)\n while num:\n b=num&(~num+1)\n yield b\n num ^=b\n \ndef show_flag_values(value):\n return list(_iter_bits_lsb(value))\n \ndef bin(num,max_bits=None):\n ''\n\n\n\n\n\n\n\n\n \n \n ceiling=2 **(num).bit_length()\n if num >=0:\n s=bltns.bin(num+ceiling).replace('1','0',1)\n else:\n s=bltns.bin(~num ^(ceiling -1)+ceiling)\n sign=s[:3]\n digits=s[3:]\n if max_bits is not None:\n if len(digits)')\n_not_given=_not_given()\n\nclass _auto_null:\n def __repr__(self):\n return '_auto_null'\n_auto_null=_auto_null()\n\nclass auto:\n ''\n\n \n def __init__(self,value=_auto_null):\n self.value=value\n \n def __repr__(self):\n return \"auto(%r)\"%self.value\n \nclass property(DynamicClassAttribute):\n ''\n\n\n\n\n\n \n \n member=None\n _attr_type=None\n _cls_type=None\n \n def __get__(self,instance,ownerclass=None):\n if instance is None:\n if self.member is not None:\n return self.member\n else:\n raise AttributeError(\n '%r has no attribute %r'%(ownerclass,self.name)\n )\n if self.fget is not None:\n \n return self.fget(instance)\n elif self._attr_type =='attr':\n \n return getattr(self._cls_type,self.name)\n elif self._attr_type =='desc':\n \n return getattr(instance._value_,self.name)\n \n try:\n return ownerclass._member_map_[self.name]\n except KeyError:\n raise AttributeError(\n '%r has no attribute %r'%(ownerclass,self.name)\n )from None\n \n def __set__(self,instance,value):\n if self.fset is not None:\n return self.fset(instance,value)\n raise AttributeError(\n \" cannot set attribute %r\"%(self.clsname,self.name)\n )\n \n def __delete__(self,instance):\n if self.fdel is not None:\n return self.fdel(instance)\n raise AttributeError(\n \" cannot delete attribute %r\"%(self.clsname,self.name)\n )\n \n def __set_name__(self,ownerclass,name):\n self.name=name\n self.clsname=ownerclass.__name__\n \n \nclass _proto_member:\n ''\n\n \n \n def __init__(self,value):\n self.value=value\n \n def __set_name__(self,enum_class,member_name):\n ''\n\n \n \n delattr(enum_class,member_name)\n \n value=self.value\n if not isinstance(value,tuple):\n args=(value,)\n else:\n args=value\n if enum_class._member_type_ is tuple:\n args=(args,)\n if not enum_class._use_args_:\n enum_member=enum_class._new_member_(enum_class)\n else:\n enum_member=enum_class._new_member_(enum_class,*args)\n if not hasattr(enum_member,'_value_'):\n if enum_class._member_type_ is object:\n enum_member._value_=value\n else:\n try:\n enum_member._value_=enum_class._member_type_(*args)\n except Exception as exc:\n new_exc=TypeError(\n '_value_ not set in __new__, unable to create it'\n )\n new_exc.__cause__=exc\n raise new_exc\n value=enum_member._value_\n enum_member._name_=member_name\n enum_member.__objclass__=enum_class\n enum_member.__init__(*args)\n enum_member._sort_order_=len(enum_class._member_names_)\n \n if Flag is not None and issubclass(enum_class,Flag):\n if isinstance(value,int):\n enum_class._flag_mask_ |=value\n if _is_single_bit(value):\n enum_class._singles_mask_ |=value\n enum_class._all_bits_=2 **((enum_class._flag_mask_).bit_length())-1\n \n \n \n try:\n try:\n \n enum_member=enum_class._value2member_map_[value]\n except TypeError:\n for name,canonical_member in enum_class._member_map_.items():\n if canonical_member._value_ ==value:\n enum_member=canonical_member\n break\n else:\n raise KeyError\n except KeyError:\n \n \n if(\n Flag is None\n or not issubclass(enum_class,Flag)\n ):\n \n enum_class._member_names_.append(member_name)\n elif(\n Flag is not None\n and issubclass(enum_class,Flag)\n and isinstance(value,int)\n and _is_single_bit(value)\n ):\n \n enum_class._member_names_.append(member_name)\n \n enum_class._add_member_(member_name,enum_member)\n try:\n \n \n \n enum_class._value2member_map_.setdefault(value,enum_member)\n except TypeError:\n \n enum_class._unhashable_values_.append(value)\n enum_class._unhashable_values_map_.setdefault(member_name,[]).append(value)\n \n \nclass EnumDict(dict):\n ''\n\n\n\n\n \n def __init__(self):\n super().__init__()\n self._member_names={}\n self._last_values=[]\n self._ignore=[]\n self._auto_called=False\n \n def __setitem__(self,key,value):\n ''\n\n\n\n\n\n\n \n if _is_private(self._cls_name,key):\n \n pass\n elif _is_sunder(key):\n if key not in(\n '_order_',\n '_generate_next_value_','_numeric_repr_','_missing_','_ignore_',\n '_iter_member_','_iter_member_by_value_','_iter_member_by_def_',\n '_add_alias_','_add_value_alias_',\n \n \n \n )and not key.startswith('_repr_'):\n raise ValueError(\n '_sunder_ names, such as %r, are reserved for future Enum use'\n %(key,)\n )\n if key =='_generate_next_value_':\n \n if self._auto_called:\n raise TypeError(\"_generate_next_value_ must be defined before members\")\n _gnv=value.__func__ if isinstance(value,staticmethod)else value\n setattr(self,'_generate_next_value',_gnv)\n elif key =='_ignore_':\n if isinstance(value,str):\n value=value.replace(',',' ').split()\n else:\n value=list(value)\n self._ignore=value\n already=set(value)&set(self._member_names)\n if already:\n raise ValueError(\n '_ignore_ cannot specify already set names: %r'\n %(already,)\n )\n elif _is_dunder(key):\n if key =='__order__':\n key='_order_'\n elif key in self._member_names:\n \n raise TypeError('%r already defined as %r'%(key,self[key]))\n elif key in self._ignore:\n pass\n elif isinstance(value,nonmember):\n \n value=value.value\n elif _is_descriptor(value):\n pass\n elif _is_internal_class(self._cls_name,value):\n \n pass\n else:\n if key in self:\n \n raise TypeError('%r already defined as %r'%(key,self[key]))\n elif isinstance(value,member):\n \n value=value.value\n non_auto_store=True\n single=False\n if isinstance(value,auto):\n single=True\n value=(value,)\n if isinstance(value,tuple)and any(isinstance(v,auto)for v in value):\n \n \n auto_valued=[]\n t=type(value)\n for v in value:\n if isinstance(v,auto):\n non_auto_store=False\n if v.value ==_auto_null:\n v.value=self._generate_next_value(\n key,1,len(self._member_names),self._last_values[:],\n )\n self._auto_called=True\n v=v.value\n self._last_values.append(v)\n auto_valued.append(v)\n if single:\n value=auto_valued[0]\n else:\n try:\n \n value=t(auto_valued)\n except TypeError:\n \n value=t(*auto_valued)\n self._member_names[key]=None\n if non_auto_store:\n self._last_values.append(value)\n super().__setitem__(key,value)\n \n @property\n def member_names(self):\n return list(self._member_names)\n \n def update(self,members,**more_members):\n try:\n for name in members.keys():\n self[name]=members[name]\n except AttributeError:\n for name,value in members:\n self[name]=value\n for name,value in more_members.items():\n self[name]=value\n \n_EnumDict=EnumDict\n\n\nclass EnumType(type):\n ''\n\n \n \n @classmethod\n def __prepare__(metacls,cls,bases,**kwds):\n \n metacls._check_for_existing_members_(cls,bases)\n \n enum_dict=EnumDict()\n enum_dict._cls_name=cls\n \n member_type,first_enum=metacls._get_mixins_(cls,bases)\n if first_enum is not None:\n enum_dict['_generate_next_value_']=getattr(\n first_enum,'_generate_next_value_',None,\n )\n return enum_dict\n \n def __new__(metacls,cls,bases,classdict,*,boundary=None,_simple=False,**kwds):\n \n \n \n \n \n if _simple:\n return super().__new__(metacls,cls,bases,classdict,**kwds)\n \n \n classdict.setdefault('_ignore_',[]).append('_ignore_')\n ignore=classdict['_ignore_']\n for key in ignore:\n classdict.pop(key,None)\n \n \n member_names=classdict._member_names\n \n \n invalid_names=set(member_names)&{'mro',''}\n if invalid_names:\n raise ValueError('invalid enum member name(s) %s'%(\n ','.join(repr(n)for n in invalid_names)\n ))\n \n \n _order_=classdict.pop('_order_',None)\n _gnv=classdict.get('_generate_next_value_')\n if _gnv is not None and type(_gnv)is not staticmethod:\n _gnv=staticmethod(_gnv)\n \n classdict=dict(classdict.items())\n if _gnv is not None:\n classdict['_generate_next_value_']=_gnv\n \n \n member_type,first_enum=metacls._get_mixins_(cls,bases)\n __new__,save_new,use_args=metacls._find_new_(\n classdict,member_type,first_enum,\n )\n classdict['_new_member_']=__new__\n classdict['_use_args_']=use_args\n \n \n for name in member_names:\n value=classdict[name]\n classdict[name]=_proto_member(value)\n \n \n classdict['_member_names_']=[]\n classdict['_member_map_']={}\n classdict['_value2member_map_']={}\n classdict['_unhashable_values_']=[]\n classdict['_unhashable_values_map_']={}\n classdict['_member_type_']=member_type\n \n classdict['_value_repr_']=metacls._find_data_repr_(cls,bases)\n \n \n classdict['_boundary_']=(\n boundary\n or getattr(first_enum,'_boundary_',None)\n )\n classdict['_flag_mask_']=0\n classdict['_singles_mask_']=0\n classdict['_all_bits_']=0\n classdict['_inverted_']=None\n try:\n exc=None\n classdict['_%s__in_progress'%cls]=True\n enum_class=super().__new__(metacls,cls,bases,classdict,**kwds)\n classdict['_%s__in_progress'%cls]=False\n delattr(enum_class,'_%s__in_progress'%cls)\n except Exception as e:\n \n \n \n exc=type(e)(str(e))\n exc.__cause__=e.__cause__\n exc.__context__=e.__context__\n tb=e.__traceback__\n if exc is not None:\n raise exc.with_traceback(tb)\n \n \n classdict.update(enum_class.__dict__)\n \n \n \n \n \n \n \n if ReprEnum is not None and ReprEnum in bases:\n if member_type is object:\n raise TypeError(\n 'ReprEnum subclasses must be mixed with a data type (i.e.'\n ' int, str, float, etc.)'\n )\n if '__format__'not in classdict:\n enum_class.__format__=member_type.__format__\n classdict['__format__']=enum_class.__format__\n if '__str__'not in classdict:\n method=member_type.__str__\n if method is object.__str__:\n \n \n method=member_type.__repr__\n enum_class.__str__=method\n classdict['__str__']=enum_class.__str__\n for name in('__repr__','__str__','__format__','__reduce_ex__'):\n if name not in classdict:\n \n enum_method=getattr(first_enum,name)\n found_method=getattr(enum_class,name)\n object_method=getattr(object,name)\n data_type_method=getattr(member_type,name)\n if found_method in(data_type_method,object_method):\n setattr(enum_class,name,enum_method)\n \n \n if Flag is not None and issubclass(enum_class,Flag):\n for name in(\n '__or__','__and__','__xor__',\n '__ror__','__rand__','__rxor__',\n '__invert__'\n ):\n if name not in classdict:\n enum_method=getattr(Flag,name)\n setattr(enum_class,name,enum_method)\n classdict[name]=enum_method\n \n \n \n if Enum is not None:\n \n \n if save_new:\n enum_class.__new_member__=__new__\n enum_class.__new__=Enum.__new__\n \n \n \n \n \n \n \n \n \n \n if _order_ is not None:\n if isinstance(_order_,str):\n _order_=_order_.replace(',',' ').split()\n \n \n if(\n Flag is None and cls !='Flag'\n or Flag is not None and not issubclass(enum_class,Flag)\n ):\n delattr(enum_class,'_boundary_')\n delattr(enum_class,'_flag_mask_')\n delattr(enum_class,'_singles_mask_')\n delattr(enum_class,'_all_bits_')\n delattr(enum_class,'_inverted_')\n elif Flag is not None and issubclass(enum_class,Flag):\n \n member_list=[m._value_ for m in enum_class]\n if member_list !=sorted(member_list):\n enum_class._iter_member_=enum_class._iter_member_by_def_\n if _order_:\n \n _order_=[\n o\n for o in _order_\n if o not in enum_class._member_map_ or _is_single_bit(enum_class[o]._value_)\n ]\n \n if _order_:\n \n _order_=[\n o\n for o in _order_\n if(\n o not in enum_class._member_map_\n or\n (o in enum_class._member_map_ and o in enum_class._member_names_)\n )]\n \n if _order_ !=enum_class._member_names_:\n raise TypeError(\n 'member order does not match _order_:\\n %r\\n %r'\n %(enum_class._member_names_,_order_)\n )\n \n return enum_class\n \n def __bool__(cls):\n ''\n\n \n return True\n \n def __call__(cls,value,names=_not_given,*values,module=None,qualname=None,type=None,start=1,boundary=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if cls._member_map_:\n \n if names is not _not_given:\n value=(value,names)+values\n return cls.__new__(cls,value)\n \n if names is _not_given and type is None:\n \n raise TypeError(\n f\"{cls} has no members; specify `names=()` if you meant to create a new, empty, enum\"\n )\n return cls._create_(\n class_name=value,\n names=None if names is _not_given else names,\n module=module,\n qualname=qualname,\n type=type,\n start=start,\n boundary=boundary,\n )\n \n def __contains__(cls,value):\n ''\n\n\n\n\n \n if isinstance(value,cls):\n return True\n try:\n return value in cls._value2member_map_\n except TypeError:\n return value in cls._unhashable_values_\n \n def __delattr__(cls,attr):\n \n \n if attr in cls._member_map_:\n raise AttributeError(\"%r cannot delete member %r.\"%(cls.__name__,attr))\n super().__delattr__(attr)\n \n def __dir__(cls):\n interesting=set([\n '__class__','__contains__','__doc__','__getitem__',\n '__iter__','__len__','__members__','__module__',\n '__name__','__qualname__',\n ]\n +cls._member_names_\n )\n if cls._new_member_ is not object.__new__:\n interesting.add('__new__')\n if cls.__init_subclass__ is not object.__init_subclass__:\n interesting.add('__init_subclass__')\n if cls._member_type_ is object:\n return sorted(interesting)\n else:\n \n return sorted(set(dir(cls._member_type_))|interesting)\n \n def __getitem__(cls,name):\n ''\n\n \n return cls._member_map_[name]\n \n def __iter__(cls):\n ''\n\n \n return(cls._member_map_[name]for name in cls._member_names_)\n \n def __len__(cls):\n ''\n\n \n return len(cls._member_names_)\n \n @bltns.property\n def __members__(cls):\n ''\n\n\n\n\n \n return MappingProxyType(cls._member_map_)\n \n def __repr__(cls):\n if Flag is not None and issubclass(cls,Flag):\n return \"\"%cls.__name__\n else:\n return \"\"%cls.__name__\n \n def __reversed__(cls):\n ''\n\n \n return(cls._member_map_[name]for name in reversed(cls._member_names_))\n \n def __setattr__(cls,name,value):\n ''\n\n\n\n\n\n \n member_map=cls.__dict__.get('_member_map_',{})\n if name in member_map:\n raise AttributeError('cannot reassign member %r'%(name,))\n super().__setattr__(name,value)\n \n def _create_(cls,class_name,names,*,module=None,qualname=None,type=None,start=1,boundary=None):\n ''\n\n\n\n\n\n\n\n\n\n \n metacls=cls.__class__\n bases=(cls,)if type is None else(type,cls)\n _,first_enum=cls._get_mixins_(class_name,bases)\n classdict=metacls.__prepare__(class_name,bases)\n \n \n if isinstance(names,str):\n names=names.replace(',',' ').split()\n if isinstance(names,(tuple,list))and names and isinstance(names[0],str):\n original_names,names=names,[]\n last_values=[]\n for count,name in enumerate(original_names):\n value=first_enum._generate_next_value_(name,start,count,last_values[:])\n last_values.append(value)\n names.append((name,value))\n if names is None:\n names=()\n \n \n for item in names:\n if isinstance(item,str):\n member_name,member_value=item,names[item]\n else:\n member_name,member_value=item\n classdict[member_name]=member_value\n \n if module is None:\n try:\n module=sys._getframemodulename(2)\n except AttributeError:\n \n try:\n module=sys._getframe(2).f_globals['__name__']\n except(AttributeError,ValueError,KeyError):\n pass\n if module is None:\n _make_class_unpicklable(classdict)\n else:\n classdict['__module__']=module\n if qualname is not None:\n classdict['__qualname__']=qualname\n \n return metacls.__new__(metacls,class_name,bases,classdict,boundary=boundary)\n \n def _convert_(cls,name,module,filter,source=None,*,boundary=None,as_global=False):\n ''\n\n \n \n \n \n \n \n module_globals=sys.modules[module].__dict__\n if source:\n source=source.__dict__\n else:\n source=module_globals\n \n \n \n members=[\n (name,value)\n for name,value in source.items()\n if filter(name)]\n try:\n \n members.sort(key=lambda t:(t[1],t[0]))\n except TypeError:\n \n members.sort(key=lambda t:t[0])\n body={t[0]:t[1]for t in members}\n body['__module__']=module\n tmp_cls=type(name,(object,),body)\n cls=_simple_enum(etype=cls,boundary=boundary or KEEP)(tmp_cls)\n if as_global:\n global_enum(cls)\n else:\n sys.modules[cls.__module__].__dict__.update(cls.__members__)\n module_globals[name]=cls\n return cls\n \n @classmethod\n def _check_for_existing_members_(mcls,class_name,bases):\n for chain in bases:\n for base in chain.__mro__:\n if isinstance(base,EnumType)and base._member_names_:\n raise TypeError(\n \" cannot extend %r\"\n %(class_name,base)\n )\n \n @classmethod\n def _get_mixins_(mcls,class_name,bases):\n ''\n\n\n\n\n \n if not bases:\n return object,Enum\n \n \n first_enum=bases[-1]\n if not isinstance(first_enum,EnumType):\n raise TypeError(\"new enumerations should be created as \"\n \"`EnumName([mixin_type, ...] [data_type,] enum_type)`\")\n member_type=mcls._find_data_type_(class_name,bases)or object\n return member_type,first_enum\n \n @classmethod\n def _find_data_repr_(mcls,class_name,bases):\n for chain in bases:\n for base in chain.__mro__:\n if base is object:\n continue\n elif isinstance(base,EnumType):\n \n return base._value_repr_\n elif '__repr__'in base.__dict__:\n \n \n if(\n '__dataclass_fields__'in base.__dict__\n and '__dataclass_params__'in base.__dict__\n and base.__dict__['__dataclass_params__'].repr\n ):\n return _dataclass_repr\n else:\n return base.__dict__['__repr__']\n return None\n \n @classmethod\n def _find_data_type_(mcls,class_name,bases):\n \n data_types=set()\n base_chain=set()\n for chain in bases:\n candidate=None\n for base in chain.__mro__:\n base_chain.add(base)\n if base is object:\n continue\n elif isinstance(base,EnumType):\n if base._member_type_ is not object:\n data_types.add(base._member_type_)\n break\n elif '__new__'in base.__dict__ or '__dataclass_fields__'in base.__dict__:\n data_types.add(candidate or base)\n break\n else:\n candidate=candidate or base\n if len(data_types)>1:\n raise TypeError('too many data types for %r: %r'%(class_name,data_types))\n elif data_types:\n return data_types.pop()\n else:\n return None\n \n @classmethod\n def _find_new_(mcls,classdict,member_type,first_enum):\n ''\n\n\n\n\n\n \n \n \n \n __new__=classdict.get('__new__',None)\n \n \n save_new=first_enum is not None and __new__ is not None\n \n if __new__ is None:\n \n \n for method in('__new_member__','__new__'):\n for possible in(member_type,first_enum):\n target=getattr(possible,method,None)\n if target not in{\n None,\n None.__new__,\n object.__new__,\n Enum.__new__,\n }:\n __new__=target\n break\n if __new__ is not None:\n break\n else:\n __new__=object.__new__\n \n \n \n \n if first_enum is None or __new__ in(Enum.__new__,object.__new__):\n use_args=False\n else:\n use_args=True\n return __new__,save_new,use_args\n \n def _add_member_(cls,name,member):\n \n if name in cls._member_map_:\n if cls._member_map_[name]is not member:\n raise NameError('%r is already bound: %r'%(name,cls._member_map_[name]))\n return\n \n \n found_descriptor=None\n descriptor_type=None\n class_type=None\n for base in cls.__mro__[1:]:\n attr=base.__dict__.get(name)\n if attr is not None:\n if isinstance(attr,(property,DynamicClassAttribute)):\n found_descriptor=attr\n class_type=base\n descriptor_type='enum'\n break\n elif _is_descriptor(attr):\n found_descriptor=attr\n descriptor_type=descriptor_type or 'desc'\n class_type=class_type or base\n continue\n else:\n descriptor_type='attr'\n class_type=base\n if found_descriptor:\n redirect=property()\n redirect.member=member\n redirect.__set_name__(cls,name)\n if descriptor_type in('enum','desc'):\n \n redirect.fget=getattr(found_descriptor,'fget',None)\n redirect._get=getattr(found_descriptor,'__get__',None)\n redirect.fset=getattr(found_descriptor,'fset',None)\n redirect._set=getattr(found_descriptor,'__set__',None)\n redirect.fdel=getattr(found_descriptor,'fdel',None)\n redirect._del=getattr(found_descriptor,'__delete__',None)\n redirect._attr_type=descriptor_type\n redirect._cls_type=class_type\n setattr(cls,name,redirect)\n else:\n setattr(cls,name,member)\n \n cls._member_map_[name]=member\n \nEnumMeta=EnumType\n\n\nclass Enum(metaclass=EnumType):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n @classmethod\n def __signature__(cls):\n if cls._member_names_:\n return '(*values)'\n else:\n return '(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)'\n \n def __new__(cls,value):\n \n \n \n if type(value)is cls:\n \n return value\n \n \n try:\n return cls._value2member_map_[value]\n except KeyError:\n \n pass\n except TypeError:\n \n for name,values in cls._unhashable_values_map_.items():\n if value in values:\n return cls[name]\n \n \n if not cls._member_map_:\n if getattr(cls,'_%s__in_progress'%cls.__name__,False):\n raise TypeError('do not use `super().__new__; call the appropriate __new__ directly')from None\n raise TypeError(\"%r has no members defined\"%cls)\n \n \n try:\n exc=None\n result=cls._missing_(value)\n except Exception as e:\n exc=e\n result=None\n try:\n if isinstance(result,cls):\n return result\n elif(\n Flag is not None and issubclass(cls,Flag)\n and cls._boundary_ is EJECT and isinstance(result,int)\n ):\n return result\n else:\n ve_exc=ValueError(\"%r is not a valid %s\"%(value,cls.__qualname__))\n if result is None and exc is None:\n raise ve_exc\n elif exc is None:\n exc=TypeError(\n 'error in %s._missing_: returned %r instead of None or a valid member'\n %(cls.__name__,result)\n )\n if not isinstance(exc,ValueError):\n exc.__context__=ve_exc\n raise exc\n finally:\n \n exc=None\n ve_exc=None\n \n def __init__(self,*args,**kwds):\n pass\n \n def _add_alias_(self,name):\n self.__class__._add_member_(name,self)\n \n def _add_value_alias_(self,value):\n cls=self.__class__\n try:\n if value in cls._value2member_map_:\n if cls._value2member_map_[value]is not self:\n raise ValueError('%r is already bound: %r'%(value,cls._value2member_map_[value]))\n return\n except TypeError:\n \n for m in cls._member_map_.values():\n if m._value_ ==value:\n if m is not self:\n raise ValueError('%r is already bound: %r'%(value,cls._value2member_map_[value]))\n return\n try:\n \n \n \n cls._value2member_map_.setdefault(value,self)\n except TypeError:\n \n cls._unhashable_values_.append(value)\n cls._unhashable_values_map_.setdefault(self.name,[]).append(value)\n \n @staticmethod\n def _generate_next_value_(name,start,count,last_values):\n ''\n\n\n\n\n\n\n \n if not last_values:\n return start\n try:\n last_value=sorted(last_values).pop()\n except TypeError:\n raise TypeError('unable to sort non-numeric values')from None\n try:\n return last_value+1\n except TypeError:\n raise TypeError('unable to increment %r'%(last_value,))from None\n \n @classmethod\n def _missing_(cls,value):\n return None\n \n def __repr__(self):\n v_repr=self.__class__._value_repr_ or repr\n return \"<%s.%s: %s>\"%(self.__class__.__name__,self._name_,v_repr(self._value_))\n \n def __str__(self):\n return \"%s.%s\"%(self.__class__.__name__,self._name_,)\n \n def __dir__(self):\n ''\n\n \n interesting=set()\n if self.__class__._member_type_ is not object:\n interesting=set(object.__dir__(self))\n for name in getattr(self,'__dict__',[]):\n if name[0]!='_'and name not in self._member_map_:\n interesting.add(name)\n for cls in self.__class__.mro():\n for name,obj in cls.__dict__.items():\n if name[0]=='_':\n continue\n if isinstance(obj,property):\n \n if obj.fget is not None or name not in self._member_map_:\n interesting.add(name)\n else:\n \n interesting.discard(name)\n elif name not in self._member_map_:\n interesting.add(name)\n names=sorted(\n set(['__class__','__doc__','__eq__','__hash__','__module__'])\n |interesting\n )\n return names\n \n def __format__(self,format_spec):\n return str.__format__(str(self),format_spec)\n \n def __hash__(self):\n return hash(self._name_)\n \n def __reduce_ex__(self,proto):\n return self.__class__,(self._value_,)\n \n def __deepcopy__(self,memo):\n return self\n \n def __copy__(self):\n return self\n \n \n \n \n \n \n \n \n \n @property\n def name(self):\n ''\n return self._name_\n \n @property\n def value(self):\n ''\n return self._value_\n \n \nclass ReprEnum(Enum):\n ''\n\n \n \n \nclass IntEnum(int,ReprEnum):\n ''\n\n \n \n \nclass StrEnum(str,ReprEnum):\n ''\n\n \n \n def __new__(cls,*values):\n ''\n if len(values)>3:\n raise TypeError('too many arguments for str(): %r'%(values,))\n if len(values)==1:\n \n if not isinstance(values[0],str):\n raise TypeError('%r is not a string'%(values[0],))\n if len(values)>=2:\n \n if not isinstance(values[1],str):\n raise TypeError('encoding must be a string, not %r'%(values[1],))\n if len(values)==3:\n \n if not isinstance(values[2],str):\n raise TypeError('errors must be a string, not %r'%(values[2]))\n value=str(*values)\n member=str.__new__(cls,value)\n member._value_=value\n return member\n \n @staticmethod\n def _generate_next_value_(name,start,count,last_values):\n ''\n\n \n return name.lower()\n \n \ndef pickle_by_global_name(self,proto):\n\n return self.name\n_reduce_ex_by_global_name=pickle_by_global_name\n\ndef pickle_by_enum_name(self,proto):\n\n return getattr,(self.__class__,self._name_)\n \nclass FlagBoundary(StrEnum):\n ''\n\n\n\n\n\n \n STRICT=auto()\n CONFORM=auto()\n EJECT=auto()\n KEEP=auto()\nSTRICT,CONFORM,EJECT,KEEP=FlagBoundary\n\n\nclass Flag(Enum,boundary=STRICT):\n ''\n\n \n \n _numeric_repr_=repr\n \n @staticmethod\n def _generate_next_value_(name,start,count,last_values):\n ''\n\n\n\n\n\n\n \n if not count:\n return start if start is not None else 1\n last_value=max(last_values)\n try:\n high_bit=_high_bit(last_value)\n except Exception:\n raise TypeError('invalid flag value %r'%last_value)from None\n return 2 **(high_bit+1)\n \n @classmethod\n def _iter_member_by_value_(cls,value):\n ''\n\n \n for val in _iter_bits_lsb(value&cls._flag_mask_):\n yield cls._value2member_map_.get(val)\n \n _iter_member_=_iter_member_by_value_\n \n @classmethod\n def _iter_member_by_def_(cls,value):\n ''\n\n \n yield from sorted(\n cls._iter_member_by_value_(value),\n key=lambda m:m._sort_order_,\n )\n \n @classmethod\n def _missing_(cls,value):\n ''\n\n\n\n \n if not isinstance(value,int):\n raise ValueError(\n \"%r is not a valid %s\"%(value,cls.__qualname__)\n )\n \n \n \n \n flag_mask=cls._flag_mask_\n singles_mask=cls._singles_mask_\n all_bits=cls._all_bits_\n neg_value=None\n if(\n not ~all_bits <=value <=all_bits\n or value&(all_bits ^flag_mask)\n ):\n if cls._boundary_ is STRICT:\n max_bits=max(value.bit_length(),flag_mask.bit_length())\n raise ValueError(\n \"%r invalid value %r\\n given %s\\n allowed %s\"%(\n cls,value,bin(value,max_bits),bin(flag_mask,max_bits),\n ))\n elif cls._boundary_ is CONFORM:\n value=value&flag_mask\n elif cls._boundary_ is EJECT:\n return value\n elif cls._boundary_ is KEEP:\n if value <0:\n value=(\n max(all_bits+1,2 **(value.bit_length()))\n +value\n )\n else:\n raise ValueError(\n '%r unknown flag boundary %r'%(cls,cls._boundary_,)\n )\n if value <0:\n neg_value=value\n value=all_bits+1+value\n \n unknown=value&~flag_mask\n aliases=value&~singles_mask\n member_value=value&singles_mask\n if unknown and cls._boundary_ is not KEEP:\n raise ValueError(\n '%s(%r) --> unknown values %r [%s]'\n %(cls.__name__,value,unknown,bin(unknown))\n )\n \n if cls._member_type_ is object:\n \n pseudo_member=object.__new__(cls)\n else:\n pseudo_member=cls._member_type_.__new__(cls,value)\n if not hasattr(pseudo_member,'_value_'):\n pseudo_member._value_=value\n if member_value or aliases:\n members=[]\n combined_value=0\n for m in cls._iter_member_(member_value):\n members.append(m)\n combined_value |=m._value_\n if aliases:\n value=member_value |aliases\n for n,pm in cls._member_map_.items():\n if pm not in members and pm._value_ and pm._value_&value ==pm._value_:\n members.append(pm)\n combined_value |=pm._value_\n unknown=value ^combined_value\n pseudo_member._name_='|'.join([m._name_ for m in members])\n if not combined_value:\n pseudo_member._name_=None\n elif unknown and cls._boundary_ is STRICT:\n raise ValueError('%r: no members with value %r'%(cls,unknown))\n elif unknown:\n pseudo_member._name_ +='|%s'%cls._numeric_repr_(unknown)\n else:\n pseudo_member._name_=None\n \n \n \n pseudo_member=cls._value2member_map_.setdefault(value,pseudo_member)\n if neg_value is not None:\n cls._value2member_map_[neg_value]=pseudo_member\n return pseudo_member\n \n def __contains__(self,other):\n ''\n\n \n if not isinstance(other,self.__class__):\n raise TypeError(\n \"unsupported operand type(s) for 'in': %r and %r\"%(\n type(other).__qualname__,self.__class__.__qualname__))\n return other._value_&self._value_ ==other._value_\n \n def __iter__(self):\n ''\n\n \n yield from self._iter_member_(self._value_)\n \n def __len__(self):\n return self._value_.bit_count()\n \n def __repr__(self):\n cls_name=self.__class__.__name__\n v_repr=self.__class__._value_repr_ or repr\n if self._name_ is None:\n return \"<%s: %s>\"%(cls_name,v_repr(self._value_))\n else:\n return \"<%s.%s: %s>\"%(cls_name,self._name_,v_repr(self._value_))\n \n def __str__(self):\n cls_name=self.__class__.__name__\n if self._name_ is None:\n return '%s(%r)'%(cls_name,self._value_)\n else:\n return \"%s.%s\"%(cls_name,self._name_)\n \n def __bool__(self):\n return bool(self._value_)\n \n def _get_value(self,flag):\n if isinstance(flag,self.__class__):\n return flag._value_\n elif self._member_type_ is not object and isinstance(flag,self._member_type_):\n return flag\n return NotImplemented\n \n def __or__(self,other):\n other_value=self._get_value(other)\n if other_value is NotImplemented:\n return NotImplemented\n \n for flag in self,other:\n if self._get_value(flag)is None:\n raise TypeError(f\"'{flag}' cannot be combined with other flags with |\")\n value=self._value_\n return self.__class__(value |other_value)\n \n def __and__(self,other):\n other_value=self._get_value(other)\n if other_value is NotImplemented:\n return NotImplemented\n \n for flag in self,other:\n if self._get_value(flag)is None:\n raise TypeError(f\"'{flag}' cannot be combined with other flags with &\")\n value=self._value_\n return self.__class__(value&other_value)\n \n def __xor__(self,other):\n other_value=self._get_value(other)\n if other_value is NotImplemented:\n return NotImplemented\n \n for flag in self,other:\n if self._get_value(flag)is None:\n raise TypeError(f\"'{flag}' cannot be combined with other flags with ^\")\n value=self._value_\n return self.__class__(value ^other_value)\n \n def __invert__(self):\n if self._get_value(self)is None:\n raise TypeError(f\"'{self}' cannot be inverted\")\n \n if self._inverted_ is None:\n if self._boundary_ in(EJECT,KEEP):\n self._inverted_=self.__class__(~self._value_)\n else:\n self._inverted_=self.__class__(self._singles_mask_&~self._value_)\n return self._inverted_\n \n __rand__=__and__\n __ror__=__or__\n __rxor__=__xor__\n \n \nclass IntFlag(int,ReprEnum,Flag,boundary=KEEP):\n ''\n\n \n \n \ndef _high_bit(value):\n ''\n\n \n return value.bit_length()-1\n \ndef unique(enumeration):\n ''\n\n \n duplicates=[]\n for name,member in enumeration.__members__.items():\n if name !=member.name:\n duplicates.append((name,member.name))\n if duplicates:\n alias_details=', '.join(\n [\"%s -> %s\"%(alias,name)for(alias,name)in duplicates])\n raise ValueError('duplicate values found in %r: %s'%\n (enumeration,alias_details))\n return enumeration\n \ndef _dataclass_repr(self):\n dcf=self.__dataclass_fields__\n return ', '.join(\n '%s=%r'%(k,getattr(self,k))\n for k in dcf.keys()\n if dcf[k].repr\n )\n \ndef global_enum_repr(self):\n ''\n\n\n\n \n module=self.__class__.__module__.split('.')[-1]\n return '%s.%s'%(module,self._name_)\n \ndef global_flag_repr(self):\n ''\n\n\n\n \n module=self.__class__.__module__.split('.')[-1]\n cls_name=self.__class__.__name__\n if self._name_ is None:\n return \"%s.%s(%r)\"%(module,cls_name,self._value_)\n if _is_single_bit(self._value_):\n return '%s.%s'%(module,self._name_)\n if self._boundary_ is not FlagBoundary.KEEP:\n return '|'.join(['%s.%s'%(module,name)for name in self.name.split('|')])\n else:\n name=[]\n for n in self._name_.split('|'):\n if n[0].isdigit():\n name.append(n)\n else:\n name.append('%s.%s'%(module,n))\n return '|'.join(name)\n \ndef global_str(self):\n ''\n\n \n if self._name_ is None:\n cls_name=self.__class__.__name__\n return \"%s(%r)\"%(cls_name,self._value_)\n else:\n return self._name_\n \ndef global_enum(cls,update_str=False):\n ''\n\n\n\n \n if issubclass(cls,Flag):\n cls.__repr__=global_flag_repr\n else:\n cls.__repr__=global_enum_repr\n if not issubclass(cls,ReprEnum)or update_str:\n cls.__str__=global_str\n sys.modules[cls.__module__].__dict__.update(cls.__members__)\n return cls\n \ndef _simple_enum(etype=Enum,*,boundary=None,use_args=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def convert_class(cls):\n nonlocal use_args\n cls_name=cls.__name__\n if use_args is None:\n use_args=etype._use_args_\n __new__=cls.__dict__.get('__new__')\n if __new__ is not None:\n new_member=__new__.__func__\n else:\n new_member=etype._member_type_.__new__\n attrs={}\n body={}\n if __new__ is not None:\n body['__new_member__']=new_member\n body['_new_member_']=new_member\n body['_use_args_']=use_args\n body['_generate_next_value_']=gnv=etype._generate_next_value_\n body['_member_names_']=member_names=[]\n body['_member_map_']=member_map={}\n body['_value2member_map_']=value2member_map={}\n body['_unhashable_values_']=unhashable_values=[]\n body['_unhashable_values_map_']={}\n body['_member_type_']=member_type=etype._member_type_\n body['_value_repr_']=etype._value_repr_\n if issubclass(etype,Flag):\n body['_boundary_']=boundary or etype._boundary_\n body['_flag_mask_']=None\n body['_all_bits_']=None\n body['_singles_mask_']=None\n body['_inverted_']=None\n body['__or__']=Flag.__or__\n body['__xor__']=Flag.__xor__\n body['__and__']=Flag.__and__\n body['__ror__']=Flag.__ror__\n body['__rxor__']=Flag.__rxor__\n body['__rand__']=Flag.__rand__\n body['__invert__']=Flag.__invert__\n for name,obj in cls.__dict__.items():\n if name in('__dict__','__weakref__'):\n continue\n if _is_dunder(name)or _is_private(cls_name,name)or _is_sunder(name)or _is_descriptor(obj):\n body[name]=obj\n else:\n attrs[name]=obj\n if cls.__dict__.get('__doc__')is None:\n body['__doc__']='An enumeration.'\n \n \n \n \n \n enum_class=type(cls_name,(etype,),body,boundary=boundary,_simple=True)\n for name in('__repr__','__str__','__format__','__reduce_ex__'):\n if name not in body:\n \n enum_method=getattr(etype,name)\n found_method=getattr(enum_class,name)\n object_method=getattr(object,name)\n data_type_method=getattr(member_type,name)\n if found_method in(data_type_method,object_method):\n setattr(enum_class,name,enum_method)\n gnv_last_values=[]\n if issubclass(enum_class,Flag):\n \n single_bits=multi_bits=0\n for name,value in attrs.items():\n if isinstance(value,auto)and auto.value is _auto_null:\n value=gnv(name,1,len(member_names),gnv_last_values)\n \n if use_args:\n if not isinstance(value,tuple):\n value=(value,)\n member=new_member(enum_class,*value)\n value=value[0]\n else:\n member=new_member(enum_class)\n if __new__ is None:\n member._value_=value\n \n try:\n contained=value2member_map.get(member._value_)\n except TypeError:\n contained=None\n if member._value_ in unhashable_values:\n for m in enum_class:\n if m._value_ ==member._value_:\n contained=m\n break\n if contained is not None:\n \n contained._add_alias_(name)\n else:\n \n member._name_=name\n member.__objclass__=enum_class\n member.__init__(value)\n member._sort_order_=len(member_names)\n if name not in('name','value'):\n setattr(enum_class,name,member)\n member_map[name]=member\n else:\n enum_class._add_member_(name,member)\n value2member_map[value]=member\n if _is_single_bit(value):\n \n member_names.append(name)\n single_bits |=value\n else:\n multi_bits |=value\n gnv_last_values.append(value)\n enum_class._flag_mask_=single_bits |multi_bits\n enum_class._singles_mask_=single_bits\n enum_class._all_bits_=2 **((single_bits |multi_bits).bit_length())-1\n \n member_list=[m._value_ for m in enum_class]\n if member_list !=sorted(member_list):\n enum_class._iter_member_=enum_class._iter_member_by_def_\n else:\n \n for name,value in attrs.items():\n if isinstance(value,auto):\n if value.value is _auto_null:\n value.value=gnv(name,1,len(member_names),gnv_last_values)\n value=value.value\n \n if use_args:\n if not isinstance(value,tuple):\n value=(value,)\n member=new_member(enum_class,*value)\n value=value[0]\n else:\n member=new_member(enum_class)\n if __new__ is None:\n member._value_=value\n \n try:\n contained=value2member_map.get(member._value_)\n except TypeError:\n contained=None\n if member._value_ in unhashable_values:\n for m in enum_class:\n if m._value_ ==member._value_:\n contained=m\n break\n if contained is not None:\n \n contained._add_alias_(name)\n else:\n \n member._name_=name\n member.__objclass__=enum_class\n member.__init__(value)\n member._sort_order_=len(member_names)\n if name not in('name','value'):\n setattr(enum_class,name,member)\n member_map[name]=member\n else:\n enum_class._add_member_(name,member)\n member_names.append(name)\n gnv_last_values.append(value)\n try:\n \n \n \n enum_class._value2member_map_.setdefault(value,member)\n except TypeError:\n \n enum_class._unhashable_values_.append(value)\n enum_class._unhashable_values_map_.setdefault(name,[]).append(value)\n if '__new__'in body:\n enum_class.__new_member__=enum_class.__new__\n enum_class.__new__=Enum.__new__\n return enum_class\n return convert_class\n \n@_simple_enum(StrEnum)\nclass EnumCheck:\n ''\n\n \n CONTINUOUS=\"no skipped integer values\"\n NAMED_FLAGS=\"multi-flag aliases may not contain unnamed flags\"\n UNIQUE=\"one name per value\"\nCONTINUOUS,NAMED_FLAGS,UNIQUE=EnumCheck\n\n\nclass verify:\n ''\n\n \n def __init__(self,*checks):\n self.checks=checks\n def __call__(self,enumeration):\n checks=self.checks\n cls_name=enumeration.__name__\n if Flag is not None and issubclass(enumeration,Flag):\n enum_type='flag'\n elif issubclass(enumeration,Enum):\n enum_type='enum'\n else:\n raise TypeError(\"the 'verify' decorator only works with Enum and Flag\")\n for check in checks:\n if check is UNIQUE:\n \n duplicates=[]\n for name,member in enumeration.__members__.items():\n if name !=member.name:\n duplicates.append((name,member.name))\n if duplicates:\n alias_details=', '.join(\n [\"%s -> %s\"%(alias,name)for(alias,name)in duplicates])\n raise ValueError('aliases found in %r: %s'%\n (enumeration,alias_details))\n elif check is CONTINUOUS:\n values=set(e.value for e in enumeration)\n if len(values)<2:\n continue\n low,high=min(values),max(values)\n missing=[]\n if enum_type =='flag':\n \n for i in range(_high_bit(low)+1,_high_bit(high)):\n if 2 **i not in values:\n missing.append(2 **i)\n elif enum_type =='enum':\n \n for i in range(low+1,high):\n if i not in values:\n missing.append(i)\n else:\n raise Exception('verify: unknown type %r'%enum_type)\n if missing:\n raise ValueError(('invalid %s %r: missing values %s'%(\n enum_type,cls_name,', '.join((str(m)for m in missing)))\n )[:256])\n \n elif check is NAMED_FLAGS:\n \n member_names=enumeration._member_names_\n member_values=[m.value for m in enumeration]\n missing_names=[]\n missing_value=0\n for name,alias in enumeration._member_map_.items():\n if name in member_names:\n \n continue\n if alias.value <0:\n \n continue\n values=list(_iter_bits_lsb(alias.value))\n missed=[v for v in values if v not in member_values]\n if missed:\n missing_names.append(name)\n for val in missed:\n missing_value |=val\n if missing_names:\n if len(missing_names)==1:\n alias='alias %s is missing'%missing_names[0]\n else:\n alias='aliases %s and %s are missing'%(\n ', '.join(missing_names[:-1]),missing_names[-1]\n )\n if _is_single_bit(missing_value):\n value='value 0x%x'%missing_value\n else:\n value='combined values of 0x%x'%missing_value\n raise ValueError(\n 'invalid Flag %r: %s %s [use enum.show_flag_values(value) for details]'\n %(cls_name,alias,value)\n )\n return enumeration\n \ndef _test_simple_enum(checked_enum,simple_enum):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n failed=[]\n if checked_enum.__dict__ !=simple_enum.__dict__:\n checked_dict=checked_enum.__dict__\n checked_keys=list(checked_dict.keys())\n simple_dict=simple_enum.__dict__\n simple_keys=list(simple_dict.keys())\n member_names=set(\n list(checked_enum._member_map_.keys())\n +list(simple_enum._member_map_.keys())\n )\n for key in set(checked_keys+simple_keys):\n if key in('__module__','_member_map_','_value2member_map_','__doc__',\n '__static_attributes__','__firstlineno__'):\n \n continue\n elif key in member_names:\n \n continue\n elif key not in simple_keys:\n failed.append(\"missing key: %r\"%(key,))\n elif key not in checked_keys:\n failed.append(\"extra key: %r\"%(key,))\n else:\n checked_value=checked_dict[key]\n simple_value=simple_dict[key]\n if callable(checked_value)or isinstance(checked_value,bltns.property):\n continue\n if key =='__doc__':\n \n compressed_checked_value=checked_value.replace(' ','').replace('\\t','')\n compressed_simple_value=simple_value.replace(' ','').replace('\\t','')\n if compressed_checked_value !=compressed_simple_value:\n failed.append(\"%r:\\n %s\\n %s\"%(\n key,\n \"checked -> %r\"%(checked_value,),\n \"simple -> %r\"%(simple_value,),\n ))\n elif checked_value !=simple_value:\n failed.append(\"%r:\\n %s\\n %s\"%(\n key,\n \"checked -> %r\"%(checked_value,),\n \"simple -> %r\"%(simple_value,),\n ))\n failed.sort()\n for name in member_names:\n failed_member=[]\n if name not in simple_keys:\n failed.append('missing member from simple enum: %r'%name)\n elif name not in checked_keys:\n failed.append('extra member in simple enum: %r'%name)\n else:\n checked_member_dict=checked_enum[name].__dict__\n checked_member_keys=list(checked_member_dict.keys())\n simple_member_dict=simple_enum[name].__dict__\n simple_member_keys=list(simple_member_dict.keys())\n for key in set(checked_member_keys+simple_member_keys):\n if key in('__module__','__objclass__','_inverted_'):\n \n continue\n elif key not in simple_member_keys:\n failed_member.append(\"missing key %r not in the simple enum member %r\"%(key,name))\n elif key not in checked_member_keys:\n failed_member.append(\"extra key %r in simple enum member %r\"%(key,name))\n else:\n checked_value=checked_member_dict[key]\n simple_value=simple_member_dict[key]\n if checked_value !=simple_value:\n failed_member.append(\"%r:\\n %s\\n %s\"%(\n key,\n \"checked member -> %r\"%(checked_value,),\n \"simple member -> %r\"%(simple_value,),\n ))\n if failed_member:\n failed.append('%r member mismatch:\\n %s'%(\n name,'\\n '.join(failed_member),\n ))\n for method in(\n '__str__','__repr__','__reduce_ex__','__format__',\n '__getnewargs_ex__','__getnewargs__','__reduce_ex__','__reduce__'\n ):\n if method in simple_keys and method in checked_keys:\n \n continue\n elif method not in simple_keys and method not in checked_keys:\n \n checked_method=getattr(checked_enum,method,None)\n simple_method=getattr(simple_enum,method,None)\n if hasattr(checked_method,'__func__'):\n checked_method=checked_method.__func__\n simple_method=simple_method.__func__\n if checked_method !=simple_method:\n failed.append(\"%r: %-30s %s\"%(\n method,\n \"checked -> %r\"%(checked_method,),\n \"simple -> %r\"%(simple_method,),\n ))\n else:\n \n \n pass\n if failed:\n raise TypeError('enum mismatch:\\n %s'%'\\n '.join(failed))\n \ndef _old_convert_(etype,name,module,filter,source=None,*,boundary=None):\n ''\n\n \n \n \n \n \n \n module_globals=sys.modules[module].__dict__\n if source:\n source=source.__dict__\n else:\n source=module_globals\n \n \n \n members=[\n (name,value)\n for name,value in source.items()\n if filter(name)]\n try:\n \n members.sort(key=lambda t:(t[1],t[0]))\n except TypeError:\n \n members.sort(key=lambda t:t[0])\n cls=etype(name,members,module=module,boundary=boundary or KEEP)\n return cls\n \n_stdlib_enums=IntEnum,StrEnum,IntFlag\n", ["builtins", "sys", "types"]], "errno": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\nE2BIG=7\n\nEACCES=13\n\nEADDRINUSE=10048\n\nEADDRNOTAVAIL=10049\n\nEAFNOSUPPORT=10047\n\nEAGAIN=11\n\nEALREADY=10037\n\nEBADF=9\n\nEBADMSG=104\n\nEBUSY=16\n\nECANCELED=105\n\nECHILD=10\n\nECONNABORTED=10053\n\nECONNREFUSED=10061\n\nECONNRESET=10054\n\nEDEADLK=36\n\nEDEADLOCK=36\n\nEDESTADDRREQ=10039\n\nEDOM=33\n\nEDQUOT=10069\n\nEEXIST=17\n\nEFAULT=14\n\nEFBIG=27\n\nEHOSTDOWN=10064\n\nEHOSTUNREACH=10065\n\nEIDRM=111\n\nEILSEQ=42\n\nEINPROGRESS=10036\n\nEINTR=4\n\nEINVAL=22\n\nEIO=5\n\nEISCONN=10056\n\nEISDIR=21\n\nELOOP=10062\n\nEMFILE=24\n\nEMLINK=31\n\nEMSGSIZE=10040\n\nENAMETOOLONG=38\n\nENETDOWN=10050\n\nENETRESET=10052\n\nENETUNREACH=10051\n\nENFILE=23\n\nENOBUFS=10055\n\nENODATA=120\n\nENODEV=19\n\nENOENT=2\n\nENOEXEC=8\n\nENOLCK=39\n\nENOLINK=121\n\nENOMEM=12\n\nENOMSG=122\n\nENOPROTOOPT=10042\n\nENOSPC=28\n\nENOSR=124\n\nENOSTR=125\n\nENOSYS=40\n\nENOTCONN=10057\n\nENOTDIR=20\n\nENOTEMPTY=41\n\nENOTRECOVERABLE=127\n\nENOTSOCK=10038\n\nENOTSUP=129\n\nENOTTY=25\n\nENXIO=6\n\nEOPNOTSUPP=10045\n\nEOVERFLOW=132\n\nEOWNERDEAD=133\n\nEPERM=1\n\nEPFNOSUPPORT=10046\n\nEPIPE=32\n\nEPROTO=134\n\nEPROTONOSUPPORT=10043\n\nEPROTOTYPE=10041\n\nERANGE=34\n\nEREMOTE=10071\n\nEROFS=30\n\nESHUTDOWN=10058\n\nESOCKTNOSUPPORT=10044\n\nESPIPE=29\n\nESRCH=3\n\nESTALE=10070\n\nETIME=137\n\nETIMEDOUT=10060\n\nETOOMANYREFS=10059\n\nETXTBSY=139\n\nEUSERS=10068\n\nEWOULDBLOCK=10035\n\nEXDEV=18\n\nWSABASEERR=10000\n\nWSAEACCES=10013\n\nWSAEADDRINUSE=10048\n\nWSAEADDRNOTAVAIL=10049\n\nWSAEAFNOSUPPORT=10047\n\nWSAEALREADY=10037\n\nWSAEBADF=10009\n\nWSAECONNABORTED=10053\n\nWSAECONNREFUSED=10061\n\nWSAECONNRESET=10054\n\nWSAEDESTADDRREQ=10039\n\nWSAEDISCON=10101\n\nWSAEDQUOT=10069\n\nWSAEFAULT=10014\n\nWSAEHOSTDOWN=10064\n\nWSAEHOSTUNREACH=10065\n\nWSAEINPROGRESS=10036\n\nWSAEINTR=10004\n\nWSAEINVAL=10022\n\nWSAEISCONN=10056\n\nWSAELOOP=10062\n\nWSAEMFILE=10024\n\nWSAEMSGSIZE=10040\n\nWSAENAMETOOLONG=10063\n\nWSAENETDOWN=10050\n\nWSAENETRESET=10052\n\nWSAENETUNREACH=10051\n\nWSAENOBUFS=10055\n\nWSAENOPROTOOPT=10042\n\nWSAENOTCONN=10057\n\nWSAENOTEMPTY=10066\n\nWSAENOTSOCK=10038\n\nWSAEOPNOTSUPP=10045\n\nWSAEPFNOSUPPORT=10046\n\nWSAEPROCLIM=10067\n\nWSAEPROTONOSUPPORT=10043\n\nWSAEPROTOTYPE=10041\n\nWSAEREMOTE=10071\n\nWSAESHUTDOWN=10058\n\nWSAESOCKTNOSUPPORT=10044\n\nWSAESTALE=10070\n\nWSAETIMEDOUT=10060\n\nWSAETOOMANYREFS=10059\n\nWSAEUSERS=10068\n\nWSAEWOULDBLOCK=10035\n\nWSANOTINITIALISED=10093\n\nWSASYSNOTREADY=10091\n\nWSAVERNOTSUPPORTED=10092\n\nerrorcode={v:k for(k,v)in globals().items()if k ==k.upper()}\n", []], "external_import": [".py", "import os\nimport sys\nfrom browser import doc\nimport urllib.request\n\n\n\n\n\nclass ModuleFinder:\n def __init__(self,path_entry):\n print(\"external_import here..\")\n \n self._module=None\n if path_entry.startswith('http://'):\n self.path_entry=path_entry\n else:\n raise ImportError()\n \n def __str__(self):\n return '<%s for \"%s\">'%(self.__class__.__name__,self.path_entry)\n \n def find_module(self,fullname,path=None):\n path=path or self.path_entry\n \n for _ext in['js','pyj','py']:\n _fp,_url,_headers=urllib.request.urlopen(path+'/'+'%s.%s'%(fullname,_ext))\n self._module=_fp.read()\n _fp.close()\n if self._module is not None:\n print(\"module found at %s:%s\"%(path,fullname))\n return ModuleLoader(path,fullname,self._module)\n \n print('module %s not found'%fullname)\n raise ImportError()\n return None\n \nclass ModuleLoader:\n ''\n \n def __init__(self,filepath,name,module_source):\n self._filepath=filepath\n self._name=name\n self._module_source=module_source\n \n def get_source(self):\n return self._module_source\n \n def is_package(self):\n return '.'in self._name\n \n def load_module(self):\n if self._name in sys.modules:\n \n mod=sys.modules[self._name]\n return mod\n \n _src=self.get_source()\n if self._filepath.endswith('.js'):\n mod=JSObject(import_js_module(_src,self._filepath,self._name))\n elif self._filepath.endswith('.py'):\n mod=JSObject(import_py_module(_src,self._filepath,self._name))\n elif self._filepath.endswith('.pyj'):\n mod=JSObject(import_pyj_module(_src,self._filepath,self._name))\n else:\n raise ImportError('Invalid Module: %s'%self._filepath)\n \n \n mod.__file__=self._filepath\n mod.__name__=self._name\n mod.__path__=os.path.abspath(self._filepath)\n mod.__loader__=self\n mod.__package__='.'.join(self._name.split('.')[:-1])\n \n if self.is_package():\n print('adding path for package')\n \n \n mod.__path__=[self._filepath]\n else:\n print('imported as regular module')\n \n print('creating a new module object for \"%s\"'%self._name)\n sys.modules.setdefault(self._name,mod)\n JSObject(__BRYTHON__.imported)[self._name]=mod\n \n return mod\n", ["browser", "os", "sys", "urllib.request"]], "faulthandler": [".py", "''\n\n\n_EXCEPTION_ACCESS_VIOLATION=-1073741819\n\n_EXCEPTION_INT_DIVIDE_BY_ZERO=-1073741676\n\n_EXCEPTION_NONCONTINUABLE=1\n\n_EXCEPTION_NONCONTINUABLE_EXCEPTION=-1073741787\n\n_EXCEPTION_STACK_OVERFLOW=-1073741571\n\nclass __loader__(object):\n ''\n\n\n\n\n \n \n \n __delattr__=\"\"\n \n __dict__=\"{'__module__': '_frozen_importlib', '__doc__': 'Meta path import for built-in modules.\\n\\n All methods are either class or static methods to avoid the need to\\n instantiate the class.\\n\\n ', 'module_repr': , 'find_spec': , 'find_module': , 'create_module': , 'exec_module': , 'get_code': , 'get_source': , 'is_package': , 'load_module': , '__dict__': , '__weakref__': }\"\n \n __dir__=\"\"\n \n __eq__=\"\"\n \n __format__=\"\"\n \n __ge__=\"\"\n \n __getattribute__=\"\"\n \n __gt__=\"\"\n \n __hash__=\"\"\n \n __init__=\"\"\n \n def __init_subclass__(*args,**kw):\n ''\n\n\n \n pass\n \n __le__=\"\"\n \n __lt__=\"\"\n \n __module__=\"\"\"_frozen_importlib\"\"\"\n \n __ne__=\"\"\n \n def __new__(*args,**kw):\n ''\n pass\n \n __reduce__=\"\"\n \n __reduce_ex__=\"\"\n \n __repr__=\"\"\n \n __setattr__=\"\"\n \n __sizeof__=\"\"\n \n __str__=\"\"\n \n def __subclasshook__(*args,**kw):\n ''\n\n\n\n\n \n pass\n \n __weakref__=\"\"\n \n create_module=\">\"\n \n exec_module=\">\"\n \n find_module=\">\"\n \n find_spec=\">\"\n \n get_code=\">\"\n \n get_source=\">\"\n \n is_package=\">\"\n \n load_module=\">\"\n \n def module_repr(*args,**kw):\n ''\n\n\n \n pass\n__spec__=\"ModuleSpec(name='faulthandler', loader=, origin='built-in')\"\n\ndef _fatal_error(*args,**kw):\n ''\n pass\n \ndef _fatal_error_c_thread(*args,**kw):\n ''\n pass\n \ndef _raise_exception(*args,**kw):\n ''\n pass\n \ndef _read_null(*args,**kw):\n ''\n pass\n \ndef _sigabrt(*args,**kw):\n ''\n pass\n \ndef _sigfpe(*args,**kw):\n ''\n pass\n \ndef _sigsegv(*args,**kw):\n ''\n pass\n \ndef cancel_dump_traceback_later(*args,**kw):\n ''\n pass\n \ndef disable(*args,**kw):\n ''\n pass\n \ndef dump_traceback(*args,**kw):\n ''\n pass\n \ndef dump_traceback_later(*args,**kw):\n ''\n \n pass\n \ndef enable(*args,**kw):\n ''\n pass\n \ndef is_enabled(*args,**kw):\n ''\n pass\n", []], "fnmatch": [".py", "''\n\n\n\n\n\n\n\n\n\n\nimport os\nimport posixpath\nimport re\nimport functools\n\n__all__=[\"filter\",\"fnmatch\",\"fnmatchcase\",\"translate\"]\n\ndef fnmatch(name,pat):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n name=os.path.normcase(name)\n pat=os.path.normcase(pat)\n return fnmatchcase(name,pat)\n \n@functools.lru_cache(maxsize=32768,typed=True)\ndef _compile_pattern(pat):\n if isinstance(pat,bytes):\n pat_str=str(pat,'ISO-8859-1')\n res_str=translate(pat_str)\n res=bytes(res_str,'ISO-8859-1')\n else:\n res=translate(pat)\n return re.compile(res).match\n \ndef filter(names,pat):\n ''\n result=[]\n pat=os.path.normcase(pat)\n match=_compile_pattern(pat)\n if os.path is posixpath:\n \n for name in names:\n if match(name):\n result.append(name)\n else:\n for name in names:\n if match(os.path.normcase(name)):\n result.append(name)\n return result\n \ndef fnmatchcase(name,pat):\n ''\n\n\n\n \n match=_compile_pattern(pat)\n return match(name)is not None\n \n \ndef translate(pat):\n ''\n\n\n \n \n STAR=object()\n parts=_translate(pat,STAR,'.')\n return _join_translated_parts(parts,STAR)\n \n \ndef _translate(pat,STAR,QUESTION_MARK):\n res=[]\n add=res.append\n i,n=0,len(pat)\n while i =n:\n add('\\\\[')\n else:\n stuff=pat[i:j]\n if '-'not in stuff:\n stuff=stuff.replace('\\\\',r'\\\\')\n else:\n chunks=[]\n k=i+2 if pat[i]=='!'else i+1\n while True:\n k=pat.find('-',k,j)\n if k <0:\n break\n chunks.append(pat[i:k])\n i=k+1\n k=k+3\n chunk=pat[i:j]\n if chunk:\n chunks.append(chunk)\n else:\n chunks[-1]+='-'\n \n for k in range(len(chunks)-1,0,-1):\n if chunks[k -1][-1]>chunks[k][0]:\n chunks[k -1]=chunks[k -1][:-1]+chunks[k][1:]\n del chunks[k]\n \n \n stuff='-'.join(s.replace('\\\\',r'\\\\').replace('-',r'\\-')\n for s in chunks)\n \n stuff=re.sub(r'([&~|])',r'\\\\\\1',stuff)\n i=j+1\n if not stuff:\n \n add('(?!)')\n elif stuff =='!':\n \n add('.')\n else:\n if stuff[0]=='!':\n stuff='^'+stuff[1:]\n elif stuff[0]in('^','['):\n stuff='\\\\'+stuff\n add(f'[{stuff}]')\n else:\n add(re.escape(c))\n assert i ==n\n return res\n \n \ndef _join_translated_parts(inp,STAR):\n\n res=[]\n add=res.append\n i,n=0,len(inp)\n \n while i .*?{fixed})\")\n assert i ==n\n res=\"\".join(res)\n return fr'(?s:{res})\\Z'\n", ["functools", "os", "posixpath", "re"]], "formatter": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport warnings\nwarnings.warn('the formatter module is deprecated',DeprecationWarning,\nstacklevel=2)\n\n\nAS_IS=None\n\n\nclass NullFormatter:\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,writer=None):\n if writer is None:\n writer=NullWriter()\n self.writer=writer\n def end_paragraph(self,blankline):pass\n def add_line_break(self):pass\n def add_hor_rule(self,*args,**kw):pass\n def add_label_data(self,format,counter,blankline=None):pass\n def add_flowing_data(self,data):pass\n def add_literal_data(self,data):pass\n def flush_softspace(self):pass\n def push_alignment(self,align):pass\n def pop_alignment(self):pass\n def push_font(self,x):pass\n def pop_font(self):pass\n def push_margin(self,margin):pass\n def pop_margin(self):pass\n def set_spacing(self,spacing):pass\n def push_style(self,*styles):pass\n def pop_style(self,n=1):pass\n def assert_line_data(self,flag=1):pass\n \n \nclass AbstractFormatter:\n ''\n\n\n\n\n\n \n \n \n \n \n \n \n def __init__(self,writer):\n self.writer=writer\n self.align=None\n self.align_stack=[]\n self.font_stack=[]\n self.margin_stack=[]\n self.spacing=None\n self.style_stack=[]\n self.nospace=1\n self.softspace=0\n self.para_end=1\n self.parskip=0\n self.hard_break=1\n self.have_label=0\n \n def end_paragraph(self,blankline):\n if not self.hard_break:\n self.writer.send_line_break()\n self.have_label=0\n if self.parskip 0:\n label=label+self.format_letter(c,counter)\n elif c in 'iI':\n if counter >0:\n label=label+self.format_roman(c,counter)\n else:\n label=label+c\n return label\n \n def format_letter(self,case,counter):\n label=''\n while counter >0:\n counter,x=divmod(counter -1,26)\n \n \n \n s=chr(ord(case)+x)\n label=s+label\n return label\n \n def format_roman(self,case,counter):\n ones=['i','x','c','m']\n fives=['v','l','d']\n label,index='',0\n \n while counter >0:\n counter,x=divmod(counter,10)\n if x ==9:\n label=ones[index]+ones[index+1]+label\n elif x ==4:\n label=ones[index]+fives[index]+label\n else:\n if x >=5:\n s=fives[index]\n x=x -5\n else:\n s=''\n s=s+ones[index]*x\n label=s+label\n index=index+1\n if case =='I':\n return label.upper()\n return label\n \n def add_flowing_data(self,data):\n if not data:return\n prespace=data[:1].isspace()\n postspace=data[-1:].isspace()\n data=\" \".join(data.split())\n if self.nospace and not data:\n return\n elif prespace or self.softspace:\n if not data:\n if not self.nospace:\n self.softspace=1\n self.parskip=0\n return\n if not self.nospace:\n data=' '+data\n self.hard_break=self.nospace=self.para_end=\\\n self.parskip=self.have_label=0\n self.softspace=postspace\n self.writer.send_flowing_data(data)\n \n def add_literal_data(self,data):\n if not data:return\n if self.softspace:\n self.writer.send_flowing_data(\" \")\n self.hard_break=data[-1:]=='\\n'\n self.nospace=self.para_end=self.softspace=\\\n self.parskip=self.have_label=0\n self.writer.send_literal_data(data)\n \n def flush_softspace(self):\n if self.softspace:\n self.hard_break=self.para_end=self.parskip=\\\n self.have_label=self.softspace=0\n self.nospace=1\n self.writer.send_flowing_data(' ')\n \n def push_alignment(self,align):\n if align and align !=self.align:\n self.writer.new_alignment(align)\n self.align=align\n self.align_stack.append(align)\n else:\n self.align_stack.append(self.align)\n \n def pop_alignment(self):\n if self.align_stack:\n del self.align_stack[-1]\n if self.align_stack:\n self.align=align=self.align_stack[-1]\n self.writer.new_alignment(align)\n else:\n self.align=None\n self.writer.new_alignment(None)\n \n def push_font(self,font):\n size,i,b,tt=font\n if self.softspace:\n self.hard_break=self.para_end=self.softspace=0\n self.nospace=1\n self.writer.send_flowing_data(' ')\n if self.font_stack:\n csize,ci,cb,ctt=self.font_stack[-1]\n if size is AS_IS:size=csize\n if i is AS_IS:i=ci\n if b is AS_IS:b=cb\n if tt is AS_IS:tt=ctt\n font=(size,i,b,tt)\n self.font_stack.append(font)\n self.writer.new_font(font)\n \n def pop_font(self):\n if self.font_stack:\n del self.font_stack[-1]\n if self.font_stack:\n font=self.font_stack[-1]\n else:\n font=None\n self.writer.new_font(font)\n \n def push_margin(self,margin):\n self.margin_stack.append(margin)\n fstack=[m for m in self.margin_stack if m]\n if not margin and fstack:\n margin=fstack[-1]\n self.writer.new_margin(margin,len(fstack))\n \n def pop_margin(self):\n if self.margin_stack:\n del self.margin_stack[-1]\n fstack=[m for m in self.margin_stack if m]\n if fstack:\n margin=fstack[-1]\n else:\n margin=None\n self.writer.new_margin(margin,len(fstack))\n \n def set_spacing(self,spacing):\n self.spacing=spacing\n self.writer.new_spacing(spacing)\n \n def push_style(self,*styles):\n if self.softspace:\n self.hard_break=self.para_end=self.softspace=0\n self.nospace=1\n self.writer.send_flowing_data(' ')\n for style in styles:\n self.style_stack.append(style)\n self.writer.new_styles(tuple(self.style_stack))\n \n def pop_style(self,n=1):\n del self.style_stack[-n:]\n self.writer.new_styles(tuple(self.style_stack))\n \n def assert_line_data(self,flag=1):\n self.nospace=self.hard_break=not flag\n self.para_end=self.parskip=self.have_label=0\n \n \nclass NullWriter:\n ''\n\n\n\n\n\n \n def __init__(self):pass\n def flush(self):pass\n def new_alignment(self,align):pass\n def new_font(self,font):pass\n def new_margin(self,margin,level):pass\n def new_spacing(self,spacing):pass\n def new_styles(self,styles):pass\n def send_paragraph(self,blankline):pass\n def send_line_break(self):pass\n def send_hor_rule(self,*args,**kw):pass\n def send_label_data(self,data):pass\n def send_flowing_data(self,data):pass\n def send_literal_data(self,data):pass\n \n \nclass AbstractWriter(NullWriter):\n ''\n\n\n\n\n \n \n def new_alignment(self,align):\n print(\"new_alignment(%r)\"%(align,))\n \n def new_font(self,font):\n print(\"new_font(%r)\"%(font,))\n \n def new_margin(self,margin,level):\n print(\"new_margin(%r, %d)\"%(margin,level))\n \n def new_spacing(self,spacing):\n print(\"new_spacing(%r)\"%(spacing,))\n \n def new_styles(self,styles):\n print(\"new_styles(%r)\"%(styles,))\n \n def send_paragraph(self,blankline):\n print(\"send_paragraph(%r)\"%(blankline,))\n \n def send_line_break(self):\n print(\"send_line_break()\")\n \n def send_hor_rule(self,*args,**kw):\n print(\"send_hor_rule()\")\n \n def send_label_data(self,data):\n print(\"send_label_data(%r)\"%(data,))\n \n def send_flowing_data(self,data):\n print(\"send_flowing_data(%r)\"%(data,))\n \n def send_literal_data(self,data):\n print(\"send_literal_data(%r)\"%(data,))\n \n \nclass DumbWriter(NullWriter):\n ''\n\n\n\n\n\n \n \n def __init__(self,file=None,maxcol=72):\n self.file=file or sys.stdout\n self.maxcol=maxcol\n NullWriter.__init__(self)\n self.reset()\n \n def reset(self):\n self.col=0\n self.atbreak=0\n \n def send_paragraph(self,blankline):\n self.file.write('\\n'*blankline)\n self.col=0\n self.atbreak=0\n \n def send_line_break(self):\n self.file.write('\\n')\n self.col=0\n self.atbreak=0\n \n def send_hor_rule(self,*args,**kw):\n self.file.write('\\n')\n self.file.write('-'*self.maxcol)\n self.file.write('\\n')\n self.col=0\n self.atbreak=0\n \n def send_literal_data(self,data):\n self.file.write(data)\n i=data.rfind('\\n')\n if i >=0:\n self.col=0\n data=data[i+1:]\n data=data.expandtabs()\n self.col=self.col+len(data)\n self.atbreak=0\n \n def send_flowing_data(self,data):\n if not data:return\n atbreak=self.atbreak or data[0].isspace()\n col=self.col\n maxcol=self.maxcol\n write=self.file.write\n for word in data.split():\n if atbreak:\n if col+len(word)>=maxcol:\n write('\\n')\n col=0\n else:\n write(' ')\n col=col+1\n write(word)\n col=col+len(word)\n atbreak=1\n self.col=col\n self.atbreak=data[-1].isspace()\n \n \ndef test(file=None):\n w=DumbWriter()\n f=AbstractFormatter(w)\n if file is not None:\n fp=open(file)\n elif sys.argv[1:]:\n fp=open(sys.argv[1])\n else:\n fp=sys.stdin\n try:\n for line in fp:\n if line =='\\n':\n f.end_paragraph(1)\n else:\n f.add_flowing_data(line)\n finally:\n if fp is not sys.stdin:\n fp.close()\n f.end_paragraph(0)\n \n \nif __name__ =='__main__':\n test()\n", ["sys", "warnings"]], "fractions": [".py", "\n\n\n\"\"\"Fraction, infinite-precision, rational numbers.\"\"\"\n\nfrom decimal import Decimal\nimport functools\nimport math\nimport numbers\nimport operator\nimport re\nimport sys\n\n__all__=['Fraction']\n\n\n\n\n_PyHASH_MODULUS=sys.hash_info.modulus\n\n\n_PyHASH_INF=sys.hash_info.inf\n\n@functools.lru_cache(maxsize=1 <<14)\ndef _hash_algorithm(numerator,denominator):\n\n\n\n\n\n\n try:\n dinv=pow(denominator,-1,_PyHASH_MODULUS)\n except ValueError:\n \n hash_=_PyHASH_INF\n else:\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n hash_=hash(hash(abs(numerator))*dinv)\n result=hash_ if numerator >=0 else -hash_\n return -2 if result ==-1 else result\n \n_RATIONAL_FORMAT=re.compile(r\"\"\"\n \\A\\s* # optional whitespace at the start,\n (?P[-+]?) # an optional sign, then\n (?=\\d|\\.\\d) # lookahead for digit or .digit\n (?P\\d*|\\d+(_\\d+)*) # numerator (possibly empty)\n (?: # followed by\n (?:\\s*/\\s*(?P\\d+(_\\d+)*))? # an optional denominator\n | # or\n (?:\\.(?P\\d*|\\d+(_\\d+)*))? # an optional fractional part\n (?:E(?P[-+]?\\d+(_\\d+)*))? # and optional exponent\n )\n \\s*\\Z # and optional whitespace to finish\n\"\"\",re.VERBOSE |re.IGNORECASE)\n\n\n\n\ndef _round_to_exponent(n,d,exponent,no_neg_zero=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if exponent >=0:\n d *=10 **exponent\n else:\n n *=10 **-exponent\n \n \n \n q,r=divmod(n+(d >>1),d)\n if r ==0 and d&1 ==0:\n q &=-2\n \n sign=q <0 if no_neg_zero else n <0\n return sign,abs(q)\n \n \ndef _round_to_figures(n,d,figures):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if n ==0:\n return False,0,1 -figures\n \n \n \n str_n,str_d=str(abs(n)),str(d)\n m=len(str_n)-len(str_d)+(str_d <=str_n)\n \n \n \n exponent=m -figures\n sign,significand=_round_to_exponent(n,d,exponent)\n \n \n \n if len(str(significand))==figures+1:\n significand //=10\n exponent +=1\n \n return sign,significand,exponent\n \n \n \n_GENERAL_FORMAT_SPECIFICATION_MATCHER=re.compile(r\"\"\"\n (?:\n (?P.)?\n (?P[<>=^])\n )?\n (?P[-+ ]?)\n # Alt flag forces a slash and denominator in the output, even for\n # integer-valued Fraction objects.\n (?P\\#)?\n # We don't implement the zeropad flag since there's no single obvious way\n # to interpret it.\n (?P0|[1-9][0-9]*)?\n (?P[,_])?\n\"\"\",re.DOTALL |re.VERBOSE).fullmatch\n\n\n\n\n_FLOAT_FORMAT_SPECIFICATION_MATCHER=re.compile(r\"\"\"\n (?:\n (?P.)?\n (?P[<>=^])\n )?\n (?P[-+ ]?)\n (?Pz)?\n (?P\\#)?\n # A '0' that's *not* followed by another digit is parsed as a minimum width\n # rather than a zeropad flag.\n (?P0(?=[0-9]))?\n (?P0|[1-9][0-9]*)?\n (?P[,_])?\n (?:\\.(?P0|[1-9][0-9]*))?\n (?P[eEfFgG%])\n\"\"\",re.DOTALL |re.VERBOSE).fullmatch\n\n\nclass Fraction(numbers.Rational):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('_numerator','_denominator')\n \n \n def __new__(cls,numerator=0,denominator=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self=super(Fraction,cls).__new__(cls)\n \n if denominator is None:\n if type(numerator)is int:\n self._numerator=numerator\n self._denominator=1\n return self\n \n elif isinstance(numerator,numbers.Rational):\n self._numerator=numerator.numerator\n self._denominator=numerator.denominator\n return self\n \n elif isinstance(numerator,(float,Decimal)):\n \n self._numerator,self._denominator=numerator.as_integer_ratio()\n return self\n \n elif isinstance(numerator,str):\n \n m=_RATIONAL_FORMAT.match(numerator)\n if m is None:\n raise ValueError('Invalid literal for Fraction: %r'%\n numerator)\n numerator=int(m.group('num')or '0')\n denom=m.group('denom')\n if denom:\n denominator=int(denom)\n else:\n denominator=1\n decimal=m.group('decimal')\n if decimal:\n decimal=decimal.replace('_','')\n scale=10 **len(decimal)\n numerator=numerator *scale+int(decimal)\n denominator *=scale\n exp=m.group('exp')\n if exp:\n exp=int(exp)\n if exp >=0:\n numerator *=10 **exp\n else:\n denominator *=10 **-exp\n if m.group('sign')=='-':\n numerator=-numerator\n \n else:\n raise TypeError(\"argument should be a string \"\n \"or a Rational instance\")\n \n elif type(numerator)is int is type(denominator):\n pass\n \n elif(isinstance(numerator,numbers.Rational)and\n isinstance(denominator,numbers.Rational)):\n numerator,denominator=(\n numerator.numerator *denominator.denominator,\n denominator.numerator *numerator.denominator\n )\n else:\n raise TypeError(\"both arguments should be \"\n \"Rational instances\")\n \n if denominator ==0:\n raise ZeroDivisionError('Fraction(%s, 0)'%numerator)\n g=math.gcd(numerator,denominator)\n if denominator <0:\n g=-g\n numerator //=g\n denominator //=g\n self._numerator=numerator\n self._denominator=denominator\n return self\n \n @classmethod\n def from_float(cls,f):\n ''\n\n\n\n \n if isinstance(f,numbers.Integral):\n return cls(f)\n elif not isinstance(f,float):\n raise TypeError(\"%s.from_float() only takes floats, not %r (%s)\"%\n (cls.__name__,f,type(f).__name__))\n return cls._from_coprime_ints(*f.as_integer_ratio())\n \n @classmethod\n def from_decimal(cls,dec):\n ''\n from decimal import Decimal\n if isinstance(dec,numbers.Integral):\n dec=Decimal(int(dec))\n elif not isinstance(dec,Decimal):\n raise TypeError(\n \"%s.from_decimal() only takes Decimals, not %r (%s)\"%\n (cls.__name__,dec,type(dec).__name__))\n return cls._from_coprime_ints(*dec.as_integer_ratio())\n \n @classmethod\n def _from_coprime_ints(cls,numerator,denominator,/):\n ''\n\n\n\n \n obj=super(Fraction,cls).__new__(cls)\n obj._numerator=numerator\n obj._denominator=denominator\n return obj\n \n def is_integer(self):\n ''\n return self._denominator ==1\n \n def as_integer_ratio(self):\n ''\n\n\n \n return(self._numerator,self._denominator)\n \n def limit_denominator(self,max_denominator=1000000):\n ''\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if max_denominator <1:\n raise ValueError(\"max_denominator should be at least 1\")\n if self._denominator <=max_denominator:\n return Fraction(self)\n \n p0,q0,p1,q1=0,1,1,0\n n,d=self._numerator,self._denominator\n while True:\n a=n //d\n q2=q0+a *q1\n if q2 >max_denominator:\n break\n p0,q0,p1,q1=p1,q1,p0+a *p1,q2\n n,d=d,n -a *d\n k=(max_denominator -q0)//q1\n \n \n \n \n \n if 2 *d *(q0+k *q1)<=self._denominator:\n return Fraction._from_coprime_ints(p1,q1)\n else:\n return Fraction._from_coprime_ints(p0+k *p1,q0+k *q1)\n \n @property\n def numerator(a):\n return a._numerator\n \n @property\n def denominator(a):\n return a._denominator\n \n def __repr__(self):\n ''\n return '%s(%s, %s)'%(self.__class__.__name__,\n self._numerator,self._denominator)\n \n def __str__(self):\n ''\n if self._denominator ==1:\n return str(self._numerator)\n else:\n return '%s/%s'%(self._numerator,self._denominator)\n \n def _format_general(self,match):\n ''\n\n\n\n \n \n fill=match[\"fill\"]or \" \"\n align=match[\"align\"]or \">\"\n pos_sign=\"\"if match[\"sign\"]==\"-\"else match[\"sign\"]\n alternate_form=bool(match[\"alt\"])\n minimumwidth=int(match[\"minimumwidth\"]or \"0\")\n thousands_sep=match[\"thousands_sep\"]or ''\n \n \n n,d=self._numerator,self._denominator\n if d >1 or alternate_form:\n body=f\"{abs(n):{thousands_sep}}/{d:{thousands_sep}}\"\n else:\n body=f\"{abs(n):{thousands_sep}}\"\n sign='-'if n <0 else pos_sign\n \n \n padding=fill *(minimumwidth -len(sign)-len(body))\n if align ==\">\":\n return padding+sign+body\n elif align ==\"<\":\n return sign+body+padding\n elif align ==\"^\":\n half=len(padding)//2\n return padding[:half]+sign+body+padding[half:]\n else:\n return sign+padding+body\n \n def _format_float_style(self,match):\n ''\n fill=match[\"fill\"]or \" \"\n align=match[\"align\"]or \">\"\n pos_sign=\"\"if match[\"sign\"]==\"-\"else match[\"sign\"]\n no_neg_zero=bool(match[\"no_neg_zero\"])\n alternate_form=bool(match[\"alt\"])\n zeropad=bool(match[\"zeropad\"])\n minimumwidth=int(match[\"minimumwidth\"]or \"0\")\n thousands_sep=match[\"thousands_sep\"]\n precision=int(match[\"precision\"]or \"6\")\n presentation_type=match[\"presentation_type\"]\n trim_zeros=presentation_type in \"gG\"and not alternate_form\n trim_point=not alternate_form\n exponent_indicator=\"E\"if presentation_type in \"EFG\"else \"e\"\n \n \n \n \n \n if presentation_type in \"fF%\":\n exponent=-precision\n if presentation_type ==\"%\":\n exponent -=2\n negative,significand=_round_to_exponent(\n self._numerator,self._denominator,exponent,no_neg_zero)\n scientific=False\n point_pos=precision\n else:\n figures=(\n max(precision,1)\n if presentation_type in \"gG\"\n else precision+1\n )\n negative,significand,exponent=_round_to_figures(\n self._numerator,self._denominator,figures)\n scientific=(\n presentation_type in \"eE\"\n or exponent >0\n or exponent+figures <=-4\n )\n point_pos=figures -1 if scientific else -exponent\n \n \n if presentation_type ==\"%\":\n suffix=\"%\"\n elif scientific:\n suffix=f\"{exponent_indicator}{exponent+point_pos:+03d}\"\n else:\n suffix=\"\"\n \n \n \n digits=f\"{significand:0{point_pos+1}d}\"\n \n \n \n \n sign=\"-\"if negative else pos_sign\n leading=digits[:len(digits)-point_pos]\n frac_part=digits[len(digits)-point_pos:]\n if trim_zeros:\n frac_part=frac_part.rstrip(\"0\")\n separator=\"\"if trim_point and not frac_part else \".\"\n trailing=separator+frac_part+suffix\n \n \n if zeropad:\n min_leading=minimumwidth -len(sign)-len(trailing)\n \n \n leading=leading.zfill(\n 3 *min_leading //4+1 if thousands_sep else min_leading\n )\n \n \n if thousands_sep:\n first_pos=1+(len(leading)-1)%3\n leading=leading[:first_pos]+\"\".join(\n thousands_sep+leading[pos:pos+3]\n for pos in range(first_pos,len(leading),3)\n )\n \n \n \n body=leading+trailing\n padding=fill *(minimumwidth -len(sign)-len(body))\n if align ==\">\":\n return padding+sign+body\n elif align ==\"<\":\n return sign+body+padding\n elif align ==\"^\":\n half=len(padding)//2\n return padding[:half]+sign+body+padding[half:]\n else:\n return sign+padding+body\n \n def __format__(self,format_spec,/):\n ''\n \n if match :=_GENERAL_FORMAT_SPECIFICATION_MATCHER(format_spec):\n return self._format_general(match)\n \n if match :=_FLOAT_FORMAT_SPECIFICATION_MATCHER(format_spec):\n \n \n if match[\"align\"]is None or match[\"zeropad\"]is None:\n return self._format_float_style(match)\n \n raise ValueError(\n f\"Invalid format specifier {format_spec !r} \"\n f\"for object of type {type(self).__name__ !r}\"\n )\n \n def _operator_fallbacks(monomorphic_operator,fallback_operator,\n handle_complex=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def forward(a,b):\n if isinstance(b,Fraction):\n return monomorphic_operator(a,b)\n elif isinstance(b,int):\n return monomorphic_operator(a,Fraction(b))\n elif isinstance(b,float):\n return fallback_operator(float(a),b)\n elif handle_complex and isinstance(b,complex):\n return fallback_operator(complex(a),b)\n else:\n return NotImplemented\n forward.__name__='__'+fallback_operator.__name__+'__'\n forward.__doc__=monomorphic_operator.__doc__\n \n def reverse(b,a):\n if isinstance(a,numbers.Rational):\n \n return monomorphic_operator(Fraction(a),b)\n elif isinstance(a,numbers.Real):\n return fallback_operator(float(a),float(b))\n elif handle_complex and isinstance(a,numbers.Complex):\n return fallback_operator(complex(a),complex(b))\n else:\n return NotImplemented\n reverse.__name__='__r'+fallback_operator.__name__+'__'\n reverse.__doc__=monomorphic_operator.__doc__\n \n return forward,reverse\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def _add(a,b):\n ''\n na,da=a._numerator,a._denominator\n nb,db=b._numerator,b._denominator\n g=math.gcd(da,db)\n if g ==1:\n return Fraction._from_coprime_ints(na *db+da *nb,da *db)\n s=da //g\n t=na *(db //g)+nb *s\n g2=math.gcd(t,g)\n if g2 ==1:\n return Fraction._from_coprime_ints(t,s *db)\n return Fraction._from_coprime_ints(t //g2,s *(db //g2))\n \n __add__,__radd__=_operator_fallbacks(_add,operator.add)\n \n def _sub(a,b):\n ''\n na,da=a._numerator,a._denominator\n nb,db=b._numerator,b._denominator\n g=math.gcd(da,db)\n if g ==1:\n return Fraction._from_coprime_ints(na *db -da *nb,da *db)\n s=da //g\n t=na *(db //g)-nb *s\n g2=math.gcd(t,g)\n if g2 ==1:\n return Fraction._from_coprime_ints(t,s *db)\n return Fraction._from_coprime_ints(t //g2,s *(db //g2))\n \n __sub__,__rsub__=_operator_fallbacks(_sub,operator.sub)\n \n def _mul(a,b):\n ''\n na,da=a._numerator,a._denominator\n nb,db=b._numerator,b._denominator\n g1=math.gcd(na,db)\n if g1 >1:\n na //=g1\n db //=g1\n g2=math.gcd(nb,da)\n if g2 >1:\n nb //=g2\n da //=g2\n return Fraction._from_coprime_ints(na *nb,db *da)\n \n __mul__,__rmul__=_operator_fallbacks(_mul,operator.mul)\n \n def _div(a,b):\n ''\n \n nb,db=b._numerator,b._denominator\n if nb ==0:\n raise ZeroDivisionError('Fraction(%s, 0)'%db)\n na,da=a._numerator,a._denominator\n g1=math.gcd(na,nb)\n if g1 >1:\n na //=g1\n nb //=g1\n g2=math.gcd(db,da)\n if g2 >1:\n da //=g2\n db //=g2\n n,d=na *db,nb *da\n if d <0:\n n,d=-n,-d\n return Fraction._from_coprime_ints(n,d)\n \n __truediv__,__rtruediv__=_operator_fallbacks(_div,operator.truediv)\n \n def _floordiv(a,b):\n ''\n return(a.numerator *b.denominator)//(a.denominator *b.numerator)\n \n __floordiv__,__rfloordiv__=_operator_fallbacks(_floordiv,operator.floordiv,False)\n \n def _divmod(a,b):\n ''\n da,db=a.denominator,b.denominator\n div,n_mod=divmod(a.numerator *db,da *b.numerator)\n return div,Fraction(n_mod,da *db)\n \n __divmod__,__rdivmod__=_operator_fallbacks(_divmod,divmod,False)\n \n def _mod(a,b):\n ''\n da,db=a.denominator,b.denominator\n return Fraction((a.numerator *db)%(b.numerator *da),da *db)\n \n __mod__,__rmod__=_operator_fallbacks(_mod,operator.mod,False)\n \n def __pow__(a,b):\n ''\n\n\n\n\n\n \n if isinstance(b,numbers.Rational):\n if b.denominator ==1:\n power=b.numerator\n if power >=0:\n return Fraction._from_coprime_ints(a._numerator **power,\n a._denominator **power)\n elif a._numerator >0:\n return Fraction._from_coprime_ints(a._denominator **-power,\n a._numerator **-power)\n elif a._numerator ==0:\n raise ZeroDivisionError('Fraction(%s, 0)'%\n a._denominator **-power)\n else:\n return Fraction._from_coprime_ints((-a._denominator)**-power,\n (-a._numerator)**-power)\n else:\n \n \n return float(a)**float(b)\n elif isinstance(b,(float,complex)):\n return float(a)**b\n else:\n return NotImplemented\n \n def __rpow__(b,a):\n ''\n if b._denominator ==1 and b._numerator >=0:\n \n return a **b._numerator\n \n if isinstance(a,numbers.Rational):\n return Fraction(a.numerator,a.denominator)**b\n \n if b._denominator ==1:\n return a **b._numerator\n \n return a **float(b)\n \n def __pos__(a):\n ''\n return Fraction._from_coprime_ints(a._numerator,a._denominator)\n \n def __neg__(a):\n ''\n return Fraction._from_coprime_ints(-a._numerator,a._denominator)\n \n def __abs__(a):\n ''\n return Fraction._from_coprime_ints(abs(a._numerator),a._denominator)\n \n def __int__(a,_index=operator.index):\n ''\n if a._numerator <0:\n return _index(-(-a._numerator //a._denominator))\n else:\n return _index(a._numerator //a._denominator)\n \n def __trunc__(a):\n ''\n if a._numerator <0:\n return -(-a._numerator //a._denominator)\n else:\n return a._numerator //a._denominator\n \n def __floor__(a):\n ''\n return a._numerator //a._denominator\n \n def __ceil__(a):\n ''\n \n return -(-a._numerator //a._denominator)\n \n def __round__(self,ndigits=None):\n ''\n\n\n \n if ndigits is None:\n d=self._denominator\n floor,remainder=divmod(self._numerator,d)\n if remainder *2 d:\n return floor+1\n \n elif floor %2 ==0:\n return floor\n else:\n return floor+1\n shift=10 **abs(ndigits)\n \n \n \n if ndigits >0:\n return Fraction(round(self *shift),shift)\n else:\n return Fraction(round(self /shift)*shift)\n \n def __hash__(self):\n ''\n return _hash_algorithm(self._numerator,self._denominator)\n \n def __eq__(a,b):\n ''\n if type(b)is int:\n return a._numerator ==b and a._denominator ==1\n if isinstance(b,numbers.Rational):\n return(a._numerator ==b.numerator and\n a._denominator ==b.denominator)\n if isinstance(b,numbers.Complex)and b.imag ==0:\n b=b.real\n if isinstance(b,float):\n if math.isnan(b)or math.isinf(b):\n \n \n return 0.0 ==b\n else:\n return a ==a.from_float(b)\n else:\n \n \n return NotImplemented\n \n def _richcmp(self,other,op):\n ''\n\n\n\n\n\n\n\n \n \n if isinstance(other,numbers.Rational):\n return op(self._numerator *other.denominator,\n self._denominator *other.numerator)\n if isinstance(other,float):\n if math.isnan(other)or math.isinf(other):\n return op(0.0,other)\n else:\n return op(self,self.from_float(other))\n else:\n return NotImplemented\n \n def __lt__(a,b):\n ''\n return a._richcmp(b,operator.lt)\n \n def __gt__(a,b):\n ''\n return a._richcmp(b,operator.gt)\n \n def __le__(a,b):\n ''\n return a._richcmp(b,operator.le)\n \n def __ge__(a,b):\n ''\n return a._richcmp(b,operator.ge)\n \n def __bool__(a):\n ''\n \n \n return bool(a._numerator)\n \n \n \n def __reduce__(self):\n return(self.__class__,(self._numerator,self._denominator))\n \n def __copy__(self):\n if type(self)==Fraction:\n return self\n return self.__class__(self._numerator,self._denominator)\n \n def __deepcopy__(self,memo):\n if type(self)==Fraction:\n return self\n return self.__class__(self._numerator,self._denominator)\n", ["decimal", "functools", "math", "numbers", "operator", "re", "sys"]], "functools": [".py", "''\n\n\n\n\n\n\n\n\n\n\n__all__=['update_wrapper','wraps','WRAPPER_ASSIGNMENTS','WRAPPER_UPDATES',\n'total_ordering','cache','cmp_to_key','lru_cache','reduce',\n'partial','partialmethod','singledispatch','singledispatchmethod',\n'cached_property']\n\nfrom abc import get_cache_token\nfrom collections import namedtuple\n\nfrom reprlib import recursive_repr\nfrom _thread import RLock\n\n\nGenericAlias=type(list[int])\n\n\n\n\n\n\n\n\nWRAPPER_ASSIGNMENTS=('__module__','__name__','__qualname__','__doc__',\n'__annotations__','__type_params__')\nWRAPPER_UPDATES=('__dict__',)\ndef update_wrapper(wrapper,\nwrapped,\nassigned=WRAPPER_ASSIGNMENTS,\nupdated=WRAPPER_UPDATES):\n ''\n\n\n\n\n\n\n\n\n\n \n for attr in assigned:\n try:\n value=getattr(wrapped,attr)\n except AttributeError:\n pass\n else:\n setattr(wrapper,attr,value)\n for attr in updated:\n getattr(wrapper,attr).update(getattr(wrapped,attr,{}))\n \n \n wrapper.__wrapped__=wrapped\n \n return wrapper\n \ndef wraps(wrapped,\nassigned=WRAPPER_ASSIGNMENTS,\nupdated=WRAPPER_UPDATES):\n ''\n\n\n\n\n\n\n \n return partial(update_wrapper,wrapped=wrapped,\n assigned=assigned,updated=updated)\n \n \n \n \n \n \n \n \n \n \n \ndef _gt_from_lt(self,other):\n ''\n op_result=type(self).__lt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result and self !=other\n \ndef _le_from_lt(self,other):\n ''\n op_result=type(self).__lt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return op_result or self ==other\n \ndef _ge_from_lt(self,other):\n ''\n op_result=type(self).__lt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _ge_from_le(self,other):\n ''\n op_result=type(self).__le__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result or self ==other\n \ndef _lt_from_le(self,other):\n ''\n op_result=type(self).__le__(self,other)\n if op_result is NotImplemented:\n return op_result\n return op_result and self !=other\n \ndef _gt_from_le(self,other):\n ''\n op_result=type(self).__le__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _lt_from_gt(self,other):\n ''\n op_result=type(self).__gt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result and self !=other\n \ndef _ge_from_gt(self,other):\n ''\n op_result=type(self).__gt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return op_result or self ==other\n \ndef _le_from_gt(self,other):\n ''\n op_result=type(self).__gt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _le_from_ge(self,other):\n ''\n op_result=type(self).__ge__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result or self ==other\n \ndef _gt_from_ge(self,other):\n ''\n op_result=type(self).__ge__(self,other)\n if op_result is NotImplemented:\n return op_result\n return op_result and self !=other\n \ndef _lt_from_ge(self,other):\n ''\n op_result=type(self).__ge__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \n_convert={\n'__lt__':[('__gt__',_gt_from_lt),\n('__le__',_le_from_lt),\n('__ge__',_ge_from_lt)],\n'__le__':[('__ge__',_ge_from_le),\n('__lt__',_lt_from_le),\n('__gt__',_gt_from_le)],\n'__gt__':[('__lt__',_lt_from_gt),\n('__ge__',_ge_from_gt),\n('__le__',_le_from_gt)],\n'__ge__':[('__le__',_le_from_ge),\n('__gt__',_gt_from_ge),\n('__lt__',_lt_from_ge)]\n}\n\ndef total_ordering(cls):\n ''\n \n roots={op for op in _convert if getattr(cls,op,None)is not getattr(object,op,None)}\n if not roots:\n raise ValueError('must define at least one ordering operation: < > <= >=')\n root=max(roots)\n for opname,opfunc in _convert[root]:\n if opname not in roots:\n opfunc.__name__=opname\n setattr(cls,opname,opfunc)\n return cls\n \n \n \n \n \n \ndef cmp_to_key(mycmp):\n ''\n class K(object):\n __slots__=['obj']\n def __init__(self,obj):\n self.obj=obj\n def __lt__(self,other):\n return mycmp(self.obj,other.obj)<0\n def __gt__(self,other):\n return mycmp(self.obj,other.obj)>0\n def __eq__(self,other):\n return mycmp(self.obj,other.obj)==0\n def __le__(self,other):\n return mycmp(self.obj,other.obj)<=0\n def __ge__(self,other):\n return mycmp(self.obj,other.obj)>=0\n __hash__=None\n return K\n \ntry:\n from _functools import cmp_to_key\nexcept ImportError:\n pass\n \n \n \n \n \n \n_initial_missing=object()\n\ndef reduce(function,sequence,initial=_initial_missing):\n ''\n\n\n\n\n\n\n\n\n \n \n it=iter(sequence)\n \n if initial is _initial_missing:\n try:\n value=next(it)\n except StopIteration:\n raise TypeError(\n \"reduce() of empty iterable with no initial value\")from None\n else:\n value=initial\n \n for element in it:\n value=function(value,element)\n \n return value\n \ntry:\n from _functools import reduce\nexcept ImportError:\n pass\n \n \n \n \n \n \n \nclass partial:\n ''\n\n \n \n __slots__=\"func\",\"args\",\"keywords\",\"__dict__\",\"__weakref__\"\n \n def __new__(cls,func,/,*args,**keywords):\n if not callable(func):\n raise TypeError(\"the first argument must be callable\")\n \n if isinstance(func,partial):\n args=func.args+args\n keywords={**func.keywords,**keywords}\n func=func.func\n \n self=super(partial,cls).__new__(cls)\n \n self.func=func\n self.args=args\n self.keywords=keywords\n return self\n \n def __call__(self,/,*args,**keywords):\n keywords={**self.keywords,**keywords}\n return self.func(*self.args,*args,**keywords)\n \n @recursive_repr()\n def __repr__(self):\n cls=type(self)\n qualname=cls.__qualname__\n module=cls.__module__\n args=[repr(self.func)]\n args.extend(repr(x)for x in self.args)\n args.extend(f\"{k}={v !r}\"for(k,v)in self.keywords.items())\n return f\"{module}.{qualname}({', '.join(args)})\"\n \n def __get__(self,obj,objtype=None):\n if obj is None:\n return self\n import warnings\n warnings.warn('functools.partial will be a method descriptor in '\n 'future Python versions; wrap it in staticmethod() '\n 'if you want to preserve the old behavior',\n FutureWarning,2)\n return self\n \n def __reduce__(self):\n return type(self),(self.func,),(self.func,self.args,\n self.keywords or None,self.__dict__ or None)\n \n def __setstate__(self,state):\n if not isinstance(state,tuple):\n raise TypeError(\"argument to __setstate__ must be a tuple\")\n if len(state)!=4:\n raise TypeError(f\"expected 4 items in state, got {len(state)}\")\n func,args,kwds,namespace=state\n if(not callable(func)or not isinstance(args,tuple)or\n (kwds is not None and not isinstance(kwds,dict))or\n (namespace is not None and not isinstance(namespace,dict))):\n raise TypeError(\"invalid partial state\")\n \n args=tuple(args)\n if kwds is None:\n kwds={}\n elif type(kwds)is not dict:\n kwds=dict(kwds)\n if namespace is None:\n namespace={}\n \n self.__dict__=namespace\n self.func=func\n self.args=args\n self.keywords=kwds\n \ntry:\n from _functools import partial\nexcept ImportError:\n pass\n \n \nclass partialmethod(object):\n ''\n\n\n\n\n \n \n def __init__(self,func,/,*args,**keywords):\n if not callable(func)and not hasattr(func,\"__get__\"):\n raise TypeError(\"{!r} is not callable or a descriptor\"\n .format(func))\n \n \n \n if isinstance(func,partialmethod):\n \n \n \n self.func=func.func\n self.args=func.args+args\n self.keywords={**func.keywords,**keywords}\n else:\n self.func=func\n self.args=args\n self.keywords=keywords\n \n def __repr__(self):\n cls=type(self)\n module=cls.__module__\n qualname=cls.__qualname__\n args=[repr(self.func)]\n args.extend(map(repr,self.args))\n args.extend(f\"{k}={v !r}\"for k,v in self.keywords.items())\n return f\"{module}.{qualname}({', '.join(args)})\"\n \n def _make_unbound_method(self):\n def _method(cls_or_self,/,*args,**keywords):\n keywords={**self.keywords,**keywords}\n return self.func(cls_or_self,*self.args,*args,**keywords)\n _method.__isabstractmethod__=self.__isabstractmethod__\n _method.__partialmethod__=self\n return _method\n \n def __get__(self,obj,cls=None):\n get=getattr(self.func,\"__get__\",None)\n result=None\n if get is not None and not isinstance(self.func,partial):\n new_func=get(obj,cls)\n if new_func is not self.func:\n \n \n result=partial(new_func,*self.args,**self.keywords)\n try:\n result.__self__=new_func.__self__\n except AttributeError:\n pass\n if result is None:\n \n \n result=self._make_unbound_method().__get__(obj,cls)\n return result\n \n @property\n def __isabstractmethod__(self):\n return getattr(self.func,\"__isabstractmethod__\",False)\n \n __class_getitem__=classmethod(GenericAlias)\n \n \n \n \ndef _unwrap_partial(func):\n while isinstance(func,partial):\n func=func.func\n return func\n \ndef _unwrap_partialmethod(func):\n prev=None\n while func is not prev:\n prev=func\n while isinstance(getattr(func,\"__partialmethod__\",None),partialmethod):\n func=func.__partialmethod__\n while isinstance(func,partialmethod):\n func=getattr(func,'func')\n func=_unwrap_partial(func)\n return func\n \n \n \n \n \n_CacheInfo=namedtuple(\"CacheInfo\",[\"hits\",\"misses\",\"maxsize\",\"currsize\"])\n\nclass _HashedSeq(list):\n ''\n\n\n\n \n \n __slots__='hashvalue'\n \n def __init__(self,tup,hash=hash):\n self[:]=tup\n self.hashvalue=hash(tup)\n \n def __hash__(self):\n return self.hashvalue\n \ndef _make_key(args,kwds,typed,\nkwd_mark=(object(),),\nfasttypes={int,str},\ntuple=tuple,type=type,len=len):\n ''\n\n\n\n\n\n\n\n\n \n \n \n \n \n key=args\n if kwds:\n key +=kwd_mark\n for item in kwds.items():\n key +=item\n if typed:\n key +=tuple(type(v)for v in args)\n if kwds:\n key +=tuple(type(v)for v in kwds.values())\n elif len(key)==1 and type(key[0])in fasttypes:\n return key[0]\n return _HashedSeq(key)\n \ndef lru_cache(maxsize=128,typed=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n if isinstance(maxsize,int):\n \n if maxsize <0:\n maxsize=0\n elif callable(maxsize)and isinstance(typed,bool):\n \n user_function,maxsize=maxsize,128\n wrapper=_lru_cache_wrapper(user_function,maxsize,typed,_CacheInfo)\n wrapper.cache_parameters=lambda:{'maxsize':maxsize,'typed':typed}\n return update_wrapper(wrapper,user_function)\n elif maxsize is not None:\n raise TypeError(\n 'Expected first argument to be an integer, a callable, or None')\n \n def decorating_function(user_function):\n wrapper=_lru_cache_wrapper(user_function,maxsize,typed,_CacheInfo)\n wrapper.cache_parameters=lambda:{'maxsize':maxsize,'typed':typed}\n return update_wrapper(wrapper,user_function)\n \n return decorating_function\n \ndef _lru_cache_wrapper(user_function,maxsize,typed,_CacheInfo):\n\n sentinel=object()\n make_key=_make_key\n PREV,NEXT,KEY,RESULT=0,1,2,3\n \n cache={}\n hits=misses=0\n full=False\n cache_get=cache.get\n cache_len=cache.__len__\n lock=RLock()\n root=[]\n root[:]=[root,root,None,None]\n \n if maxsize ==0:\n \n def wrapper(*args,**kwds):\n \n nonlocal misses\n misses +=1\n result=user_function(*args,**kwds)\n return result\n \n elif maxsize is None:\n \n def wrapper(*args,**kwds):\n \n nonlocal hits,misses\n key=make_key(args,kwds,typed)\n result=cache_get(key,sentinel)\n if result is not sentinel:\n hits +=1\n return result\n misses +=1\n result=user_function(*args,**kwds)\n cache[key]=result\n return result\n \n else:\n \n def wrapper(*args,**kwds):\n \n nonlocal root,hits,misses,full\n key=make_key(args,kwds,typed)\n with lock:\n link=cache_get(key)\n if link is not None:\n \n link_prev,link_next,_key,result=link\n link_prev[NEXT]=link_next\n link_next[PREV]=link_prev\n last=root[PREV]\n last[NEXT]=root[PREV]=link\n link[PREV]=last\n link[NEXT]=root\n hits +=1\n return result\n misses +=1\n result=user_function(*args,**kwds)\n with lock:\n if key in cache:\n \n \n \n \n pass\n elif full:\n \n oldroot=root\n oldroot[KEY]=key\n oldroot[RESULT]=result\n \n \n \n \n \n \n root=oldroot[NEXT]\n oldkey=root[KEY]\n oldresult=root[RESULT]\n root[KEY]=root[RESULT]=None\n \n del cache[oldkey]\n \n \n \n cache[key]=oldroot\n else:\n \n last=root[PREV]\n link=[last,root,key,result]\n last[NEXT]=root[PREV]=cache[key]=link\n \n \n full=(cache_len()>=maxsize)\n return result\n \n def cache_info():\n ''\n with lock:\n return _CacheInfo(hits,misses,maxsize,cache_len())\n \n def cache_clear():\n ''\n nonlocal hits,misses,full\n with lock:\n cache.clear()\n root[:]=[root,root,None,None]\n hits=misses=0\n full=False\n \n wrapper.cache_info=cache_info\n wrapper.cache_clear=cache_clear\n return wrapper\n \ntry:\n from _functools import _lru_cache_wrapper\nexcept ImportError:\n pass\n \n \n \n \n \n \ndef cache(user_function,/):\n ''\n return lru_cache(maxsize=None)(user_function)\n \n \n \n \n \n \ndef _c3_merge(sequences):\n ''\n\n\n\n \n result=[]\n while True:\n sequences=[s for s in sequences if s]\n if not sequences:\n return result\n for s1 in sequences:\n candidate=s1[0]\n for s2 in sequences:\n if candidate in s2[1:]:\n candidate=None\n break\n else:\n break\n if candidate is None:\n raise RuntimeError(\"Inconsistent hierarchy\")\n result.append(candidate)\n \n for seq in sequences:\n if seq[0]==candidate:\n del seq[0]\n \ndef _c3_mro(cls,abcs=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n for i,base in enumerate(reversed(cls.__bases__)):\n if hasattr(base,'__abstractmethods__'):\n boundary=len(cls.__bases__)-i\n break\n else:\n boundary=0\n abcs=list(abcs)if abcs else[]\n explicit_bases=list(cls.__bases__[:boundary])\n abstract_bases=[]\n other_bases=list(cls.__bases__[boundary:])\n for base in abcs:\n if issubclass(cls,base)and not any(\n issubclass(b,base)for b in cls.__bases__\n ):\n \n \n abstract_bases.append(base)\n for base in abstract_bases:\n abcs.remove(base)\n explicit_c3_mros=[_c3_mro(base,abcs=abcs)for base in explicit_bases]\n abstract_c3_mros=[_c3_mro(base,abcs=abcs)for base in abstract_bases]\n other_c3_mros=[_c3_mro(base,abcs=abcs)for base in other_bases]\n return _c3_merge(\n [[cls]]+\n explicit_c3_mros+abstract_c3_mros+other_c3_mros+\n [explicit_bases]+[abstract_bases]+[other_bases]\n )\n \ndef _compose_mro(cls,types):\n ''\n\n\n\n\n \n bases=set(cls.__mro__)\n \n def is_related(typ):\n return(typ not in bases and hasattr(typ,'__mro__')\n and not isinstance(typ,GenericAlias)\n and issubclass(cls,typ))\n types=[n for n in types if is_related(n)]\n \n \n def is_strict_base(typ):\n for other in types:\n if typ !=other and typ in other.__mro__:\n return True\n return False\n types=[n for n in types if not is_strict_base(n)]\n \n \n type_set=set(types)\n mro=[]\n for typ in types:\n found=[]\n for sub in typ.__subclasses__():\n if sub not in bases and issubclass(cls,sub):\n found.append([s for s in sub.__mro__ if s in type_set])\n if not found:\n mro.append(typ)\n continue\n \n found.sort(key=len,reverse=True)\n for sub in found:\n for subcls in sub:\n if subcls not in mro:\n mro.append(subcls)\n return _c3_mro(cls,abcs=mro)\n \ndef _find_impl(cls,registry):\n ''\n\n\n\n\n\n\n\n \n mro=_compose_mro(cls,registry.keys())\n match=None\n for t in mro:\n if match is not None:\n \n \n if(t in registry and t not in cls.__mro__\n and match not in cls.__mro__\n and not issubclass(match,t)):\n raise RuntimeError(\"Ambiguous dispatch: {} or {}\".format(\n match,t))\n break\n if t in registry:\n match=t\n return registry.get(match)\n \ndef singledispatch(func):\n ''\n\n\n\n\n\n\n \n \n \n \n import types,weakref\n \n registry={}\n dispatch_cache=weakref.WeakKeyDictionary()\n cache_token=None\n \n def dispatch(cls):\n ''\n\n\n\n\n \n nonlocal cache_token\n if cache_token is not None:\n current_token=get_cache_token()\n if cache_token !=current_token:\n dispatch_cache.clear()\n cache_token=current_token\n try:\n impl=dispatch_cache[cls]\n except KeyError:\n try:\n impl=registry[cls]\n except KeyError:\n impl=_find_impl(cls,registry)\n dispatch_cache[cls]=impl\n return impl\n \n def _is_union_type(cls):\n from typing import get_origin,Union\n return get_origin(cls)in{Union,types.UnionType}\n \n def _is_valid_dispatch_type(cls):\n if isinstance(cls,type):\n return True\n from typing import get_args\n return(_is_union_type(cls)and\n all(isinstance(arg,type)for arg in get_args(cls)))\n \n def register(cls,func=None):\n ''\n\n\n\n \n nonlocal cache_token\n if _is_valid_dispatch_type(cls):\n if func is None:\n return lambda f:register(cls,f)\n else:\n if func is not None:\n raise TypeError(\n f\"Invalid first argument to `register()`. \"\n f\"{cls !r} is not a class or union type.\"\n )\n ann=getattr(cls,'__annotations__',{})\n if not ann:\n raise TypeError(\n f\"Invalid first argument to `register()`: {cls !r}. \"\n f\"Use either `@register(some_class)` or plain `@register` \"\n f\"on an annotated function.\"\n )\n func=cls\n \n \n from typing import get_type_hints\n argname,cls=next(iter(get_type_hints(func).items()))\n if not _is_valid_dispatch_type(cls):\n if _is_union_type(cls):\n raise TypeError(\n f\"Invalid annotation for {argname !r}. \"\n f\"{cls !r} not all arguments are classes.\"\n )\n else:\n raise TypeError(\n f\"Invalid annotation for {argname !r}. \"\n f\"{cls !r} is not a class.\"\n )\n \n if _is_union_type(cls):\n from typing import get_args\n \n for arg in get_args(cls):\n registry[arg]=func\n else:\n registry[cls]=func\n if cache_token is None and hasattr(cls,'__abstractmethods__'):\n cache_token=get_cache_token()\n dispatch_cache.clear()\n return func\n \n def wrapper(*args,**kw):\n if not args:\n raise TypeError(f'{funcname} requires at least '\n '1 positional argument')\n return dispatch(args[0].__class__)(*args,**kw)\n \n funcname=getattr(func,'__name__','singledispatch function')\n registry[object]=func\n wrapper.register=register\n wrapper.dispatch=dispatch\n wrapper.registry=types.MappingProxyType(registry)\n wrapper._clear_cache=dispatch_cache.clear\n update_wrapper(wrapper,func)\n return wrapper\n \n \n \nclass singledispatchmethod:\n ''\n\n\n\n \n \n def __init__(self,func):\n if not callable(func)and not hasattr(func,\"__get__\"):\n raise TypeError(f\"{func !r} is not callable or a descriptor\")\n \n self.dispatcher=singledispatch(func)\n self.func=func\n \n import weakref\n self._method_cache=weakref.WeakKeyDictionary()\n \n def register(self,cls,method=None):\n ''\n\n\n \n return self.dispatcher.register(cls,func=method)\n \n def __get__(self,obj,cls=None):\n if self._method_cache is not None:\n try:\n _method=self._method_cache[obj]\n except TypeError:\n self._method_cache=None\n except KeyError:\n pass\n else:\n return _method\n \n dispatch=self.dispatcher.dispatch\n funcname=getattr(self.func,'__name__','singledispatchmethod method')\n def _method(*args,**kwargs):\n if not args:\n raise TypeError(f'{funcname} requires at least '\n '1 positional argument')\n return dispatch(args[0].__class__).__get__(obj,cls)(*args,**kwargs)\n \n _method.__isabstractmethod__=self.__isabstractmethod__\n _method.register=self.register\n update_wrapper(_method,self.func)\n \n if self._method_cache is not None:\n self._method_cache[obj]=_method\n \n return _method\n \n @property\n def __isabstractmethod__(self):\n return getattr(self.func,'__isabstractmethod__',False)\n \n \n \n \n \n \n_NOT_FOUND=object()\n\nclass cached_property:\n def __init__(self,func):\n self.func=func\n self.attrname=None\n self.__doc__=func.__doc__\n self.__module__=func.__module__\n \n def __set_name__(self,owner,name):\n if self.attrname is None:\n self.attrname=name\n elif name !=self.attrname:\n raise TypeError(\n \"Cannot assign the same cached_property to two different names \"\n f\"({self.attrname !r} and {name !r}).\"\n )\n \n def __get__(self,instance,owner=None):\n if instance is None:\n return self\n if self.attrname is None:\n raise TypeError(\n \"Cannot use cached_property instance without calling __set_name__ on it.\")\n try:\n cache=instance.__dict__\n except AttributeError:\n msg=(\n f\"No '__dict__' attribute on {type(instance).__name__ !r} \"\n f\"instance to cache {self.attrname !r} property.\"\n )\n raise TypeError(msg)from None\n val=cache.get(self.attrname,_NOT_FOUND)\n if val is _NOT_FOUND:\n val=self.func(instance)\n try:\n cache[self.attrname]=val\n except TypeError:\n msg=(\n f\"The '__dict__' attribute on {type(instance).__name__ !r} instance \"\n f\"does not support item assignment for caching {self.attrname !r} property.\"\n )\n raise TypeError(msg)from None\n return val\n \n __class_getitem__=classmethod(GenericAlias)\n", ["_functools", "_thread", "abc", "collections", "reprlib", "types", "typing", "warnings", "weakref"]], "gc": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nDEBUG_COLLECTABLE=2\n\nDEBUG_LEAK=38\n\nDEBUG_SAVEALL=32\n\nDEBUG_STATS=1\n\nDEBUG_UNCOLLECTABLE=4\n\nclass __loader__:\n pass\n \ncallbacks=[]\n\ndef collect(*args,**kw):\n ''\n\n\n\n\n\n \n pass\n \ndef disable(*args,**kw):\n ''\n\n \n pass\n \ndef enable(*args,**kw):\n ''\n\n \n pass\n \ngarbage=[]\n\ndef get_count(*args,**kw):\n ''\n\n \n pass\n \ndef get_debug(*args,**kw):\n ''\n\n \n pass\n \ndef get_objects(*args,**kw):\n ''\n\n\n \n pass\n \ndef get_referents(*args,**kw):\n ''\n pass\n \ndef get_referrers(*args,**kw):\n ''\n pass\n \ndef get_threshold(*args,**kw):\n ''\n\n \n pass\n \ndef is_tracked(*args,**kw):\n ''\n\n\n \n pass\n \ndef isenabled(*args,**kw):\n ''\n\n \n pass\n \ndef set_debug(*args,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n \n pass\n \ndef set_threshold(*args,**kw):\n ''\n\n\n \n pass\n", []], "genericpath": [".py", "''\n\n\n\n\nimport os\nimport stat\n\n__all__=['commonprefix','exists','getatime','getctime','getmtime',\n'getsize','isdevdrive','isdir','isfile','isjunction','islink',\n'lexists','samefile','sameopenfile','samestat']\n\n\n\n\ndef exists(path):\n ''\n try:\n os.stat(path)\n except(OSError,ValueError):\n return False\n return True\n \n \n \ndef lexists(path):\n ''\n try:\n os.lstat(path)\n except(OSError,ValueError):\n return False\n return True\n \n \n \ndef isfile(path):\n ''\n try:\n st=os.stat(path)\n except(OSError,ValueError):\n return False\n return stat.S_ISREG(st.st_mode)\n \n \n \n \n \ndef isdir(s):\n ''\n try:\n st=os.stat(s)\n except(OSError,ValueError):\n return False\n return stat.S_ISDIR(st.st_mode)\n \n \n \n \n \ndef islink(path):\n ''\n try:\n st=os.lstat(path)\n except(OSError,ValueError,AttributeError):\n return False\n return stat.S_ISLNK(st.st_mode)\n \n \n \ndef isjunction(path):\n ''\n \n os.fspath(path)\n return False\n \n \ndef isdevdrive(path):\n ''\n \n os.fspath(path)\n return False\n \n \ndef getsize(filename):\n ''\n return os.stat(filename).st_size\n \n \ndef getmtime(filename):\n ''\n return os.stat(filename).st_mtime\n \n \ndef getatime(filename):\n ''\n return os.stat(filename).st_atime\n \n \ndef getctime(filename):\n ''\n return os.stat(filename).st_ctime\n \n \n \ndef commonprefix(m):\n ''\n if not m:return ''\n \n \n \n \n if not isinstance(m[0],(list,tuple)):\n m=tuple(map(os.fspath,m))\n s1=min(m)\n s2=max(m)\n for i,c in enumerate(s1):\n if c !=s2[i]:\n return s1[:i]\n return s1\n \n \n \ndef samestat(s1,s2):\n ''\n return(s1.st_ino ==s2.st_ino and\n s1.st_dev ==s2.st_dev)\n \n \n \ndef samefile(f1,f2):\n ''\n\n\n\n \n s1=os.stat(f1)\n s2=os.stat(f2)\n return samestat(s1,s2)\n \n \n \n \ndef sameopenfile(fp1,fp2):\n ''\n s1=os.fstat(fp1)\n s2=os.fstat(fp2)\n return samestat(s1,s2)\n \n \n \n \n \n \n \n \n \ndef _splitext(p,sep,altsep,extsep):\n ''\n\n\n \n \n \n sepIndex=p.rfind(sep)\n if altsep:\n altsepIndex=p.rfind(altsep)\n sepIndex=max(sepIndex,altsepIndex)\n \n dotIndex=p.rfind(extsep)\n if dotIndex >sepIndex:\n \n filenameIndex=sepIndex+1\n while filenameIndex [ \\t]+) | # spaces and horizontal tabs\n (?P[0-9]+\\b) | # decimal integer\n (?Pn\\b) | # only n is allowed\n (?P[()]) |\n (?P[-*/%+?:]|[>,\n # <=, >=, ==, !=, &&, ||,\n # ? :\n # unary and bitwise ops\n # not allowed\n (?P\\w+|.) # invalid token\n \"\"\",re.VERBOSE |re.DOTALL)\n\n\ndef _tokenize(plural):\n for mo in re.finditer(_token_pattern,plural):\n kind=mo.lastgroup\n if kind =='WHITESPACES':\n continue\n value=mo.group(kind)\n if kind =='INVALID':\n raise ValueError('invalid token in plural form: %s'%value)\n yield value\n yield ''\n \n \ndef _error(value):\n if value:\n return ValueError('unexpected token in plural form: %s'%value)\n else:\n return ValueError('unexpected end of plural form')\n \n \n_binary_ops=(\n('||',),\n('&&',),\n('==','!='),\n('<','>','<=','>='),\n('+','-'),\n('*','/','%'),\n)\n_binary_ops={op:i for i,ops in enumerate(_binary_ops,1)for op in ops}\n_c2py_ops={'||':'or','&&':'and','/':'//'}\n\n\ndef _parse(tokens,priority=-1):\n result=''\n nexttok=next(tokens)\n while nexttok =='!':\n result +='not '\n nexttok=next(tokens)\n \n if nexttok =='(':\n sub,nexttok=_parse(tokens)\n result='%s(%s)'%(result,sub)\n if nexttok !=')':\n raise ValueError('unbalanced parenthesis in plural form')\n elif nexttok =='n':\n result='%s%s'%(result,nexttok)\n else:\n try:\n value=int(nexttok,10)\n except ValueError:\n raise _error(nexttok)from None\n result='%s%d'%(result,value)\n nexttok=next(tokens)\n \n j=100\n while nexttok in _binary_ops:\n i=_binary_ops[nexttok]\n if i 1000:\n raise ValueError('plural form expression is too long')\n try:\n result,nexttok=_parse(_tokenize(plural))\n if nexttok:\n raise _error(nexttok)\n \n depth=0\n for c in result:\n if c =='(':\n depth +=1\n if depth >20:\n \n \n raise ValueError('plural form expression is too complex')\n elif c ==')':\n depth -=1\n \n ns={'_as_int':_as_int,'__name__':__name__}\n exec('''if True:\n def func(n):\n if not isinstance(n, int):\n n = _as_int(n)\n return int(%s)\n '''%result,ns)\n return ns['func']\n except RecursionError:\n \n raise ValueError('plural form expression is too complex')\n \n \ndef _expand_lang(loc):\n import locale\n loc=locale.normalize(loc)\n COMPONENT_CODESET=1 <<0\n COMPONENT_TERRITORY=1 <<1\n COMPONENT_MODIFIER=1 <<2\n \n mask=0\n pos=loc.find('@')\n if pos >=0:\n modifier=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_MODIFIER\n else:\n modifier=''\n pos=loc.find('.')\n if pos >=0:\n codeset=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_CODESET\n else:\n codeset=''\n pos=loc.find('_')\n if pos >=0:\n territory=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_TERRITORY\n else:\n territory=''\n language=loc\n ret=[]\n for i in range(mask+1):\n if not(i&~mask):\n val=language\n if i&COMPONENT_TERRITORY:val +=territory\n if i&COMPONENT_CODESET:val +=codeset\n if i&COMPONENT_MODIFIER:val +=modifier\n ret.append(val)\n ret.reverse()\n return ret\n \n \nclass NullTranslations:\n def __init__(self,fp=None):\n self._info={}\n self._charset=None\n self._fallback=None\n if fp is not None:\n self._parse(fp)\n \n def _parse(self,fp):\n pass\n \n def add_fallback(self,fallback):\n if self._fallback:\n self._fallback.add_fallback(fallback)\n else:\n self._fallback=fallback\n \n def gettext(self,message):\n if self._fallback:\n return self._fallback.gettext(message)\n return message\n \n def ngettext(self,msgid1,msgid2,n):\n if self._fallback:\n return self._fallback.ngettext(msgid1,msgid2,n)\n n=_as_int2(n)\n if n ==1:\n return msgid1\n else:\n return msgid2\n \n def pgettext(self,context,message):\n if self._fallback:\n return self._fallback.pgettext(context,message)\n return message\n \n def npgettext(self,context,msgid1,msgid2,n):\n if self._fallback:\n return self._fallback.npgettext(context,msgid1,msgid2,n)\n n=_as_int2(n)\n if n ==1:\n return msgid1\n else:\n return msgid2\n \n def info(self):\n return self._info\n \n def charset(self):\n return self._charset\n \n def install(self,names=None):\n import builtins\n builtins.__dict__['_']=self.gettext\n if names is not None:\n allowed={'gettext','ngettext','npgettext','pgettext'}\n for name in allowed&set(names):\n builtins.__dict__[name]=getattr(self,name)\n \n \nclass GNUTranslations(NullTranslations):\n\n LE_MAGIC=0x950412de\n BE_MAGIC=0xde120495\n \n \n \n CONTEXT=\"%s\\x04%s\"\n \n \n VERSIONS=(0,1)\n \n def _get_versions(self,version):\n ''\n return(version >>16,version&0xffff)\n \n def _parse(self,fp):\n ''\n \n \n from struct import unpack\n filename=getattr(fp,'name','')\n \n \n self._catalog=catalog={}\n self.plural=lambda n:int(n !=1)\n buf=fp.read()\n buflen=len(buf)\n \n magic=unpack('4I',buf[4:20])\n ii='>II'\n else:\n raise OSError(0,'Bad magic number',filename)\n \n major_version,minor_version=self._get_versions(version)\n \n if major_version not in self.VERSIONS:\n raise OSError(0,'Bad version number '+str(major_version),filename)\n \n \n \n for i in range(0,msgcount):\n mlen,moff=unpack(ii,buf[masteridx:masteridx+8])\n mend=moff+mlen\n tlen,toff=unpack(ii,buf[transidx:transidx+8])\n tend=toff+tlen\n if mend 1 else escaped_seps\n not_sep=f'[^{escaped_seps}]'\n if include_hidden:\n one_last_segment=f'{not_sep}+'\n one_segment=f'{one_last_segment}{any_sep}'\n any_segments=f'(?:.+{any_sep})?'\n any_last_segments='.*'\n else:\n one_last_segment=f'[^{escaped_seps}.]{not_sep}*'\n one_segment=f'{one_last_segment}{any_sep}'\n any_segments=f'(?:{one_segment})*'\n any_last_segments=f'{any_segments}(?:{one_last_segment})?'\n \n results=[]\n parts=re.split(any_sep,pat)\n last_part_idx=len(parts)-1\n for idx,part in enumerate(parts):\n if part =='*':\n results.append(one_segment if idx '\n \n def _init_write(self,filename):\n self.name=filename\n self.crc=zlib.crc32(b\"\")\n self.size=0\n self.writebuf=[]\n self.bufsize=0\n self.offset=0\n \n def _write_gzip_header(self,compresslevel):\n self.fileobj.write(b'\\037\\213')\n self.fileobj.write(b'\\010')\n try:\n \n \n fname=os.path.basename(self.name)\n if not isinstance(fname,bytes):\n fname=fname.encode('latin-1')\n if fname.endswith(b'.gz'):\n fname=fname[:-3]\n except UnicodeEncodeError:\n fname=b''\n flags=0\n if fname:\n flags=FNAME\n self.fileobj.write(chr(flags).encode('latin-1'))\n mtime=self._write_mtime\n if mtime is None:\n mtime=time.time()\n write32u(self.fileobj,int(mtime))\n if compresslevel ==_COMPRESS_LEVEL_BEST:\n xfl=b'\\002'\n elif compresslevel ==_COMPRESS_LEVEL_FAST:\n xfl=b'\\004'\n else:\n xfl=b'\\000'\n self.fileobj.write(xfl)\n self.fileobj.write(b'\\377')\n if fname:\n self.fileobj.write(fname+b'\\000')\n \n def write(self,data):\n self._check_not_closed()\n if self.mode !=WRITE:\n import errno\n raise OSError(errno.EBADF,\"write() on read-only GzipFile object\")\n \n if self.fileobj is None:\n raise ValueError(\"write() on closed GzipFile object\")\n \n if isinstance(data,(bytes,bytearray)):\n length=len(data)\n else:\n \n data=memoryview(data)\n length=data.nbytes\n \n if length >0:\n self.fileobj.write(self.compress.compress(data))\n self.size +=length\n self.crc=zlib.crc32(data,self.crc)\n self.offset +=length\n \n return length\n \n def read(self,size=-1):\n self._check_not_closed()\n if self.mode !=READ:\n import errno\n raise OSError(errno.EBADF,\"read() on write-only GzipFile object\")\n return self._buffer.read(size)\n \n def read1(self,size=-1):\n ''\n\n \n self._check_not_closed()\n if self.mode !=READ:\n import errno\n raise OSError(errno.EBADF,\"read1() on write-only GzipFile object\")\n \n if size <0:\n size=io.DEFAULT_BUFFER_SIZE\n return self._buffer.read1(size)\n \n def peek(self,n):\n self._check_not_closed()\n if self.mode !=READ:\n import errno\n raise OSError(errno.EBADF,\"peek() on write-only GzipFile object\")\n return self._buffer.peek(n)\n \n @property\n def closed(self):\n return self.fileobj is None\n \n def close(self):\n fileobj=self.fileobj\n if fileobj is None:\n return\n self.fileobj=None\n try:\n if self.mode ==WRITE:\n fileobj.write(self.compress.flush())\n write32u(fileobj,self.crc)\n \n write32u(fileobj,self.size&0xffffffff)\n elif self.mode ==READ:\n self._buffer.close()\n finally:\n myfileobj=self.myfileobj\n if myfileobj:\n self.myfileobj=None\n myfileobj.close()\n \n def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):\n self._check_not_closed()\n if self.mode ==WRITE:\n \n self.fileobj.write(self.compress.flush(zlib_mode))\n self.fileobj.flush()\n \n def fileno(self):\n ''\n\n\n\n \n return self.fileobj.fileno()\n \n def rewind(self):\n ''\n \n if self.mode !=READ:\n raise OSError(\"Can't rewind in write mode\")\n self._buffer.seek(0)\n \n def readable(self):\n return self.mode ==READ\n \n def writable(self):\n return self.mode ==WRITE\n \n def seekable(self):\n return True\n \n def seek(self,offset,whence=io.SEEK_SET):\n if self.mode ==WRITE:\n if whence !=io.SEEK_SET:\n if whence ==io.SEEK_CUR:\n offset=self.offset+offset\n else:\n raise ValueError('Seek from end not supported')\n if offset startpos:\n parentpos=(pos -1)>>1\n parent=heap[parentpos]\n if newitem startpos:\n parentpos=(pos -1)>>1\n parent=heap[parentpos]\n if parent 1:\n try:\n while True:\n value,order,next=s=h[0]\n yield value\n s[0]=next()\n _heapreplace(h,s)\n except StopIteration:\n _heappop(h)\n if h:\n \n value,order,next=h[0]\n yield value\n yield from next.__self__\n return\n \n for order,it in enumerate(map(iter,iterables)):\n try:\n next=it.__next__\n value=next()\n h_append([key(value),order *direction,value,next])\n except StopIteration:\n pass\n _heapify(h)\n while len(h)>1:\n try:\n while True:\n key_value,order,value,next=s=h[0]\n yield value\n value=next()\n s[0]=key(value)\n s[2]=value\n _heapreplace(h,s)\n except StopIteration:\n _heappop(h)\n if h:\n key_value,order,value,next=h[0]\n yield value\n yield from next.__self__\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef nsmallest(n,iterable,key=None):\n ''\n\n\n \n \n \n if n ==1:\n it=iter(iterable)\n sentinel=object()\n result=min(it,default=sentinel,key=key)\n return[]if result is sentinel else[result]\n \n \n try:\n size=len(iterable)\n except(TypeError,AttributeError):\n pass\n else:\n if n >=size:\n return sorted(iterable,key=key)[:n]\n \n \n if key is None:\n it=iter(iterable)\n \n \n result=[(elem,i)for i,elem in zip(range(n),it)]\n if not result:\n return result\n _heapify_max(result)\n top=result[0][0]\n order=n\n _heapreplace=_heapreplace_max\n for elem in it:\n if elem =size:\n return sorted(iterable,key=key,reverse=True)[:n]\n \n \n if key is None:\n it=iter(iterable)\n result=[(elem,i)for i,elem in zip(range(0,-n,-1),it)]\n if not result:\n return result\n heapify(result)\n top=result[0][0]\n order=-n\n _heapreplace=heapreplace\n for elem in it:\n if top blocksize:\n key=digest_cons(key).digest()\n \n \n \n self.block_size=blocksize\n \n key=key.ljust(blocksize,b'\\0')\n self._outer.update(key.translate(trans_5C))\n self._inner.update(key.translate(trans_36))\n if msg is not None:\n self.update(msg)\n \n @property\n def name(self):\n if self._hmac:\n return self._hmac.name\n else:\n return f\"hmac-{self._inner.name}\"\n \n def update(self,msg):\n ''\n inst=self._hmac or self._inner\n inst.update(msg)\n \n def copy(self):\n ''\n\n\n \n \n other=self.__class__.__new__(self.__class__)\n other.digest_size=self.digest_size\n if self._hmac:\n other._hmac=self._hmac.copy()\n other._inner=other._outer=None\n else:\n other._hmac=None\n other._inner=self._inner.copy()\n other._outer=self._outer.copy()\n return other\n \n def _current(self):\n ''\n\n\n \n if self._hmac:\n return self._hmac\n else:\n h=self._outer.copy()\n h.update(self._inner.digest())\n return h\n \n def digest(self):\n ''\n\n\n\n\n \n h=self._current()\n return h.digest()\n \n def hexdigest(self):\n ''\n \n h=self._current()\n return h.hexdigest()\n \ndef new(key,msg=None,digestmod=''):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return HMAC(key,msg,digestmod)\n \n \ndef digest(key,msg,digest):\n ''\n\n\n\n\n\n\n \n if _hashopenssl is not None and isinstance(digest,(str,_functype)):\n try:\n return _hashopenssl.hmac_digest(key,msg,digest)\n except _hashopenssl.UnsupportedDigestmodError:\n pass\n \n if callable(digest):\n digest_cons=digest\n elif isinstance(digest,str):\n digest_cons=lambda d=b'':_hashlib.new(digest,d)\n else:\n digest_cons=lambda d=b'':digest.new(d)\n \n inner=digest_cons()\n outer=digest_cons()\n blocksize=getattr(inner,'block_size',64)\n if len(key)>blocksize:\n key=digest_cons(key).digest()\n key=key+b'\\x00'*(blocksize -len(key))\n inner.update(key.translate(trans_36))\n outer.update(key.translate(trans_5C))\n inner.update(msg)\n outer.update(inner.digest())\n return outer.digest()\n", ["_hashlib", "_operator", "hashlib", "warnings"]], "imp": [".py", "''\n\n\n\n\n\n\n\nfrom _imp import(lock_held,acquire_lock,release_lock,\nget_frozen_object,is_frozen_package,\ninit_frozen,is_builtin,is_frozen,\n_fix_co_filename,_frozen_module_names)\ntry:\n from _imp import create_dynamic\nexcept ImportError:\n\n create_dynamic=None\n \nfrom importlib._bootstrap import _ERR_MSG,_exec,_load,_builtin_from_name\nfrom importlib._bootstrap_external import SourcelessFileLoader\n\nfrom importlib import machinery\nfrom importlib import util\nimport importlib\nimport os\nimport sys\nimport tokenize\nimport types\nimport warnings\n\nwarnings.warn(\"the imp module is deprecated in favour of importlib and slated \"\n\"for removal in Python 3.12; \"\n\"see the module's documentation for alternative uses\",\nDeprecationWarning,stacklevel=2)\n\n\nSEARCH_ERROR=0\nPY_SOURCE=1\nPY_COMPILED=2\nC_EXTENSION=3\nPY_RESOURCE=4\nPKG_DIRECTORY=5\nC_BUILTIN=6\nPY_FROZEN=7\nPY_CODERESOURCE=8\nIMP_HOOK=9\n\n\ndef new_module(name):\n ''\n\n\n\n\n\n \n return types.ModuleType(name)\n \n \ndef get_magic():\n ''\n\n\n \n return util.MAGIC_NUMBER\n \n \ndef get_tag():\n ''\n return sys.implementation.cache_tag\n \n \ndef cache_from_source(path,debug_override=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n return util.cache_from_source(path,debug_override)\n \n \ndef source_from_cache(path):\n ''\n\n\n\n\n\n\n\n\n \n return util.source_from_cache(path)\n \n \ndef get_suffixes():\n ''\n extensions=[(s,'rb',C_EXTENSION)for s in machinery.EXTENSION_SUFFIXES]\n source=[(s,'r',PY_SOURCE)for s in machinery.SOURCE_SUFFIXES]\n bytecode=[(s,'rb',PY_COMPILED)for s in machinery.BYTECODE_SUFFIXES]\n \n return extensions+source+bytecode\n \n \nclass NullImporter:\n\n ''\n\n\n\n \n \n def __init__(self,path):\n if path =='':\n raise ImportError('empty pathname',path='')\n elif os.path.isdir(path):\n raise ImportError('existing directory',path=path)\n \n def find_module(self,fullname):\n ''\n return None\n \n \nclass _HackedGetData:\n\n ''\n \n \n def __init__(self,fullname,path,file=None):\n super().__init__(fullname,path)\n self.file=file\n \n def get_data(self,path):\n ''\n if self.file and path ==self.path:\n \n \n if not self.file.closed:\n file=self.file\n if 'b'not in file.mode:\n file.close()\n if self.file.closed:\n self.file=file=open(self.path,'rb')\n \n with file:\n return file.read()\n else:\n return super().get_data(path)\n \n \nclass _LoadSourceCompatibility(_HackedGetData,machinery.SourceFileLoader):\n\n ''\n \n \ndef load_source(name,pathname,file=None):\n loader=_LoadSourceCompatibility(name,pathname,file)\n spec=util.spec_from_file_location(name,pathname,loader=loader)\n if name in sys.modules:\n module=_exec(spec,sys.modules[name])\n else:\n module=_load(spec)\n \n \n module.__loader__=machinery.SourceFileLoader(name,pathname)\n module.__spec__.loader=module.__loader__\n return module\n \n \nclass _LoadCompiledCompatibility(_HackedGetData,SourcelessFileLoader):\n\n ''\n \n \ndef load_compiled(name,pathname,file=None):\n ''\n loader=_LoadCompiledCompatibility(name,pathname,file)\n spec=util.spec_from_file_location(name,pathname,loader=loader)\n if name in sys.modules:\n module=_exec(spec,sys.modules[name])\n else:\n module=_load(spec)\n \n \n module.__loader__=SourcelessFileLoader(name,pathname)\n module.__spec__.loader=module.__loader__\n return module\n \n \ndef load_package(name,path):\n ''\n if os.path.isdir(path):\n extensions=(machinery.SOURCE_SUFFIXES[:]+\n machinery.BYTECODE_SUFFIXES[:])\n for extension in extensions:\n init_path=os.path.join(path,'__init__'+extension)\n if os.path.exists(init_path):\n path=init_path\n break\n else:\n raise ValueError('{!r} is not a package'.format(path))\n spec=util.spec_from_file_location(name,path,\n submodule_search_locations=[])\n if name in sys.modules:\n return _exec(spec,sys.modules[name])\n else:\n return _load(spec)\n \n \ndef load_module(name,file,filename,details):\n ''\n\n\n\n\n\n \n suffix,mode,type_=details\n if mode and(not mode.startswith('r')or '+'in mode):\n raise ValueError('invalid file open mode {!r}'.format(mode))\n elif file is None and type_ in{PY_SOURCE,PY_COMPILED}:\n msg='file object required for import (type code {})'.format(type_)\n raise ValueError(msg)\n elif type_ ==PY_SOURCE:\n return load_source(name,filename,file)\n elif type_ ==PY_COMPILED:\n return load_compiled(name,filename,file)\n elif type_ ==C_EXTENSION and load_dynamic is not None:\n if file is None:\n with open(filename,'rb')as opened_file:\n return load_dynamic(name,filename,opened_file)\n else:\n return load_dynamic(name,filename,file)\n elif type_ ==PKG_DIRECTORY:\n return load_package(name,filename)\n elif type_ ==C_BUILTIN:\n return init_builtin(name)\n elif type_ ==PY_FROZEN:\n return init_frozen(name)\n else:\n msg=\"Don't know how to import {} (type code {})\".format(name,type_)\n raise ImportError(msg,name=name)\n \n \ndef find_module(name,path=None):\n ''\n\n\n\n\n\n\n\n\n \n if not isinstance(name,str):\n raise TypeError(\"'name' must be a str, not {}\".format(type(name)))\n elif not isinstance(path,(type(None),list)):\n \n raise RuntimeError(\"'path' must be None or a list, \"\n \"not {}\".format(type(path)))\n \n if path is None:\n if is_builtin(name):\n return None,None,('','',C_BUILTIN)\n elif is_frozen(name):\n return None,None,('','',PY_FROZEN)\n else:\n path=sys.path\n \n for entry in path:\n package_directory=os.path.join(entry,name)\n for suffix in['.py',machinery.BYTECODE_SUFFIXES[0]]:\n package_file_name='__init__'+suffix\n file_path=os.path.join(package_directory,package_file_name)\n if os.path.isfile(file_path):\n return None,package_directory,('','',PKG_DIRECTORY)\n for suffix,mode,type_ in get_suffixes():\n file_name=name+suffix\n file_path=os.path.join(entry,file_name)\n if os.path.isfile(file_path):\n break\n else:\n continue\n break\n else:\n raise ImportError(_ERR_MSG.format(name),name=name)\n \n encoding=None\n if 'b'not in mode:\n with open(file_path,'rb')as file:\n encoding=tokenize.detect_encoding(file.readline)[0]\n file=open(file_path,mode,encoding=encoding)\n return file,file_path,(suffix,mode,type_)\n \n \ndef reload(module):\n ''\n\n\n\n\n\n \n return importlib.reload(module)\n \n \ndef init_builtin(name):\n ''\n\n\n\n \n try:\n return _builtin_from_name(name)\n except ImportError:\n return None\n \n \nif create_dynamic:\n def load_dynamic(name,path,file=None):\n ''\n\n\n \n import importlib.machinery\n loader=importlib.machinery.ExtensionFileLoader(name,path)\n \n \n \n spec=importlib.machinery.ModuleSpec(\n name=name,loader=loader,origin=path)\n return _load(spec)\n \nelse:\n load_dynamic=None\n", ["_imp", "importlib", "importlib._bootstrap", "importlib._bootstrap_external", "importlib.machinery", "importlib.util", "os", "sys", "tokenize", "types", "warnings"]], "inspect": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__=('Ka-Ping Yee ',\n'Yury Selivanov ')\n\n__all__=[\n\"AGEN_CLOSED\",\n\"AGEN_CREATED\",\n\"AGEN_RUNNING\",\n\"AGEN_SUSPENDED\",\n\"ArgInfo\",\n\"Arguments\",\n\"Attribute\",\n\"BlockFinder\",\n\"BoundArguments\",\n\"BufferFlags\",\n\"CORO_CLOSED\",\n\"CORO_CREATED\",\n\"CORO_RUNNING\",\n\"CORO_SUSPENDED\",\n\"CO_ASYNC_GENERATOR\",\n\"CO_COROUTINE\",\n\"CO_GENERATOR\",\n\"CO_ITERABLE_COROUTINE\",\n\"CO_NESTED\",\n\"CO_NEWLOCALS\",\n\"CO_NOFREE\",\n\"CO_OPTIMIZED\",\n\"CO_VARARGS\",\n\"CO_VARKEYWORDS\",\n\"ClassFoundException\",\n\"ClosureVars\",\n\"EndOfBlock\",\n\"FrameInfo\",\n\"FullArgSpec\",\n\"GEN_CLOSED\",\n\"GEN_CREATED\",\n\"GEN_RUNNING\",\n\"GEN_SUSPENDED\",\n\"Parameter\",\n\"Signature\",\n\"TPFLAGS_IS_ABSTRACT\",\n\"Traceback\",\n\"classify_class_attrs\",\n\"cleandoc\",\n\"currentframe\",\n\"findsource\",\n\"formatannotation\",\n\"formatannotationrelativeto\",\n\"formatargvalues\",\n\"get_annotations\",\n\"getabsfile\",\n\"getargs\",\n\"getargvalues\",\n\"getasyncgenlocals\",\n\"getasyncgenstate\",\n\"getattr_static\",\n\"getblock\",\n\"getcallargs\",\n\"getclasstree\",\n\"getclosurevars\",\n\"getcomments\",\n\"getcoroutinelocals\",\n\"getcoroutinestate\",\n\"getdoc\",\n\"getfile\",\n\"getframeinfo\",\n\"getfullargspec\",\n\"getgeneratorlocals\",\n\"getgeneratorstate\",\n\"getinnerframes\",\n\"getlineno\",\n\"getmembers\",\n\"getmembers_static\",\n\"getmodule\",\n\"getmodulename\",\n\"getmro\",\n\"getouterframes\",\n\"getsource\",\n\"getsourcefile\",\n\"getsourcelines\",\n\"indentsize\",\n\"isabstract\",\n\"isasyncgen\",\n\"isasyncgenfunction\",\n\"isawaitable\",\n\"isbuiltin\",\n\"isclass\",\n\"iscode\",\n\"iscoroutine\",\n\"iscoroutinefunction\",\n\"isdatadescriptor\",\n\"isframe\",\n\"isfunction\",\n\"isgenerator\",\n\"isgeneratorfunction\",\n\"isgetsetdescriptor\",\n\"ismemberdescriptor\",\n\"ismethod\",\n\"ismethoddescriptor\",\n\"ismethodwrapper\",\n\"ismodule\",\n\"isroutine\",\n\"istraceback\",\n\"markcoroutinefunction\",\n\"signature\",\n\"stack\",\n\"trace\",\n\"unwrap\",\n\"walktree\",\n]\n\n\nimport abc\nimport ast\nimport dis\nimport collections.abc\nimport enum\nimport importlib.machinery\nimport itertools\nimport linecache\nimport os\nimport re\nimport sys\nimport tokenize\nimport token\nimport types\nimport functools\nimport builtins\nfrom keyword import iskeyword\nfrom operator import attrgetter\nfrom collections import namedtuple,OrderedDict\nfrom weakref import ref as make_weakref\n\n\n\nmod_dict=globals()\nfor k,v in dis.COMPILER_FLAG_NAMES.items():\n mod_dict[\"CO_\"+v]=k\ndel k,v,mod_dict\n\n\nTPFLAGS_IS_ABSTRACT=1 <<20\n\n\ndef get_annotations(obj,*,globals=None,locals=None,eval_str=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(obj,type):\n \n obj_dict=getattr(obj,'__dict__',None)\n if obj_dict and hasattr(obj_dict,'get'):\n ann=obj_dict.get('__annotations__',None)\n if isinstance(ann,types.GetSetDescriptorType):\n ann=None\n else:\n ann=None\n \n obj_globals=None\n module_name=getattr(obj,'__module__',None)\n if module_name:\n module=sys.modules.get(module_name,None)\n if module:\n obj_globals=getattr(module,'__dict__',None)\n obj_locals=dict(vars(obj))\n unwrap=obj\n elif isinstance(obj,types.ModuleType):\n \n ann=getattr(obj,'__annotations__',None)\n obj_globals=getattr(obj,'__dict__')\n obj_locals=None\n unwrap=None\n elif callable(obj):\n \n \n \n ann=getattr(obj,'__annotations__',None)\n obj_globals=getattr(obj,'__globals__',None)\n obj_locals=None\n unwrap=obj\n else:\n raise TypeError(f\"{obj !r} is not a module, class, or callable.\")\n \n if ann is None:\n return{}\n \n if not isinstance(ann,dict):\n raise ValueError(f\"{obj !r}.__annotations__ is neither a dict nor None\")\n \n if not ann:\n return{}\n \n if not eval_str:\n return dict(ann)\n \n if unwrap is not None:\n while True:\n if hasattr(unwrap,'__wrapped__'):\n unwrap=unwrap.__wrapped__\n continue\n if isinstance(unwrap,functools.partial):\n unwrap=unwrap.func\n continue\n break\n if hasattr(unwrap,\"__globals__\"):\n obj_globals=unwrap.__globals__\n \n if globals is None:\n globals=obj_globals\n if locals is None:\n locals=obj_locals or{}\n \n \n \n \n if type_params :=getattr(obj,\"__type_params__\",()):\n locals={param.__name__:param for param in type_params}|locals\n \n return_value={key:\n value if not isinstance(value,str)else eval(value,globals,locals)\n for key,value in ann.items()}\n return return_value\n \n \n \ndef ismodule(object):\n ''\n return isinstance(object,types.ModuleType)\n \ndef isclass(object):\n ''\n return isinstance(object,type)\n \ndef ismethod(object):\n ''\n return isinstance(object,types.MethodType)\n \ndef ismethoddescriptor(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isclass(object)or ismethod(object)or isfunction(object):\n \n return False\n tp=type(object)\n return(hasattr(tp,\"__get__\")\n and not hasattr(tp,\"__set__\")\n and not hasattr(tp,\"__delete__\"))\n \ndef isdatadescriptor(object):\n ''\n\n\n\n\n\n \n if isclass(object)or ismethod(object)or isfunction(object):\n \n return False\n tp=type(object)\n return hasattr(tp,\"__set__\")or hasattr(tp,\"__delete__\")\n \nif hasattr(types,'MemberDescriptorType'):\n\n def ismemberdescriptor(object):\n ''\n\n\n \n return isinstance(object,types.MemberDescriptorType)\nelse:\n\n def ismemberdescriptor(object):\n ''\n\n\n \n return False\n \nif hasattr(types,'GetSetDescriptorType'):\n\n def isgetsetdescriptor(object):\n ''\n\n\n \n return isinstance(object,types.GetSetDescriptorType)\nelse:\n\n def isgetsetdescriptor(object):\n ''\n\n\n \n return False\n \ndef isfunction(object):\n ''\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.FunctionType)\n \ndef _has_code_flag(f,flag):\n ''\n\n\n \n f=functools._unwrap_partialmethod(f)\n while ismethod(f):\n f=f.__func__\n f=functools._unwrap_partial(f)\n if not(isfunction(f)or _signature_is_functionlike(f)):\n return False\n return bool(f.__code__.co_flags&flag)\n \ndef isgeneratorfunction(obj):\n ''\n\n\n \n return _has_code_flag(obj,CO_GENERATOR)\n \n \n_is_coroutine_mark=object()\n\ndef _has_coroutine_mark(f):\n while ismethod(f):\n f=f.__func__\n f=functools._unwrap_partial(f)\n return getattr(f,\"_is_coroutine_marker\",None)is _is_coroutine_mark\n \ndef markcoroutinefunction(func):\n ''\n\n \n if hasattr(func,'__func__'):\n func=func.__func__\n func._is_coroutine_marker=_is_coroutine_mark\n return func\n \ndef iscoroutinefunction(obj):\n ''\n\n\n\n \n return _has_code_flag(obj,CO_COROUTINE)or _has_coroutine_mark(obj)\n \ndef isasyncgenfunction(obj):\n ''\n\n\n\n \n return _has_code_flag(obj,CO_ASYNC_GENERATOR)\n \ndef isasyncgen(object):\n ''\n return isinstance(object,types.AsyncGeneratorType)\n \ndef isgenerator(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.GeneratorType)\n \ndef iscoroutine(object):\n ''\n return isinstance(object,types.CoroutineType)\n \ndef isawaitable(object):\n ''\n return(isinstance(object,types.CoroutineType)or\n isinstance(object,types.GeneratorType)and\n bool(object.gi_code.co_flags&CO_ITERABLE_COROUTINE)or\n isinstance(object,collections.abc.Awaitable))\n \ndef istraceback(object):\n ''\n\n\n\n\n\n \n return isinstance(object,types.TracebackType)\n \ndef isframe(object):\n ''\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.FrameType)\n \ndef iscode(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.CodeType)\n \ndef isbuiltin(object):\n ''\n\n\n\n\n \n return isinstance(object,types.BuiltinFunctionType)\n \ndef ismethodwrapper(object):\n ''\n return isinstance(object,types.MethodWrapperType)\n \ndef isroutine(object):\n ''\n return(isbuiltin(object)\n or isfunction(object)\n or ismethod(object)\n or ismethoddescriptor(object)\n or ismethodwrapper(object))\n \ndef isabstract(object):\n ''\n if not isinstance(object,type):\n return False\n if object.__flags__&TPFLAGS_IS_ABSTRACT:\n return True\n if not issubclass(type(object),abc.ABCMeta):\n return False\n if hasattr(object,'__abstractmethods__'):\n \n \n return False\n \n \n for name,value in object.__dict__.items():\n if getattr(value,\"__isabstractmethod__\",False):\n return True\n for base in object.__bases__:\n for name in getattr(base,\"__abstractmethods__\",()):\n value=getattr(object,name,None)\n if getattr(value,\"__isabstractmethod__\",False):\n return True\n return False\n \ndef _getmembers(object,predicate,getter):\n results=[]\n processed=set()\n names=dir(object)\n if isclass(object):\n mro=getmro(object)\n \n \n \n try:\n for base in object.__bases__:\n for k,v in base.__dict__.items():\n if isinstance(v,types.DynamicClassAttribute):\n names.append(k)\n except AttributeError:\n pass\n else:\n mro=()\n for key in names:\n \n \n \n try:\n value=getter(object,key)\n \n if key in processed:\n raise AttributeError\n except AttributeError:\n for base in mro:\n if key in base.__dict__:\n value=base.__dict__[key]\n break\n else:\n \n \n continue\n if not predicate or predicate(value):\n results.append((key,value))\n processed.add(key)\n results.sort(key=lambda pair:pair[0])\n return results\n \ndef getmembers(object,predicate=None):\n ''\n \n return _getmembers(object,predicate,getattr)\n \ndef getmembers_static(object,predicate=None):\n ''\n\n\n\n\n\n\n\n\n\n \n return _getmembers(object,predicate,getattr_static)\n \nAttribute=namedtuple('Attribute','name kind defining_class object')\n\ndef classify_class_attrs(cls):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n mro=getmro(cls)\n metamro=getmro(type(cls))\n metamro=tuple(cls for cls in metamro if cls not in(type,object))\n class_bases=(cls,)+mro\n all_bases=class_bases+metamro\n names=dir(cls)\n \n \n \n for base in mro:\n for k,v in base.__dict__.items():\n if isinstance(v,types.DynamicClassAttribute)and v.fget is not None:\n names.append(k)\n result=[]\n processed=set()\n \n for name in names:\n \n \n \n \n \n \n \n \n \n homecls=None\n get_obj=None\n dict_obj=None\n if name not in processed:\n try:\n if name =='__dict__':\n raise Exception(\"__dict__ is special, don't want the proxy\")\n get_obj=getattr(cls,name)\n except Exception:\n pass\n else:\n homecls=getattr(get_obj,\"__objclass__\",homecls)\n if homecls not in class_bases:\n \n \n homecls=None\n last_cls=None\n \n for srch_cls in class_bases:\n srch_obj=getattr(srch_cls,name,None)\n if srch_obj is get_obj:\n last_cls=srch_cls\n \n for srch_cls in metamro:\n try:\n srch_obj=srch_cls.__getattr__(cls,name)\n except AttributeError:\n continue\n if srch_obj is get_obj:\n last_cls=srch_cls\n if last_cls is not None:\n homecls=last_cls\n for base in all_bases:\n if name in base.__dict__:\n dict_obj=base.__dict__[name]\n if homecls not in metamro:\n homecls=base\n break\n if homecls is None:\n \n \n continue\n obj=get_obj if get_obj is not None else dict_obj\n \n if isinstance(dict_obj,(staticmethod,types.BuiltinMethodType)):\n kind=\"static method\"\n obj=dict_obj\n elif isinstance(dict_obj,(classmethod,types.ClassMethodDescriptorType)):\n kind=\"class method\"\n obj=dict_obj\n elif isinstance(dict_obj,property):\n kind=\"property\"\n obj=dict_obj\n elif isroutine(obj):\n kind=\"method\"\n else:\n kind=\"data\"\n result.append(Attribute(name,kind,homecls,obj))\n processed.add(name)\n return result\n \n \n \ndef getmro(cls):\n ''\n return cls.__mro__\n \n \n \ndef unwrap(func,*,stop=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n f=func\n \n \n memo={id(f):f}\n recursion_limit=sys.getrecursionlimit()\n while not isinstance(func,type)and hasattr(func,'__wrapped__'):\n if stop is not None and stop(func):\n break\n func=func.__wrapped__\n id_func=id(func)\n if(id_func in memo)or(len(memo)>=recursion_limit):\n raise ValueError('wrapper loop when unwrapping {!r}'.format(f))\n memo[id_func]=func\n return func\n \n \ndef indentsize(line):\n ''\n expline=line.expandtabs()\n return len(expline)-len(expline.lstrip())\n \ndef _findclass(func):\n cls=sys.modules.get(func.__module__)\n if cls is None:\n return None\n for name in func.__qualname__.split('.')[:-1]:\n cls=getattr(cls,name)\n if not isclass(cls):\n return None\n return cls\n \ndef _finddoc(obj):\n if isclass(obj):\n for base in obj.__mro__:\n if base is not object:\n try:\n doc=base.__doc__\n except AttributeError:\n continue\n if doc is not None:\n return doc\n return None\n \n if ismethod(obj):\n name=obj.__func__.__name__\n self=obj.__self__\n if(isclass(self)and\n getattr(getattr(self,name,None),'__func__')is obj.__func__):\n \n cls=self\n else:\n cls=self.__class__\n elif isfunction(obj):\n name=obj.__name__\n cls=_findclass(obj)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif isbuiltin(obj):\n name=obj.__name__\n self=obj.__self__\n if(isclass(self)and\n self.__qualname__+'.'+name ==obj.__qualname__):\n \n cls=self\n else:\n cls=self.__class__\n \n elif isinstance(obj,property):\n name=obj.__name__\n cls=_findclass(obj.fget)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif ismethoddescriptor(obj)or isdatadescriptor(obj):\n name=obj.__name__\n cls=obj.__objclass__\n if getattr(cls,name)is not obj:\n return None\n if ismemberdescriptor(obj):\n slots=getattr(cls,'__slots__',None)\n if isinstance(slots,dict)and name in slots:\n return slots[name]\n else:\n return None\n for base in cls.__mro__:\n try:\n doc=getattr(base,name).__doc__\n except AttributeError:\n continue\n if doc is not None:\n return doc\n return None\n \ndef getdoc(object):\n ''\n\n\n\n \n try:\n doc=object.__doc__\n except AttributeError:\n return None\n if doc is None:\n try:\n doc=_finddoc(object)\n except(AttributeError,TypeError):\n return None\n if not isinstance(doc,str):\n return None\n return cleandoc(doc)\n \ndef cleandoc(doc):\n ''\n\n\n \n lines=doc.expandtabs().split('\\n')\n \n \n margin=sys.maxsize\n for line in lines[1:]:\n content=len(line.lstrip(' '))\n if content:\n indent=len(line)-content\n margin=min(margin,indent)\n \n if lines:\n lines[0]=lines[0].lstrip(' ')\n if margin ')))or file.endswith('.fwork'):\n raise OSError('source code not available')\n \n module=getmodule(object,file)\n if module:\n lines=linecache.getlines(file,module.__dict__)\n else:\n lines=linecache.getlines(file)\n if not lines:\n raise OSError('could not get source code')\n \n if ismodule(object):\n return lines,0\n \n if isclass(object):\n try:\n firstlineno=object.__firstlineno__\n except AttributeError:\n raise OSError('source code not available')\n return lines,object.__firstlineno__ -1\n \n if ismethod(object):\n object=object.__func__\n if isfunction(object):\n object=object.__code__\n if istraceback(object):\n object=object.tb_frame\n if isframe(object):\n object=object.f_code\n if iscode(object):\n if not hasattr(object,'co_firstlineno'):\n raise OSError('could not find function definition')\n lnum=object.co_firstlineno -1\n if lnum >=len(lines):\n raise OSError('lineno is out of bounds')\n return lines,lnum\n raise OSError('could not find code object')\n \ndef getcomments(object):\n ''\n\n\n \n try:\n lines,lnum=findsource(object)\n except(OSError,TypeError):\n return None\n \n if ismodule(object):\n \n start=0\n if lines and lines[0][:2]=='#!':start=1\n while start 0:\n indent=indentsize(lines[lnum])\n end=lnum -1\n if end >=0 and lines[end].lstrip()[:1]=='#'and\\\n indentsize(lines[end])==indent:\n comments=[lines[end].expandtabs().lstrip()]\n if end >0:\n end=end -1\n comment=lines[end].expandtabs().lstrip()\n while comment[:1]=='#'and indentsize(lines[end])==indent:\n comments[:0]=[comment]\n end=end -1\n if end <0:break\n comment=lines[end].expandtabs().lstrip()\n while comments and comments[0].strip()=='#':\n comments[:1]=[]\n while comments and comments[-1].strip()=='#':\n comments[-1:]=[]\n return ''.join(comments)\n \nclass EndOfBlock(Exception):pass\n\nclass BlockFinder:\n ''\n def __init__(self):\n self.indent=0\n self.islambda=False\n self.started=False\n self.passline=False\n self.indecorator=False\n self.last=1\n self.body_col0=None\n \n def tokeneater(self,type,token,srowcol,erowcol,line):\n if not self.started and not self.indecorator:\n \n if token ==\"@\":\n self.indecorator=True\n \n elif token in(\"def\",\"class\",\"lambda\"):\n if token ==\"lambda\":\n self.islambda=True\n self.started=True\n self.passline=True\n elif type ==tokenize.NEWLINE:\n self.passline=False\n self.last=srowcol[0]\n if self.islambda:\n raise EndOfBlock\n \n \n if self.indecorator:\n self.indecorator=False\n elif self.passline:\n pass\n elif type ==tokenize.INDENT:\n if self.body_col0 is None and self.started:\n self.body_col0=erowcol[1]\n self.indent=self.indent+1\n self.passline=True\n elif type ==tokenize.DEDENT:\n self.indent=self.indent -1\n \n \n \n if self.indent <=0:\n raise EndOfBlock\n elif type ==tokenize.COMMENT:\n if self.body_col0 is not None and srowcol[1]>=self.body_col0:\n \n self.last=srowcol[0]\n elif self.indent ==0 and type not in(tokenize.COMMENT,tokenize.NL):\n \n \n raise EndOfBlock\n \ndef getblock(lines):\n ''\n blockfinder=BlockFinder()\n try:\n tokens=tokenize.generate_tokens(iter(lines).__next__)\n for _token in tokens:\n blockfinder.tokeneater(*_token)\n except(EndOfBlock,IndentationError):\n pass\n except SyntaxError as e:\n if \"unmatched\"not in e.msg:\n raise e from None\n _,*_token_info=_token\n try:\n blockfinder.tokeneater(tokenize.NEWLINE,*_token_info)\n except(EndOfBlock,IndentationError):\n pass\n return lines[:blockfinder.last]\n \ndef getsourcelines(object):\n ''\n\n\n\n\n\n \n object=unwrap(object)\n lines,lnum=findsource(object)\n \n if istraceback(object):\n object=object.tb_frame\n \n \n if(ismodule(object)or\n (isframe(object)and object.f_code.co_name ==\"\")):\n return lines,0\n else:\n return getblock(lines[lnum:]),lnum+1\n \ndef getsource(object):\n ''\n\n\n\n \n lines,lnum=getsourcelines(object)\n return ''.join(lines)\n \n \ndef walktree(classes,children,parent):\n ''\n results=[]\n classes.sort(key=attrgetter('__module__','__name__'))\n for c in classes:\n results.append((c,c.__bases__))\n if c in children:\n results.append(walktree(children[c],children,c))\n return results\n \ndef getclasstree(classes,unique=False):\n ''\n\n\n\n\n\n\n \n children={}\n roots=[]\n for c in classes:\n if c.__bases__:\n for parent in c.__bases__:\n if parent not in children:\n children[parent]=[]\n if c not in children[parent]:\n children[parent].append(c)\n if unique and parent in classes:break\n elif c not in roots:\n roots.append(c)\n for parent in children:\n if parent not in classes:\n roots.append(parent)\n return walktree(roots,children,None)\n \n \nArguments=namedtuple('Arguments','args, varargs, varkw')\n\ndef getargs(co):\n ''\n\n\n\n\n \n if not iscode(co):\n raise TypeError('{!r} is not a code object'.format(co))\n \n names=co.co_varnames\n nargs=co.co_argcount\n nkwargs=co.co_kwonlyargcount\n args=list(names[:nargs])\n kwonlyargs=list(names[nargs:nargs+nkwargs])\n \n nargs +=nkwargs\n varargs=None\n if co.co_flags&CO_VARARGS:\n varargs=co.co_varnames[nargs]\n nargs=nargs+1\n varkw=None\n if co.co_flags&CO_VARKEYWORDS:\n varkw=co.co_varnames[nargs]\n return Arguments(args+kwonlyargs,varargs,varkw)\n \n \nFullArgSpec=namedtuple('FullArgSpec',\n'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')\n\ndef getfullargspec(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n sig=_signature_from_callable(func,\n follow_wrapper_chains=False,\n skip_bound_arg=False,\n sigcls=Signature,\n eval_str=False)\n except Exception as ex:\n \n \n \n \n raise TypeError('unsupported callable')from ex\n \n args=[]\n varargs=None\n varkw=None\n posonlyargs=[]\n kwonlyargs=[]\n annotations={}\n defaults=()\n kwdefaults={}\n \n if sig.return_annotation is not sig.empty:\n annotations['return']=sig.return_annotation\n \n for param in sig.parameters.values():\n kind=param.kind\n name=param.name\n \n if kind is _POSITIONAL_ONLY:\n posonlyargs.append(name)\n if param.default is not param.empty:\n defaults +=(param.default,)\n elif kind is _POSITIONAL_OR_KEYWORD:\n args.append(name)\n if param.default is not param.empty:\n defaults +=(param.default,)\n elif kind is _VAR_POSITIONAL:\n varargs=name\n elif kind is _KEYWORD_ONLY:\n kwonlyargs.append(name)\n if param.default is not param.empty:\n kwdefaults[name]=param.default\n elif kind is _VAR_KEYWORD:\n varkw=name\n \n if param.annotation is not param.empty:\n annotations[name]=param.annotation\n \n if not kwdefaults:\n \n kwdefaults=None\n \n if not defaults:\n \n defaults=None\n \n return FullArgSpec(posonlyargs+args,varargs,varkw,defaults,\n kwonlyargs,kwdefaults,annotations)\n \n \nArgInfo=namedtuple('ArgInfo','args varargs keywords locals')\n\ndef getargvalues(frame):\n ''\n\n\n\n\n \n args,varargs,varkw=getargs(frame.f_code)\n return ArgInfo(args,varargs,varkw,frame.f_locals)\n \ndef formatannotation(annotation,base_module=None):\n if getattr(annotation,'__module__',None)=='typing':\n def repl(match):\n text=match.group()\n return text.removeprefix('typing.')\n return re.sub(r'[\\w\\.]+',repl,repr(annotation))\n if isinstance(annotation,types.GenericAlias):\n return str(annotation)\n if isinstance(annotation,type):\n if annotation.__module__ in('builtins',base_module):\n return annotation.__qualname__\n return annotation.__module__+'.'+annotation.__qualname__\n return repr(annotation)\n \ndef formatannotationrelativeto(object):\n module=getattr(object,'__module__',None)\n def _formatannotation(annotation):\n return formatannotation(annotation,module)\n return _formatannotation\n \n \ndef formatargvalues(args,varargs,varkw,locals,\nformatarg=str,\nformatvarargs=lambda name:'*'+name,\nformatvarkw=lambda name:'**'+name,\nformatvalue=lambda value:'='+repr(value)):\n ''\n\n\n\n\n \n def convert(name,locals=locals,\n formatarg=formatarg,formatvalue=formatvalue):\n return formatarg(name)+formatvalue(locals[name])\n specs=[]\n for i in range(len(args)):\n specs.append(convert(args[i]))\n if varargs:\n specs.append(formatvarargs(varargs)+formatvalue(locals[varargs]))\n if varkw:\n specs.append(formatvarkw(varkw)+formatvalue(locals[varkw]))\n return '('+', '.join(specs)+')'\n \ndef _missing_arguments(f_name,argnames,pos,values):\n names=[repr(name)for name in argnames if name not in values]\n missing=len(names)\n if missing ==1:\n s=names[0]\n elif missing ==2:\n s=\"{} and {}\".format(*names)\n else:\n tail=\", {} and {}\".format(*names[-2:])\n del names[-2:]\n s=\", \".join(names)+tail\n raise TypeError(\"%s() missing %i required %s argument%s: %s\"%\n (f_name,missing,\n \"positional\"if pos else \"keyword-only\",\n \"\"if missing ==1 else \"s\",s))\n \ndef _too_many(f_name,args,kwonly,varargs,defcount,given,values):\n atleast=len(args)-defcount\n kwonly_given=len([arg for arg in kwonly if arg in values])\n if varargs:\n plural=atleast !=1\n sig=\"at least %d\"%(atleast,)\n elif defcount:\n plural=True\n sig=\"from %d to %d\"%(atleast,len(args))\n else:\n plural=len(args)!=1\n sig=str(len(args))\n kwonly_sig=\"\"\n if kwonly_given:\n msg=\" positional argument%s (and %d keyword-only argument%s)\"\n kwonly_sig=(msg %(\"s\"if given !=1 else \"\",kwonly_given,\n \"s\"if kwonly_given !=1 else \"\"))\n raise TypeError(\"%s() takes %s positional argument%s but %d%s %s given\"%\n (f_name,sig,\"s\"if plural else \"\",given,kwonly_sig,\n \"was\"if given ==1 and not kwonly_given else \"were\"))\n \ndef getcallargs(func,/,*positional,**named):\n ''\n\n\n\n \n spec=getfullargspec(func)\n args,varargs,varkw,defaults,kwonlyargs,kwonlydefaults,ann=spec\n f_name=func.__name__\n arg2value={}\n \n \n if ismethod(func)and func.__self__ is not None:\n \n positional=(func.__self__,)+positional\n num_pos=len(positional)\n num_args=len(args)\n num_defaults=len(defaults)if defaults else 0\n \n n=min(num_pos,num_args)\n for i in range(n):\n arg2value[args[i]]=positional[i]\n if varargs:\n arg2value[varargs]=tuple(positional[n:])\n possible_kwargs=set(args+kwonlyargs)\n if varkw:\n arg2value[varkw]={}\n for kw,value in named.items():\n if kw not in possible_kwargs:\n if not varkw:\n raise TypeError(\"%s() got an unexpected keyword argument %r\"%\n (f_name,kw))\n arg2value[varkw][kw]=value\n continue\n if kw in arg2value:\n raise TypeError(\"%s() got multiple values for argument %r\"%\n (f_name,kw))\n arg2value[kw]=value\n if num_pos >num_args and not varargs:\n _too_many(f_name,args,kwonlyargs,varargs,num_defaults,\n num_pos,arg2value)\n if num_pos 0:\n start=lineno -1 -context //2\n try:\n lines,lnum=findsource(frame)\n except OSError:\n lines=index=None\n else:\n start=max(0,min(start,len(lines)-context))\n lines=lines[start:start+context]\n index=lineno -1 -start\n else:\n lines=index=None\n \n return Traceback(filename,lineno,frame.f_code.co_name,lines,\n index,positions=dis.Positions(*positions))\n \ndef getlineno(frame):\n ''\n \n return frame.f_lineno\n \n_FrameInfo=namedtuple('_FrameInfo',('frame',)+Traceback._fields)\nclass FrameInfo(_FrameInfo):\n def __new__(cls,frame,filename,lineno,function,code_context,index,*,positions=None):\n instance=super().__new__(cls,frame,filename,lineno,function,code_context,index)\n instance.positions=positions\n return instance\n \n def __repr__(self):\n return('FrameInfo(frame={!r}, filename={!r}, lineno={!r}, function={!r}, '\n 'code_context={!r}, index={!r}, positions={!r})'.format(\n self.frame,self.filename,self.lineno,self.function,\n self.code_context,self.index,self.positions))\n \ndef getouterframes(frame,context=1):\n ''\n\n\n \n framelist=[]\n while frame:\n traceback_info=getframeinfo(frame,context)\n frameinfo=(frame,)+traceback_info\n framelist.append(FrameInfo(*frameinfo,positions=traceback_info.positions))\n frame=frame.f_back\n return framelist\n \ndef getinnerframes(tb,context=1):\n ''\n\n\n \n framelist=[]\n while tb:\n traceback_info=getframeinfo(tb,context)\n frameinfo=(tb.tb_frame,)+traceback_info\n framelist.append(FrameInfo(*frameinfo,positions=traceback_info.positions))\n tb=tb.tb_next\n return framelist\n \ndef currentframe():\n ''\n return sys._getframe(1)if hasattr(sys,\"_getframe\")else None\n \ndef stack(context=1):\n ''\n return getouterframes(sys._getframe(1),context)\n \ndef trace(context=1):\n ''\n exc=sys.exception()\n tb=None if exc is None else exc.__traceback__\n return getinnerframes(tb,context)\n \n \n \n \n_sentinel=object()\n_static_getmro=type.__dict__['__mro__'].__get__\n_get_dunder_dict_of_class=type.__dict__[\"__dict__\"].__get__\n\n\ndef _check_instance(obj,attr):\n instance_dict={}\n try:\n instance_dict=object.__getattribute__(obj,\"__dict__\")\n except AttributeError:\n pass\n return dict.get(instance_dict,attr,_sentinel)\n \n \ndef _check_class(klass,attr):\n for entry in _static_getmro(klass):\n if _shadowed_dict(type(entry))is _sentinel and attr in entry.__dict__:\n return entry.__dict__[attr]\n return _sentinel\n \n \n@functools.lru_cache()\ndef _shadowed_dict_from_weakref_mro_tuple(*weakref_mro):\n for weakref_entry in weakref_mro:\n \n \n \n \n \n entry=weakref_entry()\n dunder_dict=_get_dunder_dict_of_class(entry)\n if '__dict__'in dunder_dict:\n class_dict=dunder_dict['__dict__']\n if not(type(class_dict)is types.GetSetDescriptorType and\n class_dict.__name__ ==\"__dict__\"and\n class_dict.__objclass__ is entry):\n return class_dict\n return _sentinel\n \n \ndef _shadowed_dict(klass):\n\n\n\n\n\n\n\n return _shadowed_dict_from_weakref_mro_tuple(\n *[make_weakref(entry)for entry in _static_getmro(klass)]\n )\n \n \ndef getattr_static(obj,attr,default=_sentinel):\n ''\n\n\n\n\n\n\n\n\n \n instance_result=_sentinel\n \n objtype=type(obj)\n if type not in _static_getmro(objtype):\n klass=objtype\n dict_attr=_shadowed_dict(klass)\n if(dict_attr is _sentinel or\n type(dict_attr)is types.MemberDescriptorType):\n instance_result=_check_instance(obj,attr)\n else:\n klass=obj\n \n klass_result=_check_class(klass,attr)\n \n if instance_result is not _sentinel and klass_result is not _sentinel:\n if _check_class(type(klass_result),\"__get__\")is not _sentinel and(\n _check_class(type(klass_result),\"__set__\")is not _sentinel\n or _check_class(type(klass_result),\"__delete__\")is not _sentinel\n ):\n return klass_result\n \n if instance_result is not _sentinel:\n return instance_result\n if klass_result is not _sentinel:\n return klass_result\n \n if obj is klass:\n \n for entry in _static_getmro(type(klass)):\n if(\n _shadowed_dict(type(entry))is _sentinel\n and attr in entry.__dict__\n ):\n return entry.__dict__[attr]\n if default is not _sentinel:\n return default\n raise AttributeError(attr)\n \n \n \n \nGEN_CREATED='GEN_CREATED'\nGEN_RUNNING='GEN_RUNNING'\nGEN_SUSPENDED='GEN_SUSPENDED'\nGEN_CLOSED='GEN_CLOSED'\n\ndef getgeneratorstate(generator):\n ''\n\n\n\n\n\n\n \n if generator.gi_running:\n return GEN_RUNNING\n if generator.gi_suspended:\n return GEN_SUSPENDED\n if generator.gi_frame is None:\n return GEN_CLOSED\n return GEN_CREATED\n \n \ndef getgeneratorlocals(generator):\n ''\n\n\n\n \n \n if not isgenerator(generator):\n raise TypeError(\"{!r} is not a Python generator\".format(generator))\n \n frame=getattr(generator,\"gi_frame\",None)\n if frame is not None:\n return generator.gi_frame.f_locals\n else:\n return{}\n \n \n \n \nCORO_CREATED='CORO_CREATED'\nCORO_RUNNING='CORO_RUNNING'\nCORO_SUSPENDED='CORO_SUSPENDED'\nCORO_CLOSED='CORO_CLOSED'\n\ndef getcoroutinestate(coroutine):\n ''\n\n\n\n\n\n\n \n if coroutine.cr_running:\n return CORO_RUNNING\n if coroutine.cr_suspended:\n return CORO_SUSPENDED\n if coroutine.cr_frame is None:\n return CORO_CLOSED\n return CORO_CREATED\n \n \ndef getcoroutinelocals(coroutine):\n ''\n\n\n\n \n frame=getattr(coroutine,\"cr_frame\",None)\n if frame is not None:\n return frame.f_locals\n else:\n return{}\n \n \n \n \nAGEN_CREATED='AGEN_CREATED'\nAGEN_RUNNING='AGEN_RUNNING'\nAGEN_SUSPENDED='AGEN_SUSPENDED'\nAGEN_CLOSED='AGEN_CLOSED'\n\n\ndef getasyncgenstate(agen):\n ''\n\n\n\n\n\n\n \n if agen.ag_running:\n return AGEN_RUNNING\n if agen.ag_suspended:\n return AGEN_SUSPENDED\n if agen.ag_frame is None:\n return AGEN_CLOSED\n return AGEN_CREATED\n \n \ndef getasyncgenlocals(agen):\n ''\n\n\n\n\n \n \n if not isasyncgen(agen):\n raise TypeError(f\"{agen !r} is not a Python async generator\")\n \n frame=getattr(agen,\"ag_frame\",None)\n if frame is not None:\n return agen.ag_frame.f_locals\n else:\n return{}\n \n \n \n \n \n \n \n_NonUserDefinedCallables=(types.WrapperDescriptorType,\ntypes.MethodWrapperType,\ntypes.ClassMethodDescriptorType,\ntypes.BuiltinFunctionType)\n\n\ndef _signature_get_user_defined_method(cls,method_name):\n ''\n\n\n \n if method_name =='__new__':\n meth=getattr(cls,method_name,None)\n else:\n meth=getattr_static(cls,method_name,None)\n if meth is None or isinstance(meth,_NonUserDefinedCallables):\n \n \n return None\n if method_name !='__new__':\n meth=_descriptor_get(meth,cls)\n return meth\n \n \ndef _signature_get_partial(wrapped_sig,partial,extra_args=()):\n ''\n\n\n \n \n old_params=wrapped_sig.parameters\n new_params=OrderedDict(old_params.items())\n \n partial_args=partial.args or()\n partial_keywords=partial.keywords or{}\n \n if extra_args:\n partial_args=extra_args+partial_args\n \n try:\n ba=wrapped_sig.bind_partial(*partial_args,**partial_keywords)\n except TypeError as ex:\n msg='partial object {!r} has incorrect arguments'.format(partial)\n raise ValueError(msg)from ex\n \n \n transform_to_kwonly=False\n for param_name,param in old_params.items():\n try:\n arg_value=ba.arguments[param_name]\n except KeyError:\n pass\n else:\n if param.kind is _POSITIONAL_ONLY:\n \n \n new_params.pop(param_name)\n continue\n \n if param.kind is _POSITIONAL_OR_KEYWORD:\n if param_name in partial_keywords:\n \n \n \n \n \n \n \n \n \n \n \n \n transform_to_kwonly=True\n \n new_params[param_name]=param.replace(default=arg_value)\n else:\n \n new_params.pop(param.name)\n continue\n \n if param.kind is _KEYWORD_ONLY:\n \n new_params[param_name]=param.replace(default=arg_value)\n \n if transform_to_kwonly:\n assert param.kind is not _POSITIONAL_ONLY\n \n if param.kind is _POSITIONAL_OR_KEYWORD:\n new_param=new_params[param_name].replace(kind=_KEYWORD_ONLY)\n new_params[param_name]=new_param\n new_params.move_to_end(param_name)\n elif param.kind in(_KEYWORD_ONLY,_VAR_KEYWORD):\n new_params.move_to_end(param_name)\n elif param.kind is _VAR_POSITIONAL:\n new_params.pop(param.name)\n \n return wrapped_sig.replace(parameters=new_params.values())\n \n \ndef _signature_bound_method(sig):\n ''\n\n \n \n params=tuple(sig.parameters.values())\n \n if not params or params[0].kind in(_VAR_KEYWORD,_KEYWORD_ONLY):\n raise ValueError('invalid method signature')\n \n kind=params[0].kind\n if kind in(_POSITIONAL_OR_KEYWORD,_POSITIONAL_ONLY):\n \n \n params=params[1:]\n else:\n if kind is not _VAR_POSITIONAL:\n \n \n raise ValueError('invalid argument type')\n \n \n \n return sig.replace(parameters=params)\n \n \ndef _signature_is_builtin(obj):\n ''\n\n \n return(isbuiltin(obj)or\n ismethoddescriptor(obj)or\n isinstance(obj,_NonUserDefinedCallables)or\n \n \n \n \n obj is type or obj is object)\n \n \ndef _signature_is_functionlike(obj):\n ''\n\n\n\n \n \n if not callable(obj)or isclass(obj):\n \n \n return False\n \n name=getattr(obj,'__name__',None)\n code=getattr(obj,'__code__',None)\n defaults=getattr(obj,'__defaults__',_void)\n kwdefaults=getattr(obj,'__kwdefaults__',_void)\n annotations=getattr(obj,'__annotations__',None)\n \n return(isinstance(code,types.CodeType)and\n isinstance(name,str)and\n (defaults is None or isinstance(defaults,tuple))and\n (kwdefaults is None or isinstance(kwdefaults,dict))and\n (isinstance(annotations,(dict))or annotations is None))\n \n \ndef _signature_strip_non_python_syntax(signature):\n ''\n\n\n\n\n\n\n\n \n \n if not signature:\n return signature,None\n \n self_parameter=None\n \n lines=[l.encode('ascii')for l in signature.split('\\n')if l]\n generator=iter(lines).__next__\n token_stream=tokenize.tokenize(generator)\n \n text=[]\n add=text.append\n \n current_parameter=0\n OP=token.OP\n ERRORTOKEN=token.ERRORTOKEN\n \n \n t=next(token_stream)\n assert t.type ==tokenize.ENCODING\n \n for t in token_stream:\n type,string=t.type,t.string\n \n if type ==OP:\n if string ==',':\n current_parameter +=1\n \n if(type ==OP)and(string =='$'):\n assert self_parameter is None\n self_parameter=current_parameter\n continue\n \n add(string)\n if(string ==','):\n add(' ')\n clean_signature=''.join(text).strip().replace(\"\\n\",\"\")\n return clean_signature,self_parameter\n \n \ndef _signature_fromstr(cls,obj,s,skip_bound_arg=True):\n ''\n\n \n Parameter=cls._parameter_cls\n \n clean_signature,self_parameter=_signature_strip_non_python_syntax(s)\n \n program=\"def foo\"+clean_signature+\": pass\"\n \n try:\n module=ast.parse(program)\n except SyntaxError:\n module=None\n \n if not isinstance(module,ast.Module):\n raise ValueError(\"{!r} builtin has invalid signature\".format(obj))\n \n f=module.body[0]\n \n parameters=[]\n empty=Parameter.empty\n \n module=None\n module_dict={}\n \n module_name=getattr(obj,'__module__',None)\n if not module_name:\n objclass=getattr(obj,'__objclass__',None)\n module_name=getattr(objclass,'__module__',None)\n \n if module_name:\n module=sys.modules.get(module_name,None)\n if module:\n module_dict=module.__dict__\n sys_module_dict=sys.modules.copy()\n \n def parse_name(node):\n assert isinstance(node,ast.arg)\n if node.annotation is not None:\n raise ValueError(\"Annotations are not currently supported\")\n return node.arg\n \n def wrap_value(s):\n try:\n value=eval(s,module_dict)\n except NameError:\n try:\n value=eval(s,sys_module_dict)\n except NameError:\n raise ValueError\n \n if isinstance(value,(str,int,float,bytes,bool,type(None))):\n return ast.Constant(value)\n raise ValueError\n \n class RewriteSymbolics(ast.NodeTransformer):\n def visit_Attribute(self,node):\n a=[]\n n=node\n while isinstance(n,ast.Attribute):\n a.append(n.attr)\n n=n.value\n if not isinstance(n,ast.Name):\n raise ValueError\n a.append(n.id)\n value=\".\".join(reversed(a))\n return wrap_value(value)\n \n def visit_Name(self,node):\n if not isinstance(node.ctx,ast.Load):\n raise ValueError()\n return wrap_value(node.id)\n \n def visit_BinOp(self,node):\n \n \n left=self.visit(node.left)\n right=self.visit(node.right)\n if not isinstance(left,ast.Constant)or not isinstance(right,ast.Constant):\n raise ValueError\n if isinstance(node.op,ast.Add):\n return ast.Constant(left.value+right.value)\n elif isinstance(node.op,ast.Sub):\n return ast.Constant(left.value -right.value)\n elif isinstance(node.op,ast.BitOr):\n return ast.Constant(left.value |right.value)\n raise ValueError\n \n def p(name_node,default_node,default=empty):\n name=parse_name(name_node)\n if default_node and default_node is not _empty:\n try:\n default_node=RewriteSymbolics().visit(default_node)\n default=ast.literal_eval(default_node)\n except ValueError:\n raise ValueError(\"{!r} builtin has invalid signature\".format(obj))from None\n parameters.append(Parameter(name,kind,default=default,annotation=empty))\n \n \n total_non_kw_args=len(f.args.posonlyargs)+len(f.args.args)\n required_non_kw_args=total_non_kw_args -len(f.args.defaults)\n defaults=itertools.chain(itertools.repeat(None,required_non_kw_args),f.args.defaults)\n \n kind=Parameter.POSITIONAL_ONLY\n for(name,default)in zip(f.args.posonlyargs,defaults):\n p(name,default)\n \n kind=Parameter.POSITIONAL_OR_KEYWORD\n for(name,default)in zip(f.args.args,defaults):\n p(name,default)\n \n \n if f.args.vararg:\n kind=Parameter.VAR_POSITIONAL\n p(f.args.vararg,empty)\n \n \n kind=Parameter.KEYWORD_ONLY\n for name,default in zip(f.args.kwonlyargs,f.args.kw_defaults):\n p(name,default)\n \n \n if f.args.kwarg:\n kind=Parameter.VAR_KEYWORD\n p(f.args.kwarg,empty)\n \n if self_parameter is not None:\n \n \n \n \n \n assert parameters\n _self=getattr(obj,'__self__',None)\n self_isbound=_self is not None\n self_ismodule=ismodule(_self)\n if self_isbound and(self_ismodule or skip_bound_arg):\n parameters.pop(0)\n else:\n \n p=parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)\n parameters[0]=p\n \n return cls(parameters,return_annotation=cls.empty)\n \n \ndef _signature_from_builtin(cls,func,skip_bound_arg=True):\n ''\n\n \n \n if not _signature_is_builtin(func):\n raise TypeError(\"{!r} is not a Python builtin \"\n \"function\".format(func))\n \n s=getattr(func,\"__text_signature__\",None)\n if not s:\n raise ValueError(\"no signature found for builtin {!r}\".format(func))\n \n return _signature_fromstr(cls,func,s,skip_bound_arg)\n \n \ndef _signature_from_function(cls,func,skip_bound_arg=True,\nglobals=None,locals=None,eval_str=False):\n ''\n \n is_duck_function=False\n if not isfunction(func):\n if _signature_is_functionlike(func):\n is_duck_function=True\n else:\n \n \n raise TypeError('{!r} is not a Python function'.format(func))\n \n s=getattr(func,\"__text_signature__\",None)\n if s:\n return _signature_fromstr(cls,func,s,skip_bound_arg)\n \n Parameter=cls._parameter_cls\n \n \n func_code=func.__code__\n pos_count=func_code.co_argcount\n arg_names=func_code.co_varnames\n posonly_count=func_code.co_posonlyargcount\n positional=arg_names[:pos_count]\n keyword_only_count=func_code.co_kwonlyargcount\n keyword_only=arg_names[pos_count:pos_count+keyword_only_count]\n annotations=get_annotations(func,globals=globals,locals=locals,eval_str=eval_str)\n defaults=func.__defaults__\n kwdefaults=func.__kwdefaults__\n \n if defaults:\n pos_default_count=len(defaults)\n else:\n pos_default_count=0\n \n parameters=[]\n \n non_default_count=pos_count -pos_default_count\n posonly_left=posonly_count\n \n \n for name in positional[:non_default_count]:\n kind=_POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=kind))\n if posonly_left:\n posonly_left -=1\n \n \n for offset,name in enumerate(positional[non_default_count:]):\n kind=_POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=kind,\n default=defaults[offset]))\n if posonly_left:\n posonly_left -=1\n \n \n if func_code.co_flags&CO_VARARGS:\n name=arg_names[pos_count+keyword_only_count]\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_VAR_POSITIONAL))\n \n \n for name in keyword_only:\n default=_empty\n if kwdefaults is not None:\n default=kwdefaults.get(name,_empty)\n \n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_KEYWORD_ONLY,\n default=default))\n \n if func_code.co_flags&CO_VARKEYWORDS:\n index=pos_count+keyword_only_count\n if func_code.co_flags&CO_VARARGS:\n index +=1\n \n name=arg_names[index]\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_VAR_KEYWORD))\n \n \n \n return cls(parameters,\n return_annotation=annotations.get('return',_empty),\n __validate_parameters__=is_duck_function)\n \n \ndef _descriptor_get(descriptor,obj):\n if isclass(descriptor):\n return descriptor\n get=getattr(type(descriptor),'__get__',_sentinel)\n if get is _sentinel:\n return descriptor\n return get(descriptor,obj,type(obj))\n \n \ndef _signature_from_callable(obj,*,\nfollow_wrapper_chains=True,\nskip_bound_arg=True,\nglobals=None,\nlocals=None,\neval_str=False,\nsigcls):\n\n ''\n\n \n \n _get_signature_of=functools.partial(_signature_from_callable,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n globals=globals,\n locals=locals,\n sigcls=sigcls,\n eval_str=eval_str)\n \n if not callable(obj):\n raise TypeError('{!r} is not a callable object'.format(obj))\n \n if isinstance(obj,types.MethodType):\n \n \n sig=_get_signature_of(obj.__func__)\n \n if skip_bound_arg:\n return _signature_bound_method(sig)\n else:\n return sig\n \n \n if follow_wrapper_chains:\n \n \n obj=unwrap(obj,stop=(lambda f:hasattr(f,\"__signature__\")\n or isinstance(f,types.MethodType)))\n if isinstance(obj,types.MethodType):\n \n \n \n return _get_signature_of(obj)\n \n try:\n sig=obj.__signature__\n except AttributeError:\n pass\n else:\n if sig is not None:\n \n \n \n o_sig=sig\n if not isinstance(sig,(Signature,str))and callable(sig):\n sig=sig()\n if isinstance(sig,str):\n sig=_signature_fromstr(sigcls,obj,sig)\n if not isinstance(sig,Signature):\n raise TypeError(\n 'unexpected object {!r} in __signature__ '\n 'attribute'.format(o_sig))\n return sig\n \n try:\n partialmethod=obj.__partialmethod__\n except AttributeError:\n pass\n else:\n if isinstance(partialmethod,functools.partialmethod):\n \n \n \n \n \n \n \n wrapped_sig=_get_signature_of(partialmethod.func)\n \n sig=_signature_get_partial(wrapped_sig,partialmethod,(None,))\n first_wrapped_param=tuple(wrapped_sig.parameters.values())[0]\n if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:\n \n \n return sig\n else:\n sig_params=tuple(sig.parameters.values())\n assert(not sig_params or\n first_wrapped_param is not sig_params[0])\n new_params=(first_wrapped_param,)+sig_params\n return sig.replace(parameters=new_params)\n \n if isinstance(obj,functools.partial):\n wrapped_sig=_get_signature_of(obj.func)\n return _signature_get_partial(wrapped_sig,obj)\n \n if isfunction(obj)or _signature_is_functionlike(obj):\n \n \n return _signature_from_function(sigcls,obj,\n skip_bound_arg=skip_bound_arg,\n globals=globals,locals=locals,eval_str=eval_str)\n \n if _signature_is_builtin(obj):\n return _signature_from_builtin(sigcls,obj,\n skip_bound_arg=skip_bound_arg)\n \n if isinstance(obj,type):\n \n \n \n \n call=_signature_get_user_defined_method(type(obj),'__call__')\n if call is not None:\n return _get_signature_of(call)\n \n new=_signature_get_user_defined_method(obj,'__new__')\n init=_signature_get_user_defined_method(obj,'__init__')\n \n \n \n for base in obj.__mro__:\n \n if new is not None and '__new__'in base.__dict__:\n sig=_get_signature_of(new)\n if skip_bound_arg:\n sig=_signature_bound_method(sig)\n return sig\n \n elif init is not None and '__init__'in base.__dict__:\n return _get_signature_of(init)\n \n \n \n \n for base in obj.__mro__[:-1]:\n \n \n \n \n \n \n \n try:\n text_sig=base.__text_signature__\n except AttributeError:\n pass\n else:\n if text_sig:\n \n \n return _signature_fromstr(sigcls,base,text_sig)\n \n \n \n \n if type not in obj.__mro__:\n \n \n if(obj.__init__ is object.__init__ and\n obj.__new__ is object.__new__):\n \n return sigcls.from_callable(object)\n else:\n raise ValueError(\n 'no signature found for builtin type {!r}'.format(obj))\n \n else:\n \n call=getattr_static(type(obj),'__call__',None)\n if call is not None:\n try:\n text_sig=obj.__text_signature__\n except AttributeError:\n pass\n else:\n if text_sig:\n return _signature_fromstr(sigcls,obj,text_sig)\n call=_descriptor_get(call,obj)\n return _get_signature_of(call)\n \n raise ValueError('callable {!r} is not supported by signature'.format(obj))\n \n \nclass _void:\n ''\n \n \nclass _empty:\n ''\n \n \nclass _ParameterKind(enum.IntEnum):\n POSITIONAL_ONLY='positional-only'\n POSITIONAL_OR_KEYWORD='positional or keyword'\n VAR_POSITIONAL='variadic positional'\n KEYWORD_ONLY='keyword-only'\n VAR_KEYWORD='variadic keyword'\n \n def __new__(cls,description):\n value=len(cls.__members__)\n member=int.__new__(cls,value)\n member._value_=value\n member.description=description\n return member\n \n def __str__(self):\n return self.name\n \n_POSITIONAL_ONLY=_ParameterKind.POSITIONAL_ONLY\n_POSITIONAL_OR_KEYWORD=_ParameterKind.POSITIONAL_OR_KEYWORD\n_VAR_POSITIONAL=_ParameterKind.VAR_POSITIONAL\n_KEYWORD_ONLY=_ParameterKind.KEYWORD_ONLY\n_VAR_KEYWORD=_ParameterKind.VAR_KEYWORD\n\n\nclass Parameter:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('_name','_kind','_default','_annotation')\n \n POSITIONAL_ONLY=_POSITIONAL_ONLY\n POSITIONAL_OR_KEYWORD=_POSITIONAL_OR_KEYWORD\n VAR_POSITIONAL=_VAR_POSITIONAL\n KEYWORD_ONLY=_KEYWORD_ONLY\n VAR_KEYWORD=_VAR_KEYWORD\n \n empty=_empty\n \n def __init__(self,name,kind,*,default=_empty,annotation=_empty):\n try:\n self._kind=_ParameterKind(kind)\n except ValueError:\n raise ValueError(f'value {kind !r} is not a valid Parameter.kind')\n if default is not _empty:\n if self._kind in(_VAR_POSITIONAL,_VAR_KEYWORD):\n msg='{} parameters cannot have default values'\n msg=msg.format(self._kind.description)\n raise ValueError(msg)\n self._default=default\n self._annotation=annotation\n \n if name is _empty:\n raise ValueError('name is a required attribute for Parameter')\n \n if not isinstance(name,str):\n msg='name must be a str, not a {}'.format(type(name).__name__)\n raise TypeError(msg)\n \n if name[0]=='.'and name[1:].isdigit():\n \n \n \n \n if self._kind !=_POSITIONAL_OR_KEYWORD:\n msg=(\n 'implicit arguments must be passed as '\n 'positional or keyword arguments, not {}'\n )\n msg=msg.format(self._kind.description)\n raise ValueError(msg)\n self._kind=_POSITIONAL_ONLY\n name='implicit{}'.format(name[1:])\n \n \n \n is_keyword=iskeyword(name)and self._kind is not _POSITIONAL_ONLY\n if is_keyword or not name.isidentifier():\n raise ValueError('{!r} is not a valid parameter name'.format(name))\n \n self._name=name\n \n def __reduce__(self):\n return(type(self),\n (self._name,self._kind),\n {'_default':self._default,\n '_annotation':self._annotation})\n \n def __setstate__(self,state):\n self._default=state['_default']\n self._annotation=state['_annotation']\n \n @property\n def name(self):\n return self._name\n \n @property\n def default(self):\n return self._default\n \n @property\n def annotation(self):\n return self._annotation\n \n @property\n def kind(self):\n return self._kind\n \n def replace(self,*,name=_void,kind=_void,\n annotation=_void,default=_void):\n ''\n \n if name is _void:\n name=self._name\n \n if kind is _void:\n kind=self._kind\n \n if annotation is _void:\n annotation=self._annotation\n \n if default is _void:\n default=self._default\n \n return type(self)(name,kind,default=default,annotation=annotation)\n \n def __str__(self):\n kind=self.kind\n formatted=self._name\n \n \n if self._annotation is not _empty:\n formatted='{}: {}'.format(formatted,\n formatannotation(self._annotation))\n \n if self._default is not _empty:\n if self._annotation is not _empty:\n formatted='{} = {}'.format(formatted,repr(self._default))\n else:\n formatted='{}={}'.format(formatted,repr(self._default))\n \n if kind ==_VAR_POSITIONAL:\n formatted='*'+formatted\n elif kind ==_VAR_KEYWORD:\n formatted='**'+formatted\n \n return formatted\n \n __replace__=replace\n \n def __repr__(self):\n return '<{} \"{}\">'.format(self.__class__.__name__,self)\n \n def __hash__(self):\n return hash((self._name,self._kind,self._annotation,self._default))\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,Parameter):\n return NotImplemented\n return(self._name ==other._name and\n self._kind ==other._kind and\n self._default ==other._default and\n self._annotation ==other._annotation)\n \n \nclass BoundArguments:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('arguments','_signature','__weakref__')\n \n def __init__(self,signature,arguments):\n self.arguments=arguments\n self._signature=signature\n \n @property\n def signature(self):\n return self._signature\n \n @property\n def args(self):\n args=[]\n for param_name,param in self._signature.parameters.items():\n if param.kind in(_VAR_KEYWORD,_KEYWORD_ONLY):\n break\n \n try:\n arg=self.arguments[param_name]\n except KeyError:\n \n \n break\n else:\n if param.kind ==_VAR_POSITIONAL:\n \n args.extend(arg)\n else:\n \n args.append(arg)\n \n return tuple(args)\n \n @property\n def kwargs(self):\n kwargs={}\n kwargs_started=False\n for param_name,param in self._signature.parameters.items():\n if not kwargs_started:\n if param.kind in(_VAR_KEYWORD,_KEYWORD_ONLY):\n kwargs_started=True\n else:\n if param_name not in self.arguments:\n kwargs_started=True\n continue\n \n if not kwargs_started:\n continue\n \n try:\n arg=self.arguments[param_name]\n except KeyError:\n pass\n else:\n if param.kind ==_VAR_KEYWORD:\n \n kwargs.update(arg)\n else:\n \n kwargs[param_name]=arg\n \n return kwargs\n \n def apply_defaults(self):\n ''\n\n\n\n\n\n\n \n arguments=self.arguments\n new_arguments=[]\n for name,param in self._signature.parameters.items():\n try:\n new_arguments.append((name,arguments[name]))\n except KeyError:\n if param.default is not _empty:\n val=param.default\n elif param.kind is _VAR_POSITIONAL:\n val=()\n elif param.kind is _VAR_KEYWORD:\n val={}\n else:\n \n \n continue\n new_arguments.append((name,val))\n self.arguments=dict(new_arguments)\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,BoundArguments):\n return NotImplemented\n return(self.signature ==other.signature and\n self.arguments ==other.arguments)\n \n def __setstate__(self,state):\n self._signature=state['_signature']\n self.arguments=state['arguments']\n \n def __getstate__(self):\n return{'_signature':self._signature,'arguments':self.arguments}\n \n def __repr__(self):\n args=[]\n for arg,value in self.arguments.items():\n args.append('{}={!r}'.format(arg,value))\n return '<{} ({})>'.format(self.__class__.__name__,', '.join(args))\n \n \nclass Signature:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('_return_annotation','_parameters')\n \n _parameter_cls=Parameter\n _bound_arguments_cls=BoundArguments\n \n empty=_empty\n \n def __init__(self,parameters=None,*,return_annotation=_empty,\n __validate_parameters__=True):\n ''\n\n \n \n if parameters is None:\n params=OrderedDict()\n else:\n if __validate_parameters__:\n params=OrderedDict()\n top_kind=_POSITIONAL_ONLY\n seen_default=False\n \n for param in parameters:\n kind=param.kind\n name=param.name\n \n if kind top_kind:\n top_kind=kind\n \n if kind in(_POSITIONAL_ONLY,_POSITIONAL_OR_KEYWORD):\n if param.default is _empty:\n if seen_default:\n \n \n msg='non-default argument follows default '\\\n 'argument'\n raise ValueError(msg)\n else:\n \n seen_default=True\n \n if name in params:\n msg='duplicate parameter name: {!r}'.format(name)\n raise ValueError(msg)\n \n params[name]=param\n else:\n params=OrderedDict((param.name,param)for param in parameters)\n \n self._parameters=types.MappingProxyType(params)\n self._return_annotation=return_annotation\n \n @classmethod\n def from_callable(cls,obj,*,\n follow_wrapped=True,globals=None,locals=None,eval_str=False):\n ''\n return _signature_from_callable(obj,sigcls=cls,\n follow_wrapper_chains=follow_wrapped,\n globals=globals,locals=locals,eval_str=eval_str)\n \n @property\n def parameters(self):\n return self._parameters\n \n @property\n def return_annotation(self):\n return self._return_annotation\n \n def replace(self,*,parameters=_void,return_annotation=_void):\n ''\n\n\n \n \n if parameters is _void:\n parameters=self.parameters.values()\n \n if return_annotation is _void:\n return_annotation=self._return_annotation\n \n return type(self)(parameters,\n return_annotation=return_annotation)\n \n __replace__=replace\n \n def _hash_basis(self):\n params=tuple(param for param in self.parameters.values()\n if param.kind !=_KEYWORD_ONLY)\n \n kwo_params={param.name:param for param in self.parameters.values()\n if param.kind ==_KEYWORD_ONLY}\n \n return params,kwo_params,self.return_annotation\n \n def __hash__(self):\n params,kwo_params,return_annotation=self._hash_basis()\n kwo_params=frozenset(kwo_params.values())\n return hash((params,kwo_params,return_annotation))\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,Signature):\n return NotImplemented\n return self._hash_basis()==other._hash_basis()\n \n def _bind(self,args,kwargs,*,partial=False):\n ''\n \n arguments={}\n \n parameters=iter(self.parameters.values())\n parameters_ex=()\n arg_vals=iter(args)\n \n pos_only_param_in_kwargs=[]\n \n while True:\n \n \n try:\n arg_val=next(arg_vals)\n except StopIteration:\n \n try:\n param=next(parameters)\n except StopIteration:\n \n \n break\n else:\n if param.kind ==_VAR_POSITIONAL:\n \n \n break\n elif param.name in kwargs:\n if param.kind ==_POSITIONAL_ONLY:\n \n \n pos_only_param_in_kwargs.append(param)\n continue\n parameters_ex=(param,)\n break\n elif(param.kind ==_VAR_KEYWORD or\n param.default is not _empty):\n \n \n \n parameters_ex=(param,)\n break\n else:\n \n \n if partial:\n parameters_ex=(param,)\n break\n else:\n if param.kind ==_KEYWORD_ONLY:\n argtype=' keyword-only'\n else:\n argtype=''\n msg='missing a required{argtype} argument: {arg!r}'\n msg=msg.format(arg=param.name,argtype=argtype)\n raise TypeError(msg)from None\n else:\n \n try:\n param=next(parameters)\n except StopIteration:\n raise TypeError('too many positional arguments')from None\n else:\n if param.kind in(_VAR_KEYWORD,_KEYWORD_ONLY):\n \n \n raise TypeError(\n 'too many positional arguments')from None\n \n if param.kind ==_VAR_POSITIONAL:\n \n \n \n values=[arg_val]\n values.extend(arg_vals)\n arguments[param.name]=tuple(values)\n break\n \n if param.name in kwargs and param.kind !=_POSITIONAL_ONLY:\n raise TypeError(\n 'multiple values for argument {arg!r}'.format(\n arg=param.name))from None\n \n arguments[param.name]=arg_val\n \n \n \n kwargs_param=None\n for param in itertools.chain(parameters_ex,parameters):\n if param.kind ==_VAR_KEYWORD:\n \n kwargs_param=param\n continue\n \n if param.kind ==_VAR_POSITIONAL:\n \n \n \n continue\n \n param_name=param.name\n try:\n arg_val=kwargs.pop(param_name)\n except KeyError:\n \n \n \n \n if(not partial and param.kind !=_VAR_POSITIONAL and\n param.default is _empty):\n raise TypeError('missing a required argument: {arg!r}'.\\\n format(arg=param_name))from None\n \n else:\n arguments[param_name]=arg_val\n \n if kwargs:\n if kwargs_param is not None:\n \n arguments[kwargs_param.name]=kwargs\n elif pos_only_param_in_kwargs:\n raise TypeError(\n 'got some positional-only arguments passed as '\n 'keyword arguments: {arg!r}'.format(\n arg=', '.join(\n param.name\n for param in pos_only_param_in_kwargs\n ),\n ),\n )\n else:\n raise TypeError(\n 'got an unexpected keyword argument {arg!r}'.format(\n arg=next(iter(kwargs))))\n \n return self._bound_arguments_cls(self,arguments)\n \n def bind(self,/,*args,**kwargs):\n ''\n\n\n \n return self._bind(args,kwargs)\n \n def bind_partial(self,/,*args,**kwargs):\n ''\n\n\n \n return self._bind(args,kwargs,partial=True)\n \n def __reduce__(self):\n return(type(self),\n (tuple(self._parameters.values()),),\n {'_return_annotation':self._return_annotation})\n \n def __setstate__(self,state):\n self._return_annotation=state['_return_annotation']\n \n def __repr__(self):\n return '<{} {}>'.format(self.__class__.__name__,self)\n \n def __str__(self):\n return self.format()\n \n def format(self,*,max_width=None):\n ''\n\n\n\n\n\n \n result=[]\n render_pos_only_separator=False\n render_kw_only_separator=True\n for param in self.parameters.values():\n formatted=str(param)\n \n kind=param.kind\n \n if kind ==_POSITIONAL_ONLY:\n render_pos_only_separator=True\n elif render_pos_only_separator:\n \n \n result.append('/')\n render_pos_only_separator=False\n \n if kind ==_VAR_POSITIONAL:\n \n \n render_kw_only_separator=False\n elif kind ==_KEYWORD_ONLY and render_kw_only_separator:\n \n \n \n result.append('*')\n \n \n render_kw_only_separator=False\n \n result.append(formatted)\n \n if render_pos_only_separator:\n \n \n result.append('/')\n \n rendered='({})'.format(', '.join(result))\n if max_width is not None and len(rendered)>max_width:\n rendered='(\\n {}\\n)'.format(',\\n '.join(result))\n \n if self.return_annotation is not _empty:\n anno=formatannotation(self.return_annotation)\n rendered +=' -> {}'.format(anno)\n \n return rendered\n \n \ndef signature(obj,*,follow_wrapped=True,globals=None,locals=None,eval_str=False):\n ''\n return Signature.from_callable(obj,follow_wrapped=follow_wrapped,\n globals=globals,locals=locals,eval_str=eval_str)\n \n \nclass BufferFlags(enum.IntFlag):\n SIMPLE=0x0\n WRITABLE=0x1\n FORMAT=0x4\n ND=0x8\n STRIDES=0x10 |ND\n C_CONTIGUOUS=0x20 |STRIDES\n F_CONTIGUOUS=0x40 |STRIDES\n ANY_CONTIGUOUS=0x80 |STRIDES\n INDIRECT=0x100 |STRIDES\n CONTIG=ND |WRITABLE\n CONTIG_RO=ND\n STRIDED=STRIDES |WRITABLE\n STRIDED_RO=STRIDES\n RECORDS=STRIDES |WRITABLE |FORMAT\n RECORDS_RO=STRIDES |FORMAT\n FULL=INDIRECT |WRITABLE |FORMAT\n FULL_RO=INDIRECT |FORMAT\n READ=0x100\n WRITE=0x200\n \n \ndef _main():\n ''\n import argparse\n import importlib\n \n parser=argparse.ArgumentParser()\n parser.add_argument(\n 'object',\n help=\"The object to be analysed. \"\n \"It supports the 'module:qualname' syntax\")\n parser.add_argument(\n '-d','--details',action='store_true',\n help='Display info about the module rather than its source code')\n \n args=parser.parse_args()\n \n target=args.object\n mod_name,has_attrs,attrs=target.partition(\":\")\n try:\n obj=module=importlib.import_module(mod_name)\n except Exception as exc:\n msg=\"Failed to import {} ({}: {})\".format(mod_name,\n type(exc).__name__,\n exc)\n print(msg,file=sys.stderr)\n sys.exit(2)\n \n if has_attrs:\n parts=attrs.split(\".\")\n obj=module\n for part in parts:\n obj=getattr(obj,part)\n \n if module.__name__ in sys.builtin_module_names:\n print(\"Can't get info for builtin modules.\",file=sys.stderr)\n sys.exit(1)\n \n if args.details:\n print('Target: {}'.format(target))\n print('Origin: {}'.format(getsourcefile(module)))\n print('Cached: {}'.format(module.__cached__))\n if obj is module:\n print('Loader: {}'.format(repr(module.__loader__)))\n if hasattr(module,'__path__'):\n print('Submodule search path: {}'.format(module.__path__))\n else:\n try:\n __,lineno=findsource(obj)\n except Exception:\n pass\n else:\n print('Line: {}'.format(lineno))\n \n print('\\n')\n else:\n print(getsource(obj))\n \n \nif __name__ ==\"__main__\":\n _main()\n", ["abc", "argparse", "ast", "builtins", "collections", "collections.abc", "dis", "enum", "functools", "importlib", "importlib.machinery", "itertools", "keyword", "linecache", "operator", "os", "re", "sys", "token", "tokenize", "types", "weakref"]], "interpreter": [".py", "import sys\nimport builtins\nimport re\n\nimport tb as traceback\n\nfrom browser import console,document,window,html,DOMNode\nfrom browser.widgets.dialog import Dialog\n\n_credits=\"\"\" Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\n for supporting Python development. See www.python.org for more information.\"\"\"\n\n_copyright=\"\"\"Copyright (c) 2012, Pierre Quentel pierre.quentel@gmail.com\nAll Rights Reserved.\n\nCopyright (c) 2001-2022 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.\"\"\"\n\n_help=\"Type help() for interactive help, or help(object) for help about object.\"\n\n_license=\"\"\"Copyright (c) 2012, Pierre Quentel pierre.quentel@gmail.com\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer. Redistributions in binary\nform must reproduce the above copyright notice, this list of conditions and\nthe following disclaimer in the documentation and/or other materials provided\nwith the distribution.\nNeither the name of the nor the names of its contributors may\nbe used to endorse or promote products derived from this software without\nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nclass Info:\n\n def __init__(self,msg):\n self.msg=msg\n \n def __repr__(self):\n return self.msg\n \n \n \neditor_ns={\n'credits':Info(_credits),\n'copyright':Info(_copyright),\n'license':Info(_license),\n'__annotations__':{},\n'__builtins__':builtins,\n'__doc__':None,\n'__file__':'',\n'__name__':'__main__'\n}\n\n\nstyle_sheet=\"\"\"\n.brython-interpreter {\n background-color: #000;\n color: #fff;\n font-family: consolas, courier;\n caret-color: #fff;\n overflow-y: auto;\n overflow-x: hidden;\n}\n\n@keyframes blinker {\n 50% {\n opacity: 0;\n }\n}\n\npre{\n display:inline;\n}\n\"\"\"\n\nactive=[]\n\nclass Output:\n\n def __init__(self,interpreter):\n self.interpreter=interpreter\n \n def write(self,*args,**kw):\n self.interpreter.write(*args,**kw)\n \n def __len__(self):\n return len(self.interpreter.buffer)\n \n \n \n \ncolor_character_pattern=re.compile(r'^\\033\\[([0-9;]*)m')\n\ndef swap_color_bgcolor(element):\n ''\n element.style.color,element.style.backgroundColor=\\\n element.style.backgroundColor,element.style.color\n \ncc_styles={\n0:[\"fontStyle\",\"normal\"],\n1:[\"fontWeight\",\"bold\"],\n2:[\"fontWeight\",\"lighter\"],\n3:[\"fontStyle\",\"italic\"],\n4:[\"textDecoration\",\"underline\"],\n5:[\"animation\",\"blinker 1s step-start infinite\"],\n6:[\"animation\",\"blinker 0.5s step-start infinite\"],\n7:swap_color_bgcolor\n}\n\ncc_colors={\n30:\"Black\",\n31:\"Red\",\n32:\"Green\",\n33:\"Yellow\",\n34:\"Blue\",\n35:\"Magenta\",\n36:\"Cyan\",\n37:\"White\"\n}\n\ncc_bgcolors={k+10:v for(k,v)in cc_colors.items()}\n\n\nclass Trace:\n\n def __init__(self,exc):\n self.buf=\"\"\n self.is_syntax_error=exc.__name__ in['SyntaxError',\n 'IndentationError']\n \n def write(self,data):\n self.buf +=str(data)\n \n def format(self):\n ''\n lines=self.buf.strip().split(\"\\n\")\n stripped=[lines[0]]if not self.is_syntax_error else['']\n for i in range(1,len(lines),2):\n if __file__ in lines[i]:\n continue\n stripped +=lines[i:i+2]\n return \"\\n\".join(stripped)\n \n \nclass Interpreter:\n ''\n \n def __init__(self,elt_id=None,title=\"Interactive Interpreter\",\n globals=None,locals=None,history=None,\n rows=30,cols=120,default_css=True,\n clear_zone=True,banner=True):\n ''\n\n\n\n\n\n \n if default_css:\n \n for stylesheet in document.styleSheets:\n if stylesheet.ownerNode.id ==\"brython-interpreter\":\n break\n else:\n document <=html.STYLE(style_sheet,id=\"brython-interpreter\")\n \n self.cc_style=None\n self.cc_color=None\n self.cc_bgcolor=None\n self.default_cc_color='#fff'\n self.default_cc_bgcolor='#000'\n \n if elt_id is None:\n self.dialog=Dialog(title=title,top=10,left=10,\n default_css=default_css)\n self.dialog.bind('blur',self.blur)\n self.dialog.bind('click',self.focus)\n self.dialog.close_button.bind('click',self.close)\n self.zone=html.DIV(Class=\"brython-interpreter\",\n contenteditable=True)\n self.zone.style.width=f'{cols}ch'\n self.zone.style.height=f'{rows}ch'\n self.dialog.panel <=self.zone\n else:\n if isinstance(elt_id,str):\n try:\n elt=document[elt_id]\n if elt.tagName !=\"DIV\":\n raise ValueError(\n f\"element {elt_id} is a {elt.tagName}, \"+\n \"not a DIV\")\n self.zone=elt\n except KeyError:\n raise KeyError(f\"no element with id '{elt_id}'\")\n elif isinstance(elt_id,DOMNode):\n if elt_id.tagName ==\"DIV\":\n self.zone=elt_id\n else:\n raise ValueError(\"element is not a DIV\")\n else:\n raise ValueError(\"element should be a string or \"+\n f\"a DIV, got '{elt_id.__class__.__name__}'\")\n if self.zone.contentEditable !='true':\n raise ValueError(\"DIV element must be contenteditable\")\n v=sys.implementation.version\n if clear_zone:\n self.clear()\n if banner:\n self.insert(\n f\"Brython {v[0]}.{v[1]}.{v[2]} on \"\n f\"{window.navigator.appName} {window.navigator.appVersion}\"\n \"\\n\"\n )\n self.insert('Type \"help\", \"copyright\", \"credits\" '\n 'or \"license\" for more information.'+'\\n')\n self.insert_prompt()\n \n self._status=\"main\"\n self.history=history or[]\n self.current=len(self.history)\n \n self.globals={}if globals is None else globals\n self.globals.update(editor_ns)\n self.locals=self.globals if locals is None else locals\n \n self.zone.bind('keypress',self.keypress)\n self.zone.bind('keydown',self.keydown)\n self.zone.bind('mouseup',self.mouseup)\n \n self.zone.bind('focus',self.focus)\n self.zone.bind('blur',self.blur)\n self.focus()\n \n self.cursor_to_end()\n \n active.append(self)\n \n def clear(self):\n self.zone.text=''\n \n def insert(self,text):\n \n pre=html.PRE(style=\"display:inline;white-space:pre-wrap;\")\n pre.text=text\n if self.cc_color is not None:\n pre.style.color=self.cc_color\n if self.cc_bgcolor is not None:\n pre.style.backgroundColor=self.cc_bgcolor\n if self.cc_style is not None:\n style=cc_styles[self.cc_style]\n if isinstance(style,list):\n attr,value=style\n setattr(pre.style,attr,value)\n else:\n style(pre)\n self.zone <=pre\n \n def insert_prompt(self):\n self.insert('>>> ')\n \n def insert_continuation(self):\n self.insert('\\n... ')\n \n def insert_cr(self):\n self.insert('\\n')\n \n def get_content(self):\n return self.zone.text\n \n def blur(self,ev):\n if hasattr(self,'dialog'):\n self.dialog.style.zIndex=0\n \n def close(self,ev):\n active.remove(self)\n \n def cursor_to_end(self,*args):\n \n sel=window.getSelection()\n \n last_child=self.zone.lastChild.firstChild\n if last_child is None:\n last_child=self.zone.lastChild\n pos=len(last_child.text)\n \n sel.setBaseAndExtent(last_child,pos,last_child,pos)\n \n self.zone.lastChild.scrollIntoView({\"block\":\"end\",\"behaviour\":\"smooth\"})\n \n def focus(self,*args):\n ''\n if hasattr(self,'dialog'):\n \n for w in active:\n if w is not self:\n w.dialog.style.zIndex=0\n self.dialog.style.zIndex=1\n sys.stdout=sys.stderr=Output(self)\n self.zone.focus()\n \n def keypress(self,event):\n if event.key ==\"Tab\":\n event.preventDefault()\n self.insert(\" \")\n elif event.key ==\"Enter\":\n event.preventDefault()\n selection=window.getSelection().toString()\n if selection:\n \n self.cursor_to_end()\n return\n self.handle_line(event)\n \n def feed(self,src):\n ''\n\n\n \n current_indent=0\n lines=src.strip().split('\\n')\n for line in lines:\n self.insert(line)\n self.handle_line()\n \n def add_to_history(self,line):\n self.history.append(line)\n \n def handle_line(self,event=None):\n src=self.get_content().strip()\n if self._status ==\"main\":\n currentLine=src[src.rfind('\\n>>>')+5:]\n elif self._status in[\"3string\",\"parenth_expr\"]:\n currentLine=src[src.rfind('\\n>>>')+5:]\n currentLine=currentLine.replace('\\n... ','\\n')\n else:\n currentLine=src[src.rfind('\\n...')+5:]\n if self._status =='main'and not currentLine.strip():\n self.insert_cr()\n self.insert_prompt()\n self.cursor_to_end()\n if event is not None:\n event.preventDefault()\n return\n self.add_to_history(currentLine)\n self.current=len(self.history)\n if self._status in[\"main\",\"3string\",\"parenth_expr\"]:\n \n if currentLine ==\"help\":\n self.insert_cr()\n self.write(_help)\n self.insert_cr()\n self.insert_prompt()\n self.cursor_to_end()\n if event is not None:\n event.preventDefault()\n return\n try:\n code=compile(currentLine,'','eval')\n except IndentationError:\n self.insert_continuation()\n self._status=\"block\"\n except SyntaxError as msg:\n if str(msg).startswith('unterminated triple-quoted string literal'):\n self.insert_continuation()\n self._status=\"3string\"\n elif str(msg)=='decorator expects function':\n self.insert_continuation()\n self._status=\"block\"\n elif str(msg).endswith('was never closed'):\n self.insert_continuation()\n self._status=\"parenth_expr\"\n else:\n try:\n code=compile(currentLine,'','exec')\n exec(code,self.globals,self.locals)\n except SyntaxError as exc:\n if exc.args[0].startswith('expected an indented block'):\n self.insert_continuation()\n self._status=\"block\"\n else:\n self.insert_cr()\n self.print_tb(exc)\n self.insert_prompt()\n except Exception as exc:\n self.insert_cr()\n self.print_tb(msg)\n self.insert_prompt()\n self._status=\"main\"\n else:\n self.insert_cr()\n self.insert_prompt()\n self._status=\"main\"\n except Exception as exc:\n \n \n \n self.print_tb(exc)\n self.insert_prompt()\n self._status=\"main\"\n else:\n self.insert_cr()\n try:\n self.globals['_']=eval(code,\n self.globals,\n self.locals)\n if self.globals['_']is not None:\n self.write(repr(self.globals['_'])+'\\n')\n self.insert_prompt()\n self._status=\"main\"\n except Exception as exc:\n self.print_tb(exc)\n self.insert_prompt()\n self._status=\"main\"\n \n elif currentLine ==\"\":\n block=src[src.rfind('\\n>>>')+5:].splitlines()\n block=[block[0]]+[b[4:]for b in block[1:]]\n block_src='\\n'.join(block)\n self.insert_cr()\n mode=eval if self._status ==\"parenth_expr\"else exec\n \n self._status=\"main\"\n if mode is eval:\n try:\n self.globals['_']=eval(block_src,\n self.globals,\n self.locals)\n if self.globals['_']is not None:\n self.write(repr(self.globals['_'])+'\\n')\n self._status=\"main\"\n except Exception as exc:\n self.print_tb(exc)\n self._status=\"main\"\n else:\n try:\n mode(block_src,self.globals,self.locals)\n except Exception as exc:\n self.print_tb(exc)\n self.insert_prompt()\n \n else:\n self.insert_continuation()\n \n self.cursor_to_end()\n if event is not None:\n event.preventDefault()\n \n def keydown(self,event):\n sel=window.getSelection()\n if event.key in(\"ArrowLeft\",\"Backspace\"):\n \n if sel.anchorNode is not self.zone:\n caret_column=sel.anchorOffset\n if caret_column >=5:\n return\n event.preventDefault()\n event.stopPropagation()\n elif event.key ==\"Home\":\n anchor=sel.anchorNode\n sel.setBaseAndExtent(anchor,4,anchor,4)\n event.preventDefault()\n event.stopPropagation()\n elif event.key ==\"ArrowUp\":\n line=sel.anchorNode.data\n if not line.startswith('\\n...'):\n if self.current >0:\n last_child=self.zone.lastChild\n last_child.text=last_child.text[:4]+self.history[self.current -1]\n self.current -=1\n self.cursor_to_end()\n event.preventDefault()\n elif event.key ==\"ArrowDown\":\n node=sel.anchorNode.parentNode\n if not node.nextSibling:\n if self.current \",\">\")\n frames_sel <=html.OPTION(name)\n frame=frame.f_back\n frames_sel.bind(\"change\",self.change_frame)\n frame_div=html.DIV(\"Frame \"+frames_sel)\n panel_style=window.getComputedStyle(self.dialog.panel)\n frame_div.style.paddingLeft=panel_style.paddingLeft\n frame_div.style.paddingTop=panel_style.paddingTop\n self.dialog.insertBefore(frame_div,self.dialog.panel)\n \n def change_frame(self,ev):\n self.globals,self.locals=self.frames[ev.target.selectedIndex]\n \n", ["browser", "browser.widgets.dialog", "builtins", "re", "sys", "tb"]], "io": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__=(\"Guido van Rossum , \"\n\"Mike Verdone , \"\n\"Mark Russell , \"\n\"Antoine Pitrou , \"\n\"Amaury Forgeot d'Arc , \"\n\"Benjamin Peterson \")\n\n__all__=[\"BlockingIOError\",\"open\",\"open_code\",\"IOBase\",\"RawIOBase\",\n\"FileIO\",\"BytesIO\",\"StringIO\",\"BufferedIOBase\",\n\"BufferedReader\",\"BufferedWriter\",\"BufferedRWPair\",\n\"BufferedRandom\",\"TextIOBase\",\"TextIOWrapper\",\n\"UnsupportedOperation\",\"SEEK_SET\",\"SEEK_CUR\",\"SEEK_END\",\n\"DEFAULT_BUFFER_SIZE\",\"text_encoding\",\"IncrementalNewlineDecoder\"]\n\n\nimport _io\nimport abc\n\nfrom _io import(DEFAULT_BUFFER_SIZE,BlockingIOError,UnsupportedOperation,\nopen,open_code,FileIO,BytesIO,StringIO,BufferedReader,\nBufferedWriter,BufferedRWPair,BufferedRandom,\nIncrementalNewlineDecoder,text_encoding,TextIOWrapper)\n\n\n\nUnsupportedOperation.__module__=\"io\"\n\n\nSEEK_SET=0\nSEEK_CUR=1\nSEEK_END=2\n\n\n\n\nclass IOBase(_io._IOBase,metaclass=abc.ABCMeta):\n __doc__=_io._IOBase.__doc__\n \nclass RawIOBase(_io._RawIOBase,IOBase):\n __doc__=_io._RawIOBase.__doc__\n \nclass BufferedIOBase(_io._BufferedIOBase,IOBase):\n __doc__=_io._BufferedIOBase.__doc__\n \nclass TextIOBase(_io._TextIOBase,IOBase):\n __doc__=_io._TextIOBase.__doc__\n \nRawIOBase.register(FileIO)\n\nfor klass in(BytesIO,BufferedReader,BufferedWriter,BufferedRandom,\nBufferedRWPair):\n BufferedIOBase.register(klass)\n \nfor klass in(StringIO,TextIOWrapper):\n TextIOBase.register(klass)\ndel klass\n\ntry:\n from _io import _WindowsConsoleIO\nexcept ImportError:\n pass\nelse:\n RawIOBase.register(_WindowsConsoleIO)\n", ["_io", "abc"]], "ipaddress": [".py", "\n\n\n\"\"\"A fast, lightweight IPv4/IPv6 manipulation library in Python.\n\nThis library is used to create/poke/manipulate IPv4 and IPv6 addresses\nand networks.\n\n\"\"\"\n\n__version__='1.0'\n\n\nimport functools\n\nIPV4LENGTH=32\nIPV6LENGTH=128\n\n\nclass AddressValueError(ValueError):\n ''\n \n \nclass NetmaskValueError(ValueError):\n ''\n \n \ndef ip_address(address):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return IPv4Address(address)\n except(AddressValueError,NetmaskValueError):\n pass\n \n try:\n return IPv6Address(address)\n except(AddressValueError,NetmaskValueError):\n pass\n \n raise ValueError(f'{address !r} does not appear to be an IPv4 or IPv6 address')\n \n \ndef ip_network(address,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return IPv4Network(address,strict)\n except(AddressValueError,NetmaskValueError):\n pass\n \n try:\n return IPv6Network(address,strict)\n except(AddressValueError,NetmaskValueError):\n pass\n \n raise ValueError(f'{address !r} does not appear to be an IPv4 or IPv6 network')\n \n \ndef ip_interface(address):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return IPv4Interface(address)\n except(AddressValueError,NetmaskValueError):\n pass\n \n try:\n return IPv6Interface(address)\n except(AddressValueError,NetmaskValueError):\n pass\n \n raise ValueError(f'{address !r} does not appear to be an IPv4 or IPv6 interface')\n \n \ndef v4_int_to_packed(address):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return address.to_bytes(4)\n except OverflowError:\n raise ValueError(\"Address negative or too large for IPv4\")\n \n \ndef v6_int_to_packed(address):\n ''\n\n\n\n\n\n\n\n \n try:\n return address.to_bytes(16)\n except OverflowError:\n raise ValueError(\"Address negative or too large for IPv6\")\n \n \ndef _split_optional_netmask(address):\n ''\n addr=str(address).split('/')\n if len(addr)>2:\n raise AddressValueError(f\"Only one '/' permitted in {address !r}\")\n return addr\n \n \ndef _find_address_range(addresses):\n ''\n\n\n\n\n\n\n\n \n it=iter(addresses)\n first=last=next(it)\n for ip in it:\n if ip._ip !=last._ip+1:\n yield first,last\n first=ip\n last=ip\n yield first,last\n \n \ndef _count_righthand_zero_bits(number,bits):\n ''\n\n\n\n\n\n\n\n\n \n if number ==0:\n return bits\n return min(bits,(~number&(number -1)).bit_length())\n \n \ndef summarize_address_range(first,last):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if(not(isinstance(first,_BaseAddress)and\n isinstance(last,_BaseAddress))):\n raise TypeError('first and last must be IP addresses, not networks')\n if first.version !=last.version:\n raise TypeError(\"%s and %s are not of the same version\"%(\n first,last))\n if first >last:\n raise ValueError('last IP address must be greater than first')\n \n if first.version ==4:\n ip=IPv4Network\n elif first.version ==6:\n ip=IPv6Network\n else:\n raise ValueError('unknown IP version')\n \n ip_bits=first._max_prefixlen\n first_int=first._ip\n last_int=last._ip\n while first_int <=last_int:\n nbits=min(_count_righthand_zero_bits(first_int,ip_bits),\n (last_int -first_int+1).bit_length()-1)\n net=ip((first_int,ip_bits -nbits))\n yield net\n first_int +=1 <=net.broadcast_address:\n continue\n yield net\n last=net\n \n \ndef collapse_addresses(addresses):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n addrs=[]\n ips=[]\n nets=[]\n \n \n for ip in addresses:\n if isinstance(ip,_BaseAddress):\n if ips and ips[-1]._version !=ip._version:\n raise TypeError(\"%s and %s are not of the same version\"%(\n ip,ips[-1]))\n ips.append(ip)\n elif ip._prefixlen ==ip._max_prefixlen:\n if ips and ips[-1]._version !=ip._version:\n raise TypeError(\"%s and %s are not of the same version\"%(\n ip,ips[-1]))\n try:\n ips.append(ip.ip)\n except AttributeError:\n ips.append(ip.network_address)\n else:\n if nets and nets[-1]._version !=ip._version:\n raise TypeError(\"%s and %s are not of the same version\"%(\n ip,nets[-1]))\n nets.append(ip)\n \n \n ips=sorted(set(ips))\n \n \n if ips:\n for first,last in _find_address_range(ips):\n addrs.extend(summarize_address_range(first,last))\n \n return _collapse_addresses_internal(addrs+nets)\n \n \ndef get_mixed_type_key(obj):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(obj,_BaseNetwork):\n return obj._get_networks_key()\n elif isinstance(obj,_BaseAddress):\n return obj._get_address_key()\n return NotImplemented\n \n \nclass _IPAddressBase:\n\n ''\n \n __slots__=()\n \n @property\n def exploded(self):\n ''\n return self._explode_shorthand_ip_string()\n \n @property\n def compressed(self):\n ''\n return str(self)\n \n @property\n def reverse_pointer(self):\n ''\n\n\n\n\n\n \n return self._reverse_pointer()\n \n @property\n def version(self):\n msg='%200s has no version specified'%(type(self),)\n raise NotImplementedError(msg)\n \n def _check_int_address(self,address):\n if address <0:\n msg=\"%d (< 0) is not permitted as an IPv%d address\"\n raise AddressValueError(msg %(address,self._version))\n if address >self._ALL_ONES:\n msg=\"%d (>= 2**%d) is not permitted as an IPv%d address\"\n raise AddressValueError(msg %(address,self._max_prefixlen,\n self._version))\n \n def _check_packed_address(self,address,expected_len):\n address_len=len(address)\n if address_len !=expected_len:\n msg=\"%r (len %d != %d) is not permitted as an IPv%d address\"\n raise AddressValueError(msg %(address,address_len,\n expected_len,self._version))\n \n @classmethod\n def _ip_int_from_prefix(cls,prefixlen):\n ''\n\n\n\n\n\n\n\n \n return cls._ALL_ONES ^(cls._ALL_ONES >>prefixlen)\n \n @classmethod\n def _prefix_from_ip_int(cls,ip_int):\n ''\n\n\n\n\n\n\n\n\n\n \n trailing_zeroes=_count_righthand_zero_bits(ip_int,\n cls._max_prefixlen)\n prefixlen=cls._max_prefixlen -trailing_zeroes\n leading_ones=ip_int >>trailing_zeroes\n all_ones=(1 <1:\n return address\n return address[0],cls._max_prefixlen\n \n def __reduce__(self):\n return self.__class__,(str(self),)\n \n \n_address_fmt_re=None\n\n@functools.total_ordering\nclass _BaseAddress(_IPAddressBase):\n\n ''\n\n\n\n \n \n __slots__=()\n \n def __int__(self):\n return self._ip\n \n def __eq__(self,other):\n try:\n return(self._ip ==other._ip\n and self._version ==other._version)\n except AttributeError:\n return NotImplemented\n \n def __lt__(self,other):\n if not isinstance(other,_BaseAddress):\n return NotImplemented\n if self._version !=other._version:\n raise TypeError('%s and %s are not of the same version'%(\n self,other))\n if self._ip !=other._ip:\n return self._ip =0:\n if network+n >broadcast:\n raise IndexError('address out of range')\n return self._address_class(network+n)\n else:\n n +=1\n if broadcast+n other.network_address:\n return 1\n \n if self.netmask other.netmask:\n return 1\n return 0\n \n def _get_networks_key(self):\n ''\n\n\n\n\n\n \n return(self._version,self.network_address,self.netmask)\n \n def subnets(self,prefixlen_diff=1,new_prefix=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self._prefixlen ==self._max_prefixlen:\n yield self\n return\n \n if new_prefix is not None:\n if new_prefix 0')\n new_prefixlen=self._prefixlen+prefixlen_diff\n \n if new_prefixlen >self._max_prefixlen:\n raise ValueError(\n 'prefix length diff %d is invalid for netblock %s'%(\n new_prefixlen,self))\n \n start=int(self.network_address)\n end=int(self.broadcast_address)+1\n step=(int(self.hostmask)+1)>>prefixlen_diff\n for new_addr in range(start,end,step):\n current=self.__class__((new_addr,new_prefixlen))\n yield current\n \n def supernet(self,prefixlen_diff=1,new_prefix=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self._prefixlen ==0:\n return self\n \n if new_prefix is not None:\n if new_prefix >self._prefixlen:\n raise ValueError('new prefix must be shorter')\n if prefixlen_diff !=1:\n raise ValueError('cannot set prefixlen_diff and new_prefix')\n prefixlen_diff=self._prefixlen -new_prefix\n \n new_prefixlen=self.prefixlen -prefixlen_diff\n if new_prefixlen <0:\n raise ValueError(\n 'current prefixlen is %d, cannot have a prefixlen_diff of %d'%\n (self.prefixlen,prefixlen_diff))\n return self.__class__((\n int(self.network_address)&(int(self.netmask)<=a.broadcast_address)\n except AttributeError:\n raise TypeError(f\"Unable to test subnet containment \"\n f\"between {a} and {b}\")\n \n def subnet_of(self,other):\n ''\n return self._is_subnet_of(self,other)\n \n def supernet_of(self,other):\n ''\n return self._is_subnet_of(other,self)\n \n @property\n def is_reserved(self):\n ''\n\n\n\n\n\n \n return(self.network_address.is_reserved and\n self.broadcast_address.is_reserved)\n \n @property\n def is_link_local(self):\n ''\n\n\n\n\n \n return(self.network_address.is_link_local and\n self.broadcast_address.is_link_local)\n \n @property\n def is_private(self):\n ''\n\n\n\n\n\n \n return(self.network_address.is_private and\n self.broadcast_address.is_private)\n \n @property\n def is_global(self):\n ''\n\n\n\n\n\n \n return not self.is_private\n \n @property\n def is_unspecified(self):\n ''\n\n\n\n\n\n \n return(self.network_address.is_unspecified and\n self.broadcast_address.is_unspecified)\n \n @property\n def is_loopback(self):\n ''\n\n\n\n\n\n \n return(self.network_address.is_loopback and\n self.broadcast_address.is_loopback)\n \nclass _BaseV4:\n\n ''\n\n\n\n\n \n \n __slots__=()\n _version=4\n \n _ALL_ONES=(2 **IPV4LENGTH)-1\n \n _max_prefixlen=IPV4LENGTH\n \n \n _netmask_cache={}\n \n def _explode_shorthand_ip_string(self):\n return str(self)\n \n @classmethod\n def _make_netmask(cls,arg):\n ''\n\n\n\n\n\n \n if arg not in cls._netmask_cache:\n if isinstance(arg,int):\n prefixlen=arg\n if not(0 <=prefixlen <=cls._max_prefixlen):\n cls._report_invalid_netmask(prefixlen)\n else:\n try:\n \n prefixlen=cls._prefix_from_prefix_string(arg)\n except NetmaskValueError:\n \n \n prefixlen=cls._prefix_from_ip_string(arg)\n netmask=IPv4Address(cls._ip_int_from_prefix(prefixlen))\n cls._netmask_cache[arg]=netmask,prefixlen\n return cls._netmask_cache[arg]\n \n @classmethod\n def _ip_int_from_string(cls,ip_str):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not ip_str:\n raise AddressValueError('Address cannot be empty')\n \n octets=ip_str.split('.')\n if len(octets)!=4:\n raise AddressValueError(\"Expected 4 octets in %r\"%ip_str)\n \n try:\n return int.from_bytes(map(cls._parse_octet,octets),'big')\n except ValueError as exc:\n raise AddressValueError(\"%s in %r\"%(exc,ip_str))from None\n \n @classmethod\n def _parse_octet(cls,octet_str):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not octet_str:\n raise ValueError(\"Empty octet not permitted\")\n \n if not(octet_str.isascii()and octet_str.isdigit()):\n msg=\"Only decimal digits permitted in %r\"\n raise ValueError(msg %octet_str)\n \n \n if len(octet_str)>3:\n msg=\"At most 3 characters permitted in %r\"\n raise ValueError(msg %octet_str)\n \n \n if octet_str !='0'and octet_str[0]=='0':\n msg=\"Leading zeros are not permitted in %r\"\n raise ValueError(msg %octet_str)\n \n octet_int=int(octet_str,10)\n if octet_int >255:\n raise ValueError(\"Octet %d (> 255) not permitted\"%octet_int)\n return octet_int\n \n @classmethod\n def _string_from_ip_int(cls,ip_int):\n ''\n\n\n\n\n\n\n\n \n return '.'.join(map(str,ip_int.to_bytes(4,'big')))\n \n def _reverse_pointer(self):\n ''\n\n\n\n \n reverse_octets=str(self).split('.')[::-1]\n return '.'.join(reverse_octets)+'.in-addr.arpa'\n \n @property\n def max_prefixlen(self):\n return self._max_prefixlen\n \n @property\n def version(self):\n return self._version\n \n \nclass IPv4Address(_BaseV4,_BaseAddress):\n\n ''\n \n __slots__=('_ip','__weakref__')\n \n def __init__(self,address):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if isinstance(address,int):\n self._check_int_address(address)\n self._ip=address\n return\n \n \n if isinstance(address,bytes):\n self._check_packed_address(address,4)\n self._ip=int.from_bytes(address)\n return\n \n \n \n addr_str=str(address)\n if '/'in addr_str:\n raise AddressValueError(f\"Unexpected '/' in {address !r}\")\n self._ip=self._ip_int_from_string(addr_str)\n \n @property\n def packed(self):\n ''\n return v4_int_to_packed(self._ip)\n \n @property\n def is_reserved(self):\n ''\n\n\n\n\n\n \n return self in self._constants._reserved_network\n \n @property\n @functools.lru_cache()\n def is_private(self):\n ''\n\n\n\n\n\n \n return any(self in net for net in self._constants._private_networks)\n \n @property\n @functools.lru_cache()\n def is_global(self):\n return self not in self._constants._public_network and not self.is_private\n \n @property\n def is_multicast(self):\n ''\n\n\n\n\n\n \n return self in self._constants._multicast_network\n \n @property\n def is_unspecified(self):\n ''\n\n\n\n\n\n \n return self ==self._constants._unspecified_address\n \n @property\n def is_loopback(self):\n ''\n\n\n\n\n \n return self in self._constants._loopback_network\n \n @property\n def is_link_local(self):\n ''\n\n\n\n\n \n return self in self._constants._linklocal_network\n \n \nclass IPv4Interface(IPv4Address):\n\n def __init__(self,address):\n addr,mask=self._split_addr_prefix(address)\n \n IPv4Address.__init__(self,addr)\n self.network=IPv4Network((addr,mask),strict=False)\n self.netmask=self.network.netmask\n self._prefixlen=self.network._prefixlen\n \n @functools.cached_property\n def hostmask(self):\n return self.network.hostmask\n \n def __str__(self):\n return '%s/%d'%(self._string_from_ip_int(self._ip),\n self._prefixlen)\n \n def __eq__(self,other):\n address_equal=IPv4Address.__eq__(self,other)\n if address_equal is NotImplemented or not address_equal:\n return address_equal\n try:\n return self.network ==other.network\n except AttributeError:\n \n \n \n return False\n \n def __lt__(self,other):\n address_less=IPv4Address.__lt__(self,other)\n if address_less is NotImplemented:\n return NotImplemented\n try:\n return(self.network >16)&0xFFFF))\n parts.append('%x'%(ipv4_int&0xFFFF))\n \n \n \n \n _max_parts=cls._HEXTET_COUNT+1\n if len(parts)>_max_parts:\n msg=\"At most %d colons permitted in %r\"%(_max_parts -1,ip_str)\n raise AddressValueError(msg)\n \n \n \n skip_index=None\n for i in range(1,len(parts)-1):\n if not parts[i]:\n if skip_index is not None:\n \n msg=\"At most one '::' permitted in %r\"%ip_str\n raise AddressValueError(msg)\n skip_index=i\n \n \n \n if skip_index is not None:\n \n parts_hi=skip_index\n parts_lo=len(parts)-skip_index -1\n if not parts[0]:\n parts_hi -=1\n if parts_hi:\n msg=\"Leading ':' only permitted as part of '::' in %r\"\n raise AddressValueError(msg %ip_str)\n if not parts[-1]:\n parts_lo -=1\n if parts_lo:\n msg=\"Trailing ':' only permitted as part of '::' in %r\"\n raise AddressValueError(msg %ip_str)\n parts_skipped=cls._HEXTET_COUNT -(parts_hi+parts_lo)\n if parts_skipped <1:\n msg=\"Expected at most %d other parts with '::' in %r\"\n raise AddressValueError(msg %(cls._HEXTET_COUNT -1,ip_str))\n else:\n \n \n \n if len(parts)!=cls._HEXTET_COUNT:\n msg=\"Exactly %d parts expected without '::' in %r\"\n raise AddressValueError(msg %(cls._HEXTET_COUNT,ip_str))\n if not parts[0]:\n msg=\"Leading ':' only permitted as part of '::' in %r\"\n raise AddressValueError(msg %ip_str)\n if not parts[-1]:\n msg=\"Trailing ':' only permitted as part of '::' in %r\"\n raise AddressValueError(msg %ip_str)\n parts_hi=len(parts)\n parts_lo=0\n parts_skipped=0\n \n try:\n \n ip_int=0\n for i in range(parts_hi):\n ip_int <<=16\n ip_int |=cls._parse_hextet(parts[i])\n ip_int <<=16 *parts_skipped\n for i in range(-parts_lo,0):\n ip_int <<=16\n ip_int |=cls._parse_hextet(parts[i])\n return ip_int\n except ValueError as exc:\n raise AddressValueError(\"%s in %r\"%(exc,ip_str))from None\n \n @classmethod\n def _parse_hextet(cls,hextet_str):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not cls._HEX_DIGITS.issuperset(hextet_str):\n raise ValueError(\"Only hex digits permitted in %r\"%hextet_str)\n \n \n if len(hextet_str)>4:\n msg=\"At most 4 characters permitted in %r\"\n raise ValueError(msg %hextet_str)\n \n return int(hextet_str,16)\n \n @classmethod\n def _compress_hextets(cls,hextets):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n best_doublecolon_start=-1\n best_doublecolon_len=0\n doublecolon_start=-1\n doublecolon_len=0\n for index,hextet in enumerate(hextets):\n if hextet =='0':\n doublecolon_len +=1\n if doublecolon_start ==-1:\n \n doublecolon_start=index\n if doublecolon_len >best_doublecolon_len:\n \n best_doublecolon_len=doublecolon_len\n best_doublecolon_start=doublecolon_start\n else:\n doublecolon_len=0\n doublecolon_start=-1\n \n if best_doublecolon_len >1:\n best_doublecolon_end=(best_doublecolon_start+\n best_doublecolon_len)\n \n if best_doublecolon_end ==len(hextets):\n hextets +=['']\n hextets[best_doublecolon_start:best_doublecolon_end]=['']\n \n if best_doublecolon_start ==0:\n hextets=['']+hextets\n \n return hextets\n \n @classmethod\n def _string_from_ip_int(cls,ip_int=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if ip_int is None:\n ip_int=int(cls._ip)\n \n if ip_int >cls._ALL_ONES:\n raise ValueError('IPv6 address is too large')\n \n hex_str='%032x'%ip_int\n hextets=['%x'%int(hex_str[x:x+4],16)for x in range(0,32,4)]\n \n hextets=cls._compress_hextets(hextets)\n return ':'.join(hextets)\n \n def _explode_shorthand_ip_string(self):\n ''\n\n\n\n\n\n\n\n \n if isinstance(self,IPv6Network):\n ip_str=str(self.network_address)\n elif isinstance(self,IPv6Interface):\n ip_str=str(self.ip)\n else:\n ip_str=str(self)\n \n ip_int=self._ip_int_from_string(ip_str)\n hex_str='%032x'%ip_int\n parts=[hex_str[x:x+4]for x in range(0,32,4)]\n if isinstance(self,(_BaseNetwork,IPv6Interface)):\n return '%s/%d'%(':'.join(parts),self._prefixlen)\n return ':'.join(parts)\n \n def _reverse_pointer(self):\n ''\n\n\n\n \n reverse_chars=self.exploded[::-1].replace(':','')\n return '.'.join(reverse_chars)+'.ip6.arpa'\n \n @staticmethod\n def _split_scope_id(ip_str):\n ''\n\n\n\n\n\n\n\n\n\n \n addr,sep,scope_id=ip_str.partition('%')\n if not sep:\n scope_id=None\n elif not scope_id or '%'in scope_id:\n raise AddressValueError('Invalid IPv6 address: \"%r\"'%ip_str)\n return addr,scope_id\n \n @property\n def max_prefixlen(self):\n return self._max_prefixlen\n \n @property\n def version(self):\n return self._version\n \n \nclass IPv6Address(_BaseV6,_BaseAddress):\n\n ''\n \n __slots__=('_ip','_scope_id','__weakref__')\n \n def __init__(self,address):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if isinstance(address,int):\n self._check_int_address(address)\n self._ip=address\n self._scope_id=None\n return\n \n \n if isinstance(address,bytes):\n self._check_packed_address(address,16)\n self._ip=int.from_bytes(address,'big')\n self._scope_id=None\n return\n \n \n \n addr_str=str(address)\n if '/'in addr_str:\n raise AddressValueError(f\"Unexpected '/' in {address !r}\")\n addr_str,self._scope_id=self._split_scope_id(addr_str)\n \n self._ip=self._ip_int_from_string(addr_str)\n \n def __str__(self):\n ip_str=super().__str__()\n return ip_str+'%'+self._scope_id if self._scope_id else ip_str\n \n def __hash__(self):\n return hash((self._ip,self._scope_id))\n \n def __eq__(self,other):\n address_equal=super().__eq__(other)\n if address_equal is NotImplemented:\n return NotImplemented\n if not address_equal:\n return False\n return self._scope_id ==getattr(other,'_scope_id',None)\n \n @property\n def scope_id(self):\n ''\n\n\n\n\n\n\n \n return self._scope_id\n \n @property\n def packed(self):\n ''\n return v6_int_to_packed(self._ip)\n \n @property\n def is_multicast(self):\n ''\n\n\n\n\n\n \n return self in self._constants._multicast_network\n \n @property\n def is_reserved(self):\n ''\n\n\n\n\n\n \n return any(self in x for x in self._constants._reserved_networks)\n \n @property\n def is_link_local(self):\n ''\n\n\n\n\n \n return self in self._constants._linklocal_network\n \n @property\n def is_site_local(self):\n ''\n\n\n\n\n\n\n\n\n \n return self in self._constants._sitelocal_network\n \n @property\n @functools.lru_cache()\n def is_private(self):\n ''\n\n\n\n\n\n\n \n ipv4_mapped=self.ipv4_mapped\n if ipv4_mapped is not None:\n return ipv4_mapped.is_private\n return any(self in net for net in self._constants._private_networks)\n \n @property\n def is_global(self):\n ''\n\n\n\n\n\n \n return not self.is_private\n \n @property\n def is_unspecified(self):\n ''\n\n\n\n\n\n \n return self._ip ==0\n \n @property\n def is_loopback(self):\n ''\n\n\n\n\n\n \n return self._ip ==1\n \n @property\n def ipv4_mapped(self):\n ''\n\n\n\n\n\n \n if(self._ip >>32)!=0xFFFF:\n return None\n return IPv4Address(self._ip&0xFFFFFFFF)\n \n @property\n def teredo(self):\n ''\n\n\n\n\n\n\n \n if(self._ip >>96)!=0x20010000:\n return None\n return(IPv4Address((self._ip >>64)&0xFFFFFFFF),\n IPv4Address(~self._ip&0xFFFFFFFF))\n \n @property\n def sixtofour(self):\n ''\n\n\n\n\n\n \n if(self._ip >>112)!=0x2002:\n return None\n return IPv4Address((self._ip >>80)&0xFFFFFFFF)\n \n \nclass IPv6Interface(IPv6Address):\n\n def __init__(self,address):\n addr,mask=self._split_addr_prefix(address)\n \n IPv6Address.__init__(self,addr)\n self.network=IPv6Network((addr,mask),strict=False)\n self.netmask=self.network.netmask\n self._prefixlen=self.network._prefixlen\n \n @functools.cached_property\n def hostmask(self):\n return self.network.hostmask\n \n def __str__(self):\n return '%s/%d'%(super().__str__(),\n self._prefixlen)\n \n def __eq__(self,other):\n address_equal=IPv6Address.__eq__(self,other)\n if address_equal is NotImplemented or not address_equal:\n return address_equal\n try:\n return self.network ==other.network\n except AttributeError:\n \n \n \n return False\n \n def __lt__(self,other):\n address_less=IPv6Address.__lt__(self,other)\n if address_less is NotImplemented:\n return address_less\n try:\n return(self.network self.n:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in self.indices)\n else:\n try:\n for i in reversed(range(self.r)):\n if self.indices[i]!=i+self.n -self.r:\n break\n self.indices[i]+=1\n for j in range(i+1,self.r):\n self.indices[j]=self.indices[j -1]+1\n return tuple(self.pool[i]for i in self.indices)\n except:\n raise StopIteration\n \nclass combinations_with_replacement:\n def __init__(self,iterable,r):\n self.pool=tuple(iterable)\n self.n=len(self.pool)\n self.r=r\n self.indices=[0]*self.r\n self.zero=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if not self.n and self.r:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in self.indices)\n else:\n try:\n for i in reversed(range(self.r)):\n if self.indices[i]!=self.n -1:\n break\n self.indices[i:]=[self.indices[i]+1]*(self.r -i)\n return tuple(self.pool[i]for i in self.indices)\n except:\n raise StopIteration\n \n \n \nclass compress:\n def __init__(self,data,selectors):\n self.data=iter(data)\n self.selectors=iter(selectors)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n while True:\n next_item=next(self.data)\n next_selector=next(self.selectors)\n if bool(next_selector):\n return next_item\n \n \n \n \nclass count:\n ''\n\n\n\n \n def __init__(self,start=0,step=1):\n if not isinstance(start,(int,float)):\n raise TypeError('a number is required')\n self.times=start -step\n self.step=step\n \n def __iter__(self):\n return self\n \n def __next__(self):\n self.times +=self.step\n return self.times\n \n def __repr__(self):\n return 'count(%d)'%(self.times+self.step)\n \n \n \nclass cycle:\n def __init__(self,iterable):\n self._cur_iter=iter(iterable)\n self._saved=[]\n self._must_save=True\n \n def __iter__(self):\n return self\n \n def __next__(self):\n try:\n next_elt=next(self._cur_iter)\n if self._must_save:\n self._saved.append(next_elt)\n except StopIteration:\n self._cur_iter=iter(self._saved)\n next_elt=next(self._cur_iter)\n self._must_save=False\n return next_elt\n \n \n \nclass dropwhile:\n def __init__(self,predicate,iterable):\n self._predicate=predicate\n self._iter=iter(iterable)\n self._dropped=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n value=next(self._iter)\n if self._dropped:\n return value\n while self._predicate(value):\n value=next(self._iter)\n self._dropped=True\n return value\n \n \n \nclass filterfalse:\n def __init__(self,predicate,iterable):\n \n self._iter=iter(iterable)\n if predicate is None:\n self._predicate=bool\n else:\n self._predicate=predicate\n \n def __iter__(self):\n return self\n def __next__(self):\n next_elt=next(self._iter)\n while True:\n if not self._predicate(next_elt):\n return next_elt\n next_elt=next(self._iter)\n \nclass groupby:\n\n\n def __init__(self,iterable,key=None):\n if key is None:\n key=lambda x:x\n self.keyfunc=key\n self.it=iter(iterable)\n self.tgtkey=self.currkey=self.currvalue=object()\n def __iter__(self):\n return self\n def __next__(self):\n while self.currkey ==self.tgtkey:\n self.currvalue=next(self.it)\n self.currkey=self.keyfunc(self.currvalue)\n self.tgtkey=self.currkey\n return(self.currkey,self._grouper(self.tgtkey))\n def _grouper(self,tgtkey):\n while self.currkey ==tgtkey:\n yield self.currvalue\n self.currvalue=next(self.it)\n self.currkey=self.keyfunc(self.currvalue)\n \n \n \nclass islice:\n def __init__(self,iterable,*args):\n s=slice(*args)\n self.start,self.stop,self.step=s.start or 0,s.stop,s.step\n if not isinstance(self.start,int):\n raise ValueError(\"Start argument must be an integer\")\n if self.stop !=None and not isinstance(self.stop,int):\n raise ValueError(\"Stop argument must be an integer or None\")\n if self.step is None:\n self.step=1\n if self.start <0 or(self.stop !=None and self.stop <0\n )or self.step <=0:\n raise ValueError(\"indices for islice() must be positive\")\n self.it=iter(iterable)\n self.donext=None\n self.cnt=0\n \n def __iter__(self):\n return self\n \n def __next__(self):\n nextindex=self.start\n if self.stop !=None and nextindex >=self.stop:\n raise StopIteration\n while self.cnt <=nextindex:\n nextitem=next(self.it)\n self.cnt +=1\n self.start +=self.step\n return nextitem\n \nclass permutations:\n def __init__(self,iterable,r=None):\n self.pool=tuple(iterable)\n self.n=len(self.pool)\n self.r=self.n if r is None else r\n self.indices=list(range(self.n))\n self.cycles=list(range(self.n,self.n -self.r,-1))\n self.zero=False\n self.stop=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n indices=self.indices\n if self.r >self.n:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in indices[:self.r])\n \n i=self.r -1\n while i >=0:\n j=self.cycles[i]-1\n if j >0:\n self.cycles[i]=j\n indices[i],indices[-j]=indices[-j],indices[i]\n return tuple(self.pool[i]for i in indices[:self.r])\n self.cycles[i]=len(indices)-i\n n1=len(indices)-1\n assert n1 >=0\n num=indices[i]\n for k in range(i,n1):\n indices[k]=indices[k+1]\n indices[n1]=num\n i -=1\n raise StopIteration\n \n \ndef product(*args,repeat=1):\n\n\n pools=[tuple(pool)for pool in args]*repeat\n result=[[]]\n for pool in pools:\n result=[x+[y]for x in result for y in pool]\n for prod in result:\n yield tuple(prod)\n \n \n \n \n \n \n \n \nclass _product:\n def __init__(self,*args,**kw):\n if len(kw)>1:\n raise TypeError(\"product() takes at most 1 argument (%d given)\"%\n len(kw))\n self.repeat=kw.get('repeat',1)\n if not isinstance(self.repeat,int):\n raise TypeError(\"integer argument expected, got %s\"%\n type(self.repeat))\n self.gears=[x for x in args]*self.repeat\n self.num_gears=len(self.gears)\n \n self.indicies=[(0,len(self.gears[x]))\n for x in range(0,self.num_gears)]\n self.cont=True\n self.zero=False\n \n def roll_gears(self):\n \n \n \n should_carry=True\n for n in range(0,self.num_gears):\n nth_gear=self.num_gears -n -1\n if should_carry:\n count,lim=self.indicies[nth_gear]\n count +=1\n if count ==lim and nth_gear ==0:\n self.cont=False\n if count ==lim:\n should_carry=True\n count=0\n else:\n should_carry=False\n self.indicies[nth_gear]=(count,lim)\n else:\n break\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if self.zero:\n raise StopIteration\n if self.repeat >0:\n if not self.cont:\n raise StopIteration\n l=[]\n for x in range(0,self.num_gears):\n index,limit=self.indicies[x]\n print('itertools 353',self.gears,x,index)\n l.append(self.gears[x][index])\n self.roll_gears()\n return tuple(l)\n elif self.repeat ==0:\n self.zero=True\n return()\n else:\n raise ValueError(\"repeat argument cannot be negative\")\n \n \n \nclass repeat:\n def __init__(self,obj,times=None):\n self._obj=obj\n if times is not None:\n range(times)\n if times <0:\n times=0\n self._times=times\n \n def __iter__(self):\n return self\n \n def __next__(self):\n \n if self._times is not None:\n if self._times <=0:\n raise StopIteration()\n self._times -=1\n return self._obj\n \n def __repr__(self):\n if self._times is not None:\n return 'repeat(%r, %r)'%(self._obj,self._times)\n else:\n return 'repeat(%r)'%(self._obj,)\n \n def __len__(self):\n if self._times ==-1 or self._times is None:\n raise TypeError(\"len() of uniszed object\")\n return self._times\n \n \n \nclass starmap(object):\n def __init__(self,function,iterable):\n self._func=function\n self._iter=iter(iterable)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n t=next(self._iter)\n return self._func(*t)\n \n \n \nclass takewhile(object):\n def __init__(self,predicate,iterable):\n self._predicate=predicate\n self._iter=iter(iterable)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n value=next(self._iter)\n if not self._predicate(value):\n raise StopIteration()\n return value\n \n \n \nclass TeeData(object):\n def __init__(self,iterator):\n self.data=[]\n self._iter=iterator\n \n def __getitem__(self,i):\n \n while i >=len(self.data):\n self.data.append(next(self._iter))\n return self.data[i]\n \n \nclass TeeObject(object):\n def __init__(self,iterable=None,tee_data=None):\n if tee_data:\n self.tee_data=tee_data\n self.pos=0\n \n elif isinstance(iterable,TeeObject):\n self.tee_data=iterable.tee_data\n self.pos=iterable.pos\n else:\n self.tee_data=TeeData(iter(iterable))\n self.pos=0\n \n def __next__(self):\n data=self.tee_data[self.pos]\n self.pos +=1\n return data\n \n def __iter__(self):\n return self\n \n \ndef tee(iterable,n=2):\n if isinstance(iterable,TeeObject):\n return tuple([iterable]+\n [TeeObject(tee_data=iterable.tee_data)for i in range(n -1)])\n tee_data=TeeData(iter(iterable))\n return tuple([TeeObject(tee_data=tee_data)for i in range(n)])\n \nclass zip_longest:\n def __init__(self,*args,fillvalue=None):\n self.args=[iter(arg)for arg in args]\n self.fillvalue=fillvalue\n self.units=len(args)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n temp=[]\n nb=0\n for i in range(self.units):\n try:\n temp.append(next(self.args[i]))\n nb +=1\n except StopIteration:\n temp.append(self.fillvalue)\n if nb ==0:\n raise StopIteration\n return tuple(temp)\n", ["operator"]], "keyword": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\"iskeyword\",\"issoftkeyword\",\"kwlist\",\"softkwlist\"]\n\nkwlist=[\n'False',\n'None',\n'True',\n'and',\n'as',\n'assert',\n'async',\n'await',\n'break',\n'class',\n'continue',\n'def',\n'del',\n'elif',\n'else',\n'except',\n'finally',\n'for',\n'from',\n'global',\n'if',\n'import',\n'in',\n'is',\n'lambda',\n'nonlocal',\n'not',\n'or',\n'pass',\n'raise',\n'return',\n'try',\n'while',\n'with',\n'yield'\n]\n\nsoftkwlist=[\n'_',\n'case',\n'match',\n'type'\n]\n\niskeyword=frozenset(kwlist).__contains__\nissoftkeyword=frozenset(softkwlist).__contains__\n", []], "linecache": [".py", "''\n\n\n\n\n\n\n__all__=[\"getline\",\"clearcache\",\"checkcache\",\"lazycache\"]\n\n\n\n\ncache={}\n\n\ndef clearcache():\n ''\n cache.clear()\n \n \ndef getline(filename,lineno,module_globals=None):\n ''\n \n \n lines=getlines(filename,module_globals)\n if 1 <=lineno <=len(lines):\n return lines[lineno -1]\n return ''\n \n \ndef getlines(filename,module_globals=None):\n ''\n \n \n if filename in cache:\n entry=cache[filename]\n if len(entry)!=1:\n return cache[filename][2]\n \n try:\n return updatecache(filename,module_globals)\n except MemoryError:\n clearcache()\n return[]\n \n \ndef checkcache(filename=None):\n ''\n \n \n if filename is None:\n filenames=list(cache.keys())\n elif filename in cache:\n filenames=[filename]\n else:\n return\n \n for filename in filenames:\n entry=cache[filename]\n if len(entry)==1:\n \n continue\n size,mtime,lines,fullname=entry\n if mtime is None:\n continue\n try:\n \n import os\n except ImportError:\n return\n try:\n stat=os.stat(fullname)\n except OSError:\n cache.pop(filename,None)\n continue\n if size !=stat.st_size or mtime !=stat.st_mtime:\n cache.pop(filename,None)\n \n \ndef updatecache(filename,module_globals=None):\n ''\n\n \n \n \n \n \n import os\n import sys\n import tokenize\n \n if filename in cache:\n if len(cache[filename])!=1:\n cache.pop(filename,None)\n if not filename or(filename.startswith('<')and filename.endswith('>')):\n return[]\n \n fullname=filename\n try:\n stat=os.stat(fullname)\n except OSError:\n basename=filename\n \n \n \n if lazycache(filename,module_globals):\n try:\n data=cache[filename][0]()\n except(ImportError,OSError):\n pass\n else:\n if data is None:\n \n \n return[]\n cache[filename]=(\n len(data),\n None,\n [line+'\\n'for line in data.splitlines()],\n fullname\n )\n return cache[filename][2]\n \n \n \n if os.path.isabs(filename):\n return[]\n \n for dirname in sys.path:\n try:\n fullname=os.path.join(dirname,basename)\n except(TypeError,AttributeError):\n \n continue\n try:\n stat=os.stat(fullname)\n break\n except OSError:\n pass\n else:\n return[]\n try:\n with tokenize.open(fullname)as fp:\n lines=fp.readlines()\n except(OSError,UnicodeDecodeError,SyntaxError):\n return[]\n if not lines:\n lines=['\\n']\n elif not lines[-1].endswith('\\n'):\n lines[-1]+='\\n'\n size,mtime=stat.st_size,stat.st_mtime\n cache[filename]=size,mtime,lines,fullname\n return lines\n \n \ndef lazycache(filename,module_globals):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if filename in cache:\n if len(cache[filename])==1:\n return True\n else:\n return False\n if not filename or(filename.startswith('<')and filename.endswith('>')):\n return False\n \n if module_globals and '__name__'in module_globals:\n spec=module_globals.get('__spec__')\n name=getattr(spec,'name',None)or module_globals['__name__']\n loader=getattr(spec,'loader',None)\n if loader is None:\n loader=module_globals.get('__loader__')\n get_source=getattr(loader,'get_source',None)\n \n if name and get_source:\n def get_lines(name=name,*args,**kwargs):\n return get_source(name,*args,**kwargs)\n cache[filename]=(get_lines,)\n return True\n return False\n \n \ndef _register_code(code,string,name):\n cache[code]=(\n len(string),\n None,\n [line+'\\n'for line in string.splitlines()],\n name)\n", ["os", "sys", "tokenize"]], "locale": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport encodings\nimport encodings.aliases\nimport re\nimport _collections_abc\nfrom builtins import str as _builtin_str\nimport functools\n\n\n\n\n\n\n\n__all__=[\"getlocale\",\"getdefaultlocale\",\"getpreferredencoding\",\"Error\",\n\"setlocale\",\"localeconv\",\"strcoll\",\"strxfrm\",\n\"str\",\"atof\",\"atoi\",\"format_string\",\"currency\",\n\"normalize\",\"LC_CTYPE\",\"LC_COLLATE\",\"LC_TIME\",\"LC_MONETARY\",\n\"LC_NUMERIC\",\"LC_ALL\",\"CHAR_MAX\",\"getencoding\"]\n\ndef _strcoll(a,b):\n ''\n\n \n return(a >b)-(a .*?)\\))?'\nr'(?P[-#0-9 +*.hlL]*?)[eEfFgGdiouxXcrs%]')\n\ndef _format(percent,value,grouping=False,monetary=False,*additional):\n if additional:\n formatted=percent %((value,)+additional)\n else:\n formatted=percent %value\n if percent[-1]in 'eEfFgGdiu':\n formatted=_localize(formatted,grouping,monetary)\n return formatted\n \n \ndef _localize(formatted,grouping=False,monetary=False):\n\n if '.'in formatted:\n seps=0\n parts=formatted.split('.')\n if grouping:\n parts[0],seps=_group(parts[0],monetary=monetary)\n decimal_point=localeconv()[monetary and 'mon_decimal_point'\n or 'decimal_point']\n formatted=decimal_point.join(parts)\n if seps:\n formatted=_strip_padding(formatted,seps)\n else:\n seps=0\n if grouping:\n formatted,seps=_group(formatted,monetary=monetary)\n if seps:\n formatted=_strip_padding(formatted,seps)\n return formatted\n \ndef format_string(f,val,grouping=False,monetary=False):\n ''\n\n\n\n\n \n percents=list(_percent_re.finditer(f))\n new_f=_percent_re.sub('%s',f)\n \n if isinstance(val,_collections_abc.Mapping):\n new_val=[]\n for perc in percents:\n if perc.group()[-1]=='%':\n new_val.append('%')\n else:\n new_val.append(_format(perc.group(),val,grouping,monetary))\n else:\n if not isinstance(val,tuple):\n val=(val,)\n new_val=[]\n i=0\n for perc in percents:\n if perc.group()[-1]=='%':\n new_val.append('%')\n else:\n starcount=perc.group('modifiers').count('*')\n new_val.append(_format(perc.group(),\n val[i],\n grouping,\n monetary,\n *val[i+1:i+1+starcount]))\n i +=(1+starcount)\n val=tuple(new_val)\n \n return new_f %val\n \ndef currency(val,symbol=True,grouping=False,international=False):\n ''\n \n conv=localeconv()\n \n \n digits=conv[international and 'int_frac_digits'or 'frac_digits']\n if digits ==127:\n raise ValueError(\"Currency formatting is not possible using \"\n \"the 'C' locale.\")\n \n s=_localize(f'{abs(val):.{digits}f}',grouping,monetary=True)\n \n s='<'+s+'>'\n \n if symbol:\n smb=conv[international and 'int_curr_symbol'or 'currency_symbol']\n precedes=conv[val <0 and 'n_cs_precedes'or 'p_cs_precedes']\n separated=conv[val <0 and 'n_sep_by_space'or 'p_sep_by_space']\n \n if precedes:\n s=smb+(separated and ' 'or '')+s\n else:\n if international and smb[-1]==' ':\n smb=smb[:-1]\n s=s+(separated and ' 'or '')+smb\n \n sign_pos=conv[val <0 and 'n_sign_posn'or 'p_sign_posn']\n sign=conv[val <0 and 'negative_sign'or 'positive_sign']\n \n if sign_pos ==0:\n s='('+s+')'\n elif sign_pos ==1:\n s=sign+s\n elif sign_pos ==2:\n s=s+sign\n elif sign_pos ==3:\n s=s.replace('<',sign)\n elif sign_pos ==4:\n s=s.replace('>',sign)\n else:\n \n \n s=sign+s\n \n return s.replace('<','').replace('>','')\n \ndef str(val):\n ''\n return _format(\"%.12g\",val)\n \ndef delocalize(string):\n ''\n \n conv=localeconv()\n \n \n ts=conv['thousands_sep']\n if ts:\n string=string.replace(ts,'')\n \n \n dd=conv['decimal_point']\n if dd:\n string=string.replace(dd,'.')\n return string\n \ndef localize(string,grouping=False,monetary=False):\n ''\n return _localize(string,grouping,monetary)\n \ndef atof(string,func=float):\n ''\n return func(delocalize(string))\n \ndef atoi(string):\n ''\n return int(delocalize(string))\n \ndef _test():\n setlocale(LC_ALL,\"\")\n \n s1=format_string(\"%d\",123456789,1)\n print(s1,\"is\",atoi(s1))\n \n s1=str(3.14)\n print(s1,\"is\",atof(s1))\n \n \n \n \n \n \n \n \n_setlocale=setlocale\n\ndef _replace_encoding(code,encoding):\n if '.'in code:\n langname=code[:code.index('.')]\n else:\n langname=code\n \n norm_encoding=encodings.normalize_encoding(encoding)\n \n norm_encoding=encodings.aliases.aliases.get(norm_encoding.lower(),\n norm_encoding)\n \n encoding=norm_encoding\n norm_encoding=norm_encoding.lower()\n if norm_encoding in locale_encoding_alias:\n encoding=locale_encoding_alias[norm_encoding]\n else:\n norm_encoding=norm_encoding.replace('_','')\n norm_encoding=norm_encoding.replace('-','')\n if norm_encoding in locale_encoding_alias:\n encoding=locale_encoding_alias[norm_encoding]\n \n return langname+'.'+encoding\n \ndef _append_modifier(code,modifier):\n if modifier =='euro':\n if '.'not in code:\n return code+'.ISO8859-15'\n _,_,encoding=code.partition('.')\n if encoding in('ISO8859-15','UTF-8'):\n return code\n if encoding =='ISO8859-1':\n return _replace_encoding(code,'ISO8859-15')\n return code+'@'+modifier\n \ndef normalize(localename):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n code=localename.lower()\n if ':'in code:\n \n code=code.replace(':','.')\n if '@'in code:\n code,modifier=code.split('@',1)\n else:\n modifier=''\n if '.'in code:\n langname,encoding=code.split('.')[:2]\n else:\n langname=code\n encoding=''\n \n \n lang_enc=langname\n if encoding:\n norm_encoding=encoding.replace('-','')\n norm_encoding=norm_encoding.replace('_','')\n lang_enc +='.'+norm_encoding\n lookup_name=lang_enc\n if modifier:\n lookup_name +='@'+modifier\n code=locale_alias.get(lookup_name,None)\n if code is not None:\n return code\n \n \n if modifier:\n \n code=locale_alias.get(lang_enc,None)\n if code is not None:\n \n if '@'not in code:\n return _append_modifier(code,modifier)\n if code.split('@',1)[1].lower()==modifier:\n return code\n \n \n if encoding:\n \n lookup_name=langname\n if modifier:\n lookup_name +='@'+modifier\n code=locale_alias.get(lookup_name,None)\n if code is not None:\n \n if '@'not in code:\n return _replace_encoding(code,encoding)\n code,modifier=code.split('@',1)\n return _replace_encoding(code,encoding)+'@'+modifier\n \n if modifier:\n \n code=locale_alias.get(langname,None)\n if code is not None:\n \n if '@'not in code:\n code=_replace_encoding(code,encoding)\n return _append_modifier(code,modifier)\n code,defmod=code.split('@',1)\n if defmod.lower()==modifier:\n return _replace_encoding(code,encoding)+'@'+defmod\n \n return localename\n \ndef _parse_localename(localename):\n\n ''\n\n\n\n\n\n\n\n\n\n\n \n code=normalize(localename)\n if '@'in code:\n \n code,modifier=code.split('@',1)\n if modifier =='euro'and '.'not in code:\n \n \n \n return code,'iso-8859-15'\n \n if '.'in code:\n return tuple(code.split('.')[:2])\n elif code =='C':\n return None,None\n elif code =='UTF-8':\n \n \n return None,'UTF-8'\n raise ValueError('unknown locale: %s'%localename)\n \ndef _build_localename(localetuple):\n\n ''\n\n\n\n\n \n try:\n language,encoding=localetuple\n \n if language is None:\n language='C'\n if encoding is None:\n return language\n else:\n return language+'.'+encoding\n except(TypeError,ValueError):\n raise TypeError('Locale must be None, a string, or an iterable of '\n 'two strings -- language code, encoding.')from None\n \ndef getdefaultlocale(envvars=('LC_ALL','LC_CTYPE','LANG','LANGUAGE')):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n import warnings\n warnings._deprecated(\n \"locale.getdefaultlocale\",\n \"{name!r} is deprecated and slated for removal in Python {remove}. \"\n \"Use setlocale(), getencoding() and getlocale() instead.\",\n remove=(3,15))\n return _getdefaultlocale(envvars)\n \n \ndef _getdefaultlocale(envvars=('LC_ALL','LC_CTYPE','LANG','LANGUAGE')):\n try:\n \n import _locale\n code,encoding=_locale._getdefaultlocale()\n except(ImportError,AttributeError):\n pass\n else:\n \n if sys.platform ==\"win32\"and code and code[:2]==\"0x\":\n \n code=windows_locale.get(int(code,0))\n \n \n return code,encoding\n \n \n import os\n lookup=os.environ.get\n for variable in envvars:\n localename=lookup(variable,None)\n if localename:\n if variable =='LANGUAGE':\n localename=localename.split(':')[0]\n break\n else:\n localename='C'\n return _parse_localename(localename)\n \n \ndef getlocale(category=LC_CTYPE):\n\n ''\n\n\n\n\n\n\n\n\n\n \n localename=_setlocale(category)\n if category ==LC_ALL and ';'in localename:\n raise TypeError('category LC_ALL is not supported')\n return _parse_localename(localename)\n \ndef setlocale(category,locale=None):\n\n ''\n\n\n\n\n\n\n\n\n \n if locale and not isinstance(locale,_builtin_str):\n \n locale=normalize(_build_localename(locale))\n return _setlocale(category,locale)\n \n \ntry:\n from _locale import getencoding\nexcept ImportError:\n\n\n def getencoding():\n return sys.getfilesystemencoding()\n \n \ntry:\n CODESET\nexcept NameError:\n def getpreferredencoding(do_setlocale=True):\n ''\n if sys.flags.warn_default_encoding:\n import warnings\n warnings.warn(\n \"UTF-8 Mode affects locale.getpreferredencoding(). Consider locale.getencoding() instead.\",\n EncodingWarning,2)\n if sys.flags.utf8_mode:\n return 'utf-8'\n return getencoding()\nelse:\n\n def getpreferredencoding(do_setlocale=True):\n ''\n \n \n if sys.flags.warn_default_encoding:\n import warnings\n warnings.warn(\n \"UTF-8 Mode affects locale.getpreferredencoding(). Consider locale.getencoding() instead.\",\n EncodingWarning,2)\n if sys.flags.utf8_mode:\n return 'utf-8'\n \n if not do_setlocale:\n return getencoding()\n \n old_loc=setlocale(LC_CTYPE)\n try:\n try:\n setlocale(LC_CTYPE,\"\")\n except Error:\n pass\n return getencoding()\n finally:\n setlocale(LC_CTYPE,old_loc)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nlocale_encoding_alias={\n\n\n'437':'C',\n'c':'C',\n'en':'ISO8859-1',\n'jis':'JIS7',\n'jis7':'JIS7',\n'ajec':'eucJP',\n'koi8c':'KOI8-C',\n'microsoftcp1251':'CP1251',\n'microsoftcp1255':'CP1255',\n'microsoftcp1256':'CP1256',\n'88591':'ISO8859-1',\n'88592':'ISO8859-2',\n'88595':'ISO8859-5',\n'885915':'ISO8859-15',\n\n\n'ascii':'ISO8859-1',\n'latin_1':'ISO8859-1',\n'iso8859_1':'ISO8859-1',\n'iso8859_10':'ISO8859-10',\n'iso8859_11':'ISO8859-11',\n'iso8859_13':'ISO8859-13',\n'iso8859_14':'ISO8859-14',\n'iso8859_15':'ISO8859-15',\n'iso8859_16':'ISO8859-16',\n'iso8859_2':'ISO8859-2',\n'iso8859_3':'ISO8859-3',\n'iso8859_4':'ISO8859-4',\n'iso8859_5':'ISO8859-5',\n'iso8859_6':'ISO8859-6',\n'iso8859_7':'ISO8859-7',\n'iso8859_8':'ISO8859-8',\n'iso8859_9':'ISO8859-9',\n'iso2022_jp':'JIS7',\n'shift_jis':'SJIS',\n'tactis':'TACTIS',\n'euc_jp':'eucJP',\n'euc_kr':'eucKR',\n'utf_8':'UTF-8',\n'koi8_r':'KOI8-R',\n'koi8_t':'KOI8-T',\n'koi8_u':'KOI8-U',\n'kz1048':'RK1048',\n'cp1251':'CP1251',\n'cp1255':'CP1255',\n'cp1256':'CP1256',\n\n\n\n}\n\nfor k,v in sorted(locale_encoding_alias.items()):\n k=k.replace('_','')\n locale_encoding_alias.setdefault(k,v)\ndel k,v\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nlocale_alias={\n'a3':'az_AZ.KOI8-C',\n'a3_az':'az_AZ.KOI8-C',\n'a3_az.koic':'az_AZ.KOI8-C',\n'aa_dj':'aa_DJ.ISO8859-1',\n'aa_er':'aa_ER.UTF-8',\n'aa_et':'aa_ET.UTF-8',\n'af':'af_ZA.ISO8859-1',\n'af_za':'af_ZA.ISO8859-1',\n'agr_pe':'agr_PE.UTF-8',\n'ak_gh':'ak_GH.UTF-8',\n'am':'am_ET.UTF-8',\n'am_et':'am_ET.UTF-8',\n'american':'en_US.ISO8859-1',\n'an_es':'an_ES.ISO8859-15',\n'anp_in':'anp_IN.UTF-8',\n'ar':'ar_AA.ISO8859-6',\n'ar_aa':'ar_AA.ISO8859-6',\n'ar_ae':'ar_AE.ISO8859-6',\n'ar_bh':'ar_BH.ISO8859-6',\n'ar_dz':'ar_DZ.ISO8859-6',\n'ar_eg':'ar_EG.ISO8859-6',\n'ar_in':'ar_IN.UTF-8',\n'ar_iq':'ar_IQ.ISO8859-6',\n'ar_jo':'ar_JO.ISO8859-6',\n'ar_kw':'ar_KW.ISO8859-6',\n'ar_lb':'ar_LB.ISO8859-6',\n'ar_ly':'ar_LY.ISO8859-6',\n'ar_ma':'ar_MA.ISO8859-6',\n'ar_om':'ar_OM.ISO8859-6',\n'ar_qa':'ar_QA.ISO8859-6',\n'ar_sa':'ar_SA.ISO8859-6',\n'ar_sd':'ar_SD.ISO8859-6',\n'ar_ss':'ar_SS.UTF-8',\n'ar_sy':'ar_SY.ISO8859-6',\n'ar_tn':'ar_TN.ISO8859-6',\n'ar_ye':'ar_YE.ISO8859-6',\n'arabic':'ar_AA.ISO8859-6',\n'as':'as_IN.UTF-8',\n'as_in':'as_IN.UTF-8',\n'ast_es':'ast_ES.ISO8859-15',\n'ayc_pe':'ayc_PE.UTF-8',\n'az':'az_AZ.ISO8859-9E',\n'az_az':'az_AZ.ISO8859-9E',\n'az_az.iso88599e':'az_AZ.ISO8859-9E',\n'az_ir':'az_IR.UTF-8',\n'be':'be_BY.CP1251',\n'be@latin':'be_BY.UTF-8@latin',\n'be_bg.utf8':'bg_BG.UTF-8',\n'be_by':'be_BY.CP1251',\n'be_by@latin':'be_BY.UTF-8@latin',\n'bem_zm':'bem_ZM.UTF-8',\n'ber_dz':'ber_DZ.UTF-8',\n'ber_ma':'ber_MA.UTF-8',\n'bg':'bg_BG.CP1251',\n'bg_bg':'bg_BG.CP1251',\n'bhb_in.utf8':'bhb_IN.UTF-8',\n'bho_in':'bho_IN.UTF-8',\n'bho_np':'bho_NP.UTF-8',\n'bi_vu':'bi_VU.UTF-8',\n'bn_bd':'bn_BD.UTF-8',\n'bn_in':'bn_IN.UTF-8',\n'bo_cn':'bo_CN.UTF-8',\n'bo_in':'bo_IN.UTF-8',\n'bokmal':'nb_NO.ISO8859-1',\n'bokm\\xe5l':'nb_NO.ISO8859-1',\n'br':'br_FR.ISO8859-1',\n'br_fr':'br_FR.ISO8859-1',\n'brx_in':'brx_IN.UTF-8',\n'bs':'bs_BA.ISO8859-2',\n'bs_ba':'bs_BA.ISO8859-2',\n'bulgarian':'bg_BG.CP1251',\n'byn_er':'byn_ER.UTF-8',\n'c':'C',\n'c-french':'fr_CA.ISO8859-1',\n'c.ascii':'C',\n'c.en':'C',\n'c.iso88591':'en_US.ISO8859-1',\n'c.utf8':'C.UTF-8',\n'c_c':'C',\n'c_c.c':'C',\n'ca':'ca_ES.ISO8859-1',\n'ca_ad':'ca_AD.ISO8859-1',\n'ca_es':'ca_ES.ISO8859-1',\n'ca_es@valencia':'ca_ES.UTF-8@valencia',\n'ca_fr':'ca_FR.ISO8859-1',\n'ca_it':'ca_IT.ISO8859-1',\n'catalan':'ca_ES.ISO8859-1',\n'ce_ru':'ce_RU.UTF-8',\n'cextend':'en_US.ISO8859-1',\n'chinese-s':'zh_CN.eucCN',\n'chinese-t':'zh_TW.eucTW',\n'chr_us':'chr_US.UTF-8',\n'ckb_iq':'ckb_IQ.UTF-8',\n'cmn_tw':'cmn_TW.UTF-8',\n'crh_ua':'crh_UA.UTF-8',\n'croatian':'hr_HR.ISO8859-2',\n'cs':'cs_CZ.ISO8859-2',\n'cs_cs':'cs_CZ.ISO8859-2',\n'cs_cz':'cs_CZ.ISO8859-2',\n'csb_pl':'csb_PL.UTF-8',\n'cv_ru':'cv_RU.UTF-8',\n'cy':'cy_GB.ISO8859-1',\n'cy_gb':'cy_GB.ISO8859-1',\n'cz':'cs_CZ.ISO8859-2',\n'cz_cz':'cs_CZ.ISO8859-2',\n'czech':'cs_CZ.ISO8859-2',\n'da':'da_DK.ISO8859-1',\n'da_dk':'da_DK.ISO8859-1',\n'danish':'da_DK.ISO8859-1',\n'dansk':'da_DK.ISO8859-1',\n'de':'de_DE.ISO8859-1',\n'de_at':'de_AT.ISO8859-1',\n'de_be':'de_BE.ISO8859-1',\n'de_ch':'de_CH.ISO8859-1',\n'de_de':'de_DE.ISO8859-1',\n'de_it':'de_IT.ISO8859-1',\n'de_li.utf8':'de_LI.UTF-8',\n'de_lu':'de_LU.ISO8859-1',\n'deutsch':'de_DE.ISO8859-1',\n'doi_in':'doi_IN.UTF-8',\n'dutch':'nl_NL.ISO8859-1',\n'dutch.iso88591':'nl_BE.ISO8859-1',\n'dv_mv':'dv_MV.UTF-8',\n'dz_bt':'dz_BT.UTF-8',\n'ee':'ee_EE.ISO8859-4',\n'ee_ee':'ee_EE.ISO8859-4',\n'eesti':'et_EE.ISO8859-1',\n'el':'el_GR.ISO8859-7',\n'el_cy':'el_CY.ISO8859-7',\n'el_gr':'el_GR.ISO8859-7',\n'el_gr@euro':'el_GR.ISO8859-15',\n'en':'en_US.ISO8859-1',\n'en_ag':'en_AG.UTF-8',\n'en_au':'en_AU.ISO8859-1',\n'en_be':'en_BE.ISO8859-1',\n'en_bw':'en_BW.ISO8859-1',\n'en_ca':'en_CA.ISO8859-1',\n'en_dk':'en_DK.ISO8859-1',\n'en_dl.utf8':'en_DL.UTF-8',\n'en_gb':'en_GB.ISO8859-1',\n'en_hk':'en_HK.ISO8859-1',\n'en_ie':'en_IE.ISO8859-1',\n'en_il':'en_IL.UTF-8',\n'en_in':'en_IN.ISO8859-1',\n'en_ng':'en_NG.UTF-8',\n'en_nz':'en_NZ.ISO8859-1',\n'en_ph':'en_PH.ISO8859-1',\n'en_sc.utf8':'en_SC.UTF-8',\n'en_sg':'en_SG.ISO8859-1',\n'en_uk':'en_GB.ISO8859-1',\n'en_us':'en_US.ISO8859-1',\n'en_us@euro@euro':'en_US.ISO8859-15',\n'en_za':'en_ZA.ISO8859-1',\n'en_zm':'en_ZM.UTF-8',\n'en_zw':'en_ZW.ISO8859-1',\n'en_zw.utf8':'en_ZS.UTF-8',\n'eng_gb':'en_GB.ISO8859-1',\n'english':'en_EN.ISO8859-1',\n'english.iso88591':'en_US.ISO8859-1',\n'english_uk':'en_GB.ISO8859-1',\n'english_united-states':'en_US.ISO8859-1',\n'english_united-states.437':'C',\n'english_us':'en_US.ISO8859-1',\n'eo':'eo_XX.ISO8859-3',\n'eo.utf8':'eo.UTF-8',\n'eo_eo':'eo_EO.ISO8859-3',\n'eo_us.utf8':'eo_US.UTF-8',\n'eo_xx':'eo_XX.ISO8859-3',\n'es':'es_ES.ISO8859-1',\n'es_ar':'es_AR.ISO8859-1',\n'es_bo':'es_BO.ISO8859-1',\n'es_cl':'es_CL.ISO8859-1',\n'es_co':'es_CO.ISO8859-1',\n'es_cr':'es_CR.ISO8859-1',\n'es_cu':'es_CU.UTF-8',\n'es_do':'es_DO.ISO8859-1',\n'es_ec':'es_EC.ISO8859-1',\n'es_es':'es_ES.ISO8859-1',\n'es_gt':'es_GT.ISO8859-1',\n'es_hn':'es_HN.ISO8859-1',\n'es_mx':'es_MX.ISO8859-1',\n'es_ni':'es_NI.ISO8859-1',\n'es_pa':'es_PA.ISO8859-1',\n'es_pe':'es_PE.ISO8859-1',\n'es_pr':'es_PR.ISO8859-1',\n'es_py':'es_PY.ISO8859-1',\n'es_sv':'es_SV.ISO8859-1',\n'es_us':'es_US.ISO8859-1',\n'es_uy':'es_UY.ISO8859-1',\n'es_ve':'es_VE.ISO8859-1',\n'estonian':'et_EE.ISO8859-1',\n'et':'et_EE.ISO8859-15',\n'et_ee':'et_EE.ISO8859-15',\n'eu':'eu_ES.ISO8859-1',\n'eu_es':'eu_ES.ISO8859-1',\n'eu_fr':'eu_FR.ISO8859-1',\n'fa':'fa_IR.UTF-8',\n'fa_ir':'fa_IR.UTF-8',\n'fa_ir.isiri3342':'fa_IR.ISIRI-3342',\n'ff_sn':'ff_SN.UTF-8',\n'fi':'fi_FI.ISO8859-15',\n'fi_fi':'fi_FI.ISO8859-15',\n'fil_ph':'fil_PH.UTF-8',\n'finnish':'fi_FI.ISO8859-1',\n'fo':'fo_FO.ISO8859-1',\n'fo_fo':'fo_FO.ISO8859-1',\n'fr':'fr_FR.ISO8859-1',\n'fr_be':'fr_BE.ISO8859-1',\n'fr_ca':'fr_CA.ISO8859-1',\n'fr_ch':'fr_CH.ISO8859-1',\n'fr_fr':'fr_FR.ISO8859-1',\n'fr_lu':'fr_LU.ISO8859-1',\n'fran\\xe7ais':'fr_FR.ISO8859-1',\n'fre_fr':'fr_FR.ISO8859-1',\n'french':'fr_FR.ISO8859-1',\n'french.iso88591':'fr_CH.ISO8859-1',\n'french_france':'fr_FR.ISO8859-1',\n'fur_it':'fur_IT.UTF-8',\n'fy_de':'fy_DE.UTF-8',\n'fy_nl':'fy_NL.UTF-8',\n'ga':'ga_IE.ISO8859-1',\n'ga_ie':'ga_IE.ISO8859-1',\n'galego':'gl_ES.ISO8859-1',\n'galician':'gl_ES.ISO8859-1',\n'gd':'gd_GB.ISO8859-1',\n'gd_gb':'gd_GB.ISO8859-1',\n'ger_de':'de_DE.ISO8859-1',\n'german':'de_DE.ISO8859-1',\n'german.iso88591':'de_CH.ISO8859-1',\n'german_germany':'de_DE.ISO8859-1',\n'gez_er':'gez_ER.UTF-8',\n'gez_et':'gez_ET.UTF-8',\n'gl':'gl_ES.ISO8859-1',\n'gl_es':'gl_ES.ISO8859-1',\n'greek':'el_GR.ISO8859-7',\n'gu_in':'gu_IN.UTF-8',\n'gv':'gv_GB.ISO8859-1',\n'gv_gb':'gv_GB.ISO8859-1',\n'ha_ng':'ha_NG.UTF-8',\n'hak_tw':'hak_TW.UTF-8',\n'he':'he_IL.ISO8859-8',\n'he_il':'he_IL.ISO8859-8',\n'hebrew':'he_IL.ISO8859-8',\n'hi':'hi_IN.ISCII-DEV',\n'hi_in':'hi_IN.ISCII-DEV',\n'hi_in.isciidev':'hi_IN.ISCII-DEV',\n'hif_fj':'hif_FJ.UTF-8',\n'hne':'hne_IN.UTF-8',\n'hne_in':'hne_IN.UTF-8',\n'hr':'hr_HR.ISO8859-2',\n'hr_hr':'hr_HR.ISO8859-2',\n'hrvatski':'hr_HR.ISO8859-2',\n'hsb_de':'hsb_DE.ISO8859-2',\n'ht_ht':'ht_HT.UTF-8',\n'hu':'hu_HU.ISO8859-2',\n'hu_hu':'hu_HU.ISO8859-2',\n'hungarian':'hu_HU.ISO8859-2',\n'hy_am':'hy_AM.UTF-8',\n'hy_am.armscii8':'hy_AM.ARMSCII_8',\n'ia':'ia.UTF-8',\n'ia_fr':'ia_FR.UTF-8',\n'icelandic':'is_IS.ISO8859-1',\n'id':'id_ID.ISO8859-1',\n'id_id':'id_ID.ISO8859-1',\n'ig_ng':'ig_NG.UTF-8',\n'ik_ca':'ik_CA.UTF-8',\n'in':'id_ID.ISO8859-1',\n'in_id':'id_ID.ISO8859-1',\n'is':'is_IS.ISO8859-1',\n'is_is':'is_IS.ISO8859-1',\n'iso-8859-1':'en_US.ISO8859-1',\n'iso-8859-15':'en_US.ISO8859-15',\n'iso8859-1':'en_US.ISO8859-1',\n'iso8859-15':'en_US.ISO8859-15',\n'iso_8859_1':'en_US.ISO8859-1',\n'iso_8859_15':'en_US.ISO8859-15',\n'it':'it_IT.ISO8859-1',\n'it_ch':'it_CH.ISO8859-1',\n'it_it':'it_IT.ISO8859-1',\n'italian':'it_IT.ISO8859-1',\n'iu':'iu_CA.NUNACOM-8',\n'iu_ca':'iu_CA.NUNACOM-8',\n'iu_ca.nunacom8':'iu_CA.NUNACOM-8',\n'iw':'he_IL.ISO8859-8',\n'iw_il':'he_IL.ISO8859-8',\n'iw_il.utf8':'iw_IL.UTF-8',\n'ja':'ja_JP.eucJP',\n'ja_jp':'ja_JP.eucJP',\n'ja_jp.euc':'ja_JP.eucJP',\n'ja_jp.mscode':'ja_JP.SJIS',\n'ja_jp.pck':'ja_JP.SJIS',\n'japan':'ja_JP.eucJP',\n'japanese':'ja_JP.eucJP',\n'japanese-euc':'ja_JP.eucJP',\n'japanese.euc':'ja_JP.eucJP',\n'jp_jp':'ja_JP.eucJP',\n'ka':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge.georgianacademy':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge.georgianps':'ka_GE.GEORGIAN-PS',\n'ka_ge.georgianrs':'ka_GE.GEORGIAN-ACADEMY',\n'kab_dz':'kab_DZ.UTF-8',\n'kk_kz':'kk_KZ.ptcp154',\n'kl':'kl_GL.ISO8859-1',\n'kl_gl':'kl_GL.ISO8859-1',\n'km_kh':'km_KH.UTF-8',\n'kn':'kn_IN.UTF-8',\n'kn_in':'kn_IN.UTF-8',\n'ko':'ko_KR.eucKR',\n'ko_kr':'ko_KR.eucKR',\n'ko_kr.euc':'ko_KR.eucKR',\n'kok_in':'kok_IN.UTF-8',\n'korean':'ko_KR.eucKR',\n'korean.euc':'ko_KR.eucKR',\n'ks':'ks_IN.UTF-8',\n'ks_in':'ks_IN.UTF-8',\n'ks_in@devanagari.utf8':'ks_IN.UTF-8@devanagari',\n'ku_tr':'ku_TR.ISO8859-9',\n'kw':'kw_GB.ISO8859-1',\n'kw_gb':'kw_GB.ISO8859-1',\n'ky':'ky_KG.UTF-8',\n'ky_kg':'ky_KG.UTF-8',\n'lb_lu':'lb_LU.UTF-8',\n'lg_ug':'lg_UG.ISO8859-10',\n'li_be':'li_BE.UTF-8',\n'li_nl':'li_NL.UTF-8',\n'lij_it':'lij_IT.UTF-8',\n'lithuanian':'lt_LT.ISO8859-13',\n'ln_cd':'ln_CD.UTF-8',\n'lo':'lo_LA.MULELAO-1',\n'lo_la':'lo_LA.MULELAO-1',\n'lo_la.cp1133':'lo_LA.IBM-CP1133',\n'lo_la.ibmcp1133':'lo_LA.IBM-CP1133',\n'lo_la.mulelao1':'lo_LA.MULELAO-1',\n'lt':'lt_LT.ISO8859-13',\n'lt_lt':'lt_LT.ISO8859-13',\n'lv':'lv_LV.ISO8859-13',\n'lv_lv':'lv_LV.ISO8859-13',\n'lzh_tw':'lzh_TW.UTF-8',\n'mag_in':'mag_IN.UTF-8',\n'mai':'mai_IN.UTF-8',\n'mai_in':'mai_IN.UTF-8',\n'mai_np':'mai_NP.UTF-8',\n'mfe_mu':'mfe_MU.UTF-8',\n'mg_mg':'mg_MG.ISO8859-15',\n'mhr_ru':'mhr_RU.UTF-8',\n'mi':'mi_NZ.ISO8859-1',\n'mi_nz':'mi_NZ.ISO8859-1',\n'miq_ni':'miq_NI.UTF-8',\n'mjw_in':'mjw_IN.UTF-8',\n'mk':'mk_MK.ISO8859-5',\n'mk_mk':'mk_MK.ISO8859-5',\n'ml':'ml_IN.UTF-8',\n'ml_in':'ml_IN.UTF-8',\n'mn_mn':'mn_MN.UTF-8',\n'mni_in':'mni_IN.UTF-8',\n'mr':'mr_IN.UTF-8',\n'mr_in':'mr_IN.UTF-8',\n'ms':'ms_MY.ISO8859-1',\n'ms_my':'ms_MY.ISO8859-1',\n'mt':'mt_MT.ISO8859-3',\n'mt_mt':'mt_MT.ISO8859-3',\n'my_mm':'my_MM.UTF-8',\n'nan_tw':'nan_TW.UTF-8',\n'nb':'nb_NO.ISO8859-1',\n'nb_no':'nb_NO.ISO8859-1',\n'nds_de':'nds_DE.UTF-8',\n'nds_nl':'nds_NL.UTF-8',\n'ne_np':'ne_NP.UTF-8',\n'nhn_mx':'nhn_MX.UTF-8',\n'niu_nu':'niu_NU.UTF-8',\n'niu_nz':'niu_NZ.UTF-8',\n'nl':'nl_NL.ISO8859-1',\n'nl_aw':'nl_AW.UTF-8',\n'nl_be':'nl_BE.ISO8859-1',\n'nl_nl':'nl_NL.ISO8859-1',\n'nn':'nn_NO.ISO8859-1',\n'nn_no':'nn_NO.ISO8859-1',\n'no':'no_NO.ISO8859-1',\n'no@nynorsk':'ny_NO.ISO8859-1',\n'no_no':'no_NO.ISO8859-1',\n'no_no.iso88591@bokmal':'no_NO.ISO8859-1',\n'no_no.iso88591@nynorsk':'no_NO.ISO8859-1',\n'norwegian':'no_NO.ISO8859-1',\n'nr':'nr_ZA.ISO8859-1',\n'nr_za':'nr_ZA.ISO8859-1',\n'nso':'nso_ZA.ISO8859-15',\n'nso_za':'nso_ZA.ISO8859-15',\n'ny':'ny_NO.ISO8859-1',\n'ny_no':'ny_NO.ISO8859-1',\n'nynorsk':'nn_NO.ISO8859-1',\n'oc':'oc_FR.ISO8859-1',\n'oc_fr':'oc_FR.ISO8859-1',\n'om_et':'om_ET.UTF-8',\n'om_ke':'om_KE.ISO8859-1',\n'or':'or_IN.UTF-8',\n'or_in':'or_IN.UTF-8',\n'os_ru':'os_RU.UTF-8',\n'pa':'pa_IN.UTF-8',\n'pa_in':'pa_IN.UTF-8',\n'pa_pk':'pa_PK.UTF-8',\n'pap_an':'pap_AN.UTF-8',\n'pap_aw':'pap_AW.UTF-8',\n'pap_cw':'pap_CW.UTF-8',\n'pd':'pd_US.ISO8859-1',\n'pd_de':'pd_DE.ISO8859-1',\n'pd_us':'pd_US.ISO8859-1',\n'ph':'ph_PH.ISO8859-1',\n'ph_ph':'ph_PH.ISO8859-1',\n'pl':'pl_PL.ISO8859-2',\n'pl_pl':'pl_PL.ISO8859-2',\n'polish':'pl_PL.ISO8859-2',\n'portuguese':'pt_PT.ISO8859-1',\n'portuguese_brazil':'pt_BR.ISO8859-1',\n'posix':'C',\n'posix-utf2':'C',\n'pp':'pp_AN.ISO8859-1',\n'pp_an':'pp_AN.ISO8859-1',\n'ps_af':'ps_AF.UTF-8',\n'pt':'pt_PT.ISO8859-1',\n'pt_br':'pt_BR.ISO8859-1',\n'pt_pt':'pt_PT.ISO8859-1',\n'quz_pe':'quz_PE.UTF-8',\n'raj_in':'raj_IN.UTF-8',\n'ro':'ro_RO.ISO8859-2',\n'ro_ro':'ro_RO.ISO8859-2',\n'romanian':'ro_RO.ISO8859-2',\n'ru':'ru_RU.UTF-8',\n'ru_ru':'ru_RU.UTF-8',\n'ru_ua':'ru_UA.KOI8-U',\n'rumanian':'ro_RO.ISO8859-2',\n'russian':'ru_RU.KOI8-R',\n'rw':'rw_RW.ISO8859-1',\n'rw_rw':'rw_RW.ISO8859-1',\n'sa_in':'sa_IN.UTF-8',\n'sat_in':'sat_IN.UTF-8',\n'sc_it':'sc_IT.UTF-8',\n'sd':'sd_IN.UTF-8',\n'sd_in':'sd_IN.UTF-8',\n'sd_in@devanagari.utf8':'sd_IN.UTF-8@devanagari',\n'sd_pk':'sd_PK.UTF-8',\n'se_no':'se_NO.UTF-8',\n'serbocroatian':'sr_RS.UTF-8@latin',\n'sgs_lt':'sgs_LT.UTF-8',\n'sh':'sr_RS.UTF-8@latin',\n'sh_ba.iso88592@bosnia':'sr_CS.ISO8859-2',\n'sh_hr':'sh_HR.ISO8859-2',\n'sh_hr.iso88592':'hr_HR.ISO8859-2',\n'sh_sp':'sr_CS.ISO8859-2',\n'sh_yu':'sr_RS.UTF-8@latin',\n'shn_mm':'shn_MM.UTF-8',\n'shs_ca':'shs_CA.UTF-8',\n'si':'si_LK.UTF-8',\n'si_lk':'si_LK.UTF-8',\n'sid_et':'sid_ET.UTF-8',\n'sinhala':'si_LK.UTF-8',\n'sk':'sk_SK.ISO8859-2',\n'sk_sk':'sk_SK.ISO8859-2',\n'sl':'sl_SI.ISO8859-2',\n'sl_cs':'sl_CS.ISO8859-2',\n'sl_si':'sl_SI.ISO8859-2',\n'slovak':'sk_SK.ISO8859-2',\n'slovene':'sl_SI.ISO8859-2',\n'slovenian':'sl_SI.ISO8859-2',\n'sm_ws':'sm_WS.UTF-8',\n'so_dj':'so_DJ.ISO8859-1',\n'so_et':'so_ET.UTF-8',\n'so_ke':'so_KE.ISO8859-1',\n'so_so':'so_SO.ISO8859-1',\n'sp':'sr_CS.ISO8859-5',\n'sp_yu':'sr_CS.ISO8859-5',\n'spanish':'es_ES.ISO8859-1',\n'spanish_spain':'es_ES.ISO8859-1',\n'sq':'sq_AL.ISO8859-2',\n'sq_al':'sq_AL.ISO8859-2',\n'sq_mk':'sq_MK.UTF-8',\n'sr':'sr_RS.UTF-8',\n'sr@cyrillic':'sr_RS.UTF-8',\n'sr@latn':'sr_CS.UTF-8@latin',\n'sr_cs':'sr_CS.UTF-8',\n'sr_cs.iso88592@latn':'sr_CS.ISO8859-2',\n'sr_cs@latn':'sr_CS.UTF-8@latin',\n'sr_me':'sr_ME.UTF-8',\n'sr_rs':'sr_RS.UTF-8',\n'sr_rs@latn':'sr_RS.UTF-8@latin',\n'sr_sp':'sr_CS.ISO8859-2',\n'sr_yu':'sr_RS.UTF-8@latin',\n'sr_yu.cp1251@cyrillic':'sr_CS.CP1251',\n'sr_yu.iso88592':'sr_CS.ISO8859-2',\n'sr_yu.iso88595':'sr_CS.ISO8859-5',\n'sr_yu.iso88595@cyrillic':'sr_CS.ISO8859-5',\n'sr_yu.microsoftcp1251@cyrillic':'sr_CS.CP1251',\n'sr_yu.utf8':'sr_RS.UTF-8',\n'sr_yu.utf8@cyrillic':'sr_RS.UTF-8',\n'sr_yu@cyrillic':'sr_RS.UTF-8',\n'ss':'ss_ZA.ISO8859-1',\n'ss_za':'ss_ZA.ISO8859-1',\n'st':'st_ZA.ISO8859-1',\n'st_za':'st_ZA.ISO8859-1',\n'sv':'sv_SE.ISO8859-1',\n'sv_fi':'sv_FI.ISO8859-1',\n'sv_se':'sv_SE.ISO8859-1',\n'sw_ke':'sw_KE.UTF-8',\n'sw_tz':'sw_TZ.UTF-8',\n'swedish':'sv_SE.ISO8859-1',\n'szl_pl':'szl_PL.UTF-8',\n'ta':'ta_IN.TSCII-0',\n'ta_in':'ta_IN.TSCII-0',\n'ta_in.tscii':'ta_IN.TSCII-0',\n'ta_in.tscii0':'ta_IN.TSCII-0',\n'ta_lk':'ta_LK.UTF-8',\n'tcy_in.utf8':'tcy_IN.UTF-8',\n'te':'te_IN.UTF-8',\n'te_in':'te_IN.UTF-8',\n'tg':'tg_TJ.KOI8-C',\n'tg_tj':'tg_TJ.KOI8-C',\n'th':'th_TH.ISO8859-11',\n'th_th':'th_TH.ISO8859-11',\n'th_th.tactis':'th_TH.TIS620',\n'th_th.tis620':'th_TH.TIS620',\n'thai':'th_TH.ISO8859-11',\n'the_np':'the_NP.UTF-8',\n'ti_er':'ti_ER.UTF-8',\n'ti_et':'ti_ET.UTF-8',\n'tig_er':'tig_ER.UTF-8',\n'tk_tm':'tk_TM.UTF-8',\n'tl':'tl_PH.ISO8859-1',\n'tl_ph':'tl_PH.ISO8859-1',\n'tn':'tn_ZA.ISO8859-15',\n'tn_za':'tn_ZA.ISO8859-15',\n'to_to':'to_TO.UTF-8',\n'tpi_pg':'tpi_PG.UTF-8',\n'tr':'tr_TR.ISO8859-9',\n'tr_cy':'tr_CY.ISO8859-9',\n'tr_tr':'tr_TR.ISO8859-9',\n'ts':'ts_ZA.ISO8859-1',\n'ts_za':'ts_ZA.ISO8859-1',\n'tt':'tt_RU.TATAR-CYR',\n'tt_ru':'tt_RU.TATAR-CYR',\n'tt_ru.tatarcyr':'tt_RU.TATAR-CYR',\n'tt_ru@iqtelif':'tt_RU.UTF-8@iqtelif',\n'turkish':'tr_TR.ISO8859-9',\n'ug_cn':'ug_CN.UTF-8',\n'uk':'uk_UA.KOI8-U',\n'uk_ua':'uk_UA.KOI8-U',\n'univ':'en_US.utf',\n'universal':'en_US.utf',\n'universal.utf8@ucs4':'en_US.UTF-8',\n'unm_us':'unm_US.UTF-8',\n'ur':'ur_PK.CP1256',\n'ur_in':'ur_IN.UTF-8',\n'ur_pk':'ur_PK.CP1256',\n'uz':'uz_UZ.UTF-8',\n'uz_uz':'uz_UZ.UTF-8',\n'uz_uz@cyrillic':'uz_UZ.UTF-8',\n've':'ve_ZA.UTF-8',\n've_za':'ve_ZA.UTF-8',\n'vi':'vi_VN.TCVN',\n'vi_vn':'vi_VN.TCVN',\n'vi_vn.tcvn':'vi_VN.TCVN',\n'vi_vn.tcvn5712':'vi_VN.TCVN',\n'vi_vn.viscii':'vi_VN.VISCII',\n'vi_vn.viscii111':'vi_VN.VISCII',\n'wa':'wa_BE.ISO8859-1',\n'wa_be':'wa_BE.ISO8859-1',\n'wae_ch':'wae_CH.UTF-8',\n'wal_et':'wal_ET.UTF-8',\n'wo_sn':'wo_SN.UTF-8',\n'xh':'xh_ZA.ISO8859-1',\n'xh_za':'xh_ZA.ISO8859-1',\n'yi':'yi_US.CP1255',\n'yi_us':'yi_US.CP1255',\n'yo_ng':'yo_NG.UTF-8',\n'yue_hk':'yue_HK.UTF-8',\n'yuw_pg':'yuw_PG.UTF-8',\n'zh':'zh_CN.eucCN',\n'zh_cn':'zh_CN.gb2312',\n'zh_cn.big5':'zh_TW.big5',\n'zh_cn.euc':'zh_CN.eucCN',\n'zh_hk':'zh_HK.big5hkscs',\n'zh_hk.big5hk':'zh_HK.big5hkscs',\n'zh_sg':'zh_SG.GB2312',\n'zh_sg.gbk':'zh_SG.GBK',\n'zh_tw':'zh_TW.big5',\n'zh_tw.euc':'zh_TW.eucTW',\n'zh_tw.euctw':'zh_TW.eucTW',\n'zu':'zu_ZA.ISO8859-1',\n'zu_za':'zu_ZA.ISO8859-1',\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nwindows_locale={\n0x0436:\"af_ZA\",\n0x041c:\"sq_AL\",\n0x0484:\"gsw_FR\",\n0x045e:\"am_ET\",\n0x0401:\"ar_SA\",\n0x0801:\"ar_IQ\",\n0x0c01:\"ar_EG\",\n0x1001:\"ar_LY\",\n0x1401:\"ar_DZ\",\n0x1801:\"ar_MA\",\n0x1c01:\"ar_TN\",\n0x2001:\"ar_OM\",\n0x2401:\"ar_YE\",\n0x2801:\"ar_SY\",\n0x2c01:\"ar_JO\",\n0x3001:\"ar_LB\",\n0x3401:\"ar_KW\",\n0x3801:\"ar_AE\",\n0x3c01:\"ar_BH\",\n0x4001:\"ar_QA\",\n0x042b:\"hy_AM\",\n0x044d:\"as_IN\",\n0x042c:\"az_AZ\",\n0x082c:\"az_AZ\",\n0x046d:\"ba_RU\",\n0x042d:\"eu_ES\",\n0x0423:\"be_BY\",\n0x0445:\"bn_IN\",\n0x201a:\"bs_BA\",\n0x141a:\"bs_BA\",\n0x047e:\"br_FR\",\n0x0402:\"bg_BG\",\n\n0x0403:\"ca_ES\",\n0x0004:\"zh_CHS\",\n0x0404:\"zh_TW\",\n0x0804:\"zh_CN\",\n0x0c04:\"zh_HK\",\n0x1004:\"zh_SG\",\n0x1404:\"zh_MO\",\n0x7c04:\"zh_CHT\",\n0x0483:\"co_FR\",\n0x041a:\"hr_HR\",\n0x101a:\"hr_BA\",\n0x0405:\"cs_CZ\",\n0x0406:\"da_DK\",\n0x048c:\"gbz_AF\",\n0x0465:\"div_MV\",\n0x0413:\"nl_NL\",\n0x0813:\"nl_BE\",\n0x0409:\"en_US\",\n0x0809:\"en_GB\",\n0x0c09:\"en_AU\",\n0x1009:\"en_CA\",\n0x1409:\"en_NZ\",\n0x1809:\"en_IE\",\n0x1c09:\"en_ZA\",\n0x2009:\"en_JA\",\n0x2409:\"en_CB\",\n0x2809:\"en_BZ\",\n0x2c09:\"en_TT\",\n0x3009:\"en_ZW\",\n0x3409:\"en_PH\",\n0x4009:\"en_IN\",\n0x4409:\"en_MY\",\n0x4809:\"en_IN\",\n0x0425:\"et_EE\",\n0x0438:\"fo_FO\",\n0x0464:\"fil_PH\",\n0x040b:\"fi_FI\",\n0x040c:\"fr_FR\",\n0x080c:\"fr_BE\",\n0x0c0c:\"fr_CA\",\n0x100c:\"fr_CH\",\n0x140c:\"fr_LU\",\n0x180c:\"fr_MC\",\n0x0462:\"fy_NL\",\n0x0456:\"gl_ES\",\n0x0437:\"ka_GE\",\n0x0407:\"de_DE\",\n0x0807:\"de_CH\",\n0x0c07:\"de_AT\",\n0x1007:\"de_LU\",\n0x1407:\"de_LI\",\n0x0408:\"el_GR\",\n0x046f:\"kl_GL\",\n0x0447:\"gu_IN\",\n0x0468:\"ha_NG\",\n0x040d:\"he_IL\",\n0x0439:\"hi_IN\",\n0x040e:\"hu_HU\",\n0x040f:\"is_IS\",\n0x0421:\"id_ID\",\n0x045d:\"iu_CA\",\n0x085d:\"iu_CA\",\n0x083c:\"ga_IE\",\n0x0410:\"it_IT\",\n0x0810:\"it_CH\",\n0x0411:\"ja_JP\",\n0x044b:\"kn_IN\",\n0x043f:\"kk_KZ\",\n0x0453:\"kh_KH\",\n0x0486:\"qut_GT\",\n0x0487:\"rw_RW\",\n0x0457:\"kok_IN\",\n0x0412:\"ko_KR\",\n0x0440:\"ky_KG\",\n0x0454:\"lo_LA\",\n0x0426:\"lv_LV\",\n0x0427:\"lt_LT\",\n0x082e:\"dsb_DE\",\n0x046e:\"lb_LU\",\n0x042f:\"mk_MK\",\n0x043e:\"ms_MY\",\n0x083e:\"ms_BN\",\n0x044c:\"ml_IN\",\n0x043a:\"mt_MT\",\n0x0481:\"mi_NZ\",\n0x047a:\"arn_CL\",\n0x044e:\"mr_IN\",\n0x047c:\"moh_CA\",\n0x0450:\"mn_MN\",\n0x0850:\"mn_CN\",\n0x0461:\"ne_NP\",\n0x0414:\"nb_NO\",\n0x0814:\"nn_NO\",\n0x0482:\"oc_FR\",\n0x0448:\"or_IN\",\n0x0463:\"ps_AF\",\n0x0429:\"fa_IR\",\n0x0415:\"pl_PL\",\n0x0416:\"pt_BR\",\n0x0816:\"pt_PT\",\n0x0446:\"pa_IN\",\n0x046b:\"quz_BO\",\n0x086b:\"quz_EC\",\n0x0c6b:\"quz_PE\",\n0x0418:\"ro_RO\",\n0x0417:\"rm_CH\",\n0x0419:\"ru_RU\",\n0x243b:\"smn_FI\",\n0x103b:\"smj_NO\",\n0x143b:\"smj_SE\",\n0x043b:\"se_NO\",\n0x083b:\"se_SE\",\n0x0c3b:\"se_FI\",\n0x203b:\"sms_FI\",\n0x183b:\"sma_NO\",\n0x1c3b:\"sma_SE\",\n0x044f:\"sa_IN\",\n0x0c1a:\"sr_SP\",\n0x1c1a:\"sr_BA\",\n0x081a:\"sr_SP\",\n0x181a:\"sr_BA\",\n0x045b:\"si_LK\",\n0x046c:\"ns_ZA\",\n0x0432:\"tn_ZA\",\n0x041b:\"sk_SK\",\n0x0424:\"sl_SI\",\n0x040a:\"es_ES\",\n0x080a:\"es_MX\",\n0x0c0a:\"es_ES\",\n0x100a:\"es_GT\",\n0x140a:\"es_CR\",\n0x180a:\"es_PA\",\n0x1c0a:\"es_DO\",\n0x200a:\"es_VE\",\n0x240a:\"es_CO\",\n0x280a:\"es_PE\",\n0x2c0a:\"es_AR\",\n0x300a:\"es_EC\",\n0x340a:\"es_CL\",\n0x380a:\"es_UR\",\n0x3c0a:\"es_PY\",\n0x400a:\"es_BO\",\n0x440a:\"es_SV\",\n0x480a:\"es_HN\",\n0x4c0a:\"es_NI\",\n0x500a:\"es_PR\",\n0x540a:\"es_US\",\n\n0x0441:\"sw_KE\",\n0x041d:\"sv_SE\",\n0x081d:\"sv_FI\",\n0x045a:\"syr_SY\",\n0x0428:\"tg_TJ\",\n0x085f:\"tmz_DZ\",\n0x0449:\"ta_IN\",\n0x0444:\"tt_RU\",\n0x044a:\"te_IN\",\n0x041e:\"th_TH\",\n0x0851:\"bo_BT\",\n0x0451:\"bo_CN\",\n0x041f:\"tr_TR\",\n0x0442:\"tk_TM\",\n0x0480:\"ug_CN\",\n0x0422:\"uk_UA\",\n0x042e:\"wen_DE\",\n0x0420:\"ur_PK\",\n0x0820:\"ur_IN\",\n0x0443:\"uz_UZ\",\n0x0843:\"uz_UZ\",\n0x042a:\"vi_VN\",\n0x0452:\"cy_GB\",\n0x0488:\"wo_SN\",\n0x0434:\"xh_ZA\",\n0x0485:\"sah_RU\",\n0x0478:\"ii_CN\",\n0x046a:\"yo_NG\",\n0x0435:\"zu_ZA\",\n}\n\ndef _print_locale():\n\n ''\n \n categories={}\n def _init_categories(categories=categories):\n for k,v in globals().items():\n if k[:3]=='LC_':\n categories[k]=v\n _init_categories()\n del categories['LC_ALL']\n \n print('Locale defaults as determined by getdefaultlocale():')\n print('-'*72)\n lang,enc=getdefaultlocale()\n print('Language: ',lang or '(undefined)')\n print('Encoding: ',enc or '(undefined)')\n print()\n \n print('Locale settings on startup:')\n print('-'*72)\n for name,category in categories.items():\n print(name,'...')\n lang,enc=getlocale(category)\n print(' Language: ',lang or '(undefined)')\n print(' Encoding: ',enc or '(undefined)')\n print()\n \n try:\n setlocale(LC_ALL,\"\")\n except:\n print('NOTE:')\n print('setlocale(LC_ALL, \"\") does not support the default locale')\n print('given in the OS environment variables.')\n else:\n print()\n print('Locale settings after calling setlocale(LC_ALL, \"\"):')\n print('-'*72)\n for name,category in categories.items():\n print(name,'...')\n lang,enc=getlocale(category)\n print(' Language: ',lang or '(undefined)')\n print(' Encoding: ',enc or '(undefined)')\n print()\n \n \n \ntry:\n LC_MESSAGES\nexcept NameError:\n pass\nelse:\n __all__.append(\"LC_MESSAGES\")\n \nif __name__ =='__main__':\n print('Locale aliasing:')\n print()\n _print_locale()\n print()\n print('Number formatting:')\n print()\n _test()\n", ["_collections_abc", "_locale", "builtins", "encodings", "encodings.aliases", "functools", "os", "re", "sys", "warnings"]], "mimetypes": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport os\nimport sys\nimport posixpath\nimport urllib.parse\n\ntry:\n from _winapi import _mimetypes_read_windows_registry\nexcept ImportError:\n _mimetypes_read_windows_registry=None\n \ntry:\n import winreg as _winreg\nexcept ImportError:\n _winreg=None\n \n__all__=[\n\"knownfiles\",\"inited\",\"MimeTypes\",\n\"guess_type\",\"guess_file_type\",\"guess_all_extensions\",\"guess_extension\",\n\"add_type\",\"init\",\"read_mime_types\",\n\"suffix_map\",\"encodings_map\",\"types_map\",\"common_types\"\n]\n\nknownfiles=[\n\"/etc/mime.types\",\n\"/etc/httpd/mime.types\",\n\"/etc/httpd/conf/mime.types\",\n\"/etc/apache/mime.types\",\n\"/etc/apache2/mime.types\",\n\"/usr/local/etc/httpd/conf/mime.types\",\n\"/usr/local/lib/netscape/mime.types\",\n\"/usr/local/etc/httpd/conf/mime.types\",\n\"/usr/local/etc/mime.types\",\n]\n\ninited=False\n_db=None\n\n\nclass MimeTypes:\n ''\n\n\n\n\n \n \n def __init__(self,filenames=(),strict=True):\n if not inited:\n init()\n self.encodings_map=_encodings_map_default.copy()\n self.suffix_map=_suffix_map_default.copy()\n self.types_map=({},{})\n self.types_map_inv=({},{})\n for(ext,type)in _types_map_default.items():\n self.add_type(type,ext,True)\n for(ext,type)in _common_types_default.items():\n self.add_type(type,ext,False)\n for name in filenames:\n self.read(name,strict)\n \n def add_type(self,type,ext,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n \n self.types_map[strict][ext]=type\n exts=self.types_map_inv[strict].setdefault(type,[])\n if ext not in exts:\n exts.append(ext)\n \n def guess_type(self,url,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n url=os.fspath(url)\n p=urllib.parse.urlparse(url)\n if p.scheme and len(p.scheme)>1:\n scheme=p.scheme\n url=p.path\n else:\n return self.guess_file_type(url,strict=strict)\n if scheme =='data':\n \n \n \n \n \n \n comma=url.find(',')\n if comma <0:\n \n return None,None\n semi=url.find(';',0,comma)\n if semi >=0:\n type=url[:semi]\n else:\n type=url[:comma]\n if '='in type or '/'not in type:\n type='text/plain'\n return type,None\n return self._guess_file_type(url,strict,posixpath.splitext)\n \n def guess_file_type(self,path,*,strict=True):\n ''\n\n\n \n path=os.fsdecode(path)\n path=os.path.splitdrive(path)[1]\n return self._guess_file_type(path,strict,os.path.splitext)\n \n def _guess_file_type(self,path,strict,splitext):\n base,ext=splitext(path)\n while(ext_lower :=ext.lower())in self.suffix_map:\n base,ext=splitext(base+self.suffix_map[ext_lower])\n \n if ext in self.encodings_map:\n encoding=self.encodings_map[ext]\n base,ext=splitext(base)\n else:\n encoding=None\n ext=ext.lower()\n types_map=self.types_map[True]\n if ext in types_map:\n return types_map[ext],encoding\n elif strict:\n return None,encoding\n types_map=self.types_map[False]\n if ext in types_map:\n return types_map[ext],encoding\n else:\n return None,encoding\n \n def guess_all_extensions(self,type,strict=True):\n ''\n\n\n\n\n\n\n\n\n \n type=type.lower()\n extensions=list(self.types_map_inv[True].get(type,[]))\n if not strict:\n for ext in self.types_map_inv[False].get(type,[]):\n if ext not in extensions:\n extensions.append(ext)\n return extensions\n \n def guess_extension(self,type,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n \n extensions=self.guess_all_extensions(type,strict)\n if not extensions:\n return None\n return extensions[0]\n \n def read(self,filename,strict=True):\n ''\n\n\n\n\n\n \n with open(filename,encoding='utf-8')as fp:\n self.readfp(fp,strict)\n \n def readfp(self,fp,strict=True):\n ''\n\n\n\n\n\n \n while line :=fp.readline():\n words=line.split()\n for i in range(len(words)):\n if words[i][0]=='#':\n del words[i:]\n break\n if not words:\n continue\n type,suffixes=words[0],words[1:]\n for suff in suffixes:\n self.add_type(type,'.'+suff,strict)\n \n def read_windows_registry(self,strict=True):\n ''\n\n\n\n\n\n \n \n if not _mimetypes_read_windows_registry and not _winreg:\n return\n \n add_type=self.add_type\n if strict:\n add_type=lambda type,ext:self.add_type(type,ext,True)\n \n \n if _mimetypes_read_windows_registry:\n _mimetypes_read_windows_registry(add_type)\n elif _winreg:\n self._read_windows_registry(add_type)\n \n @classmethod\n def _read_windows_registry(cls,add_type):\n def enum_types(mimedb):\n i=0\n while True:\n try:\n ctype=_winreg.EnumKey(mimedb,i)\n except OSError:\n break\n else:\n if '\\0'not in ctype:\n yield ctype\n i +=1\n \n with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,'')as hkcr:\n for subkeyname in enum_types(hkcr):\n try:\n with _winreg.OpenKey(hkcr,subkeyname)as subkey:\n \n if not subkeyname.startswith(\".\"):\n continue\n \n mimetype,datatype=_winreg.QueryValueEx(\n subkey,'Content Type')\n if datatype !=_winreg.REG_SZ:\n continue\n add_type(mimetype,subkeyname)\n except OSError:\n continue\n \ndef guess_type(url,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if _db is None:\n init()\n return _db.guess_type(url,strict)\n \n \ndef guess_file_type(path,*,strict=True):\n ''\n\n\n \n if _db is None:\n init()\n return _db.guess_file_type(path,strict=strict)\n \n \ndef guess_all_extensions(type,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if _db is None:\n init()\n return _db.guess_all_extensions(type,strict)\n \ndef guess_extension(type,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n \n if _db is None:\n init()\n return _db.guess_extension(type,strict)\n \ndef add_type(type,ext,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n \n if _db is None:\n init()\n return _db.add_type(type,ext,strict)\n \n \ndef init(files=None):\n global suffix_map,types_map,encodings_map,common_types\n global inited,_db\n inited=True\n \n if files is None or _db is None:\n db=MimeTypes()\n \n db.read_windows_registry()\n \n if files is None:\n files=knownfiles\n else:\n files=knownfiles+list(files)\n else:\n db=_db\n \n for file in files:\n if os.path.isfile(file):\n db.read(file)\n encodings_map=db.encodings_map\n suffix_map=db.suffix_map\n types_map=db.types_map[True]\n common_types=db.types_map[False]\n \n _db=db\n \n \ndef read_mime_types(file):\n try:\n f=open(file,encoding='utf-8')\n except OSError:\n return None\n with f:\n db=MimeTypes()\n db.readfp(f,True)\n return db.types_map[True]\n \n \ndef _default_mime_types():\n global suffix_map,_suffix_map_default\n global encodings_map,_encodings_map_default\n global types_map,_types_map_default\n global common_types,_common_types_default\n \n suffix_map=_suffix_map_default={\n '.svgz':'.svg.gz',\n '.tgz':'.tar.gz',\n '.taz':'.tar.gz',\n '.tz':'.tar.gz',\n '.tbz2':'.tar.bz2',\n '.txz':'.tar.xz',\n }\n \n encodings_map=_encodings_map_default={\n '.gz':'gzip',\n '.Z':'compress',\n '.bz2':'bzip2',\n '.xz':'xz',\n '.br':'br',\n }\n \n \n \n \n \n \n \n \n types_map=_types_map_default={\n '.js':'text/javascript',\n '.mjs':'text/javascript',\n '.json':'application/json',\n '.webmanifest':'application/manifest+json',\n '.doc':'application/msword',\n '.dot':'application/msword',\n '.wiz':'application/msword',\n '.nq':'application/n-quads',\n '.nt':'application/n-triples',\n '.bin':'application/octet-stream',\n '.a':'application/octet-stream',\n '.dll':'application/octet-stream',\n '.exe':'application/octet-stream',\n '.o':'application/octet-stream',\n '.obj':'application/octet-stream',\n '.so':'application/octet-stream',\n '.oda':'application/oda',\n '.pdf':'application/pdf',\n '.p7c':'application/pkcs7-mime',\n '.ps':'application/postscript',\n '.ai':'application/postscript',\n '.eps':'application/postscript',\n '.trig':'application/trig',\n '.m3u':'application/vnd.apple.mpegurl',\n '.m3u8':'application/vnd.apple.mpegurl',\n '.xls':'application/vnd.ms-excel',\n '.xlb':'application/vnd.ms-excel',\n '.ppt':'application/vnd.ms-powerpoint',\n '.pot':'application/vnd.ms-powerpoint',\n '.ppa':'application/vnd.ms-powerpoint',\n '.pps':'application/vnd.ms-powerpoint',\n '.pwz':'application/vnd.ms-powerpoint',\n '.wasm':'application/wasm',\n '.bcpio':'application/x-bcpio',\n '.cpio':'application/x-cpio',\n '.csh':'application/x-csh',\n '.dvi':'application/x-dvi',\n '.gtar':'application/x-gtar',\n '.hdf':'application/x-hdf',\n '.h5':'application/x-hdf5',\n '.latex':'application/x-latex',\n '.mif':'application/x-mif',\n '.cdf':'application/x-netcdf',\n '.nc':'application/x-netcdf',\n '.p12':'application/x-pkcs12',\n '.pfx':'application/x-pkcs12',\n '.ram':'application/x-pn-realaudio',\n '.pyc':'application/x-python-code',\n '.pyo':'application/x-python-code',\n '.sh':'application/x-sh',\n '.shar':'application/x-shar',\n '.swf':'application/x-shockwave-flash',\n '.sv4cpio':'application/x-sv4cpio',\n '.sv4crc':'application/x-sv4crc',\n '.tar':'application/x-tar',\n '.tcl':'application/x-tcl',\n '.tex':'application/x-tex',\n '.texi':'application/x-texinfo',\n '.texinfo':'application/x-texinfo',\n '.roff':'application/x-troff',\n '.t':'application/x-troff',\n '.tr':'application/x-troff',\n '.man':'application/x-troff-man',\n '.me':'application/x-troff-me',\n '.ms':'application/x-troff-ms',\n '.ustar':'application/x-ustar',\n '.src':'application/x-wais-source',\n '.xsl':'application/xml',\n '.rdf':'application/xml',\n '.wsdl':'application/xml',\n '.xpdl':'application/xml',\n '.zip':'application/zip',\n '.3gp':'audio/3gpp',\n '.3gpp':'audio/3gpp',\n '.3g2':'audio/3gpp2',\n '.3gpp2':'audio/3gpp2',\n '.aac':'audio/aac',\n '.adts':'audio/aac',\n '.loas':'audio/aac',\n '.ass':'audio/aac',\n '.au':'audio/basic',\n '.snd':'audio/basic',\n '.mp3':'audio/mpeg',\n '.mp2':'audio/mpeg',\n '.opus':'audio/opus',\n '.aif':'audio/x-aiff',\n '.aifc':'audio/x-aiff',\n '.aiff':'audio/x-aiff',\n '.ra':'audio/x-pn-realaudio',\n '.wav':'audio/x-wav',\n '.avif':'image/avif',\n '.bmp':'image/bmp',\n '.gif':'image/gif',\n '.ief':'image/ief',\n '.jpg':'image/jpeg',\n '.jpe':'image/jpeg',\n '.jpeg':'image/jpeg',\n '.heic':'image/heic',\n '.heif':'image/heif',\n '.png':'image/png',\n '.svg':'image/svg+xml',\n '.tiff':'image/tiff',\n '.tif':'image/tiff',\n '.ico':'image/vnd.microsoft.icon',\n '.webp':'image/webp',\n '.ras':'image/x-cmu-raster',\n '.pnm':'image/x-portable-anymap',\n '.pbm':'image/x-portable-bitmap',\n '.pgm':'image/x-portable-graymap',\n '.ppm':'image/x-portable-pixmap',\n '.rgb':'image/x-rgb',\n '.xbm':'image/x-xbitmap',\n '.xpm':'image/x-xpixmap',\n '.xwd':'image/x-xwindowdump',\n '.eml':'message/rfc822',\n '.mht':'message/rfc822',\n '.mhtml':'message/rfc822',\n '.nws':'message/rfc822',\n '.css':'text/css',\n '.csv':'text/csv',\n '.html':'text/html',\n '.htm':'text/html',\n '.md':'text/markdown',\n '.markdown':'text/markdown',\n '.n3':'text/n3',\n '.txt':'text/plain',\n '.bat':'text/plain',\n '.c':'text/plain',\n '.h':'text/plain',\n '.ksh':'text/plain',\n '.pl':'text/plain',\n '.srt':'text/plain',\n '.rtx':'text/richtext',\n '.rtf':'text/rtf',\n '.tsv':'text/tab-separated-values',\n '.vtt':'text/vtt',\n '.py':'text/x-python',\n '.rst':'text/x-rst',\n '.etx':'text/x-setext',\n '.sgm':'text/x-sgml',\n '.sgml':'text/x-sgml',\n '.vcf':'text/x-vcard',\n '.xml':'text/xml',\n '.mp4':'video/mp4',\n '.mpeg':'video/mpeg',\n '.m1v':'video/mpeg',\n '.mpa':'video/mpeg',\n '.mpe':'video/mpeg',\n '.mpg':'video/mpeg',\n '.mov':'video/quicktime',\n '.qt':'video/quicktime',\n '.webm':'video/webm',\n '.avi':'video/x-msvideo',\n '.movie':'video/x-sgi-movie',\n }\n \n \n \n \n \n common_types=_common_types_default={\n '.rtf':'application/rtf',\n '.midi':'audio/midi',\n '.mid':'audio/midi',\n '.jpg':'image/jpg',\n '.pict':'image/pict',\n '.pct':'image/pict',\n '.pic':'image/pict',\n '.xul':'text/xul',\n }\n \n \n_default_mime_types()\n\n\ndef _main():\n import getopt\n \n USAGE=\"\"\"\\\nUsage: mimetypes.py [options] type\n\nOptions:\n --help / -h -- print this message and exit\n --lenient / -l -- additionally search of some common, but non-standard\n types.\n --extension / -e -- guess extension instead of type\n\nMore than one type argument may be given.\n\"\"\"\n \n def usage(code,msg=''):\n print(USAGE)\n if msg:print(msg)\n sys.exit(code)\n \n try:\n opts,args=getopt.getopt(sys.argv[1:],'hle',\n ['help','lenient','extension'])\n except getopt.error as msg:\n usage(1,msg)\n \n strict=1\n extension=0\n for opt,arg in opts:\n if opt in('-h','--help'):\n usage(0)\n elif opt in('-l','--lenient'):\n strict=0\n elif opt in('-e','--extension'):\n extension=1\n for gtype in args:\n if extension:\n guess=guess_extension(gtype,strict)\n if not guess:print(\"I don't know anything about type\",gtype)\n else:print(guess)\n else:\n guess,encoding=guess_type(gtype,strict)\n if not guess:print(\"I don't know anything about type\",gtype)\n else:print('type:',guess,'encoding:',encoding)\n \n \nif __name__ =='__main__':\n _main()\n", ["_winapi", "getopt", "os", "posixpath", "sys", "urllib.parse", "winreg"]], "ntpath": [".py", "\n''\n\n\n\n\n\n\n\n\ncurdir='.'\npardir='..'\nextsep='.'\nsep='\\\\'\npathsep=';'\naltsep='/'\ndefpath='.;C:\\\\bin'\ndevnull='nul'\n\nimport os\nimport sys\nimport stat\nimport genericpath\nfrom genericpath import *\n\n\n__all__=[\"normcase\",\"isabs\",\"join\",\"splitdrive\",\"splitroot\",\"split\",\"splitext\",\n\"basename\",\"dirname\",\"commonprefix\",\"getsize\",\"getmtime\",\n\"getatime\",\"getctime\",\"islink\",\"exists\",\"lexists\",\"isdir\",\"isfile\",\n\"ismount\",\"expanduser\",\"expandvars\",\"normpath\",\"abspath\",\n\"curdir\",\"pardir\",\"sep\",\"pathsep\",\"defpath\",\"altsep\",\n\"extsep\",\"devnull\",\"realpath\",\"supports_unicode_filenames\",\"relpath\",\n\"samefile\",\"sameopenfile\",\"samestat\",\"commonpath\",\"isjunction\"]\n\ndef _get_bothseps(path):\n if isinstance(path,bytes):\n return b'\\\\/'\n else:\n return '\\\\/'\n \n \n \n \n \ntry:\n from _winapi import(\n LCMapStringEx as _LCMapStringEx,\n LOCALE_NAME_INVARIANT as _LOCALE_NAME_INVARIANT,\n LCMAP_LOWERCASE as _LCMAP_LOWERCASE)\n \n def normcase(s):\n ''\n\n\n \n s=os.fspath(s)\n if not s:\n return s\n if isinstance(s,bytes):\n encoding=sys.getfilesystemencoding()\n s=s.decode(encoding,'surrogateescape').replace('/','\\\\')\n s=_LCMapStringEx(_LOCALE_NAME_INVARIANT,\n _LCMAP_LOWERCASE,s)\n return s.encode(encoding,'surrogateescape')\n else:\n return _LCMapStringEx(_LOCALE_NAME_INVARIANT,\n _LCMAP_LOWERCASE,\n s.replace('/','\\\\'))\nexcept ImportError:\n def normcase(s):\n ''\n\n\n \n s=os.fspath(s)\n if isinstance(s,bytes):\n return os.fsencode(os.fsdecode(s).replace('/','\\\\').lower())\n return s.replace('/','\\\\').lower()\n \n \n \n \n \n \n \n \ndef isabs(s):\n ''\n s=os.fspath(s)\n if isinstance(s,bytes):\n sep=b'\\\\'\n altsep=b'/'\n colon_sep=b':\\\\'\n else:\n sep='\\\\'\n altsep='/'\n colon_sep=':\\\\'\n s=s[:3].replace(altsep,sep)\n \n \n if s.startswith(sep)or s.startswith(colon_sep,1):\n return True\n return False\n \n \n \ndef join(path,*paths):\n path=os.fspath(path)\n if isinstance(path,bytes):\n sep=b'\\\\'\n seps=b'\\\\/'\n colon=b':'\n else:\n sep='\\\\'\n seps='\\\\/'\n colon=':'\n try:\n if not paths:\n path[:0]+sep\n result_drive,result_root,result_path=splitroot(path)\n for p in map(os.fspath,paths):\n p_drive,p_root,p_path=splitroot(p)\n if p_root:\n \n if p_drive or not result_drive:\n result_drive=p_drive\n result_root=p_root\n result_path=p_path\n continue\n elif p_drive and p_drive !=result_drive:\n if p_drive.lower()!=result_drive.lower():\n \n result_drive=p_drive\n result_root=p_root\n result_path=p_path\n continue\n \n result_drive=p_drive\n \n if result_path and result_path[-1]not in seps:\n result_path=result_path+sep\n result_path=result_path+p_path\n \n if(result_path and not result_root and\n result_drive and result_drive[-1:]not in colon+seps):\n return result_drive+sep+result_path\n return result_drive+result_root+result_path\n except(TypeError,AttributeError,BytesWarning):\n genericpath._check_arg_types('join',path,*paths)\n raise\n \n \n \n \n \ndef splitdrive(p):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n drive,root,tail=splitroot(p)\n return drive,root+tail\n \n \ndef splitroot(p):\n ''\n\n\n\n\n\n\n\n\n \n p=os.fspath(p)\n if isinstance(p,bytes):\n sep=b'\\\\'\n altsep=b'/'\n colon=b':'\n unc_prefix=b'\\\\\\\\?\\\\UNC\\\\'\n empty=b''\n else:\n sep='\\\\'\n altsep='/'\n colon=':'\n unc_prefix='\\\\\\\\?\\\\UNC\\\\'\n empty=''\n normp=p.replace(altsep,sep)\n if normp[:1]==sep:\n if normp[1:2]==sep:\n \n \n start=8 if normp[:8].upper()==unc_prefix else 2\n index=normp.find(sep,start)\n if index ==-1:\n return p,empty,empty\n index2=normp.find(sep,index+1)\n if index2 ==-1:\n return p,empty,empty\n return p[:index2],p[index2:index2+1],p[index2+1:]\n else:\n \n return empty,p[:1],p[1:]\n elif normp[1:2]==colon:\n if normp[2:3]==sep:\n \n return p[:2],p[2:3],p[3:]\n else:\n \n return p[:2],empty,p[2:]\n else:\n \n return empty,empty,p\n \n \n \n \n \n \n \ndef split(p):\n ''\n\n\n \n p=os.fspath(p)\n seps=_get_bothseps(p)\n d,r,p=splitroot(p)\n \n i=len(p)\n while i and p[i -1]not in seps:\n i -=1\n head,tail=p[:i],p[i:]\n return d+r+head.rstrip(seps),tail\n \n \n \n \n \n \n \ndef splitext(p):\n p=os.fspath(p)\n if isinstance(p,bytes):\n return genericpath._splitext(p,b'\\\\',b'/',b'.')\n else:\n return genericpath._splitext(p,'\\\\','/','.')\nsplitext.__doc__=genericpath._splitext.__doc__\n\n\n\n\ndef basename(p):\n ''\n return split(p)[1]\n \n \n \n \ndef dirname(p):\n ''\n return split(p)[0]\n \n \n \n \nif hasattr(os.stat_result,'st_reparse_tag'):\n def isjunction(path):\n ''\n try:\n st=os.lstat(path)\n except(OSError,ValueError,AttributeError):\n return False\n return bool(st.st_reparse_tag ==stat.IO_REPARSE_TAG_MOUNT_POINT)\nelse:\n def isjunction(path):\n ''\n os.fspath(path)\n return False\n \n \n \n \ndef lexists(path):\n ''\n try:\n st=os.lstat(path)\n except(OSError,ValueError):\n return False\n return True\n \n \n \n \n \n \n \n \n \n \n \ntry:\n from nt import _getvolumepathname\nexcept ImportError:\n _getvolumepathname=None\ndef ismount(path):\n ''\n \n path=os.fspath(path)\n seps=_get_bothseps(path)\n path=abspath(path)\n drive,root,rest=splitroot(path)\n if drive and drive[0]in seps:\n return not rest\n if root and not rest:\n return True\n \n if _getvolumepathname:\n x=path.rstrip(seps)\n y=_getvolumepathname(path).rstrip(seps)\n return x.casefold()==y.casefold()\n else:\n return False\n \n \n \n \n \n \n \n \n \n \n \ndef expanduser(path):\n ''\n\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n tilde=b'~'\n else:\n tilde='~'\n if not path.startswith(tilde):\n return path\n i,n=1,len(path)\n while i 0 and comps[i -1]!=pardir:\n del comps[i -1:i+1]\n i -=1\n elif i ==0 and root:\n del comps[i]\n else:\n i +=1\n else:\n i +=1\n \n if not prefix and not comps:\n comps.append(curdir)\n return prefix+sep.join(comps)\n \nelse:\n def normpath(path):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n return os.fsencode(_path_normpath(os.fsdecode(path)))or b\".\"\n return _path_normpath(path)or \".\"\n \n \ndef _abspath_fallback(path):\n ''\n\n\n\n \n \n path=os.fspath(path)\n if not isabs(path):\n if isinstance(path,bytes):\n cwd=os.getcwdb()\n else:\n cwd=os.getcwd()\n path=join(cwd,path)\n return normpath(path)\n \n \ntry:\n from nt import _getfullpathname\n \nexcept ImportError:\n abspath=_abspath_fallback\n \nelse:\n def abspath(path):\n ''\n try:\n return _getfullpathname(normpath(path))\n except(OSError,ValueError):\n return _abspath_fallback(path)\n \ntry:\n from nt import _getfinalpathname,readlink as _nt_readlink\nexcept ImportError:\n\n realpath=abspath\nelse:\n def _readlink_deep(path):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n allowed_winerror=1,2,3,5,21,32,50,67,87,4390,4392,4393\n \n seen=set()\n while normcase(path)not in seen:\n seen.add(normcase(path))\n try:\n old_path=path\n path=_nt_readlink(path)\n \n \n if not isabs(path):\n \n \n \n if not islink(old_path):\n path=old_path\n break\n path=normpath(join(dirname(old_path),path))\n except OSError as ex:\n if ex.winerror in allowed_winerror:\n break\n raise\n except ValueError:\n \n break\n return path\n \n def _getfinalpathname_nonstrict(path):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n allowed_winerror=1,2,3,5,21,32,50,53,65,67,87,123,161,1920,1921\n \n \n \n tail=path[:0]\n while path:\n try:\n path=_getfinalpathname(path)\n return join(path,tail)if tail else path\n except OSError as ex:\n if ex.winerror not in allowed_winerror:\n raise\n try:\n \n \n \n new_path=_readlink_deep(path)\n if new_path !=path:\n return join(new_path,tail)if tail else new_path\n except OSError:\n \n pass\n path,name=split(path)\n \n \n \n if path and not name:\n return path+tail\n tail=join(name,tail)if tail else name\n return tail\n \n def realpath(path,*,strict=False):\n path=normpath(path)\n if isinstance(path,bytes):\n prefix=b'\\\\\\\\?\\\\'\n unc_prefix=b'\\\\\\\\?\\\\UNC\\\\'\n new_unc_prefix=b'\\\\\\\\'\n cwd=os.getcwdb()\n \n if normcase(path)==normcase(os.fsencode(devnull)):\n return b'\\\\\\\\.\\\\NUL'\n else:\n prefix='\\\\\\\\?\\\\'\n unc_prefix='\\\\\\\\?\\\\UNC\\\\'\n new_unc_prefix='\\\\\\\\'\n cwd=os.getcwd()\n \n if normcase(path)==normcase(devnull):\n return '\\\\\\\\.\\\\NUL'\n had_prefix=path.startswith(prefix)\n if not had_prefix and not isabs(path):\n path=join(cwd,path)\n try:\n path=_getfinalpathname(path)\n initial_winerror=0\n except OSError as ex:\n if strict:\n raise\n initial_winerror=ex.winerror\n path=_getfinalpathname_nonstrict(path)\n \n \n \n if not had_prefix and path.startswith(prefix):\n \n \n if path.startswith(unc_prefix):\n spath=new_unc_prefix+path[len(unc_prefix):]\n else:\n spath=path[len(prefix):]\n \n try:\n if _getfinalpathname(spath)==path:\n path=spath\n except OSError as ex:\n \n \n if ex.winerror ==initial_winerror:\n path=spath\n return path\n \n \n \nsupports_unicode_filenames=True\n\ndef relpath(path,start=None):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n sep=b'\\\\'\n curdir=b'.'\n pardir=b'..'\n else:\n sep='\\\\'\n curdir='.'\n pardir='..'\n \n if start is None:\n start=curdir\n \n if not path:\n raise ValueError(\"no path specified\")\n \n start=os.fspath(start)\n try:\n start_abs=abspath(normpath(start))\n path_abs=abspath(normpath(path))\n start_drive,_,start_rest=splitroot(start_abs)\n path_drive,_,path_rest=splitroot(path_abs)\n if normcase(start_drive)!=normcase(path_drive):\n raise ValueError(\"path is on mount %r, start on mount %r\"%(\n path_drive,start_drive))\n \n start_list=[x for x in start_rest.split(sep)if x]\n path_list=[x for x in path_rest.split(sep)if x]\n \n i=0\n for e1,e2 in zip(start_list,path_list):\n if normcase(e1)!=normcase(e2):\n break\n i +=1\n \n rel_list=[pardir]*(len(start_list)-i)+path_list[i:]\n if not rel_list:\n return curdir\n return join(*rel_list)\n except(TypeError,ValueError,AttributeError,BytesWarning,DeprecationWarning):\n genericpath._check_arg_types('relpath',path,start)\n raise\n \n \n \n \n \n \n \n \n \n \n \n \ndef commonpath(paths):\n ''\n \n if not paths:\n raise ValueError('commonpath() arg is an empty sequence')\n \n paths=tuple(map(os.fspath,paths))\n if isinstance(paths[0],bytes):\n sep=b'\\\\'\n altsep=b'/'\n curdir=b'.'\n else:\n sep='\\\\'\n altsep='/'\n curdir='.'\n \n try:\n drivesplits=[splitroot(p.replace(altsep,sep).lower())for p in paths]\n split_paths=[p.split(sep)for d,r,p in drivesplits]\n \n if len({r for d,r,p in drivesplits})!=1:\n raise ValueError(\"Can't mix absolute and relative paths\")\n \n \n \n \n if len({d for d,r,p in drivesplits})!=1:\n raise ValueError(\"Paths don't have the same drive\")\n \n drive,root,path=splitroot(paths[0].replace(altsep,sep))\n common=path.split(sep)\n common=[c for c in common if c and c !=curdir]\n \n split_paths=[[c for c in s if c and c !=curdir]for s in split_paths]\n s1=min(split_paths)\n s2=max(split_paths)\n for i,c in enumerate(s1):\n if c !=s2[i]:\n common=common[:i]\n break\n else:\n common=common[:len(s1)]\n \n return drive+root+sep.join(common)\n except(TypeError,AttributeError):\n genericpath._check_arg_types('commonpath',*paths)\n raise\n \n \ntry:\n\n\n\n from nt import _path_isdir as isdir\n from nt import _path_isfile as isfile\n from nt import _path_islink as islink\n from nt import _path_exists as exists\nexcept ImportError:\n\n pass\n \n \ntry:\n from nt import _path_isdevdrive\nexcept ImportError:\n def isdevdrive(path):\n ''\n \n return False\nelse:\n def isdevdrive(path):\n ''\n try:\n return _path_isdevdrive(abspath(path))\n except OSError:\n return False\n", ["_winapi", "genericpath", "nt", "os", "stat", "string", "sys"]], "numbers": [".py", "\n\n\n\"\"\"Abstract Base Classes (ABCs) for numbers, according to PEP 3141.\n\nTODO: Fill out more detailed documentation on the operators.\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom abc import ABCMeta,abstractmethod\n\n__all__=[\"Number\",\"Complex\",\"Real\",\"Rational\",\"Integral\"]\n\nclass Number(metaclass=ABCMeta):\n ''\n\n\n\n \n __slots__=()\n \n \n __hash__=None\n \n \n \n \n \n \n \n \n \n \nclass Complex(Number):\n ''\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __complex__(self):\n ''\n \n def __bool__(self):\n ''\n return self !=0\n \n @property\n @abstractmethod\n def real(self):\n ''\n\n\n \n raise NotImplementedError\n \n @property\n @abstractmethod\n def imag(self):\n ''\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __add__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __radd__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __neg__(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __pos__(self):\n ''\n raise NotImplementedError\n \n def __sub__(self,other):\n ''\n return self+-other\n \n def __rsub__(self,other):\n ''\n return -self+other\n \n @abstractmethod\n def __mul__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rmul__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __truediv__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rtruediv__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __pow__(self,exponent):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rpow__(self,base):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __abs__(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def conjugate(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __eq__(self,other):\n ''\n raise NotImplementedError\n \nComplex.register(complex)\n\n\nclass Real(Complex):\n ''\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __float__(self):\n ''\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __trunc__(self):\n ''\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __floor__(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __ceil__(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __round__(self,ndigits=None):\n ''\n\n\n\n \n raise NotImplementedError\n \n def __divmod__(self,other):\n ''\n\n\n\n \n return(self //other,self %other)\n \n def __rdivmod__(self,other):\n ''\n\n\n\n \n return(other //self,other %self)\n \n @abstractmethod\n def __floordiv__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rfloordiv__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __mod__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rmod__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __lt__(self,other):\n ''\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __le__(self,other):\n ''\n raise NotImplementedError\n \n \n def __complex__(self):\n ''\n return complex(float(self))\n \n @property\n def real(self):\n ''\n return+self\n \n @property\n def imag(self):\n ''\n return 0\n \n def conjugate(self):\n ''\n return+self\n \nReal.register(float)\n\n\nclass Rational(Real):\n ''\n \n __slots__=()\n \n @property\n @abstractmethod\n def numerator(self):\n raise NotImplementedError\n \n @property\n @abstractmethod\n def denominator(self):\n raise NotImplementedError\n \n \n def __float__(self):\n ''\n\n\n\n\n\n \n return int(self.numerator)/int(self.denominator)\n \n \nclass Integral(Rational):\n ''\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __int__(self):\n ''\n raise NotImplementedError\n \n def __index__(self):\n ''\n return int(self)\n \n @abstractmethod\n def __pow__(self,exponent,modulus=None):\n ''\n\n\n\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __lshift__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rlshift__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rshift__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rrshift__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __and__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rand__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __xor__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rxor__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __or__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __ror__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __invert__(self):\n ''\n raise NotImplementedError\n \n \n def __float__(self):\n ''\n return float(int(self))\n \n @property\n def numerator(self):\n ''\n return+self\n \n @property\n def denominator(self):\n ''\n return 1\n \nIntegral.register(int)\n", ["abc"]], "opcode": [".py", "\n\"\"\"\nopcode module - potentially shared between dis and other modules which\noperate on bytecodes (e.g. peephole optimizers).\n\"\"\"\n\n\n__all__=[\"cmp_op\",\"stack_effect\",\"hascompare\",\"opname\",\"opmap\",\n\"HAVE_ARGUMENT\",\"EXTENDED_ARG\",\"hasarg\",\"hasconst\",\"hasname\",\n\"hasjump\",\"hasjrel\",\"hasjabs\",\"hasfree\",\"haslocal\",\"hasexc\"]\n\nimport _opcode\nfrom _opcode import stack_effect\n\nfrom _opcode_metadata import(_specializations,_specialized_opmap,opmap,\nHAVE_ARGUMENT,MIN_INSTRUMENTED_OPCODE)\nEXTENDED_ARG=opmap['EXTENDED_ARG']\n\nopname=['<%r>'%(op,)for op in range(max(opmap.values())+1)]\nfor op,i in opmap.items():\n opname[i]=op\n \ncmp_op=('<','<=','==','!=','>','>=')\n\n\nhasarg=[op for op in opmap.values()if _opcode.has_arg(op)]\nhasconst=[op for op in opmap.values()if _opcode.has_const(op)]\nhasname=[op for op in opmap.values()if _opcode.has_name(op)]\nhasjump=[op for op in opmap.values()if _opcode.has_jump(op)]\nhasjrel=hasjump\nhasjabs=[]\nhasfree=[op for op in opmap.values()if _opcode.has_free(op)]\nhaslocal=[op for op in opmap.values()if _opcode.has_local(op)]\nhasexc=[op for op in opmap.values()if _opcode.has_exc(op)]\n\n\n_intrinsic_1_descs=_opcode.get_intrinsic1_descs()\n_intrinsic_2_descs=_opcode.get_intrinsic2_descs()\n_nb_ops=_opcode.get_nb_ops()\n\nhascompare=[opmap[\"COMPARE_OP\"]]\n\n_cache_format={\n\"LOAD_GLOBAL\":{\n\"counter\":1,\n\"index\":1,\n\"module_keys_version\":1,\n\"builtin_keys_version\":1,\n},\n\"BINARY_OP\":{\n\"counter\":1,\n},\n\"UNPACK_SEQUENCE\":{\n\"counter\":1,\n},\n\"COMPARE_OP\":{\n\"counter\":1,\n},\n\"CONTAINS_OP\":{\n\"counter\":1,\n},\n\"BINARY_SUBSCR\":{\n\"counter\":1,\n},\n\"FOR_ITER\":{\n\"counter\":1,\n},\n\"LOAD_SUPER_ATTR\":{\n\"counter\":1,\n},\n\"LOAD_ATTR\":{\n\"counter\":1,\n\"version\":2,\n\"keys_version\":2,\n\"descr\":4,\n},\n\"STORE_ATTR\":{\n\"counter\":1,\n\"version\":2,\n\"index\":1,\n},\n\"CALL\":{\n\"counter\":1,\n\"func_version\":2,\n},\n\"STORE_SUBSCR\":{\n\"counter\":1,\n},\n\"SEND\":{\n\"counter\":1,\n},\n\"JUMP_BACKWARD\":{\n\"counter\":1,\n},\n\"TO_BOOL\":{\n\"counter\":1,\n\"version\":2,\n},\n\"POP_JUMP_IF_TRUE\":{\n\"counter\":1,\n},\n\"POP_JUMP_IF_FALSE\":{\n\"counter\":1,\n},\n\"POP_JUMP_IF_NONE\":{\n\"counter\":1,\n},\n\"POP_JUMP_IF_NOT_NONE\":{\n\"counter\":1,\n},\n}\n\n_inline_cache_entries={\nname:sum(value.values())for(name,value)in _cache_format.items()\n}\n", ["_opcode", "_opcode_metadata"]], "operator": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n__all__=['abs','add','and_','attrgetter','call','concat','contains','countOf',\n'delitem','eq','floordiv','ge','getitem','gt','iadd','iand',\n'iconcat','ifloordiv','ilshift','imatmul','imod','imul',\n'index','indexOf','inv','invert','ior','ipow','irshift',\n'is_','is_not','isub','itemgetter','itruediv','ixor','le',\n'length_hint','lshift','lt','matmul','methodcaller','mod',\n'mul','ne','neg','not_','or_','pos','pow','rshift',\n'setitem','sub','truediv','truth','xor']\n\nfrom builtins import abs as _abs\n\n\n\n\ndef lt(a,b):\n ''\n return a =b\n \ndef gt(a,b):\n ''\n return a >b\n \n \n \ndef not_(a):\n ''\n return not a\n \ndef truth(a):\n ''\n return True if a else False\n \ndef is_(a,b):\n ''\n return a is b\n \ndef is_not(a,b):\n ''\n return a is not b\n \n \n \ndef abs(a):\n ''\n return _abs(a)\n \ndef add(a,b):\n ''\n return a+b\n \ndef and_(a,b):\n ''\n return a&b\n \ndef floordiv(a,b):\n ''\n return a //b\n \ndef index(a):\n ''\n return a.__index__()\n \ndef inv(a):\n ''\n return ~a\ninvert=inv\n\ndef lshift(a,b):\n ''\n return a <>b\n \ndef sub(a,b):\n ''\n return a -b\n \ndef truediv(a,b):\n ''\n return a /b\n \ndef xor(a,b):\n ''\n return a ^b\n \n \n \ndef concat(a,b):\n ''\n if not hasattr(a,'__getitem__'):\n msg=\"'%s' object can't be concatenated\"%type(a).__name__\n raise TypeError(msg)\n return a+b\n \ndef contains(a,b):\n ''\n return b in a\n \ndef countOf(a,b):\n ''\n count=0\n for i in a:\n if i is b or i ==b:\n count +=1\n return count\n \ndef delitem(a,b):\n ''\n del a[b]\n \ndef getitem(a,b):\n ''\n return a[b]\n \ndef indexOf(a,b):\n ''\n for i,j in enumerate(a):\n if j is b or j ==b:\n return i\n else:\n raise ValueError('sequence.index(x): x not in sequence')\n \ndef setitem(a,b,c):\n ''\n a[b]=c\n \ndef length_hint(obj,default=0):\n ''\n\n\n\n\n\n\n \n if not isinstance(default,int):\n msg=(\"'%s' object cannot be interpreted as an integer\"%\n type(default).__name__)\n raise TypeError(msg)\n \n try:\n return len(obj)\n except TypeError:\n pass\n \n try:\n hint=type(obj).__length_hint__\n except AttributeError:\n return default\n \n try:\n val=hint(obj)\n except TypeError:\n return default\n if val is NotImplemented:\n return default\n if not isinstance(val,int):\n msg=('__length_hint__ must be integer, not %s'%\n type(val).__name__)\n raise TypeError(msg)\n if val <0:\n msg='__length_hint__() should return >= 0'\n raise ValueError(msg)\n return val\n \n \n \ndef call(obj,/,*args,**kwargs):\n ''\n return obj(*args,**kwargs)\n \n \n \nclass attrgetter:\n ''\n\n\n\n\n\n \n __slots__=('_attrs','_call')\n \n def __init__(self,attr,/,*attrs):\n if not attrs:\n if not isinstance(attr,str):\n raise TypeError('attribute name must be a string')\n self._attrs=(attr,)\n names=attr.split('.')\n def func(obj):\n for name in names:\n obj=getattr(obj,name)\n return obj\n self._call=func\n else:\n self._attrs=(attr,)+attrs\n getters=tuple(map(attrgetter,self._attrs))\n def func(obj):\n return tuple(getter(obj)for getter in getters)\n self._call=func\n \n def __call__(self,obj,/):\n return self._call(obj)\n \n def __repr__(self):\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__qualname__,\n ', '.join(map(repr,self._attrs)))\n \n def __reduce__(self):\n return self.__class__,self._attrs\n \nclass itemgetter:\n ''\n\n\n\n \n __slots__=('_items','_call')\n \n def __init__(self,item,/,*items):\n if not items:\n self._items=(item,)\n def func(obj):\n return obj[item]\n self._call=func\n else:\n self._items=items=(item,)+items\n def func(obj):\n return tuple(obj[i]for i in items)\n self._call=func\n \n def __call__(self,obj,/):\n return self._call(obj)\n \n def __repr__(self):\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__name__,\n ', '.join(map(repr,self._items)))\n \n def __reduce__(self):\n return self.__class__,self._items\n \nclass methodcaller:\n ''\n\n\n\n\n \n __slots__=('_name','_args','_kwargs')\n \n def __init__(self,name,/,*args,**kwargs):\n self._name=name\n if not isinstance(self._name,str):\n raise TypeError('method name must be a string')\n self._args=args\n self._kwargs=kwargs\n \n def __call__(self,obj,/):\n return getattr(obj,self._name)(*self._args,**self._kwargs)\n \n def __repr__(self):\n args=[repr(self._name)]\n args.extend(map(repr,self._args))\n args.extend('%s=%r'%(k,v)for k,v in self._kwargs.items())\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__name__,\n ', '.join(args))\n \n def __reduce__(self):\n if not self._kwargs:\n return self.__class__,(self._name,)+self._args\n else:\n from functools import partial\n return partial(self.__class__,self._name,**self._kwargs),self._args\n \n \n \n \ndef iadd(a,b):\n ''\n a +=b\n return a\n \ndef iand(a,b):\n ''\n a &=b\n return a\n \ndef iconcat(a,b):\n ''\n if not hasattr(a,'__getitem__'):\n msg=\"'%s' object can't be concatenated\"%type(a).__name__\n raise TypeError(msg)\n a +=b\n return a\n \ndef ifloordiv(a,b):\n ''\n a //=b\n return a\n \ndef ilshift(a,b):\n ''\n a <<=b\n return a\n \ndef imod(a,b):\n ''\n a %=b\n return a\n \ndef imul(a,b):\n ''\n a *=b\n return a\n \ndef imatmul(a,b):\n ''\n a @=b\n return a\n \ndef ior(a,b):\n ''\n a |=b\n return a\n \ndef ipow(a,b):\n ''\n a **=b\n return a\n \ndef irshift(a,b):\n ''\n a >>=b\n return a\n \ndef isub(a,b):\n ''\n a -=b\n return a\n \ndef itruediv(a,b):\n ''\n a /=b\n return a\n \ndef ixor(a,b):\n ''\n a ^=b\n return a\n \n \ntry:\n from _operator import *\nexcept ImportError:\n pass\nelse:\n from _operator import __doc__\n \n \n \n__lt__=lt\n__le__=le\n__eq__=eq\n__ne__=ne\n__ge__=ge\n__gt__=gt\n__not__=not_\n__abs__=abs\n__add__=add\n__and__=and_\n__call__=call\n__floordiv__=floordiv\n__index__=index\n__inv__=inv\n__invert__=invert\n__lshift__=lshift\n__mod__=mod\n__mul__=mul\n__matmul__=matmul\n__neg__=neg\n__or__=or_\n__pos__=pos\n__pow__=pow\n__rshift__=rshift\n__sub__=sub\n__truediv__=truediv\n__xor__=xor\n__concat__=concat\n__contains__=contains\n__delitem__=delitem\n__getitem__=getitem\n__setitem__=setitem\n__iadd__=iadd\n__iand__=iand\n__iconcat__=iconcat\n__ifloordiv__=ifloordiv\n__ilshift__=ilshift\n__imod__=imod\n__imul__=imul\n__imatmul__=imatmul\n__ior__=ior\n__ipow__=ipow\n__irshift__=irshift\n__isub__=isub\n__itruediv__=itruediv\n__ixor__=ixor\n", ["_operator", "builtins", "functools"]], "optparse": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__=\"1.5.3\"\n\n__all__=['Option',\n'make_option',\n'SUPPRESS_HELP',\n'SUPPRESS_USAGE',\n'Values',\n'OptionContainer',\n'OptionGroup',\n'OptionParser',\n'HelpFormatter',\n'IndentedHelpFormatter',\n'TitledHelpFormatter',\n'OptParseError',\n'OptionError',\n'OptionConflictError',\n'OptionValueError',\n'BadOptionError',\n'check_choice']\n\n__copyright__=\"\"\"\nCopyright (c) 2001-2006 Gregory P. Ward. All rights reserved.\nCopyright (c) 2002-2006 Python Software Foundation. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport sys,os\nimport textwrap\n\ndef _repr(self):\n return \"<%s at 0x%x: %s>\"%(self.__class__.__name__,id(self),self)\n \n \n \n \n \n \n \n \ntry:\n from gettext import gettext,ngettext\nexcept ImportError:\n def gettext(message):\n return message\n \n def ngettext(singular,plural,n):\n if n ==1:\n return singular\n return plural\n \n_=gettext\n\n\nclass OptParseError(Exception):\n def __init__(self,msg):\n self.msg=msg\n \n def __str__(self):\n return self.msg\n \n \nclass OptionError(OptParseError):\n ''\n\n\n \n \n def __init__(self,msg,option):\n self.msg=msg\n self.option_id=str(option)\n \n def __str__(self):\n if self.option_id:\n return \"option %s: %s\"%(self.option_id,self.msg)\n else:\n return self.msg\n \nclass OptionConflictError(OptionError):\n ''\n\n \n \nclass OptionValueError(OptParseError):\n ''\n\n\n \n \nclass BadOptionError(OptParseError):\n ''\n\n \n def __init__(self,opt_str):\n self.opt_str=opt_str\n \n def __str__(self):\n return _(\"no such option: %s\")%self.opt_str\n \nclass AmbiguousOptionError(BadOptionError):\n ''\n\n \n def __init__(self,opt_str,possibilities):\n BadOptionError.__init__(self,opt_str)\n self.possibilities=possibilities\n \n def __str__(self):\n return(_(\"ambiguous option: %s (%s?)\")\n %(self.opt_str,\", \".join(self.possibilities)))\n \n \nclass HelpFormatter:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n NO_DEFAULT_VALUE=\"none\"\n \n def __init__(self,\n indent_increment,\n max_help_position,\n width,\n short_first):\n self.parser=None\n self.indent_increment=indent_increment\n if width is None:\n try:\n width=int(os.environ['COLUMNS'])\n except(KeyError,ValueError):\n width=80\n width -=2\n self.width=width\n self.help_position=self.max_help_position=\\\n min(max_help_position,max(width -20,indent_increment *2))\n self.current_indent=0\n self.level=0\n self.help_width=None\n self.short_first=short_first\n self.default_tag=\"%default\"\n self.option_strings={}\n self._short_opt_fmt=\"%s %s\"\n self._long_opt_fmt=\"%s=%s\"\n \n def set_parser(self,parser):\n self.parser=parser\n \n def set_short_opt_delimiter(self,delim):\n if delim not in(\"\",\" \"):\n raise ValueError(\n \"invalid metavar delimiter for short options: %r\"%delim)\n self._short_opt_fmt=\"%s\"+delim+\"%s\"\n \n def set_long_opt_delimiter(self,delim):\n if delim not in(\"=\",\" \"):\n raise ValueError(\n \"invalid metavar delimiter for long options: %r\"%delim)\n self._long_opt_fmt=\"%s\"+delim+\"%s\"\n \n def indent(self):\n self.current_indent +=self.indent_increment\n self.level +=1\n \n def dedent(self):\n self.current_indent -=self.indent_increment\n assert self.current_indent >=0,\"Indent decreased below 0.\"\n self.level -=1\n \n def format_usage(self,usage):\n raise NotImplementedError(\"subclasses must implement\")\n \n def format_heading(self,heading):\n raise NotImplementedError(\"subclasses must implement\")\n \n def _format_text(self,text):\n ''\n\n\n \n text_width=max(self.width -self.current_indent,11)\n indent=\" \"*self.current_indent\n return textwrap.fill(text,\n text_width,\n initial_indent=indent,\n subsequent_indent=indent)\n \n def format_description(self,description):\n if description:\n return self._format_text(description)+\"\\n\"\n else:\n return \"\"\n \n def format_epilog(self,epilog):\n if epilog:\n return \"\\n\"+self._format_text(epilog)+\"\\n\"\n else:\n return \"\"\n \n \n def expand_default(self,option):\n if self.parser is None or not self.default_tag:\n return option.help\n \n default_value=self.parser.defaults.get(option.dest)\n if default_value is NO_DEFAULT or default_value is None:\n default_value=self.NO_DEFAULT_VALUE\n \n return option.help.replace(self.default_tag,str(default_value))\n \n def format_option(self,option):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n result=[]\n opts=self.option_strings[option]\n opt_width=self.help_position -self.current_indent -2\n if len(opts)>opt_width:\n opts=\"%*s%s\\n\"%(self.current_indent,\"\",opts)\n indent_first=self.help_position\n else:\n opts=\"%*s%-*s \"%(self.current_indent,\"\",opt_width,opts)\n indent_first=0\n result.append(opts)\n if option.help:\n help_text=self.expand_default(option)\n help_lines=textwrap.wrap(help_text,self.help_width)\n result.append(\"%*s%s\\n\"%(indent_first,\"\",help_lines[0]))\n result.extend([\"%*s%s\\n\"%(self.help_position,\"\",line)\n for line in help_lines[1:]])\n elif opts[-1]!=\"\\n\":\n result.append(\"\\n\")\n return \"\".join(result)\n \n def store_option_strings(self,parser):\n self.indent()\n max_len=0\n for opt in parser.option_list:\n strings=self.format_option_strings(opt)\n self.option_strings[opt]=strings\n max_len=max(max_len,len(strings)+self.current_indent)\n self.indent()\n for group in parser.option_groups:\n for opt in group.option_list:\n strings=self.format_option_strings(opt)\n self.option_strings[opt]=strings\n max_len=max(max_len,len(strings)+self.current_indent)\n self.dedent()\n self.dedent()\n self.help_position=min(max_len+2,self.max_help_position)\n self.help_width=max(self.width -self.help_position,11)\n \n def format_option_strings(self,option):\n ''\n if option.takes_value():\n metavar=option.metavar or option.dest.upper()\n short_opts=[self._short_opt_fmt %(sopt,metavar)\n for sopt in option._short_opts]\n long_opts=[self._long_opt_fmt %(lopt,metavar)\n for lopt in option._long_opts]\n else:\n short_opts=option._short_opts\n long_opts=option._long_opts\n \n if self.short_first:\n opts=short_opts+long_opts\n else:\n opts=long_opts+short_opts\n \n return \", \".join(opts)\n \nclass IndentedHelpFormatter(HelpFormatter):\n ''\n \n \n def __init__(self,\n indent_increment=2,\n max_help_position=24,\n width=None,\n short_first=1):\n HelpFormatter.__init__(\n self,indent_increment,max_help_position,width,short_first)\n \n def format_usage(self,usage):\n return _(\"Usage: %s\\n\")%usage\n \n def format_heading(self,heading):\n return \"%*s%s:\\n\"%(self.current_indent,\"\",heading)\n \n \nclass TitledHelpFormatter(HelpFormatter):\n ''\n \n \n def __init__(self,\n indent_increment=0,\n max_help_position=24,\n width=None,\n short_first=0):\n HelpFormatter.__init__(\n self,indent_increment,max_help_position,width,short_first)\n \n def format_usage(self,usage):\n return \"%s %s\\n\"%(self.format_heading(_(\"Usage\")),usage)\n \n def format_heading(self,heading):\n return \"%s\\n%s\\n\"%(heading,\"=-\"[self.level]*len(heading))\n \n \ndef _parse_num(val,type):\n if val[:2].lower()==\"0x\":\n radix=16\n elif val[:2].lower()==\"0b\":\n radix=2\n val=val[2:]or \"0\"\n elif val[:1]==\"0\":\n radix=8\n else:\n radix=10\n \n return type(val,radix)\n \ndef _parse_int(val):\n return _parse_num(val,int)\n \n_builtin_cvt={\"int\":(_parse_int,_(\"integer\")),\n\"long\":(_parse_int,_(\"integer\")),\n\"float\":(float,_(\"floating-point\")),\n\"complex\":(complex,_(\"complex\"))}\n\ndef check_builtin(option,opt,value):\n (cvt,what)=_builtin_cvt[option.type]\n try:\n return cvt(value)\n except ValueError:\n raise OptionValueError(\n _(\"option %s: invalid %s value: %r\")%(opt,what,value))\n \ndef check_choice(option,opt,value):\n if value in option.choices:\n return value\n else:\n choices=\", \".join(map(repr,option.choices))\n raise OptionValueError(\n _(\"option %s: invalid choice: %r (choose from %s)\")\n %(opt,value,choices))\n \n \n \nNO_DEFAULT=(\"NO\",\"DEFAULT\")\n\n\nclass Option:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n ATTRS=['action',\n 'type',\n 'dest',\n 'default',\n 'nargs',\n 'const',\n 'choices',\n 'callback',\n 'callback_args',\n 'callback_kwargs',\n 'help',\n 'metavar']\n \n \n \n ACTIONS=(\"store\",\n \"store_const\",\n \"store_true\",\n \"store_false\",\n \"append\",\n \"append_const\",\n \"count\",\n \"callback\",\n \"help\",\n \"version\")\n \n \n \n \n STORE_ACTIONS=(\"store\",\n \"store_const\",\n \"store_true\",\n \"store_false\",\n \"append\",\n \"append_const\",\n \"count\")\n \n \n \n TYPED_ACTIONS=(\"store\",\n \"append\",\n \"callback\")\n \n \n \n ALWAYS_TYPED_ACTIONS=(\"store\",\n \"append\")\n \n \n CONST_ACTIONS=(\"store_const\",\n \"append_const\")\n \n \n \n TYPES=(\"string\",\"int\",\"long\",\"float\",\"complex\",\"choice\")\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n TYPE_CHECKER={\"int\":check_builtin,\n \"long\":check_builtin,\n \"float\":check_builtin,\n \"complex\":check_builtin,\n \"choice\":check_choice,\n }\n \n \n \n \n \n \n \n \n \n \n CHECK_METHODS=None\n \n \n \n \n def __init__(self,*opts,**attrs):\n \n \n self._short_opts=[]\n self._long_opts=[]\n opts=self._check_opt_strings(opts)\n self._set_opt_strings(opts)\n \n \n self._set_attrs(attrs)\n \n \n \n \n \n \n for checker in self.CHECK_METHODS:\n checker(self)\n \n def _check_opt_strings(self,opts):\n \n \n \n opts=[opt for opt in opts if opt]\n if not opts:\n raise TypeError(\"at least one option string must be supplied\")\n return opts\n \n def _set_opt_strings(self,opts):\n for opt in opts:\n if len(opt)<2:\n raise OptionError(\n \"invalid option string %r: \"\n \"must be at least two characters long\"%opt,self)\n elif len(opt)==2:\n if not(opt[0]==\"-\"and opt[1]!=\"-\"):\n raise OptionError(\n \"invalid short option string %r: \"\n \"must be of the form -x, (x any non-dash char)\"%opt,\n self)\n self._short_opts.append(opt)\n else:\n if not(opt[0:2]==\"--\"and opt[2]!=\"-\"):\n raise OptionError(\n \"invalid long option string %r: \"\n \"must start with --, followed by non-dash\"%opt,\n self)\n self._long_opts.append(opt)\n \n def _set_attrs(self,attrs):\n for attr in self.ATTRS:\n if attr in attrs:\n setattr(self,attr,attrs[attr])\n del attrs[attr]\n else:\n if attr =='default':\n setattr(self,attr,NO_DEFAULT)\n else:\n setattr(self,attr,None)\n if attrs:\n attrs=sorted(attrs.keys())\n raise OptionError(\n \"invalid keyword arguments: %s\"%\", \".join(attrs),\n self)\n \n \n \n \n def _check_action(self):\n if self.action is None:\n self.action=\"store\"\n elif self.action not in self.ACTIONS:\n raise OptionError(\"invalid action: %r\"%self.action,self)\n \n def _check_type(self):\n if self.type is None:\n if self.action in self.ALWAYS_TYPED_ACTIONS:\n if self.choices is not None:\n \n self.type=\"choice\"\n else:\n \n self.type=\"string\"\n else:\n \n \n if isinstance(self.type,type):\n self.type=self.type.__name__\n \n if self.type ==\"str\":\n self.type=\"string\"\n \n if self.type not in self.TYPES:\n raise OptionError(\"invalid option type: %r\"%self.type,self)\n if self.action not in self.TYPED_ACTIONS:\n raise OptionError(\n \"must not supply a type for action %r\"%self.action,self)\n \n def _check_choice(self):\n if self.type ==\"choice\":\n if self.choices is None:\n raise OptionError(\n \"must supply a list of choices for type 'choice'\",self)\n elif not isinstance(self.choices,(tuple,list)):\n raise OptionError(\n \"choices must be a list of strings ('%s' supplied)\"\n %str(type(self.choices)).split(\"'\")[1],self)\n elif self.choices is not None:\n raise OptionError(\n \"must not supply choices for type %r\"%self.type,self)\n \n def _check_dest(self):\n \n \n takes_value=(self.action in self.STORE_ACTIONS or\n self.type is not None)\n if self.dest is None and takes_value:\n \n \n \n if self._long_opts:\n \n self.dest=self._long_opts[0][2:].replace('-','_')\n else:\n self.dest=self._short_opts[0][1]\n \n def _check_const(self):\n if self.action not in self.CONST_ACTIONS and self.const is not None:\n raise OptionError(\n \"'const' must not be supplied for action %r\"%self.action,\n self)\n \n def _check_nargs(self):\n if self.action in self.TYPED_ACTIONS:\n if self.nargs is None:\n self.nargs=1\n elif self.nargs is not None:\n raise OptionError(\n \"'nargs' must not be supplied for action %r\"%self.action,\n self)\n \n def _check_callback(self):\n if self.action ==\"callback\":\n if not callable(self.callback):\n raise OptionError(\n \"callback not callable: %r\"%self.callback,self)\n if(self.callback_args is not None and\n not isinstance(self.callback_args,tuple)):\n raise OptionError(\n \"callback_args, if supplied, must be a tuple: not %r\"\n %self.callback_args,self)\n if(self.callback_kwargs is not None and\n not isinstance(self.callback_kwargs,dict)):\n raise OptionError(\n \"callback_kwargs, if supplied, must be a dict: not %r\"\n %self.callback_kwargs,self)\n else:\n if self.callback is not None:\n raise OptionError(\n \"callback supplied (%r) for non-callback option\"\n %self.callback,self)\n if self.callback_args is not None:\n raise OptionError(\n \"callback_args supplied for non-callback option\",self)\n if self.callback_kwargs is not None:\n raise OptionError(\n \"callback_kwargs supplied for non-callback option\",self)\n \n \n CHECK_METHODS=[_check_action,\n _check_type,\n _check_choice,\n _check_dest,\n _check_const,\n _check_nargs,\n _check_callback]\n \n \n \n \n def __str__(self):\n return \"/\".join(self._short_opts+self._long_opts)\n \n __repr__=_repr\n \n def takes_value(self):\n return self.type is not None\n \n def get_opt_string(self):\n if self._long_opts:\n return self._long_opts[0]\n else:\n return self._short_opts[0]\n \n \n \n \n def check_value(self,opt,value):\n checker=self.TYPE_CHECKER.get(self.type)\n if checker is None:\n return value\n else:\n return checker(self,opt,value)\n \n def convert_value(self,opt,value):\n if value is not None:\n if self.nargs ==1:\n return self.check_value(opt,value)\n else:\n return tuple([self.check_value(opt,v)for v in value])\n \n def process(self,opt,value,values,parser):\n \n \n \n value=self.convert_value(opt,value)\n \n \n \n \n return self.take_action(\n self.action,self.dest,opt,value,values,parser)\n \n def take_action(self,action,dest,opt,value,values,parser):\n if action ==\"store\":\n setattr(values,dest,value)\n elif action ==\"store_const\":\n setattr(values,dest,self.const)\n elif action ==\"store_true\":\n setattr(values,dest,True)\n elif action ==\"store_false\":\n setattr(values,dest,False)\n elif action ==\"append\":\n values.ensure_value(dest,[]).append(value)\n elif action ==\"append_const\":\n values.ensure_value(dest,[]).append(self.const)\n elif action ==\"count\":\n setattr(values,dest,values.ensure_value(dest,0)+1)\n elif action ==\"callback\":\n args=self.callback_args or()\n kwargs=self.callback_kwargs or{}\n self.callback(self,opt,value,parser,*args,**kwargs)\n elif action ==\"help\":\n parser.print_help()\n parser.exit()\n elif action ==\"version\":\n parser.print_version()\n parser.exit()\n else:\n raise ValueError(\"unknown action %r\"%self.action)\n \n return 1\n \n \n \n \nSUPPRESS_HELP=\"SUPPRESS\"+\"HELP\"\nSUPPRESS_USAGE=\"SUPPRESS\"+\"USAGE\"\n\nclass Values:\n\n def __init__(self,defaults=None):\n if defaults:\n for(attr,val)in defaults.items():\n setattr(self,attr,val)\n \n def __str__(self):\n return str(self.__dict__)\n \n __repr__=_repr\n \n def __eq__(self,other):\n if isinstance(other,Values):\n return self.__dict__ ==other.__dict__\n elif isinstance(other,dict):\n return self.__dict__ ==other\n else:\n return NotImplemented\n \n def _update_careful(self,dict):\n ''\n\n\n\n\n \n for attr in dir(self):\n if attr in dict:\n dval=dict[attr]\n if dval is not None:\n setattr(self,attr,dval)\n \n def _update_loose(self,dict):\n ''\n\n\n\n \n self.__dict__.update(dict)\n \n def _update(self,dict,mode):\n if mode ==\"careful\":\n self._update_careful(dict)\n elif mode ==\"loose\":\n self._update_loose(dict)\n else:\n raise ValueError(\"invalid update mode: %r\"%mode)\n \n def read_module(self,modname,mode=\"careful\"):\n __import__(modname)\n mod=sys.modules[modname]\n self._update(vars(mod),mode)\n \n def read_file(self,filename,mode=\"careful\"):\n vars={}\n exec(open(filename).read(),vars)\n self._update(vars,mode)\n \n def ensure_value(self,attr,value):\n if not hasattr(self,attr)or getattr(self,attr)is None:\n setattr(self,attr,value)\n return getattr(self,attr)\n \n \nclass OptionContainer:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,option_class,conflict_handler,description):\n \n \n \n \n self._create_option_list()\n \n self.option_class=option_class\n self.set_conflict_handler(conflict_handler)\n self.set_description(description)\n \n def _create_option_mappings(self):\n \n \n \n self._short_opt={}\n self._long_opt={}\n self.defaults={}\n \n \n def _share_option_mappings(self,parser):\n \n \n self._short_opt=parser._short_opt\n self._long_opt=parser._long_opt\n self.defaults=parser.defaults\n \n def set_conflict_handler(self,handler):\n if handler not in(\"error\",\"resolve\"):\n raise ValueError(\"invalid conflict_resolution value %r\"%handler)\n self.conflict_handler=handler\n \n def set_description(self,description):\n self.description=description\n \n def get_description(self):\n return self.description\n \n \n def destroy(self):\n ''\n del self._short_opt\n del self._long_opt\n del self.defaults\n \n \n \n \n def _check_conflict(self,option):\n conflict_opts=[]\n for opt in option._short_opts:\n if opt in self._short_opt:\n conflict_opts.append((opt,self._short_opt[opt]))\n for opt in option._long_opts:\n if opt in self._long_opt:\n conflict_opts.append((opt,self._long_opt[opt]))\n \n if conflict_opts:\n handler=self.conflict_handler\n if handler ==\"error\":\n raise OptionConflictError(\n \"conflicting option string(s): %s\"\n %\", \".join([co[0]for co in conflict_opts]),\n option)\n elif handler ==\"resolve\":\n for(opt,c_option)in conflict_opts:\n if opt.startswith(\"--\"):\n c_option._long_opts.remove(opt)\n del self._long_opt[opt]\n else:\n c_option._short_opts.remove(opt)\n del self._short_opt[opt]\n if not(c_option._short_opts or c_option._long_opts):\n c_option.container.option_list.remove(c_option)\n \n def add_option(self,*args,**kwargs):\n ''\n\n \n if isinstance(args[0],str):\n option=self.option_class(*args,**kwargs)\n elif len(args)==1 and not kwargs:\n option=args[0]\n if not isinstance(option,Option):\n raise TypeError(\"not an Option instance: %r\"%option)\n else:\n raise TypeError(\"invalid arguments\")\n \n self._check_conflict(option)\n \n self.option_list.append(option)\n option.container=self\n for opt in option._short_opts:\n self._short_opt[opt]=option\n for opt in option._long_opts:\n self._long_opt[opt]=option\n \n if option.dest is not None:\n if option.default is not NO_DEFAULT:\n self.defaults[option.dest]=option.default\n elif option.dest not in self.defaults:\n self.defaults[option.dest]=None\n \n return option\n \n def add_options(self,option_list):\n for option in option_list:\n self.add_option(option)\n \n \n \n def get_option(self,opt_str):\n return(self._short_opt.get(opt_str)or\n self._long_opt.get(opt_str))\n \n def has_option(self,opt_str):\n return(opt_str in self._short_opt or\n opt_str in self._long_opt)\n \n def remove_option(self,opt_str):\n option=self._short_opt.get(opt_str)\n if option is None:\n option=self._long_opt.get(opt_str)\n if option is None:\n raise ValueError(\"no such option %r\"%opt_str)\n \n for opt in option._short_opts:\n del self._short_opt[opt]\n for opt in option._long_opts:\n del self._long_opt[opt]\n option.container.option_list.remove(option)\n \n \n \n \n def format_option_help(self,formatter):\n if not self.option_list:\n return \"\"\n result=[]\n for option in self.option_list:\n if not option.help is SUPPRESS_HELP:\n result.append(formatter.format_option(option))\n return \"\".join(result)\n \n def format_description(self,formatter):\n return formatter.format_description(self.get_description())\n \n def format_help(self,formatter):\n result=[]\n if self.description:\n result.append(self.format_description(formatter))\n if self.option_list:\n result.append(self.format_option_help(formatter))\n return \"\\n\".join(result)\n \n \nclass OptionGroup(OptionContainer):\n\n def __init__(self,parser,title,description=None):\n self.parser=parser\n OptionContainer.__init__(\n self,parser.option_class,parser.conflict_handler,description)\n self.title=title\n \n def _create_option_list(self):\n self.option_list=[]\n self._share_option_mappings(self.parser)\n \n def set_title(self,title):\n self.title=title\n \n def destroy(self):\n ''\n OptionContainer.destroy(self)\n del self.option_list\n \n \n \n def format_help(self,formatter):\n result=formatter.format_heading(self.title)\n formatter.indent()\n result +=OptionContainer.format_help(self,formatter)\n formatter.dedent()\n return result\n \n \nclass OptionParser(OptionContainer):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n standard_option_list=[]\n \n def __init__(self,\n usage=None,\n option_list=None,\n option_class=Option,\n version=None,\n conflict_handler=\"error\",\n description=None,\n formatter=None,\n add_help_option=True,\n prog=None,\n epilog=None):\n OptionContainer.__init__(\n self,option_class,conflict_handler,description)\n self.set_usage(usage)\n self.prog=prog\n self.version=version\n self.allow_interspersed_args=True\n self.process_default_values=True\n if formatter is None:\n formatter=IndentedHelpFormatter()\n self.formatter=formatter\n self.formatter.set_parser(self)\n self.epilog=epilog\n \n \n \n \n \n self._populate_option_list(option_list,\n add_help=add_help_option)\n \n self._init_parsing_state()\n \n \n def destroy(self):\n ''\n\n\n\n\n \n OptionContainer.destroy(self)\n for group in self.option_groups:\n group.destroy()\n del self.option_list\n del self.option_groups\n del self.formatter\n \n \n \n \n \n def _create_option_list(self):\n self.option_list=[]\n self.option_groups=[]\n self._create_option_mappings()\n \n def _add_help_option(self):\n self.add_option(\"-h\",\"--help\",\n action=\"help\",\n help=_(\"show this help message and exit\"))\n \n def _add_version_option(self):\n self.add_option(\"--version\",\n action=\"version\",\n help=_(\"show program's version number and exit\"))\n \n def _populate_option_list(self,option_list,add_help=True):\n if self.standard_option_list:\n self.add_options(self.standard_option_list)\n if option_list:\n self.add_options(option_list)\n if self.version:\n self._add_version_option()\n if add_help:\n self._add_help_option()\n \n def _init_parsing_state(self):\n \n self.rargs=None\n self.largs=None\n self.values=None\n \n \n \n \n def set_usage(self,usage):\n if usage is None:\n self.usage=_(\"%prog [options]\")\n elif usage is SUPPRESS_USAGE:\n self.usage=None\n \n elif usage.lower().startswith(\"usage: \"):\n self.usage=usage[7:]\n else:\n self.usage=usage\n \n def enable_interspersed_args(self):\n ''\n\n\n\n \n self.allow_interspersed_args=True\n \n def disable_interspersed_args(self):\n ''\n\n\n\n \n self.allow_interspersed_args=False\n \n def set_process_default_values(self,process):\n self.process_default_values=process\n \n def set_default(self,dest,value):\n self.defaults[dest]=value\n \n def set_defaults(self,**kwargs):\n self.defaults.update(kwargs)\n \n def _get_all_options(self):\n options=self.option_list[:]\n for group in self.option_groups:\n options.extend(group.option_list)\n return options\n \n def get_default_values(self):\n if not self.process_default_values:\n \n return Values(self.defaults)\n \n defaults=self.defaults.copy()\n for option in self._get_all_options():\n default=defaults.get(option.dest)\n if isinstance(default,str):\n opt_str=option.get_opt_string()\n defaults[option.dest]=option.check_value(opt_str,default)\n \n return Values(defaults)\n \n \n \n \n def add_option_group(self,*args,**kwargs):\n \n if isinstance(args[0],str):\n group=OptionGroup(self,*args,**kwargs)\n elif len(args)==1 and not kwargs:\n group=args[0]\n if not isinstance(group,OptionGroup):\n raise TypeError(\"not an OptionGroup instance: %r\"%group)\n if group.parser is not self:\n raise ValueError(\"invalid OptionGroup (wrong parser)\")\n else:\n raise TypeError(\"invalid arguments\")\n \n self.option_groups.append(group)\n return group\n \n def get_option_group(self,opt_str):\n option=(self._short_opt.get(opt_str)or\n self._long_opt.get(opt_str))\n if option and option.container is not self:\n return option.container\n return None\n \n \n \n \n def _get_args(self,args):\n if args is None:\n return sys.argv[1:]\n else:\n return args[:]\n \n def parse_args(self,args=None,values=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n rargs=self._get_args(args)\n if values is None:\n values=self.get_default_values()\n \n \n \n \n \n \n \n \n \n \n self.rargs=rargs\n self.largs=largs=[]\n self.values=values\n \n try:\n stop=self._process_args(largs,rargs,values)\n except(BadOptionError,OptionValueError)as err:\n self.error(str(err))\n \n args=largs+rargs\n return self.check_values(values,args)\n \n def check_values(self,values,args):\n ''\n\n\n\n\n\n\n\n\n \n return(values,args)\n \n def _process_args(self,largs,rargs,values):\n ''\n\n\n\n\n\n\n\n \n while rargs:\n arg=rargs[0]\n \n \n \n if arg ==\"--\":\n del rargs[0]\n return\n elif arg[0:2]==\"--\":\n \n self._process_long_opt(rargs,values)\n elif arg[:1]==\"-\"and len(arg)>1:\n \n \n self._process_short_opts(rargs,values)\n elif self.allow_interspersed_args:\n largs.append(arg)\n del rargs[0]\n else:\n return\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def _match_long_opt(self,opt):\n ''\n\n\n\n\n \n return _match_abbrev(opt,self._long_opt)\n \n def _process_long_opt(self,rargs,values):\n arg=rargs.pop(0)\n \n \n \n if \"=\"in arg:\n (opt,next_arg)=arg.split(\"=\",1)\n rargs.insert(0,next_arg)\n had_explicit_value=True\n else:\n opt=arg\n had_explicit_value=False\n \n opt=self._match_long_opt(opt)\n option=self._long_opt[opt]\n if option.takes_value():\n nargs=option.nargs\n if len(rargs)\".format(self.path)\n return \"\"\n \n def add_dll_directory(path):\n ''\n\n\n\n\n\n\n\n \n import nt\n cookie=nt._add_dll_directory(path)\n return _AddedDllDirectory(\n path,\n cookie,\n nt._remove_dll_directory\n )\n \n \ndef scandir(*args,**kw):\n raise NotImplementedError('browsers cannot read a directory content')\n \ndef waitstatus_to_exitcode(status):\n return status >>8\n \n_set=set()\n\nsupports_dir_fd=_set\n\nsupports_effective_ids=_set\n\nsupports_fd=_set\n\nsupports_follow_symlinks=_set\n\n", ["abc", "nt", "os.path", "posix", "posixpath", "sys"]], "pathlib": [".py", "''\n\n\n\n\n\n\nimport fnmatch\nimport functools\nimport io\nimport ntpath\nimport os\nimport posixpath\nimport re\nimport sys\nimport warnings\nfrom _collections_abc import Sequence\nfrom errno import ENOENT,ENOTDIR,EBADF,ELOOP\nfrom stat import S_ISDIR,S_ISLNK,S_ISREG,S_ISSOCK,S_ISBLK,S_ISCHR,S_ISFIFO\nfrom urllib.parse import quote_from_bytes as urlquote_from_bytes\n\n\n__all__=[\n\"PurePath\",\"PurePosixPath\",\"PureWindowsPath\",\n\"Path\",\"PosixPath\",\"WindowsPath\",\n]\n\n\n\n\n\n\n\n_WIN_RESERVED_NAMES=frozenset(\n{'CON','PRN','AUX','NUL','CONIN$','CONOUT$'}|\n{f'COM{c}'for c in '123456789\\xb9\\xb2\\xb3'}|\n{f'LPT{c}'for c in '123456789\\xb9\\xb2\\xb3'}\n)\n\n_WINERROR_NOT_READY=21\n_WINERROR_INVALID_NAME=123\n_WINERROR_CANT_RESOLVE_FILENAME=1921\n\n\n_IGNORED_ERRNOS=(ENOENT,ENOTDIR,EBADF,ELOOP)\n\n_IGNORED_WINERRORS=(\n_WINERROR_NOT_READY,\n_WINERROR_INVALID_NAME,\n_WINERROR_CANT_RESOLVE_FILENAME)\n\ndef _ignore_error(exception):\n return(getattr(exception,'errno',None)in _IGNORED_ERRNOS or\n getattr(exception,'winerror',None)in _IGNORED_WINERRORS)\n \n \n@functools.cache\ndef _is_case_sensitive(flavour):\n return flavour.normcase('Aa')=='Aa'\n \n \n \n \n \n \n \n \n \n \n \n \n \n_FNMATCH_PREFIX,_FNMATCH_SUFFIX=fnmatch.translate('_').split('_')\n_FNMATCH_SLICE=slice(len(_FNMATCH_PREFIX),-len(_FNMATCH_SUFFIX))\n_SWAP_SEP_AND_NEWLINE={\n'/':str.maketrans({'/':'\\n','\\n':'/'}),\n'\\\\':str.maketrans({'\\\\':'\\n','\\n':'\\\\'}),\n}\n\n\n@functools.lru_cache()\ndef _make_selector(pattern_parts,flavour,case_sensitive):\n pat=pattern_parts[0]\n if not pat:\n return _TerminatingSelector()\n if pat =='**':\n child_parts_idx=1\n while child_parts_idx =len(self)or idx <-len(self):\n raise IndexError(idx)\n if idx <0:\n idx +=len(self)\n return self._path._from_parsed_parts(self._drv,self._root,\n self._tail[:-idx -1])\n \n def __repr__(self):\n return \"<{}.parents>\".format(type(self._path).__name__)\n \n \nclass PurePath(object):\n ''\n\n\n\n\n\n\n \n \n __slots__=(\n \n \n '_raw_paths',\n \n \n \n \n \n \n \n \n '_drv','_root','_tail_cached',\n \n \n \n \n '_str',\n \n \n \n \n \n '_str_normcase_cached',\n \n \n \n \n \n '_parts_normcase_cached',\n \n \n \n '_lines_cached',\n \n \n \n '_hash',\n )\n _flavour=os.path\n \n def __new__(cls,*args,**kwargs):\n ''\n\n\n\n \n if cls is PurePath:\n cls=PureWindowsPath if os.name =='nt'else PurePosixPath\n return object.__new__(cls)\n \n def __reduce__(self):\n \n \n return(self.__class__,self.parts)\n \n def __init__(self,*args):\n paths=[]\n for arg in args:\n if isinstance(arg,PurePath):\n if arg._flavour is ntpath and self._flavour is posixpath:\n \n paths.extend(path.replace('\\\\','/')for path in arg._raw_paths)\n else:\n paths.extend(arg._raw_paths)\n else:\n try:\n path=os.fspath(arg)\n except TypeError:\n path=arg\n if not isinstance(path,str):\n raise TypeError(\n \"argument should be a str or an os.PathLike \"\n \"object where __fspath__ returns a str, \"\n f\"not {type(path).__name__ !r}\")\n paths.append(path)\n self._raw_paths=paths\n \n def with_segments(self,*pathsegments):\n ''\n\n\n \n return type(self)(*pathsegments)\n \n @classmethod\n def _parse_path(cls,path):\n if not path:\n return '','',[]\n sep=cls._flavour.sep\n altsep=cls._flavour.altsep\n if altsep:\n path=path.replace(altsep,sep)\n drv,root,rel=cls._flavour.splitroot(path)\n if not root and drv.startswith(sep)and not drv.endswith(sep):\n drv_parts=drv.split(sep)\n if len(drv_parts)==4 and drv_parts[2]not in '?.':\n \n root=sep\n elif len(drv_parts)==6:\n \n root=sep\n parsed=[sys.intern(str(x))for x in rel.split(sep)if x and x !='.']\n return drv,root,parsed\n \n def _load_parts(self):\n paths=self._raw_paths\n if len(paths)==0:\n path=''\n elif len(paths)==1:\n path=paths[0]\n else:\n path=self._flavour.join(*paths)\n drv,root,tail=self._parse_path(path)\n self._drv=drv\n self._root=root\n self._tail_cached=tail\n \n def _from_parsed_parts(self,drv,root,tail):\n path_str=self._format_parsed_parts(drv,root,tail)\n path=self.with_segments(path_str)\n path._str=path_str or '.'\n path._drv=drv\n path._root=root\n path._tail_cached=tail\n return path\n \n @classmethod\n def _format_parsed_parts(cls,drv,root,tail):\n if drv or root:\n return drv+root+cls._flavour.sep.join(tail)\n elif tail and cls._flavour.splitdrive(tail[0])[0]:\n tail=['.']+tail\n return cls._flavour.sep.join(tail)\n \n def __str__(self):\n ''\n \n try:\n return self._str\n except AttributeError:\n self._str=self._format_parsed_parts(self.drive,self.root,\n self._tail)or '.'\n return self._str\n \n def __fspath__(self):\n return str(self)\n \n def as_posix(self):\n ''\n \n f=self._flavour\n return str(self).replace(f.sep,'/')\n \n def __bytes__(self):\n ''\n \n return os.fsencode(self)\n \n def __repr__(self):\n return \"{}({!r})\".format(self.__class__.__name__,self.as_posix())\n \n def as_uri(self):\n ''\n if not self.is_absolute():\n raise ValueError(\"relative path can't be expressed as a file URI\")\n \n drive=self.drive\n if len(drive)==2 and drive[1]==':':\n \n prefix='file:///'+drive\n path=self.as_posix()[2:]\n elif drive:\n \n prefix='file:'\n path=self.as_posix()\n else:\n \n prefix='file://'\n path=str(self)\n return prefix+urlquote_from_bytes(os.fsencode(path))\n \n @property\n def _str_normcase(self):\n \n try:\n return self._str_normcase_cached\n except AttributeError:\n if _is_case_sensitive(self._flavour):\n self._str_normcase_cached=str(self)\n else:\n self._str_normcase_cached=str(self).lower()\n return self._str_normcase_cached\n \n @property\n def _parts_normcase(self):\n \n try:\n return self._parts_normcase_cached\n except AttributeError:\n self._parts_normcase_cached=self._str_normcase.split(self._flavour.sep)\n return self._parts_normcase_cached\n \n @property\n def _lines(self):\n \n try:\n return self._lines_cached\n except AttributeError:\n path_str=str(self)\n if path_str =='.':\n self._lines_cached=''\n else:\n trans=_SWAP_SEP_AND_NEWLINE[self._flavour.sep]\n self._lines_cached=path_str.translate(trans)\n return self._lines_cached\n \n def __eq__(self,other):\n if not isinstance(other,PurePath):\n return NotImplemented\n return self._str_normcase ==other._str_normcase and self._flavour is other._flavour\n \n def __hash__(self):\n try:\n return self._hash\n except AttributeError:\n self._hash=hash(self._str_normcase)\n return self._hash\n \n def __lt__(self,other):\n if not isinstance(other,PurePath)or self._flavour is not other._flavour:\n return NotImplemented\n return self._parts_normcase other._parts_normcase\n \n def __ge__(self,other):\n if not isinstance(other,PurePath)or self._flavour is not other._flavour:\n return NotImplemented\n return self._parts_normcase >=other._parts_normcase\n \n @property\n def drive(self):\n ''\n try:\n return self._drv\n except AttributeError:\n self._load_parts()\n return self._drv\n \n @property\n def root(self):\n ''\n try:\n return self._root\n except AttributeError:\n self._load_parts()\n return self._root\n \n @property\n def _tail(self):\n try:\n return self._tail_cached\n except AttributeError:\n self._load_parts()\n return self._tail_cached\n \n @property\n def anchor(self):\n ''\n anchor=self.drive+self.root\n return anchor\n \n @property\n def name(self):\n ''\n tail=self._tail\n if not tail:\n return ''\n return tail[-1]\n \n @property\n def suffix(self):\n ''\n\n\n\n \n name=self.name\n i=name.rfind('.')\n if 0 >> import pdb\n >>> pdb.run('')\n\nThe debugger's prompt is '(Pdb) '. This will stop in the first\nfunction call in .\n\nAlternatively, if a statement terminated with an unhandled exception,\nyou can use pdb's post-mortem facility to inspect the contents of the\ntraceback:\n\n >>> \n \n >>> import pdb\n >>> pdb.pm()\n\nThe commands recognized by the debugger are listed in the next\nsection. Most can be abbreviated as indicated; e.g., h(elp) means\nthat 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',\nnor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in\nsquare brackets. Alternatives in the command syntax are separated\nby a vertical bar (|).\n\nA blank line repeats the previous command literally, except for\n'list', where it lists the next 11 lines.\n\nCommands that the debugger doesn't recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged. Python statements can also be prefixed with an exclamation\npoint ('!'). This is a powerful way to inspect the program being\ndebugged; it is even possible to change variables or call functions.\nWhen an exception occurs in such a statement, the exception name is\nprinted but the debugger's state is not changed.\n\nThe debugger supports aliases, which can save typing. And aliases can\nhave parameters (see the alias help entry) which allows one a certain\nlevel of adaptability to the context under examination.\n\nMultiple commands may be entered on a single line, separated by the\npair ';;'. No intelligence is applied to separating the commands; the\ninput is split at the first ';;', even if it is in the middle of a\nquoted string.\n\nIf a file \".pdbrc\" exists in your home directory or in the current\ndirectory, it is read in and executed as if it had been typed at the\ndebugger prompt. This is particularly useful for aliases. If both\nfiles exist, the one in the home directory is read first and aliases\ndefined there can be overridden by the local file. This behavior can be\ndisabled by passing the \"readrc=False\" argument to the Pdb constructor.\n\nAside from aliases, the debugger is not directly programmable; but it\nis implemented as a class from which you can derive your own debugger\nclass, which you can make as fancy as you like.\n\n\nDebugger commands\n=================\n\n\"\"\"\n\n\n\nimport os\nimport io\nimport re\nimport sys\nimport cmd\nimport bdb\nimport dis\nimport code\nimport glob\nimport token\nimport types\nimport codeop\nimport pprint\nimport signal\nimport inspect\nimport textwrap\nimport tokenize\nimport traceback\nimport linecache\nimport _colorize\n\nfrom contextlib import contextmanager\nfrom rlcompleter import Completer\nfrom types import CodeType\n\n\nclass Restart(Exception):\n ''\n pass\n \n__all__=[\"run\",\"pm\",\"Pdb\",\"runeval\",\"runctx\",\"runcall\",\"set_trace\",\n\"post_mortem\",\"help\"]\n\n\ndef find_first_executable_line(code):\n ''\n\n\n\n\n\n \n prev=None\n for instr in dis.get_instructions(code):\n if prev is not None and prev.opname =='RESUME':\n if instr.positions.lineno is not None:\n return instr.positions.lineno\n return code.co_firstlineno\n prev=instr\n return code.co_firstlineno\n \ndef find_function(funcname,filename):\n cre=re.compile(r'def\\s+%s\\s*[(]'%re.escape(funcname))\n try:\n fp=tokenize.open(filename)\n except OSError:\n lines=linecache.getlines(filename)\n if not lines:\n return None\n fp=io.StringIO(''.join(lines))\n funcdef=\"\"\n funcstart=None\n \n with fp:\n for lineno,line in enumerate(fp,start=1):\n if cre.match(line):\n funcstart,funcdef=lineno,line\n elif funcdef:\n funcdef +=line\n \n if funcdef:\n try:\n funccode=compile(funcdef,filename,'exec').co_consts[0]\n except SyntaxError:\n continue\n lineno_offset=find_first_executable_line(funccode)\n return funcname,filename,funcstart+lineno_offset -1\n return None\n \ndef lasti2lineno(code,lasti):\n linestarts=list(dis.findlinestarts(code))\n linestarts.reverse()\n for i,lineno in linestarts:\n if lasti >=i:\n return lineno\n return 0\n \n \nclass _rstr(str):\n ''\n def __repr__(self):\n return self\n \n \nclass _ExecutableTarget:\n filename:str\n code:CodeType |str\n namespace:dict\n \n \nclass _ScriptTarget(_ExecutableTarget):\n def __init__(self,target):\n self._target=os.path.realpath(target)\n \n if not os.path.exists(self._target):\n print(f'Error: {target} does not exist')\n sys.exit(1)\n if os.path.isdir(self._target):\n print(f'Error: {target} is a directory')\n sys.exit(1)\n \n \n \n if not sys.flags.safe_path:\n sys.path[0]=os.path.dirname(self._target)\n \n def __repr__(self):\n return self._target\n \n @property\n def filename(self):\n return self._target\n \n @property\n def code(self):\n \n with io.open_code(self._target)as fp:\n return f\"exec(compile({fp.read()!r}, {self._target !r}, 'exec'))\"\n \n @property\n def namespace(self):\n return dict(\n __name__='__main__',\n __file__=self._target,\n __builtins__=__builtins__,\n __spec__=None,\n )\n \n \nclass _ModuleTarget(_ExecutableTarget):\n def __init__(self,target):\n self._target=target\n \n import runpy\n try:\n _,self._spec,self._code=runpy._get_module_details(self._target)\n except ImportError as e:\n print(f\"ImportError: {e}\")\n sys.exit(1)\n except Exception:\n traceback.print_exc()\n sys.exit(1)\n \n def __repr__(self):\n return self._target\n \n @property\n def filename(self):\n return self._code.co_filename\n \n @property\n def code(self):\n return self._code\n \n @property\n def namespace(self):\n return dict(\n __name__='__main__',\n __file__=os.path.normcase(os.path.abspath(self.filename)),\n __package__=self._spec.parent,\n __loader__=self._spec.loader,\n __spec__=self._spec,\n __builtins__=__builtins__,\n )\n \n \nclass _ZipTarget(_ExecutableTarget):\n def __init__(self,target):\n import runpy\n \n self._target=os.path.realpath(target)\n sys.path.insert(0,self._target)\n try:\n _,self._spec,self._code=runpy._get_main_module_details()\n except ImportError as e:\n print(f\"ImportError: {e}\")\n sys.exit(1)\n except Exception:\n traceback.print_exc()\n sys.exit(1)\n \n def __repr__(self):\n return self._target\n \n @property\n def filename(self):\n return self._code.co_filename\n \n @property\n def code(self):\n return self._code\n \n @property\n def namespace(self):\n return dict(\n __name__='__main__',\n __file__=os.path.normcase(os.path.abspath(self.filename)),\n __package__=self._spec.parent,\n __loader__=self._spec.loader,\n __spec__=self._spec,\n __builtins__=__builtins__,\n )\n \n \nclass _PdbInteractiveConsole(code.InteractiveConsole):\n def __init__(self,ns,message):\n self._message=message\n super().__init__(locals=ns,local_exit=True)\n \n def write(self,data):\n self._message(data,end='')\n \n \n \n \n \n \n \nline_prefix='\\n-> '\n\n\n\nclass Pdb(bdb.Bdb,cmd.Cmd):\n _previous_sigint_handler=None\n \n \n \n MAX_CHAINED_EXCEPTION_DEPTH=999\n \n _file_mtime_table={}\n \n def __init__(self,completekey='tab',stdin=None,stdout=None,skip=None,\n nosigint=False,readrc=True):\n bdb.Bdb.__init__(self,skip=skip)\n cmd.Cmd.__init__(self,completekey,stdin,stdout)\n sys.audit(\"pdb.Pdb\")\n if stdout:\n self.use_rawinput=0\n self.prompt='(Pdb) '\n self.aliases={}\n self.displaying={}\n self.mainpyfile=''\n self._wait_for_mainpyfile=False\n self.tb_lineno={}\n \n try:\n import readline\n \n readline.set_completer_delims(' \\t\\n`@#%^&*()=+[{]}\\\\|;:\\'\",<>?')\n except ImportError:\n pass\n self.allow_kbdint=False\n self.nosigint=nosigint\n \n \n self.identchars=cmd.Cmd.identchars+'=.[](),\"\\'+-*/%@&|<>~^'\n \n \n self.rcLines=[]\n if readrc:\n try:\n with open(os.path.expanduser('~/.pdbrc'),encoding='utf-8')as rcFile:\n self.rcLines.extend(rcFile)\n except OSError:\n pass\n try:\n with open(\".pdbrc\",encoding='utf-8')as rcFile:\n self.rcLines.extend(rcFile)\n except OSError:\n pass\n \n self.commands={}\n self.commands_doprompt={}\n \n self.commands_silent={}\n \n self.commands_defining=False\n \n self.commands_bnum=None\n \n \n self._chained_exceptions=tuple()\n self._chained_exception_index=0\n \n def sigint_handler(self,signum,frame):\n if self.allow_kbdint:\n raise KeyboardInterrupt\n self.message(\"\\nProgram interrupted. (Use 'cont' to resume).\")\n self.set_step()\n self.set_trace(frame)\n \n def reset(self):\n bdb.Bdb.reset(self)\n self.forget()\n \n def forget(self):\n self.lineno=None\n self.stack=[]\n self.curindex=0\n if hasattr(self,'curframe')and self.curframe:\n self.curframe.f_globals.pop('__pdb_convenience_variables',None)\n self.curframe=None\n self.tb_lineno.clear()\n \n def setup(self,f,tb):\n self.forget()\n self.stack,self.curindex=self.get_stack(f,tb)\n while tb:\n \n \n \n lineno=lasti2lineno(tb.tb_frame.f_code,tb.tb_lasti)\n self.tb_lineno[tb.tb_frame]=lineno\n tb=tb.tb_next\n self.curframe=self.stack[self.curindex][0]\n \n \n \n \n \n \n self.curframe_locals=self.curframe.f_locals\n self.set_convenience_variable(self.curframe,'_frame',self.curframe)\n \n if self._chained_exceptions:\n self.set_convenience_variable(\n self.curframe,\n '_exception',\n self._chained_exceptions[self._chained_exception_index],\n )\n \n if self.rcLines:\n self.cmdqueue=[\n line for line in self.rcLines\n if line.strip()and not line.strip().startswith(\"#\")\n ]\n self.rcLines=[]\n \n \n \n def user_call(self,frame,argument_list):\n ''\n \n if self._wait_for_mainpyfile:\n return\n if self.stop_here(frame):\n self.message('--Call--')\n self.interaction(frame,None)\n \n def user_line(self,frame):\n ''\n if self._wait_for_mainpyfile:\n if(self.mainpyfile !=self.canonic(frame.f_code.co_filename)\n or frame.f_lineno <=0):\n return\n self._wait_for_mainpyfile=False\n if self.bp_commands(frame):\n self.interaction(frame,None)\n \n user_opcode=user_line\n \n def bp_commands(self,frame):\n ''\n\n\n\n \n \n if getattr(self,\"currentbp\",False)and\\\n self.currentbp in self.commands:\n currentbp=self.currentbp\n self.currentbp=0\n lastcmd_back=self.lastcmd\n self.setup(frame,None)\n for line in self.commands[currentbp]:\n self.onecmd(line)\n self.lastcmd=lastcmd_back\n if not self.commands_silent[currentbp]:\n self.print_stack_entry(self.stack[self.curindex])\n if self.commands_doprompt[currentbp]:\n self._cmdloop()\n self.forget()\n return\n return 1\n \n def user_return(self,frame,return_value):\n ''\n if self._wait_for_mainpyfile:\n return\n frame.f_locals['__return__']=return_value\n self.set_convenience_variable(frame,'_retval',return_value)\n self.message('--Return--')\n self.interaction(frame,None)\n \n def user_exception(self,frame,exc_info):\n ''\n \n if self._wait_for_mainpyfile:\n return\n exc_type,exc_value,exc_traceback=exc_info\n frame.f_locals['__exception__']=exc_type,exc_value\n self.set_convenience_variable(frame,'_exception',exc_value)\n \n \n \n \n \n \n prefix='Internal 'if(not exc_traceback\n and exc_type is StopIteration)else ''\n self.message('%s%s'%(prefix,self._format_exc(exc_value)))\n self.interaction(frame,exc_traceback)\n \n \n def _cmdloop(self):\n while True:\n try:\n \n \n self.allow_kbdint=True\n self.cmdloop()\n self.allow_kbdint=False\n break\n except KeyboardInterrupt:\n self.message('--KeyboardInterrupt--')\n \n def _validate_file_mtime(self):\n ''\n \n try:\n filename=self.curframe.f_code.co_filename\n mtime=os.path.getmtime(filename)\n except Exception:\n return\n if(filename in self._file_mtime_table and\n mtime !=self._file_mtime_table[filename]):\n self.message(f\"*** WARNING: file '{filename}' was edited, \"\n \"running stale code until the program is rerun\")\n self._file_mtime_table[filename]=mtime\n \n \n \n def _show_display(self):\n displaying=self.displaying.get(self.curframe)\n if displaying:\n for expr,oldvalue in displaying.items():\n newvalue=self._getval_except(expr)\n \n \n \n if newvalue is not oldvalue and newvalue !=oldvalue:\n displaying[expr]=newvalue\n self.message('display %s: %s [old: %s]'%\n (expr,self._safe_repr(newvalue,expr),\n self._safe_repr(oldvalue,expr)))\n \n def _get_tb_and_exceptions(self,tb_or_exc):\n ''\n\n\n\n\n\n\n\n \n _exceptions=[]\n if isinstance(tb_or_exc,BaseException):\n traceback,current=tb_or_exc.__traceback__,tb_or_exc\n \n while current is not None:\n if current in _exceptions:\n break\n _exceptions.append(current)\n if current.__cause__ is not None:\n current=current.__cause__\n elif(\n current.__context__ is not None and not current.__suppress_context__\n ):\n current=current.__context__\n \n if len(_exceptions)>=self.MAX_CHAINED_EXCEPTION_DEPTH:\n self.message(\n f\"More than {self.MAX_CHAINED_EXCEPTION_DEPTH}\"\n \" chained exceptions found, not all exceptions\"\n \"will be browsable with `exceptions`.\"\n )\n break\n else:\n traceback=tb_or_exc\n return tuple(reversed(_exceptions)),traceback\n \n @contextmanager\n def _hold_exceptions(self,exceptions):\n ''\n\n\n\n\n\n\n\n \n try:\n self._chained_exceptions=exceptions\n self._chained_exception_index=len(exceptions)-1\n yield\n finally:\n \n \n self._chained_exceptions=tuple()\n self._chained_exception_index=0\n \n def interaction(self,frame,tb_or_exc):\n \n if Pdb._previous_sigint_handler:\n try:\n signal.signal(signal.SIGINT,Pdb._previous_sigint_handler)\n except ValueError:\n pass\n else:\n Pdb._previous_sigint_handler=None\n \n _chained_exceptions,tb=self._get_tb_and_exceptions(tb_or_exc)\n if isinstance(tb_or_exc,BaseException):\n assert tb is not None,\"main exception must have a traceback\"\n with self._hold_exceptions(_chained_exceptions):\n self.setup(frame,tb)\n \n \n \n \n \n self.cmdqueue.append('_pdbcmd_print_frame_status')\n self._cmdloop()\n \n if self.cmdqueue and self.cmdqueue[-1]=='_pdbcmd_print_frame_status':\n self.cmdqueue.pop()\n self.forget()\n \n def displayhook(self,obj):\n ''\n\n \n \n if obj is not None:\n self.message(repr(obj))\n \n @contextmanager\n def _disable_command_completion(self):\n completenames=self.completenames\n try:\n self.completenames=self.completedefault\n yield\n finally:\n self.completenames=completenames\n return\n \n def _exec_in_closure(self,source,globals,locals):\n ''\n\n\n\n \n \n \n \n \n \n code=compile(source,\"\",\"exec\")\n if not any(isinstance(const,CodeType)for const in code.co_consts):\n return False\n \n \n \n locals_copy=dict(locals)\n \n locals_copy[\"__pdb_eval__\"]={\n \"result\":None,\n \"write_back\":{}\n }\n \n \n try:\n compile(source,\"\",\"eval\")\n except SyntaxError:\n pass\n else:\n source=\"__pdb_eval__['result'] = \"+source\n \n \n source=(\"try:\\n\"+\n textwrap.indent(source,\" \")+\"\\n\"+\n \"finally:\\n\"+\n \" __pdb_eval__['write_back'] = locals()\")\n \n \n \n \n \n \n \n \n source_with_closure=(\"def __pdb_outer():\\n\"+\n \"\\n\".join(f\" {var} = None\"for var in locals_copy)+\"\\n\"+\n \" def __pdb_scope():\\n\"+\n \"\\n\".join(f\" nonlocal {var}\"for var in locals_copy)+\"\\n\"+\n textwrap.indent(source,\" \")+\"\\n\"+\n \" return __pdb_scope.__code__\"\n )\n \n \n \n \n ns={}\n try:\n exec(source_with_closure,{},ns)\n except Exception:\n return False\n code=ns[\"__pdb_outer\"]()\n \n cells=tuple(types.CellType(locals_copy.get(var))for var in code.co_freevars)\n \n try:\n exec(code,globals,locals_copy,closure=cells)\n except Exception:\n return False\n \n \n pdb_eval=locals_copy[\"__pdb_eval__\"]\n \n \n pdb_eval[\"write_back\"].pop(\"__pdb_eval__\")\n \n \n locals.update(pdb_eval[\"write_back\"])\n eval_result=pdb_eval[\"result\"]\n if eval_result is not None:\n print(repr(eval_result))\n \n return True\n \n def default(self,line):\n if line[:1]=='!':line=line[1:].strip()\n locals=self.curframe_locals\n globals=self.curframe.f_globals\n try:\n buffer=line\n if(code :=codeop.compile_command(line+'\\n','','single'))is None:\n \n with self._disable_command_completion():\n buffer=line\n continue_prompt=\"... \"\n while(code :=codeop.compile_command(buffer,'','single'))is None:\n if self.use_rawinput:\n try:\n line=input(continue_prompt)\n except(EOFError,KeyboardInterrupt):\n self.lastcmd=\"\"\n print('\\n')\n return\n else:\n self.stdout.write(continue_prompt)\n self.stdout.flush()\n line=self.stdin.readline()\n if not len(line):\n self.lastcmd=\"\"\n self.stdout.write('\\n')\n self.stdout.flush()\n return\n else:\n line=line.rstrip('\\r\\n')\n buffer +='\\n'+line\n save_stdout=sys.stdout\n save_stdin=sys.stdin\n save_displayhook=sys.displayhook\n try:\n sys.stdin=self.stdin\n sys.stdout=self.stdout\n sys.displayhook=self.displayhook\n if not self._exec_in_closure(buffer,globals,locals):\n exec(code,globals,locals)\n finally:\n sys.stdout=save_stdout\n sys.stdin=save_stdin\n sys.displayhook=save_displayhook\n except:\n self._error_exc()\n \n def _replace_convenience_variables(self,line):\n ''\n\n \n \n if \"$\"not in line:\n return line\n \n dollar_start=dollar_end=-1\n replace_variables=[]\n try:\n for t in tokenize.generate_tokens(io.StringIO(line).readline):\n token_type,token_string,start,end,_=t\n if token_type ==token.OP and token_string =='$':\n dollar_start,dollar_end=start,end\n elif start ==dollar_end and token_type ==token.NAME:\n \n replace_variables.append((dollar_start[1],end[1],token_string))\n except tokenize.TokenError:\n return line\n \n if not replace_variables:\n return line\n \n last_end=0\n line_pieces=[]\n for start,end,name in replace_variables:\n line_pieces.append(line[last_end:start]+f'__pdb_convenience_variables[\"{name}\"]')\n last_end=end\n line_pieces.append(line[last_end:])\n \n return ''.join(line_pieces)\n \n def precmd(self,line):\n ''\n if not line.strip():\n return line\n args=line.split()\n while args[0]in self.aliases:\n line=self.aliases[args[0]]\n for idx in range(1,10):\n if f'%{idx}'in line:\n if idx >=len(args):\n self.error(f\"Not enough arguments for alias '{args[0]}'\")\n \n return \"!\"\n line=line.replace(f'%{idx}',args[idx])\n elif '%*'not in line:\n if idx =0:\n \n next=line[marker+2:].lstrip()\n self.cmdqueue.insert(0,next)\n line=line[:marker].rstrip()\n \n \n line=self._replace_convenience_variables(line)\n \n return line\n \n def onecmd(self,line):\n ''\n\n\n\n\n \n if not self.commands_defining:\n self._validate_file_mtime()\n if line.startswith('_pdbcmd'):\n command,arg,line=self.parseline(line)\n if hasattr(self,command):\n return getattr(self,command)(arg)\n return cmd.Cmd.onecmd(self,line)\n else:\n return self.handle_command_def(line)\n \n def handle_command_def(self,line):\n ''\n cmd,arg,line=self.parseline(line)\n if not cmd:\n return False\n if cmd =='silent':\n self.commands_silent[self.commands_bnum]=True\n return False\n elif cmd =='end':\n return True\n cmdlist=self.commands[self.commands_bnum]\n if arg:\n cmdlist.append(cmd+' '+arg)\n else:\n cmdlist.append(cmd)\n \n try:\n func=getattr(self,'do_'+cmd)\n except AttributeError:\n func=self.default\n \n if func.__name__ in self.commands_resuming:\n self.commands_doprompt[self.commands_bnum]=False\n return True\n return False\n \n \n \n def message(self,msg,end='\\n'):\n print(msg,end=end,file=self.stdout)\n \n def error(self,msg):\n print('***',msg,file=self.stdout)\n \n \n \n def set_convenience_variable(self,frame,name,value):\n if '__pdb_convenience_variables'not in frame.f_globals:\n frame.f_globals['__pdb_convenience_variables']={}\n frame.f_globals['__pdb_convenience_variables'][name]=value\n \n \n \n \n def completenames(self,text,line,begidx,endidx):\n \n \n commands=super().completenames(text,line,begidx,endidx)\n for alias in self.aliases:\n if alias.startswith(text):\n commands.append(alias)\n if commands:\n return commands\n else:\n expressions=self._complete_expression(text,line,begidx,endidx)\n if expressions:\n return expressions\n return self.completedefault(text,line,begidx,endidx)\n \n def _complete_location(self,text,line,begidx,endidx):\n \n if line.strip().endswith((':',',')):\n \n return[]\n \n try:\n ret=self._complete_expression(text,line,begidx,endidx)\n except Exception:\n ret=[]\n \n globs=glob.glob(glob.escape(text)+'*')\n for fn in globs:\n if os.path.isdir(fn):\n ret.append(fn+'/')\n elif os.path.isfile(fn)and fn.lower().endswith(('.py','.pyw')):\n ret.append(fn+':')\n return ret\n \n def _complete_bpnumber(self,text,line,begidx,endidx):\n \n \n \n return[str(i)for i,bp in enumerate(bdb.Breakpoint.bpbynumber)\n if bp is not None and str(i).startswith(text)]\n \n def _complete_expression(self,text,line,begidx,endidx):\n \n if not self.curframe:\n return[]\n \n \n \n ns={**self.curframe.f_globals,**self.curframe_locals}\n if text.startswith(\"$\"):\n \n conv_vars=self.curframe.f_globals.get('__pdb_convenience_variables',{})\n return[f\"${name}\"for name in conv_vars if name.startswith(text[1:])]\n if '.'in text:\n \n \n \n dotted=text.split('.')\n try:\n obj=ns[dotted[0]]\n for part in dotted[1:-1]:\n obj=getattr(obj,part)\n except(KeyError,AttributeError):\n return[]\n prefix='.'.join(dotted[:-1])+'.'\n return[prefix+n for n in dir(obj)if n.startswith(dotted[-1])]\n else:\n \n return[n for n in ns.keys()if n.startswith(text)]\n \n def completedefault(self,text,line,begidx,endidx):\n if text.startswith(\"$\"):\n \n conv_vars=self.curframe.f_globals.get('__pdb_convenience_variables',{})\n return[f\"${name}\"for name in conv_vars if name.startswith(text[1:])]\n \n \n state=0\n matches=[]\n completer=Completer(self.curframe.f_globals |self.curframe_locals)\n while(match :=completer.complete(text,state))is not None:\n matches.append(match)\n state +=1\n return matches\n \n \n \n def _pdbcmd_print_frame_status(self,arg):\n self.print_stack_entry(self.stack[self.curindex])\n self._show_display()\n \n \n \n \n \n def do_commands(self,arg):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not arg:\n bnum=len(bdb.Breakpoint.bpbynumber)-1\n else:\n try:\n bnum=int(arg)\n except:\n self._print_invalid_arg(arg)\n return\n try:\n self.get_bpbynumber(bnum)\n except ValueError as err:\n self.error('cannot set commands: %s'%err)\n return\n \n self.commands_bnum=bnum\n \n if bnum in self.commands:\n old_command_defs=(self.commands[bnum],\n self.commands_doprompt[bnum],\n self.commands_silent[bnum])\n else:\n old_command_defs=None\n self.commands[bnum]=[]\n self.commands_doprompt[bnum]=True\n self.commands_silent[bnum]=False\n \n prompt_back=self.prompt\n self.prompt='(com) '\n self.commands_defining=True\n try:\n self.cmdloop()\n except KeyboardInterrupt:\n \n if old_command_defs:\n self.commands[bnum]=old_command_defs[0]\n self.commands_doprompt[bnum]=old_command_defs[1]\n self.commands_silent[bnum]=old_command_defs[2]\n else:\n del self.commands[bnum]\n del self.commands_doprompt[bnum]\n del self.commands_silent[bnum]\n self.error('command definition aborted, old commands restored')\n finally:\n self.commands_defining=False\n self.prompt=prompt_back\n \n complete_commands=_complete_bpnumber\n \n def do_break(self,arg,temporary=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not arg:\n if self.breaks:\n self.message(\"Num Type Disp Enb Where\")\n for bp in bdb.Breakpoint.bpbynumber:\n if bp:\n self.message(bp.bpformat())\n return\n \n \n filename=None\n lineno=None\n cond=None\n comma=arg.find(',')\n if comma >0:\n \n cond=arg[comma+1:].lstrip()\n if err :=self._compile_error_message(cond):\n self.error('Invalid condition %s: %r'%(cond,err))\n return\n arg=arg[:comma].rstrip()\n \n colon=arg.rfind(':')\n funcname=None\n if colon >=0:\n filename=arg[:colon].rstrip()\n f=self.lookupmodule(filename)\n if not f:\n self.error('%r not found from sys.path'%filename)\n return\n else:\n filename=f\n arg=arg[colon+1:].lstrip()\n try:\n lineno=int(arg)\n except ValueError:\n self.error('Bad lineno: %s'%arg)\n return\n else:\n \n try:\n lineno=int(arg)\n except ValueError:\n try:\n func=eval(arg,\n self.curframe.f_globals,\n self.curframe_locals)\n except:\n func=arg\n try:\n if hasattr(func,'__func__'):\n func=func.__func__\n code=func.__code__\n \n \n funcname=code.co_name\n lineno=find_first_executable_line(code)\n filename=code.co_filename\n except:\n \n (ok,filename,ln)=self.lineinfo(arg)\n if not ok:\n self.error('The specified object %r is not a function '\n 'or was not found along sys.path.'%arg)\n return\n funcname=ok\n lineno=int(ln)\n if not filename:\n filename=self.defaultFile()\n \n line=self.checkline(filename,lineno)\n if line:\n \n err=self.set_break(filename,line,temporary,cond,funcname)\n if err:\n self.error(err)\n else:\n bp=self.get_breaks(filename,line)[-1]\n self.message(\"Breakpoint %d at %s:%d\"%\n (bp.number,bp.file,bp.line))\n \n \n def defaultFile(self):\n ''\n filename=self.curframe.f_code.co_filename\n if filename ==''and self.mainpyfile:\n filename=self.mainpyfile\n return filename\n \n do_b=do_break\n \n complete_break=_complete_location\n complete_b=_complete_location\n \n def do_tbreak(self,arg):\n ''\n\n\n\n \n self.do_break(arg,1)\n \n complete_tbreak=_complete_location\n \n def lineinfo(self,identifier):\n failed=(None,None,None)\n \n idstring=identifier.split(\"'\")\n if len(idstring)==1:\n \n id=idstring[0].strip()\n elif len(idstring)==3:\n \n id=idstring[1].strip()\n else:\n return failed\n if id =='':return failed\n parts=id.split('.')\n \n if parts[0]=='self':\n del parts[0]\n if len(parts)==0:\n return failed\n \n fname=self.defaultFile()\n if len(parts)==1:\n item=parts[0]\n else:\n \n \n f=self.lookupmodule(parts[0])\n if f:\n fname=f\n item=parts[1]\n answer=find_function(item,self.canonic(fname))\n return answer or failed\n \n def checkline(self,filename,lineno):\n ''\n\n\n\n \n \n \n frame=getattr(self,'curframe',None)\n globs=frame.f_globals if frame else None\n line=linecache.getline(filename,lineno,globs)\n if not line:\n self.message('End of file')\n return 0\n line=line.strip()\n \n if(not line or(line[0]=='#')or\n (line[:3]=='\"\"\"')or line[:3]==\"'''\"):\n self.error('Blank or comment')\n return 0\n return lineno\n \n def do_enable(self,arg):\n ''\n\n\n\n \n args=arg.split()\n for i in args:\n try:\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else:\n bp.enable()\n self.message('Enabled %s'%bp)\n \n complete_enable=_complete_bpnumber\n \n def do_disable(self,arg):\n ''\n\n\n\n\n\n\n \n args=arg.split()\n for i in args:\n try:\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else:\n bp.disable()\n self.message('Disabled %s'%bp)\n \n complete_disable=_complete_bpnumber\n \n def do_condition(self,arg):\n ''\n\n\n\n\n\n \n args=arg.split(' ',1)\n try:\n cond=args[1]\n if err :=self._compile_error_message(cond):\n self.error('Invalid condition %s: %r'%(cond,err))\n return\n except IndexError:\n cond=None\n try:\n bp=self.get_bpbynumber(args[0].strip())\n except IndexError:\n self.error('Breakpoint number expected')\n except ValueError as err:\n self.error(err)\n else:\n bp.cond=cond\n if not cond:\n self.message('Breakpoint %d is now unconditional.'%bp.number)\n else:\n self.message('New condition set for breakpoint %d.'%bp.number)\n \n complete_condition=_complete_bpnumber\n \n def do_ignore(self,arg):\n ''\n\n\n\n\n\n\n\n \n args=arg.split()\n if not args:\n self.error('Breakpoint number expected')\n return\n if len(args)==1:\n count=0\n elif len(args)==2:\n try:\n count=int(args[1])\n except ValueError:\n self._print_invalid_arg(arg)\n return\n else:\n self._print_invalid_arg(arg)\n return\n try:\n bp=self.get_bpbynumber(args[0].strip())\n except ValueError as err:\n self.error(err)\n else:\n bp.ignore=count\n if count >0:\n if count >1:\n countstr='%d crossings'%count\n else:\n countstr='1 crossing'\n self.message('Will ignore next %s of breakpoint %d.'%\n (countstr,bp.number))\n else:\n self.message('Will stop next time breakpoint %d is reached.'\n %bp.number)\n \n complete_ignore=_complete_bpnumber\n \n def do_clear(self,arg):\n ''\n\n\n\n\n\n \n if not arg:\n try:\n reply=input('Clear all breaks? ')\n except EOFError:\n reply='no'\n reply=reply.strip().lower()\n if reply in('y','yes'):\n bplist=[bp for bp in bdb.Breakpoint.bpbynumber if bp]\n self.clear_all_breaks()\n for bp in bplist:\n self.message('Deleted %s'%bp)\n return\n if ':'in arg:\n \n i=arg.rfind(':')\n filename=arg[:i]\n arg=arg[i+1:]\n try:\n lineno=int(arg)\n except ValueError:\n err=\"Invalid line number (%s)\"%arg\n else:\n bplist=self.get_breaks(filename,lineno)[:]\n err=self.clear_break(filename,lineno)\n if err:\n self.error(err)\n else:\n for bp in bplist:\n self.message('Deleted %s'%bp)\n return\n numberlist=arg.split()\n for i in numberlist:\n try:\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else:\n self.clear_bpbynumber(i)\n self.message('Deleted %s'%bp)\n do_cl=do_clear\n \n complete_clear=_complete_location\n complete_cl=_complete_location\n \n def do_where(self,arg):\n ''\n\n\n\n\n \n if arg:\n self._print_invalid_arg(arg)\n return\n self.print_stack_trace()\n do_w=do_where\n do_bt=do_where\n \n def _select_frame(self,number):\n assert 0 <=number \"if ix ==self._chained_exception_index else \" \"\n rep=repr(exc)\n if len(rep)>80:\n rep=rep[:77]+\"...\"\n indicator=(\n \" -\"\n if self._chained_exceptions[ix].__traceback__ is None\n else f\"{ix:>3}\"\n )\n self.message(f\"{prompt} {indicator} {rep}\")\n else:\n try:\n number=int(arg)\n except ValueError:\n self.error(\"Argument must be an integer\")\n return\n if 0 <=number =2:\n self.error('No help for %r; please do not run Python with -OO '\n 'if you need command help'%arg)\n return\n if command.__doc__ is None:\n self.error('No help for %r; __doc__ string missing'%arg)\n return\n self.message(self._help_message_from_doc(command.__doc__))\n \n do_h=do_help\n \n def help_exec(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self.message((self.help_exec.__doc__ or '').strip())\n \n def help_pdb(self):\n help()\n \n \n \n def lookupmodule(self,filename):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not filename.endswith('.py'):\n \n filename=filename.replace('.',os.sep)+'.py'\n \n if os.path.isabs(filename):\n if os.path.exists(filename):\n return filename\n return None\n \n for dirname in sys.path:\n while os.path.islink(dirname):\n dirname=os.readlink(dirname)\n fullname=os.path.join(dirname,filename)\n if os.path.exists(fullname):\n return fullname\n return None\n \n def _run(self,target:_ExecutableTarget):\n \n \n \n \n \n self._wait_for_mainpyfile=True\n self._user_requested_quit=False\n \n self.mainpyfile=self.canonic(target.filename)\n \n \n \n \n import __main__\n __main__.__dict__.clear()\n __main__.__dict__.update(target.namespace)\n \n \n \n self._file_mtime_table.clear()\n \n self.run(target.code)\n \n def _format_exc(self,exc:BaseException):\n return traceback.format_exception_only(exc)[-1].strip()\n \n def _compile_error_message(self,expr):\n ''\n try:\n compile(expr,\"\",\"eval\")\n except SyntaxError as exc:\n return _rstr(self._format_exc(exc))\n return \"\"\n \n def _getsourcelines(self,obj):\n \n \n \n \n \n lines,lineno=inspect.getsourcelines(obj)\n lineno=max(1,lineno)\n return lines,lineno\n \n def _help_message_from_doc(self,doc,usage_only=False):\n lines=[line.strip()for line in doc.rstrip().splitlines()]\n if not lines:\n return \"No help message found.\"\n if \"\"in lines:\n usage_end=lines.index(\"\")\n else:\n usage_end=1\n formatted=[]\n indent=\" \"*len(self.prompt)\n for i,line in enumerate(lines):\n if i ==0:\n prefix=\"Usage: \"\n elif i 0:\n self.commit_frame(force=True)\n self.current_frame=None\n \n def commit_frame(self,force=False):\n if self.current_frame:\n f=self.current_frame\n if f.tell()>=self._FRAME_SIZE_TARGET or force:\n data=f.getbuffer()\n write=self.file_write\n if len(data)>=self._FRAME_SIZE_MIN:\n \n \n \n \n write(FRAME+pack(\"':\n raise AttributeError(\"Can't get local attribute {!r} on {!r}\"\n .format(name,obj))\n try:\n parent=obj\n obj=getattr(obj,subpath)\n except AttributeError:\n raise AttributeError(\"Can't get attribute {!r} on {!r}\"\n .format(name,obj))from None\n return obj,parent\n \ndef whichmodule(obj,name):\n ''\n module_name=getattr(obj,'__module__',None)\n if module_name is not None:\n return module_name\n \n \n for module_name,module in sys.modules.copy().items():\n if(module_name =='__main__'\n or module_name =='__mp_main__'\n or module is None):\n continue\n try:\n if _getattribute(module,name)[0]is obj:\n return module_name\n except AttributeError:\n pass\n return '__main__'\n \ndef encode_long(x):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if x ==0:\n return b''\n nbytes=(x.bit_length()>>3)+1\n result=x.to_bytes(nbytes,byteorder='little',signed=True)\n if x <0 and nbytes >1:\n if result[-1]==0xff and(result[-2]&0x80)!=0:\n result=result[:-1]\n return result\n \ndef decode_long(data):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return int.from_bytes(data,byteorder='little',signed=True)\n \n \n_NoValue=object()\n\n\n\nclass _Pickler:\n\n def __init__(self,file,protocol=None,*,fix_imports=True,\n buffer_callback=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if protocol is None:\n protocol=DEFAULT_PROTOCOL\n if protocol <0:\n protocol=HIGHEST_PROTOCOL\n elif not 0 <=protocol <=HIGHEST_PROTOCOL:\n raise ValueError(\"pickle protocol must be <= %d\"%HIGHEST_PROTOCOL)\n if buffer_callback is not None and protocol <5:\n raise ValueError(\"buffer_callback needs protocol >= 5\")\n self._buffer_callback=buffer_callback\n try:\n self._file_write=file.write\n except AttributeError:\n raise TypeError(\"file must have a 'write' attribute\")\n self.framer=_Framer(self._file_write)\n self.write=self.framer.write\n self._write_large_bytes=self.framer.write_large_bytes\n self.memo={}\n self.proto=int(protocol)\n self.bin=protocol >=1\n self.fast=0\n self.fix_imports=fix_imports and protocol <3\n \n def clear_memo(self):\n ''\n\n\n\n\n\n \n self.memo.clear()\n \n def dump(self,obj):\n ''\n \n \n if not hasattr(self,\"_file_write\"):\n raise PicklingError(\"Pickler.__init__() was not called by \"\n \"%s.__init__()\"%(self.__class__.__name__,))\n if self.proto >=2:\n self.write(PROTO+pack(\"=4:\n self.framer.start_framing()\n self.save(obj)\n self.write(STOP)\n self.framer.end_framing()\n \n def memoize(self,obj):\n ''\n \n \n \n \n \n \n \n \n \n \n \n \n \n if self.fast:\n return\n assert id(obj)not in self.memo\n idx=len(self.memo)\n self.write(self.put(idx))\n self.memo[id(obj)]=idx,obj\n \n \n def put(self,idx):\n if self.proto >=4:\n return MEMOIZE\n elif self.bin:\n if idx <256:\n return BINPUT+pack(\"=2 and func_name ==\"__newobj_ex__\":\n cls,args,kwargs=args\n if not hasattr(cls,\"__new__\"):\n raise PicklingError(\"args[0] from {} args has no __new__\"\n .format(func_name))\n if obj is not None and cls is not obj.__class__:\n raise PicklingError(\"args[0] from {} args has the wrong class\"\n .format(func_name))\n if self.proto >=4:\n save(cls)\n save(args)\n save(kwargs)\n write(NEWOBJ_EX)\n else:\n func=partial(cls.__new__,cls,*args,**kwargs)\n save(func)\n save(())\n write(REDUCE)\n elif self.proto >=2 and func_name ==\"__newobj__\":\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n cls=args[0]\n if not hasattr(cls,\"__new__\"):\n raise PicklingError(\n \"args[0] from __newobj__ args has no __new__\")\n if obj is not None and cls is not obj.__class__:\n raise PicklingError(\n \"args[0] from __newobj__ args has the wrong class\")\n args=args[1:]\n save(cls)\n save(args)\n write(NEWOBJ)\n else:\n save(func)\n save(args)\n write(REDUCE)\n \n if obj is not None:\n \n \n \n if id(obj)in self.memo:\n write(POP+self.get(self.memo[id(obj)][0]))\n else:\n self.memoize(obj)\n \n \n \n \n \n \n if listitems is not None:\n self._batch_appends(listitems)\n \n if dictitems is not None:\n self._batch_setitems(dictitems)\n \n if state is not None:\n if state_setter is None:\n save(state)\n write(BUILD)\n else:\n \n \n \n \n save(state_setter)\n save(obj)\n save(state)\n write(TUPLE2)\n \n write(REDUCE)\n \n \n \n \n write(POP)\n \n \n \n dispatch={}\n \n def save_none(self,obj):\n self.write(NONE)\n dispatch[type(None)]=save_none\n \n def save_bool(self,obj):\n if self.proto >=2:\n self.write(NEWTRUE if obj else NEWFALSE)\n else:\n self.write(TRUE if obj else FALSE)\n dispatch[bool]=save_bool\n \n def save_long(self,obj):\n if self.bin:\n \n \n \n \n if obj >=0:\n if obj <=0xff:\n self.write(BININT1+pack(\"=2:\n encoded=encode_long(obj)\n n=len(encoded)\n if n <256:\n self.write(LONG1+pack(\"d',obj))\n else:\n self.write(FLOAT+repr(obj).encode(\"ascii\")+b'\\n')\n dispatch[float]=save_float\n \n def _save_bytes_no_memo(self,obj):\n \n \n assert self.proto >=3\n n=len(obj)\n if n <=0xff:\n self.write(SHORT_BINBYTES+pack(\"0xffffffff and self.proto >=4:\n self._write_large_bytes(BINBYTES8+pack(\"=self.framer._FRAME_SIZE_TARGET:\n self._write_large_bytes(BINBYTES+pack(\"=5\n n=len(obj)\n if n >=self.framer._FRAME_SIZE_TARGET:\n self._write_large_bytes(BYTEARRAY8+pack(\"= 5\")\n with obj.raw()as m:\n if not m.contiguous:\n raise PicklingError(\"PickleBuffer can not be pickled when \"\n \"pointing to a non-contiguous buffer\")\n in_band=True\n if self._buffer_callback is not None:\n in_band=bool(self._buffer_callback(obj))\n if in_band:\n \n \n buf=m.tobytes()\n in_memo=id(buf)in self.memo\n if m.readonly:\n if in_memo:\n self._save_bytes_no_memo(buf)\n else:\n self.save_bytes(buf)\n else:\n if in_memo:\n self._save_bytearray_no_memo(buf)\n else:\n self.save_bytearray(buf)\n else:\n \n self.write(NEXT_BUFFER)\n if m.readonly:\n self.write(READONLY_BUFFER)\n \n dispatch[PickleBuffer]=save_picklebuffer\n \n def save_str(self,obj):\n if self.bin:\n encoded=obj.encode('utf-8','surrogatepass')\n n=len(encoded)\n if n <=0xff and self.proto >=4:\n self.write(SHORT_BINUNICODE+pack(\"0xffffffff and self.proto >=4:\n self._write_large_bytes(BINUNICODE8+pack(\"=self.framer._FRAME_SIZE_TARGET:\n self._write_large_bytes(BINUNICODE+pack(\"=2:\n for element in obj:\n save(element)\n \n if id(obj)in memo:\n get=self.get(memo[id(obj)][0])\n self.write(POP *n+get)\n else:\n self.write(_tuplesize2code[n])\n self.memoize(obj)\n return\n \n \n \n write=self.write\n write(MARK)\n for element in obj:\n save(element)\n \n if id(obj)in memo:\n \n \n \n \n \n \n \n get=self.get(memo[id(obj)][0])\n if self.bin:\n write(POP_MARK+get)\n else:\n write(POP *(n+1)+get)\n return\n \n \n write(TUPLE)\n self.memoize(obj)\n \n dispatch[tuple]=save_tuple\n \n def save_list(self,obj):\n if self.bin:\n self.write(EMPTY_LIST)\n else:\n self.write(MARK+LIST)\n \n self.memoize(obj)\n self._batch_appends(obj)\n \n dispatch[list]=save_list\n \n _BATCHSIZE=1000\n \n def _batch_appends(self,items):\n \n save=self.save\n write=self.write\n \n if not self.bin:\n for x in items:\n save(x)\n write(APPEND)\n return\n \n it=iter(items)\n while True:\n tmp=list(islice(it,self._BATCHSIZE))\n n=len(tmp)\n if n >1:\n write(MARK)\n for x in tmp:\n save(x)\n write(APPENDS)\n elif n:\n save(tmp[0])\n write(APPEND)\n \n if n 1:\n write(MARK)\n for k,v in tmp:\n save(k)\n save(v)\n write(SETITEMS)\n elif n:\n k,v=tmp[0]\n save(k)\n save(v)\n write(SETITEM)\n \n if n 0:\n write(MARK)\n for item in batch:\n save(item)\n write(ADDITEMS)\n if n =2:\n code=_extension_registry.get((module_name,name))\n if code:\n assert code >0\n if code <=0xff:\n write(EXT1+pack(\"=4:\n self.save(module_name)\n self.save(name)\n write(STACK_GLOBAL)\n elif parent is not module:\n self.save_reduce(getattr,(parent,lastname))\n elif self.proto >=3:\n write(GLOBAL+bytes(module_name,\"utf-8\")+b'\\n'+\n bytes(name,\"utf-8\")+b'\\n')\n else:\n if self.fix_imports:\n r_name_mapping=_compat_pickle.REVERSE_NAME_MAPPING\n r_import_mapping=_compat_pickle.REVERSE_IMPORT_MAPPING\n if(module_name,name)in r_name_mapping:\n module_name,name=r_name_mapping[(module_name,name)]\n elif module_name in r_import_mapping:\n module_name=r_import_mapping[module_name]\n try:\n write(GLOBAL+bytes(module_name,\"ascii\")+b'\\n'+\n bytes(name,\"ascii\")+b'\\n')\n except UnicodeEncodeError:\n raise PicklingError(\n \"can't pickle global identifier '%s.%s' using \"\n \"pickle protocol %i\"%(module,name,self.proto))from None\n \n self.memoize(obj)\n \n def save_type(self,obj):\n if obj is type(None):\n return self.save_reduce(type,(None,),obj=obj)\n elif obj is type(NotImplemented):\n return self.save_reduce(type,(NotImplemented,),obj=obj)\n elif obj is type(...):\n return self.save_reduce(type,(...,),obj=obj)\n return self.save_global(obj)\n \n dispatch[FunctionType]=save_global\n dispatch[type]=save_type\n \n \n \n \nclass _Unpickler:\n\n def __init__(self,file,*,fix_imports=True,\n encoding=\"ASCII\",errors=\"strict\",buffers=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._buffers=iter(buffers)if buffers is not None else None\n self._file_readline=file.readline\n self._file_read=file.read\n self.memo={}\n self.encoding=encoding\n self.errors=errors\n self.proto=0\n self.fix_imports=fix_imports\n \n def load(self):\n ''\n\n\n \n \n \n if not hasattr(self,\"_file_read\"):\n raise UnpicklingError(\"Unpickler.__init__() was not called by \"\n \"%s.__init__()\"%(self.__class__.__name__,))\n self._unframer=_Unframer(self._file_read,self._file_readline)\n self.read=self._unframer.read\n self.readinto=self._unframer.readinto\n self.readline=self._unframer.readline\n self.metastack=[]\n self.stack=[]\n self.append=self.stack.append\n self.proto=0\n read=self.read\n dispatch=self.dispatch\n try:\n while True:\n key=read(1)\n if not key:\n raise EOFError\n assert isinstance(key,bytes_types)\n dispatch[key[0]](self)\n except _Stop as stopinst:\n return stopinst.value\n \n \n def pop_mark(self):\n items=self.stack\n self.stack=self.metastack.pop()\n self.append=self.stack.append\n return items\n \n def persistent_load(self,pid):\n raise UnpicklingError(\"unsupported persistent id encountered\")\n \n dispatch={}\n \n def load_proto(self):\n proto=self.read(1)[0]\n if not 0 <=proto <=HIGHEST_PROTOCOL:\n raise ValueError(\"unsupported pickle protocol: %d\"%proto)\n self.proto=proto\n dispatch[PROTO[0]]=load_proto\n \n def load_frame(self):\n frame_size,=unpack('sys.maxsize:\n raise ValueError(\"frame size > sys.maxsize: %d\"%frame_size)\n self._unframer.load_frame(frame_size)\n dispatch[FRAME[0]]=load_frame\n \n def load_persid(self):\n try:\n pid=self.readline()[:-1].decode(\"ascii\")\n except UnicodeDecodeError:\n raise UnpicklingError(\n \"persistent IDs in protocol 0 must be ASCII strings\")\n self.append(self.persistent_load(pid))\n dispatch[PERSID[0]]=load_persid\n \n def load_binpersid(self):\n pid=self.stack.pop()\n self.append(self.persistent_load(pid))\n dispatch[BINPERSID[0]]=load_binpersid\n \n def load_none(self):\n self.append(None)\n dispatch[NONE[0]]=load_none\n \n def load_false(self):\n self.append(False)\n dispatch[NEWFALSE[0]]=load_false\n \n def load_true(self):\n self.append(True)\n dispatch[NEWTRUE[0]]=load_true\n \n def load_int(self):\n data=self.readline()\n if data ==FALSE[1:]:\n val=False\n elif data ==TRUE[1:]:\n val=True\n else:\n val=int(data,0)\n self.append(val)\n dispatch[INT[0]]=load_int\n \n def load_binint(self):\n self.append(unpack('d',self.read(8))[0])\n dispatch[BINFLOAT[0]]=load_binfloat\n \n def _decode_string(self,value):\n \n \n \n if self.encoding ==\"bytes\":\n return value\n else:\n return value.decode(self.encoding,self.errors)\n \n def load_string(self):\n data=self.readline()[:-1]\n \n if len(data)>=2 and data[0]==data[-1]and data[0]in b'\"\\'':\n data=data[1:-1]\n else:\n raise UnpicklingError(\"the STRING opcode argument must be quoted\")\n self.append(self._decode_string(codecs.escape_decode(data)[0]))\n dispatch[STRING[0]]=load_string\n \n def load_binstring(self):\n \n len,=unpack('maxsize:\n raise UnpicklingError(\"BINBYTES exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n self.append(self.read(len))\n dispatch[BINBYTES[0]]=load_binbytes\n \n def load_unicode(self):\n self.append(str(self.readline()[:-1],'raw-unicode-escape'))\n dispatch[UNICODE[0]]=load_unicode\n \n def load_binunicode(self):\n len,=unpack('maxsize:\n raise UnpicklingError(\"BINUNICODE exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n self.append(str(self.read(len),'utf-8','surrogatepass'))\n dispatch[BINUNICODE[0]]=load_binunicode\n \n def load_binunicode8(self):\n len,=unpack('maxsize:\n raise UnpicklingError(\"BINUNICODE8 exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n self.append(str(self.read(len),'utf-8','surrogatepass'))\n dispatch[BINUNICODE8[0]]=load_binunicode8\n \n def load_binbytes8(self):\n len,=unpack('maxsize:\n raise UnpicklingError(\"BINBYTES8 exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n self.append(self.read(len))\n dispatch[BINBYTES8[0]]=load_binbytes8\n \n def load_bytearray8(self):\n len,=unpack('maxsize:\n raise UnpicklingError(\"BYTEARRAY8 exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n b=bytearray(len)\n self.readinto(b)\n self.append(b)\n dispatch[BYTEARRAY8[0]]=load_bytearray8\n \n def load_next_buffer(self):\n if self._buffers is None:\n raise UnpicklingError(\"pickle stream refers to out-of-band data \"\n \"but no *buffers* argument was given\")\n try:\n buf=next(self._buffers)\n except StopIteration:\n raise UnpicklingError(\"not enough out-of-band buffers\")\n self.append(buf)\n dispatch[NEXT_BUFFER[0]]=load_next_buffer\n \n def load_readonly_buffer(self):\n buf=self.stack[-1]\n with memoryview(buf)as m:\n if not m.readonly:\n self.stack[-1]=m.toreadonly()\n dispatch[READONLY_BUFFER[0]]=load_readonly_buffer\n \n def load_short_binstring(self):\n len=self.read(1)[0]\n data=self.read(len)\n self.append(self._decode_string(data))\n dispatch[SHORT_BINSTRING[0]]=load_short_binstring\n \n def load_short_binbytes(self):\n len=self.read(1)[0]\n self.append(self.read(len))\n dispatch[SHORT_BINBYTES[0]]=load_short_binbytes\n \n def load_short_binunicode(self):\n len=self.read(1)[0]\n self.append(str(self.read(len),'utf-8','surrogatepass'))\n dispatch[SHORT_BINUNICODE[0]]=load_short_binunicode\n \n def load_tuple(self):\n items=self.pop_mark()\n self.append(tuple(items))\n dispatch[TUPLE[0]]=load_tuple\n \n def load_empty_tuple(self):\n self.append(())\n dispatch[EMPTY_TUPLE[0]]=load_empty_tuple\n \n def load_tuple1(self):\n self.stack[-1]=(self.stack[-1],)\n dispatch[TUPLE1[0]]=load_tuple1\n \n def load_tuple2(self):\n self.stack[-2:]=[(self.stack[-2],self.stack[-1])]\n dispatch[TUPLE2[0]]=load_tuple2\n \n def load_tuple3(self):\n self.stack[-3:]=[(self.stack[-3],self.stack[-2],self.stack[-1])]\n dispatch[TUPLE3[0]]=load_tuple3\n \n def load_empty_list(self):\n self.append([])\n dispatch[EMPTY_LIST[0]]=load_empty_list\n \n def load_empty_dictionary(self):\n self.append({})\n dispatch[EMPTY_DICT[0]]=load_empty_dictionary\n \n def load_empty_set(self):\n self.append(set())\n dispatch[EMPTY_SET[0]]=load_empty_set\n \n def load_frozenset(self):\n items=self.pop_mark()\n self.append(frozenset(items))\n dispatch[FROZENSET[0]]=load_frozenset\n \n def load_list(self):\n items=self.pop_mark()\n self.append(items)\n dispatch[LIST[0]]=load_list\n \n def load_dict(self):\n items=self.pop_mark()\n d={items[i]:items[i+1]\n for i in range(0,len(items),2)}\n self.append(d)\n dispatch[DICT[0]]=load_dict\n \n \n \n \n \n \n def _instantiate(self,klass,args):\n if(args or not isinstance(klass,type)or\n hasattr(klass,\"__getinitargs__\")):\n try:\n value=klass(*args)\n except TypeError as err:\n raise TypeError(\"in constructor for %s: %s\"%\n (klass.__name__,str(err)),err.__traceback__)\n else:\n value=klass.__new__(klass)\n self.append(value)\n \n def load_inst(self):\n module=self.readline()[:-1].decode(\"ascii\")\n name=self.readline()[:-1].decode(\"ascii\")\n klass=self.find_class(module,name)\n self._instantiate(klass,self.pop_mark())\n dispatch[INST[0]]=load_inst\n \n def load_obj(self):\n \n args=self.pop_mark()\n cls=args.pop(0)\n self._instantiate(cls,args)\n dispatch[OBJ[0]]=load_obj\n \n def load_newobj(self):\n args=self.stack.pop()\n cls=self.stack.pop()\n obj=cls.__new__(cls,*args)\n self.append(obj)\n dispatch[NEWOBJ[0]]=load_newobj\n \n def load_newobj_ex(self):\n kwargs=self.stack.pop()\n args=self.stack.pop()\n cls=self.stack.pop()\n obj=cls.__new__(cls,*args,**kwargs)\n self.append(obj)\n dispatch[NEWOBJ_EX[0]]=load_newobj_ex\n \n def load_global(self):\n module=self.readline()[:-1].decode(\"utf-8\")\n name=self.readline()[:-1].decode(\"utf-8\")\n klass=self.find_class(module,name)\n self.append(klass)\n dispatch[GLOBAL[0]]=load_global\n \n def load_stack_global(self):\n name=self.stack.pop()\n module=self.stack.pop()\n if type(name)is not str or type(module)is not str:\n raise UnpicklingError(\"STACK_GLOBAL requires str\")\n self.append(self.find_class(module,name))\n dispatch[STACK_GLOBAL[0]]=load_stack_global\n \n def load_ext1(self):\n code=self.read(1)[0]\n self.get_extension(code)\n dispatch[EXT1[0]]=load_ext1\n \n def load_ext2(self):\n code,=unpack('=4:\n return _getattribute(sys.modules[module],name)[0]\n else:\n return getattr(sys.modules[module],name)\n \n def load_reduce(self):\n stack=self.stack\n args=stack.pop()\n func=stack[-1]\n stack[-1]=func(*args)\n dispatch[REDUCE[0]]=load_reduce\n \n def load_pop(self):\n if self.stack:\n del self.stack[-1]\n else:\n self.pop_mark()\n dispatch[POP[0]]=load_pop\n \n def load_pop_mark(self):\n self.pop_mark()\n dispatch[POP_MARK[0]]=load_pop_mark\n \n def load_dup(self):\n self.append(self.stack[-1])\n dispatch[DUP[0]]=load_dup\n \n def load_get(self):\n i=int(self.readline()[:-1])\n try:\n self.append(self.memo[i])\n except KeyError:\n msg=f'Memo value not found at index {i}'\n raise UnpicklingError(msg)from None\n dispatch[GET[0]]=load_get\n \n def load_binget(self):\n i=self.read(1)[0]\n try:\n self.append(self.memo[i])\n except KeyError as exc:\n msg=f'Memo value not found at index {i}'\n raise UnpicklingError(msg)from None\n dispatch[BINGET[0]]=load_binget\n \n def load_long_binget(self):\n i,=unpack('maxsize:\n raise ValueError(\"negative LONG_BINPUT argument\")\n self.memo[i]=self.stack[-1]\n dispatch[LONG_BINPUT[0]]=load_long_binput\n \n def load_memoize(self):\n memo=self.memo\n memo[len(memo)]=self.stack[-1]\n dispatch[MEMOIZE[0]]=load_memoize\n \n def load_append(self):\n stack=self.stack\n value=stack.pop()\n list=stack[-1]\n list.append(value)\n dispatch[APPEND[0]]=load_append\n \n def load_appends(self):\n items=self.pop_mark()\n list_obj=self.stack[-1]\n try:\n extend=list_obj.extend\n except AttributeError:\n pass\n else:\n extend(items)\n return\n \n \n \n append=list_obj.append\n for item in items:\n append(item)\n dispatch[APPENDS[0]]=load_appends\n \n def load_setitem(self):\n stack=self.stack\n value=stack.pop()\n key=stack.pop()\n dict=stack[-1]\n dict[key]=value\n dispatch[SETITEM[0]]=load_setitem\n \n def load_setitems(self):\n items=self.pop_mark()\n dict=self.stack[-1]\n for i in range(0,len(items),2):\n dict[items[i]]=items[i+1]\n dispatch[SETITEMS[0]]=load_setitems\n \n def load_additems(self):\n items=self.pop_mark()\n set_obj=self.stack[-1]\n if isinstance(set_obj,set):\n set_obj.update(items)\n else:\n add=set_obj.add\n for item in items:\n add(item)\n dispatch[ADDITEMS[0]]=load_additems\n \n def load_build(self):\n stack=self.stack\n state=stack.pop()\n inst=stack[-1]\n setstate=getattr(inst,\"__setstate__\",_NoValue)\n if setstate is not _NoValue:\n setstate(state)\n return\n slotstate=None\n if isinstance(state,tuple)and len(state)==2:\n state,slotstate=state\n if state:\n inst_dict=inst.__dict__\n intern=sys.intern\n for k,v in state.items():\n if type(k)is str:\n inst_dict[intern(k)]=v\n else:\n inst_dict[k]=v\n if slotstate:\n for k,v in slotstate.items():\n setattr(inst,k,v)\n dispatch[BUILD[0]]=load_build\n \n def load_mark(self):\n self.metastack.append(self.stack)\n self.stack=[]\n self.append=self.stack.append\n dispatch[MARK[0]]=load_mark\n \n def load_stop(self):\n value=self.stack.pop()\n raise _Stop(value)\n dispatch[STOP[0]]=load_stop\n \n \n \n \ndef _dump(obj,file,protocol=None,*,fix_imports=True,buffer_callback=None):\n _Pickler(file,protocol,fix_imports=fix_imports,\n buffer_callback=buffer_callback).dump(obj)\n \ndef _dumps(obj,protocol=None,*,fix_imports=True,buffer_callback=None):\n f=io.BytesIO()\n _Pickler(f,protocol,fix_imports=fix_imports,\n buffer_callback=buffer_callback).dump(obj)\n res=f.getvalue()\n assert isinstance(res,bytes_types)\n return res\n \ndef _load(file,*,fix_imports=True,encoding=\"ASCII\",errors=\"strict\",\nbuffers=None):\n return _Unpickler(file,fix_imports=fix_imports,buffers=buffers,\n encoding=encoding,errors=errors).load()\n \ndef _loads(s,/,*,fix_imports=True,encoding=\"ASCII\",errors=\"strict\",\nbuffers=None):\n if isinstance(s,str):\n raise TypeError(\"Can't load pickle from unicode string\")\n file=io.BytesIO(s)\n return _Unpickler(file,fix_imports=fix_imports,buffers=buffers,\n encoding=encoding,errors=errors).load()\n \n \ntry:\n from _pickle import(\n PickleError,\n PicklingError,\n UnpicklingError,\n Pickler,\n Unpickler,\n dump,\n dumps,\n load,\n loads\n )\nexcept ImportError:\n Pickler,Unpickler=_Pickler,_Unpickler\n dump,dumps,load,loads=_dump,_dumps,_load,_loads\n \n \ndef _test():\n import doctest\n return doctest.testmod()\n \nif __name__ ==\"__main__\":\n import argparse\n parser=argparse.ArgumentParser(\n description='display contents of the pickle files')\n parser.add_argument(\n 'pickle_file',\n nargs='*',help='the pickle file')\n parser.add_argument(\n '-t','--test',action='store_true',\n help='run self-test suite')\n parser.add_argument(\n '-v',action='store_true',\n help='run verbosely; only affects self-test run')\n args=parser.parse_args()\n if args.test:\n _test()\n else:\n if not args.pickle_file:\n parser.print_help()\n else:\n import pprint\n for fn in args.pickle_file:\n if fn =='-':\n obj=load(sys.stdin.buffer)\n else:\n with open(fn,'rb')as f:\n obj=load(f)\n pprint.pprint(obj)\n", ["_compat_pickle", "_pickle", "argparse", "codecs", "copyreg", "doctest", "functools", "io", "itertools", "pprint", "re", "struct", "sys", "types"]], "pkgutil": [".py", "''\n\nfrom collections import namedtuple\nfrom functools import singledispatch as simplegeneric\nimport importlib\nimport importlib.util\nimport importlib.machinery\nimport os\nimport os.path\nimport sys\nfrom types import ModuleType\nimport warnings\n\n__all__=[\n'get_importer','iter_importers','get_loader','find_loader',\n'walk_packages','iter_modules','get_data',\n'read_code','extend_path',\n'ModuleInfo',\n]\n\n\nModuleInfo=namedtuple('ModuleInfo','module_finder name ispkg')\nModuleInfo.__doc__='A namedtuple with minimal info about a module.'\n\n\ndef read_code(stream):\n\n\n import marshal\n \n magic=stream.read(4)\n if magic !=importlib.util.MAGIC_NUMBER:\n return None\n \n stream.read(12)\n return marshal.load(stream)\n \n \ndef walk_packages(path=None,prefix='',onerror=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def seen(p,m={}):\n if p in m:\n return True\n m[p]=True\n \n for info in iter_modules(path,prefix):\n yield info\n \n if info.ispkg:\n try:\n __import__(info.name)\n except ImportError:\n if onerror is not None:\n onerror(info.name)\n except Exception:\n if onerror is not None:\n onerror(info.name)\n else:\n raise\n else:\n path=getattr(sys.modules[info.name],'__path__',None)or[]\n \n \n path=[p for p in path if not seen(p)]\n \n yield from walk_packages(path,info.name+'.',onerror)\n \n \ndef iter_modules(path=None,prefix=''):\n ''\n\n\n\n\n\n\n\n \n if path is None:\n importers=iter_importers()\n elif isinstance(path,str):\n raise ValueError(\"path must be None or list of paths to look for \"\n \"modules in\")\n else:\n importers=map(get_importer,path)\n \n yielded={}\n for i in importers:\n for name,ispkg in iter_importer_modules(i,prefix):\n if name not in yielded:\n yielded[name]=1\n yield ModuleInfo(i,name,ispkg)\n \n \n@simplegeneric\ndef iter_importer_modules(importer,prefix=''):\n if not hasattr(importer,'iter_modules'):\n return[]\n return importer.iter_modules(prefix)\n \n \n \ndef _iter_file_finder_modules(importer,prefix=''):\n if importer.path is None or not os.path.isdir(importer.path):\n return\n \n yielded={}\n import inspect\n try:\n filenames=os.listdir(importer.path)\n except OSError:\n \n filenames=[]\n filenames.sort()\n \n for fn in filenames:\n modname=inspect.getmodulename(fn)\n if modname =='__init__'or modname in yielded:\n continue\n \n path=os.path.join(importer.path,fn)\n ispkg=False\n \n if not modname and os.path.isdir(path)and '.'not in fn:\n modname=fn\n try:\n dircontents=os.listdir(path)\n except OSError:\n \n dircontents=[]\n for fn in dircontents:\n subname=inspect.getmodulename(fn)\n if subname =='__init__':\n ispkg=True\n break\n else:\n continue\n \n if modname and '.'not in modname:\n yielded[modname]=1\n yield prefix+modname,ispkg\n \niter_importer_modules.register(\nimportlib.machinery.FileFinder,_iter_file_finder_modules)\n\n\ntry:\n import zipimport\n from zipimport import zipimporter\n \n def iter_zipimport_modules(importer,prefix=''):\n dirlist=sorted(zipimport._zip_directory_cache[importer.archive])\n _prefix=importer.prefix\n plen=len(_prefix)\n yielded={}\n import inspect\n for fn in dirlist:\n if not fn.startswith(_prefix):\n continue\n \n fn=fn[plen:].split(os.sep)\n \n if len(fn)==2 and fn[1].startswith('__init__.py'):\n if fn[0]not in yielded:\n yielded[fn[0]]=1\n yield prefix+fn[0],True\n \n if len(fn)!=1:\n continue\n \n modname=inspect.getmodulename(fn[0])\n if modname =='__init__':\n continue\n \n if modname and '.'not in modname and modname not in yielded:\n yielded[modname]=1\n yield prefix+modname,False\n \n iter_importer_modules.register(zipimporter,iter_zipimport_modules)\n \nexcept ImportError:\n pass\n \n \ndef get_importer(path_item):\n ''\n\n\n\n\n\n\n \n path_item=os.fsdecode(path_item)\n try:\n importer=sys.path_importer_cache[path_item]\n except KeyError:\n for path_hook in sys.path_hooks:\n try:\n importer=path_hook(path_item)\n sys.path_importer_cache.setdefault(path_item,importer)\n break\n except ImportError:\n pass\n else:\n importer=None\n return importer\n \n \ndef iter_importers(fullname=\"\"):\n ''\n\n\n\n\n\n\n\n\n\n \n if fullname.startswith('.'):\n msg=\"Relative module name {!r} not supported\".format(fullname)\n raise ImportError(msg)\n if '.'in fullname:\n \n pkg_name=fullname.rpartition(\".\")[0]\n pkg=importlib.import_module(pkg_name)\n path=getattr(pkg,'__path__',None)\n if path is None:\n return\n else:\n yield from sys.meta_path\n path=sys.path\n for item in path:\n yield get_importer(item)\n \n \ndef get_loader(module_or_name):\n ''\n\n\n\n\n \n warnings._deprecated(\"pkgutil.get_loader\",\n f\"{warnings._DEPRECATED_MSG}; \"\n \"use importlib.util.find_spec() instead\",\n remove=(3,14))\n if module_or_name in sys.modules:\n module_or_name=sys.modules[module_or_name]\n if module_or_name is None:\n return None\n if isinstance(module_or_name,ModuleType):\n module=module_or_name\n loader=getattr(module,'__loader__',None)\n if loader is not None:\n return loader\n if getattr(module,'__spec__',None)is None:\n return None\n fullname=module.__name__\n else:\n fullname=module_or_name\n return find_loader(fullname)\n \n \ndef find_loader(fullname):\n ''\n\n\n\n\n \n warnings._deprecated(\"pkgutil.find_loader\",\n f\"{warnings._DEPRECATED_MSG}; \"\n \"use importlib.util.find_spec() instead\",\n remove=(3,14))\n if fullname.startswith('.'):\n msg=\"Relative module name {!r} not supported\".format(fullname)\n raise ImportError(msg)\n try:\n spec=importlib.util.find_spec(fullname)\n except(ImportError,AttributeError,TypeError,ValueError)as ex:\n \n \n \n msg=\"Error while finding loader for {!r} ({}: {})\"\n raise ImportError(msg.format(fullname,type(ex),ex))from ex\n return spec.loader if spec is not None else None\n \n \ndef extend_path(path,name):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not isinstance(path,list):\n \n \n return path\n \n sname_pkg=name+\".pkg\"\n \n path=path[:]\n \n parent_package,_,final_name=name.rpartition('.')\n if parent_package:\n try:\n search_path=sys.modules[parent_package].__path__\n except(KeyError,AttributeError):\n \n \n return path\n else:\n search_path=sys.path\n \n for dir in search_path:\n if not isinstance(dir,str):\n continue\n \n finder=get_importer(dir)\n if finder is not None:\n portions=[]\n if hasattr(finder,'find_spec'):\n spec=finder.find_spec(final_name)\n if spec is not None:\n portions=spec.submodule_search_locations or[]\n \n elif hasattr(finder,'find_loader'):\n _,portions=finder.find_loader(final_name)\n \n for portion in portions:\n \n \n if portion not in path:\n path.append(portion)\n \n \n \n pkgfile=os.path.join(dir,sname_pkg)\n if os.path.isfile(pkgfile):\n try:\n f=open(pkgfile)\n except OSError as msg:\n sys.stderr.write(\"Can't open %s: %s\\n\"%\n (pkgfile,msg))\n else:\n with f:\n for line in f:\n line=line.rstrip('\\n')\n if not line or line.startswith('#'):\n continue\n path.append(line)\n \n return path\n \n \ndef get_data(package,resource):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n spec=importlib.util.find_spec(package)\n if spec is None:\n return None\n loader=spec.loader\n if loader is None or not hasattr(loader,'get_data'):\n return None\n \n mod=(sys.modules.get(package)or\n importlib._bootstrap._load(spec))\n if mod is None or not hasattr(mod,'__file__'):\n return None\n \n \n \n \n parts=resource.split('/')\n parts.insert(0,os.path.dirname(mod.__file__))\n resource_name=os.path.join(*parts)\n return loader.get_data(resource_name)\n \n \n_NAME_PATTERN=None\n\ndef resolve_name(name):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _NAME_PATTERN\n if _NAME_PATTERN is None:\n \n import re\n dotted_words=r'(?!\\d)(\\w+)(\\.(?!\\d)(\\w+))*'\n _NAME_PATTERN=re.compile(f'^(?P{dotted_words})'\n f'(?P:(?P{dotted_words})?)?$',\n re.UNICODE)\n \n m=_NAME_PATTERN.match(name)\n if not m:\n raise ValueError(f'invalid format: {name !r}')\n gd=m.groupdict()\n if gd.get('cln'):\n \n mod=importlib.import_module(gd['pkg'])\n parts=gd.get('obj')\n parts=parts.split('.')if parts else[]\n else:\n \n parts=name.split('.')\n modname=parts.pop(0)\n \n mod=importlib.import_module(modname)\n while parts:\n p=parts[0]\n s=f'{modname}.{p}'\n try:\n mod=importlib.import_module(s)\n parts.pop(0)\n modname=s\n except ImportError:\n break\n \n \n \n result=mod\n for p in parts:\n result=getattr(result,p)\n return result\n", ["collections", "functools", "importlib", "importlib.machinery", "importlib.util", "inspect", "marshal", "os", "os.path", "re", "sys", "types", "warnings", "zipimport"]], "platform": [".py", "''\n\n\n\nfrom browser import self as window\n\ndef architecture(*args,**kw):\n return \"\",window.navigator.platform\n \ndef machine(*args,**kw):\n return ''\n \ndef node(*args,**kw):\n return ''\n \ndef platform(*args,**kw):\n return window.navigator.platform\n \ndef processor(*args,**kw):\n return ''\n \ndef python_build():\n return('.'.join(map(str,__BRYTHON__.implementation[:-1])),\n __BRYTHON__.compiled_date)\n \ndef python_compiler():\n return ''\n \ndef python_branch():\n return ''\n \ndef python_implementation():\n return 'Brython'\n \ndef python_revision():\n return ''\n \ndef python_version():\n return '.'.join(map(str,__BRYTHON__.version_info[:3]))\n \ndef python_version_tuple():\n return __BRYTHON__.version_info[:3]\n \ndef release():\n return ''\n \ndef system():\n return window.navigator.platform\n \ndef system_alias(*args,**kw):\n return window.navigator.platform\n \ndef uname():\n from collections import namedtuple\n klass=namedtuple('uname_result',\n 'system node release version machine processor')\n return klass(window.navigator.platform,'','','','','')\n", ["browser", "collections"]], "posixpath": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ncurdir='.'\npardir='..'\nextsep='.'\nsep='/'\npathsep=':'\ndefpath='/bin:/usr/bin'\naltsep=None\ndevnull='/dev/null'\n\nimport os\nimport sys\nimport stat\nimport genericpath\nfrom genericpath import *\n\n__all__=[\"normcase\",\"isabs\",\"join\",\"splitdrive\",\"splitroot\",\"split\",\"splitext\",\n\"basename\",\"dirname\",\"commonprefix\",\"getsize\",\"getmtime\",\n\"getatime\",\"getctime\",\"islink\",\"exists\",\"lexists\",\"isdir\",\"isfile\",\n\"ismount\",\"expanduser\",\"expandvars\",\"normpath\",\"abspath\",\n\"samefile\",\"sameopenfile\",\"samestat\",\n\"curdir\",\"pardir\",\"sep\",\"pathsep\",\"defpath\",\"altsep\",\"extsep\",\n\"devnull\",\"realpath\",\"supports_unicode_filenames\",\"relpath\",\n\"commonpath\",\"isjunction\"]\n\n\ndef _get_sep(path):\n if isinstance(path,bytes):\n return b'/'\n else:\n return '/'\n \n \n \n \n \n \ndef normcase(s):\n ''\n return os.fspath(s)\n \n \n \n \n \ndef isabs(s):\n ''\n s=os.fspath(s)\n sep=_get_sep(s)\n return s.startswith(sep)\n \n \n \n \n \n \ndef join(a,*p):\n ''\n\n\n \n a=os.fspath(a)\n sep=_get_sep(a)\n path=a\n try:\n if not p:\n path[:0]+sep\n for b in map(os.fspath,p):\n if b.startswith(sep):\n path=b\n elif not path or path.endswith(sep):\n path +=b\n else:\n path +=sep+b\n except(TypeError,AttributeError,BytesWarning):\n genericpath._check_arg_types('join',a,*p)\n raise\n return path\n \n \n \n \n \n \n \ndef split(p):\n ''\n \n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n head,tail=p[:i],p[i:]\n if head and head !=sep *len(head):\n head=head.rstrip(sep)\n return head,tail\n \n \n \n \n \n \n \ndef splitext(p):\n p=os.fspath(p)\n if isinstance(p,bytes):\n sep=b'/'\n extsep=b'.'\n else:\n sep='/'\n extsep='.'\n return genericpath._splitext(p,sep,None,extsep)\nsplitext.__doc__=genericpath._splitext.__doc__\n\n\n\n\ndef splitdrive(p):\n ''\n \n p=os.fspath(p)\n return p[:0],p\n \n \ndef splitroot(p):\n ''\n\n\n\n\n\n\n\n \n p=os.fspath(p)\n if isinstance(p,bytes):\n sep=b'/'\n empty=b''\n else:\n sep='/'\n empty=''\n if p[:1]!=sep:\n \n return empty,empty,p\n elif p[1:2]!=sep or p[2:3]==sep:\n \n return empty,sep,p[1:]\n else:\n \n \n return empty,p[:2],p[2:]\n \n \n \n \ndef basename(p):\n ''\n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n return p[i:]\n \n \n \n \ndef dirname(p):\n ''\n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n head=p[:i]\n if head and head !=sep *len(head):\n head=head.rstrip(sep)\n return head\n \n \n \n \ndef isjunction(path):\n ''\n \n os.fspath(path)\n return False\n \n \n \n \ndef lexists(path):\n ''\n try:\n os.lstat(path)\n except(OSError,ValueError):\n return False\n return True\n \n \n \n \n \ndef ismount(path):\n ''\n try:\n s1=os.lstat(path)\n except(OSError,ValueError):\n \n return False\n else:\n \n if stat.S_ISLNK(s1.st_mode):\n return False\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n parent=join(path,b'..')\n else:\n parent=join(path,'..')\n parent=realpath(parent)\n try:\n s2=os.lstat(parent)\n except(OSError,ValueError):\n return False\n \n dev1=s1.st_dev\n dev2=s2.st_dev\n if dev1 !=dev2:\n return True\n ino1=s1.st_ino\n ino2=s2.st_ino\n if ino1 ==ino2:\n return True\n return False\n \n \n \n \n \n \n \n \n \n \n \ndef expanduser(path):\n ''\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n tilde=b'~'\n else:\n tilde='~'\n if not path.startswith(tilde):\n return path\n sep=_get_sep(path)\n i=path.find(sep,1)\n if i <0:\n i=len(path)\n if i ==1:\n if 'HOME'not in os.environ:\n try:\n import pwd\n except ImportError:\n \n return path\n try:\n userhome=pwd.getpwuid(os.getuid()).pw_dir\n except KeyError:\n \n \n return path\n else:\n userhome=os.environ['HOME']\n else:\n try:\n import pwd\n except ImportError:\n \n return path\n name=path[1:i]\n if isinstance(name,bytes):\n name=str(name,'ASCII')\n try:\n pwent=pwd.getpwnam(name)\n except KeyError:\n \n \n return path\n userhome=pwent.pw_dir\n \n if userhome is None and sys.platform ==\"vxworks\":\n return path\n if isinstance(path,bytes):\n userhome=os.fsencode(userhome)\n root=b'/'\n else:\n root='/'\n userhome=userhome.rstrip(root)\n return(userhome+path[i:])or root\n \n \n \n \n \n \n_varprog=None\n_varprogb=None\n\ndef expandvars(path):\n ''\n \n path=os.fspath(path)\n global _varprog,_varprogb\n if isinstance(path,bytes):\n if b'$'not in path:\n return path\n if not _varprogb:\n import re\n _varprogb=re.compile(br'\\$(\\w+|\\{[^}]*\\})',re.ASCII)\n search=_varprogb.search\n start=b'{'\n end=b'}'\n environ=getattr(os,'environb',None)\n else:\n if '$'not in path:\n return path\n if not _varprog:\n import re\n _varprog=re.compile(r'\\$(\\w+|\\{[^}]*\\})',re.ASCII)\n search=_varprog.search\n start='{'\n end='}'\n environ=os.environ\n i=0\n while True:\n m=search(path,i)\n if not m:\n break\n i,j=m.span(0)\n name=m.group(1)\n if name.startswith(start)and name.endswith(end):\n name=name[1:-1]\n try:\n if environ is None:\n value=os.fsencode(os.environ[os.fsdecode(name)])\n else:\n value=environ[name]\n except KeyError:\n i=j\n else:\n tail=path[j:]\n path=path[:i]+value\n i=len(path)\n path +=tail\n return path\n \n \n \n \n \n \ntry:\n from posix import _path_normpath\n \nexcept ImportError:\n def normpath(path):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n sep=b'/'\n empty=b''\n dot=b'.'\n dotdot=b'..'\n else:\n sep='/'\n empty=''\n dot='.'\n dotdot='..'\n if path ==empty:\n return dot\n _,initial_slashes,path=splitroot(path)\n comps=path.split(sep)\n new_comps=[]\n for comp in comps:\n if comp in(empty,dot):\n continue\n if(comp !=dotdot or(not initial_slashes and not new_comps)or\n (new_comps and new_comps[-1]==dotdot)):\n new_comps.append(comp)\n elif new_comps:\n new_comps.pop()\n comps=new_comps\n path=initial_slashes+sep.join(comps)\n return path or dot\n \nelse:\n def normpath(path):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n return os.fsencode(_path_normpath(os.fsdecode(path)))or b\".\"\n return _path_normpath(path)or \".\"\n \n \ndef abspath(path):\n ''\n path=os.fspath(path)\n if not isabs(path):\n if isinstance(path,bytes):\n cwd=os.getcwdb()\n else:\n cwd=os.getcwd()\n path=join(cwd,path)\n return normpath(path)\n \n \n \n \n \ndef realpath(filename,*,strict=False):\n ''\n \n filename=os.fspath(filename)\n path,ok=_joinrealpath(filename[:0],filename,strict,{})\n return abspath(path)\n \n \n \ndef _joinrealpath(path,rest,strict,seen):\n if isinstance(path,bytes):\n sep=b'/'\n curdir=b'.'\n pardir=b'..'\n else:\n sep='/'\n curdir='.'\n pardir='..'\n \n if isabs(rest):\n rest=rest[1:]\n path=sep\n \n while rest:\n name,_,rest=rest.partition(sep)\n if not name or name ==curdir:\n \n continue\n if name ==pardir:\n \n if path:\n path,name=split(path)\n if name ==pardir:\n path=join(path,pardir,pardir)\n else:\n path=pardir\n continue\n newpath=join(path,name)\n try:\n st=os.lstat(newpath)\n except OSError:\n if strict:\n raise\n is_link=False\n else:\n is_link=stat.S_ISLNK(st.st_mode)\n if not is_link:\n path=newpath\n continue\n \n if newpath in seen:\n \n path=seen[newpath]\n if path is not None:\n \n continue\n \n if strict:\n \n os.stat(newpath)\n else:\n \n return join(newpath,rest),False\n seen[newpath]=None\n path,ok=_joinrealpath(path,os.readlink(newpath),strict,seen)\n if not ok:\n return join(path,rest),False\n seen[newpath]=path\n \n return path,True\n \n \nsupports_unicode_filenames=(sys.platform =='darwin')\n\ndef relpath(path,start=None):\n ''\n \n if not path:\n raise ValueError(\"no path specified\")\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n curdir=b'.'\n sep=b'/'\n pardir=b'..'\n else:\n curdir='.'\n sep='/'\n pardir='..'\n \n if start is None:\n start=curdir\n else:\n start=os.fspath(start)\n \n try:\n start_list=[x for x in abspath(start).split(sep)if x]\n path_list=[x for x in abspath(path).split(sep)if x]\n \n i=len(commonprefix([start_list,path_list]))\n \n rel_list=[pardir]*(len(start_list)-i)+path_list[i:]\n if not rel_list:\n return curdir\n return join(*rel_list)\n except(TypeError,AttributeError,BytesWarning,DeprecationWarning):\n genericpath._check_arg_types('relpath',path,start)\n raise\n \n \n \n \n \n \n \ndef commonpath(paths):\n ''\n \n if not paths:\n raise ValueError('commonpath() arg is an empty sequence')\n \n paths=tuple(map(os.fspath,paths))\n if isinstance(paths[0],bytes):\n sep=b'/'\n curdir=b'.'\n else:\n sep='/'\n curdir='.'\n \n try:\n split_paths=[path.split(sep)for path in paths]\n \n try:\n isabs,=set(p[:1]==sep for p in paths)\n except ValueError:\n raise ValueError(\"Can't mix absolute and relative paths\")from None\n \n split_paths=[[c for c in s if c and c !=curdir]for s in split_paths]\n s1=min(split_paths)\n s2=max(split_paths)\n common=s1\n for i,c in enumerate(s1):\n if c !=s2[i]:\n common=s1[:i]\n break\n \n prefix=sep if isabs else sep[:0]\n return prefix+sep.join(common)\n except(TypeError,AttributeError):\n genericpath._check_arg_types('commonpath',*paths)\n raise\n \n", ["genericpath", "os", "posix", "pwd", "re", "stat", "sys"]], "pprint": [".py", "\n\n\n\n\n\n\n\n\n\n\"\"\"Support to pretty-print lists, tuples, & dictionaries recursively.\n\nVery simple, but useful, especially in debugging data structures.\n\nClasses\n-------\n\nPrettyPrinter()\n Handle pretty-printing operations onto a stream using a configured\n set of formatting parameters.\n\nFunctions\n---------\n\npformat()\n Format a Python object into a pretty-printed representation.\n\npprint()\n Pretty-print a Python object to a stream [default is sys.stdout].\n\nsaferepr()\n Generate a 'standard' repr()-like value, but protect against recursive\n data structures.\n\n\"\"\"\n\nimport collections as _collections\nimport dataclasses as _dataclasses\nimport re\nimport sys as _sys\nimport types as _types\nfrom io import StringIO as _StringIO\n\n__all__=[\"pprint\",\"pformat\",\"isreadable\",\"isrecursive\",\"saferepr\",\n\"PrettyPrinter\",\"pp\"]\n\n\ndef pprint(object,stream=None,indent=1,width=80,depth=None,*,\ncompact=False,sort_dicts=True,underscore_numbers=False):\n ''\n printer=PrettyPrinter(\n stream=stream,indent=indent,width=width,depth=depth,\n compact=compact,sort_dicts=sort_dicts,\n underscore_numbers=underscore_numbers)\n printer.pprint(object)\n \ndef pformat(object,indent=1,width=80,depth=None,*,\ncompact=False,sort_dicts=True,underscore_numbers=False):\n ''\n return PrettyPrinter(indent=indent,width=width,depth=depth,\n compact=compact,sort_dicts=sort_dicts,\n underscore_numbers=underscore_numbers).pformat(object)\n \ndef pp(object,*args,sort_dicts=False,**kwargs):\n ''\n pprint(object,*args,sort_dicts=sort_dicts,**kwargs)\n \ndef saferepr(object):\n ''\n return PrettyPrinter()._safe_repr(object,{},None,0)[0]\n \ndef isreadable(object):\n ''\n return PrettyPrinter()._safe_repr(object,{},None,0)[1]\n \ndef isrecursive(object):\n ''\n return PrettyPrinter()._safe_repr(object,{},None,0)[2]\n \nclass _safe_key:\n ''\n\n\n\n\n\n\n \n \n __slots__=['obj']\n \n def __init__(self,obj):\n self.obj=obj\n \n def __lt__(self,other):\n try:\n return self.obj = 0')\n if depth is not None and depth <=0:\n raise ValueError('depth must be > 0')\n if not width:\n raise ValueError('width must be != 0')\n self._depth=depth\n self._indent_per_level=indent\n self._width=width\n if stream is not None:\n self._stream=stream\n else:\n self._stream=_sys.stdout\n self._compact=bool(compact)\n self._sort_dicts=sort_dicts\n self._underscore_numbers=underscore_numbers\n \n def pprint(self,object):\n if self._stream is not None:\n self._format(object,self._stream,0,0,{},0)\n self._stream.write(\"\\n\")\n \n def pformat(self,object):\n sio=_StringIO()\n self._format(object,sio,0,0,{},0)\n return sio.getvalue()\n \n def isrecursive(self,object):\n return self.format(object,{},0,0)[2]\n \n def isreadable(self,object):\n s,readable,recursive=self.format(object,{},0,0)\n return readable and not recursive\n \n def _format(self,object,stream,indent,allowance,context,level):\n objid=id(object)\n if objid in context:\n stream.write(_recursion(object))\n self._recursive=True\n self._readable=False\n return\n rep=self._repr(object,context,level)\n max_width=self._width -indent -allowance\n if len(rep)>max_width:\n p=self._dispatch.get(type(object).__repr__,None)\n if p is not None:\n context[objid]=1\n p(self,object,stream,indent,allowance,context,level+1)\n del context[objid]\n return\n elif(_dataclasses.is_dataclass(object)and\n not isinstance(object,type)and\n object.__dataclass_params__.repr and\n \n hasattr(object.__repr__,\"__wrapped__\")and\n \"__create_fn__\"in object.__repr__.__wrapped__.__qualname__):\n context[objid]=1\n self._pprint_dataclass(object,stream,indent,allowance,context,level+1)\n del context[objid]\n return\n stream.write(rep)\n \n def _pprint_dataclass(self,object,stream,indent,allowance,context,level):\n cls_name=object.__class__.__name__\n indent +=len(cls_name)+1\n items=[(f.name,getattr(object,f.name))for f in _dataclasses.fields(object)if f.repr]\n stream.write(cls_name+'(')\n self._format_namespace_items(items,stream,indent,allowance,context,level)\n stream.write(')')\n \n _dispatch={}\n \n def _pprint_dict(self,object,stream,indent,allowance,context,level):\n write=stream.write\n write('{')\n if self._indent_per_level >1:\n write((self._indent_per_level -1)*' ')\n length=len(object)\n if length:\n if self._sort_dicts:\n items=sorted(object.items(),key=_safe_tuple)\n else:\n items=object.items()\n self._format_dict_items(items,stream,indent,allowance+1,\n context,level)\n write('}')\n \n _dispatch[dict.__repr__]=_pprint_dict\n \n def _pprint_ordered_dict(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n self._format(list(object.items()),stream,\n indent+len(cls.__name__)+1,allowance+1,\n context,level)\n stream.write(')')\n \n _dispatch[_collections.OrderedDict.__repr__]=_pprint_ordered_dict\n \n def _pprint_list(self,object,stream,indent,allowance,context,level):\n stream.write('[')\n self._format_items(object,stream,indent,allowance+1,\n context,level)\n stream.write(']')\n \n _dispatch[list.__repr__]=_pprint_list\n \n def _pprint_tuple(self,object,stream,indent,allowance,context,level):\n stream.write('(')\n endchar=',)'if len(object)==1 else ')'\n self._format_items(object,stream,indent,allowance+len(endchar),\n context,level)\n stream.write(endchar)\n \n _dispatch[tuple.__repr__]=_pprint_tuple\n \n def _pprint_set(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n typ=object.__class__\n if typ is set:\n stream.write('{')\n endchar='}'\n else:\n stream.write(typ.__name__+'({')\n endchar='})'\n indent +=len(typ.__name__)+1\n object=sorted(object,key=_safe_key)\n self._format_items(object,stream,indent,allowance+len(endchar),\n context,level)\n stream.write(endchar)\n \n _dispatch[set.__repr__]=_pprint_set\n _dispatch[frozenset.__repr__]=_pprint_set\n \n def _pprint_str(self,object,stream,indent,allowance,context,level):\n write=stream.write\n if not len(object):\n write(repr(object))\n return\n chunks=[]\n lines=object.splitlines(True)\n if level ==1:\n indent +=1\n allowance +=1\n max_width1=max_width=self._width -indent\n for i,line in enumerate(lines):\n rep=repr(line)\n if i ==len(lines)-1:\n max_width1 -=allowance\n if len(rep)<=max_width1:\n chunks.append(rep)\n else:\n \n parts=re.findall(r'\\S*\\s*',line)\n assert parts\n assert not parts[-1]\n parts.pop()\n max_width2=max_width\n current=''\n for j,part in enumerate(parts):\n candidate=current+part\n if j ==len(parts)-1 and i ==len(lines)-1:\n max_width2 -=allowance\n if len(repr(candidate))>max_width2:\n if current:\n chunks.append(repr(current))\n current=part\n else:\n current=candidate\n if current:\n chunks.append(repr(current))\n if len(chunks)==1:\n write(rep)\n return\n if level ==1:\n write('(')\n for i,rep in enumerate(chunks):\n if i >0:\n write('\\n'+' '*indent)\n write(rep)\n if level ==1:\n write(')')\n \n _dispatch[str.__repr__]=_pprint_str\n \n def _pprint_bytes(self,object,stream,indent,allowance,context,level):\n write=stream.write\n if len(object)<=4:\n write(repr(object))\n return\n parens=level ==1\n if parens:\n indent +=1\n allowance +=1\n write('(')\n delim=''\n for rep in _wrap_bytes_repr(object,self._width -indent,allowance):\n write(delim)\n write(rep)\n if not delim:\n delim='\\n'+' '*indent\n if parens:\n write(')')\n \n _dispatch[bytes.__repr__]=_pprint_bytes\n \n def _pprint_bytearray(self,object,stream,indent,allowance,context,level):\n write=stream.write\n write('bytearray(')\n self._pprint_bytes(bytes(object),stream,indent+10,\n allowance+1,context,level+1)\n write(')')\n \n _dispatch[bytearray.__repr__]=_pprint_bytearray\n \n def _pprint_mappingproxy(self,object,stream,indent,allowance,context,level):\n stream.write('mappingproxy(')\n self._format(object.copy(),stream,indent+13,allowance+1,\n context,level)\n stream.write(')')\n \n _dispatch[_types.MappingProxyType.__repr__]=_pprint_mappingproxy\n \n def _pprint_simplenamespace(self,object,stream,indent,allowance,context,level):\n if type(object)is _types.SimpleNamespace:\n \n \n cls_name='namespace'\n else:\n cls_name=object.__class__.__name__\n indent +=len(cls_name)+1\n items=object.__dict__.items()\n stream.write(cls_name+'(')\n self._format_namespace_items(items,stream,indent,allowance,context,level)\n stream.write(')')\n \n _dispatch[_types.SimpleNamespace.__repr__]=_pprint_simplenamespace\n \n def _format_dict_items(self,items,stream,indent,allowance,context,\n level):\n write=stream.write\n indent +=self._indent_per_level\n delimnl=',\\n'+' '*indent\n last_index=len(items)-1\n for i,(key,ent)in enumerate(items):\n last=i ==last_index\n rep=self._repr(key,context,level)\n write(rep)\n write(': ')\n self._format(ent,stream,indent+len(rep)+2,\n allowance if last else 1,\n context,level)\n if not last:\n write(delimnl)\n \n def _format_namespace_items(self,items,stream,indent,allowance,context,level):\n write=stream.write\n delimnl=',\\n'+' '*indent\n last_index=len(items)-1\n for i,(key,ent)in enumerate(items):\n last=i ==last_index\n write(key)\n write('=')\n if id(ent)in context:\n \n \n write(\"...\")\n else:\n self._format(ent,stream,indent+len(key)+1,\n allowance if last else 1,\n context,level)\n if not last:\n write(delimnl)\n \n def _format_items(self,items,stream,indent,allowance,context,level):\n write=stream.write\n indent +=self._indent_per_level\n if self._indent_per_level >1:\n write((self._indent_per_level -1)*' ')\n delimnl=',\\n'+' '*indent\n delim=''\n width=max_width=self._width -indent+1\n it=iter(items)\n try:\n next_ent=next(it)\n except StopIteration:\n return\n last=False\n while not last:\n ent=next_ent\n try:\n next_ent=next(it)\n except StopIteration:\n last=True\n max_width -=allowance\n width -=allowance\n if self._compact:\n rep=self._repr(ent,context,level)\n w=len(rep)+2\n if width =w:\n width -=w\n write(delim)\n delim=', '\n write(rep)\n continue\n write(delim)\n delim=delimnl\n self._format(ent,stream,indent,\n allowance if last else 1,\n context,level)\n \n def _repr(self,object,context,level):\n repr,readable,recursive=self.format(object,context.copy(),\n self._depth,level)\n if not readable:\n self._readable=False\n if recursive:\n self._recursive=True\n return repr\n \n def format(self,object,context,maxlevels,level):\n ''\n\n\n \n return self._safe_repr(object,context,maxlevels,level)\n \n def _pprint_default_dict(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n rdf=self._repr(object.default_factory,context,level)\n cls=object.__class__\n indent +=len(cls.__name__)+1\n stream.write('%s(%s,\\n%s'%(cls.__name__,rdf,' '*indent))\n self._pprint_dict(object,stream,indent,allowance+1,context,level)\n stream.write(')')\n \n _dispatch[_collections.defaultdict.__repr__]=_pprint_default_dict\n \n def _pprint_counter(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'({')\n if self._indent_per_level >1:\n stream.write((self._indent_per_level -1)*' ')\n items=object.most_common()\n self._format_dict_items(items,stream,\n indent+len(cls.__name__)+1,allowance+2,\n context,level)\n stream.write('})')\n \n _dispatch[_collections.Counter.__repr__]=_pprint_counter\n \n def _pprint_chain_map(self,object,stream,indent,allowance,context,level):\n if not len(object.maps):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n indent +=len(cls.__name__)+1\n for i,m in enumerate(object.maps):\n if i ==len(object.maps)-1:\n self._format(m,stream,indent,allowance+1,context,level)\n stream.write(')')\n else:\n self._format(m,stream,indent,1,context,level)\n stream.write(',\\n'+' '*indent)\n \n _dispatch[_collections.ChainMap.__repr__]=_pprint_chain_map\n \n def _pprint_deque(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n indent +=len(cls.__name__)+1\n stream.write('[')\n if object.maxlen is None:\n self._format_items(object,stream,indent,allowance+2,\n context,level)\n stream.write('])')\n else:\n self._format_items(object,stream,indent,2,\n context,level)\n rml=self._repr(object.maxlen,context,level)\n stream.write('],\\n%smaxlen=%s)'%(' '*indent,rml))\n \n _dispatch[_collections.deque.__repr__]=_pprint_deque\n \n def _pprint_user_dict(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserDict.__repr__]=_pprint_user_dict\n \n def _pprint_user_list(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserList.__repr__]=_pprint_user_list\n \n def _pprint_user_string(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserString.__repr__]=_pprint_user_string\n \n def _safe_repr(self,object,context,maxlevels,level):\n \n typ=type(object)\n if typ in _builtin_scalars:\n return repr(object),True,False\n \n r=getattr(typ,\"__repr__\",None)\n \n if issubclass(typ,int)and r is int.__repr__:\n if self._underscore_numbers:\n return f\"{object:_d}\",True,False\n else:\n return repr(object),True,False\n \n if issubclass(typ,dict)and r is dict.__repr__:\n if not object:\n return \"{}\",True,False\n objid=id(object)\n if maxlevels and level >=maxlevels:\n return \"{...}\",False,objid in context\n if objid in context:\n return _recursion(object),False,True\n context[objid]=1\n readable=True\n recursive=False\n components=[]\n append=components.append\n level +=1\n if self._sort_dicts:\n items=sorted(object.items(),key=_safe_tuple)\n else:\n items=object.items()\n for k,v in items:\n krepr,kreadable,krecur=self.format(\n k,context,maxlevels,level)\n vrepr,vreadable,vrecur=self.format(\n v,context,maxlevels,level)\n append(\"%s: %s\"%(krepr,vrepr))\n readable=readable and kreadable and vreadable\n if krecur or vrecur:\n recursive=True\n del context[objid]\n return \"{%s}\"%\", \".join(components),readable,recursive\n \n if(issubclass(typ,list)and r is list.__repr__)or\\\n (issubclass(typ,tuple)and r is tuple.__repr__):\n if issubclass(typ,list):\n if not object:\n return \"[]\",True,False\n format=\"[%s]\"\n elif len(object)==1:\n format=\"(%s,)\"\n else:\n if not object:\n return \"()\",True,False\n format=\"(%s)\"\n objid=id(object)\n if maxlevels and level >=maxlevels:\n return format %\"...\",False,objid in context\n if objid in context:\n return _recursion(object),False,True\n context[objid]=1\n readable=True\n recursive=False\n components=[]\n append=components.append\n level +=1\n for o in object:\n orepr,oreadable,orecur=self.format(\n o,context,maxlevels,level)\n append(orepr)\n if not oreadable:\n readable=False\n if orecur:\n recursive=True\n del context[objid]\n return format %\", \".join(components),readable,recursive\n \n rep=repr(object)\n return rep,(rep and not rep.startswith('<')),False\n \n_builtin_scalars=frozenset({str,bytes,bytearray,float,complex,\nbool,type(None)})\n\ndef _recursion(object):\n return(\"\"\n %(type(object).__name__,id(object)))\n \n \ndef _wrap_bytes_repr(object,width,allowance):\n current=b''\n last=len(object)//4 *4\n for i in range(0,len(object),4):\n part=object[i:i+4]\n candidate=current+part\n if i ==last:\n width -=allowance\n if len(repr(candidate))>width:\n if current:\n yield repr(current)\n current=part\n else:\n current=candidate\n if current:\n yield repr(current)\n", ["collections", "dataclasses", "io", "re", "sys", "types"]], "profile": [".py", "#! /usr/bin/env python3\n\n\n\n\n\n\n\n\"\"\"Class for profiling Python code.\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport importlib.machinery\nimport io\nimport sys\nimport time\nimport marshal\n\n__all__=[\"run\",\"runctx\",\"Profile\"]\n\n\n\n\n\n\n\n\n\nclass _Utils:\n ''\n\n\n \n \n def __init__(self,profiler):\n self.profiler=profiler\n \n def run(self,statement,filename,sort):\n prof=self.profiler()\n try:\n prof.run(statement)\n except SystemExit:\n pass\n finally:\n self._show(prof,filename,sort)\n \n def runctx(self,statement,globals,locals,filename,sort):\n prof=self.profiler()\n try:\n prof.runctx(statement,globals,locals)\n except SystemExit:\n pass\n finally:\n self._show(prof,filename,sort)\n \n def _show(self,prof,filename,sort):\n if filename is not None:\n prof.dump_stats(filename)\n else:\n prof.print_stats(sort)\n \n \n \n \n \n \n \ndef run(statement,filename=None,sort=-1):\n ''\n\n\n\n\n\n\n\n\n \n return _Utils(Profile).run(statement,filename,sort)\n \ndef runctx(statement,globals,locals,filename=None,sort=-1):\n ''\n\n\n\n \n return _Utils(Profile).runctx(statement,globals,locals,filename,sort)\n \n \nclass Profile:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n bias=0\n \n def __init__(self,timer=None,bias=None):\n self.timings={}\n self.cur=None\n self.cmd=\"\"\n self.c_func_name=\"\"\n \n if bias is None:\n bias=self.bias\n self.bias=bias\n \n if not timer:\n self.timer=self.get_time=time.process_time\n self.dispatcher=self.trace_dispatch_i\n else:\n self.timer=timer\n t=self.timer()\n try:\n length=len(t)\n except TypeError:\n self.get_time=timer\n self.dispatcher=self.trace_dispatch_i\n else:\n if length ==2:\n self.dispatcher=self.trace_dispatch\n else:\n self.dispatcher=self.trace_dispatch_l\n \n \n \n \n \n def get_time_timer(timer=timer,sum=sum):\n return sum(timer())\n self.get_time=get_time_timer\n self.t=self.get_time()\n self.simulate_call('profiler')\n \n \n \n def trace_dispatch(self,frame,event,arg):\n timer=self.timer\n t=timer()\n t=t[0]+t[1]-self.t -self.bias\n \n if event ==\"c_call\":\n self.c_func_name=arg.__name__\n \n if self.dispatch[event](self,frame,t):\n t=timer()\n self.t=t[0]+t[1]\n else:\n r=timer()\n self.t=r[0]+r[1]-t\n \n \n \n \n def trace_dispatch_i(self,frame,event,arg):\n timer=self.timer\n t=timer()-self.t -self.bias\n \n if event ==\"c_call\":\n self.c_func_name=arg.__name__\n \n if self.dispatch[event](self,frame,t):\n self.t=timer()\n else:\n self.t=timer()-t\n \n \n \n \n def trace_dispatch_mac(self,frame,event,arg):\n timer=self.timer\n t=timer()/60.0 -self.t -self.bias\n \n if event ==\"c_call\":\n self.c_func_name=arg.__name__\n \n if self.dispatch[event](self,frame,t):\n self.t=timer()/60.0\n else:\n self.t=timer()/60.0 -t\n \n \n \n def trace_dispatch_l(self,frame,event,arg):\n get_time=self.get_time\n t=get_time()-self.t -self.bias\n \n if event ==\"c_call\":\n self.c_func_name=arg.__name__\n \n if self.dispatch[event](self,frame,t):\n self.t=get_time()\n else:\n self.t=get_time()-t\n \n \n \n \n \n \n \n \n def trace_dispatch_exception(self,frame,t):\n rpt,rit,ret,rfn,rframe,rcur=self.cur\n if(rframe is not frame)and rcur:\n return self.trace_dispatch_return(rframe,t)\n self.cur=rpt,rit+t,ret,rfn,rframe,rcur\n return 1\n \n \n def trace_dispatch_call(self,frame,t):\n if self.cur and frame.f_back is not self.cur[-2]:\n rpt,rit,ret,rfn,rframe,rcur=self.cur\n if not isinstance(rframe,Profile.fake_frame):\n assert rframe.f_back is frame.f_back,(\"Bad call\",rfn,\n rframe,rframe.f_back,\n frame,frame.f_back)\n self.trace_dispatch_return(rframe,0)\n assert(self.cur is None or\\\n frame.f_back is self.cur[-2]),(\"Bad call\",\n self.cur[-3])\n fcode=frame.f_code\n fn=(fcode.co_filename,fcode.co_firstlineno,fcode.co_name)\n self.cur=(t,0,0,fn,frame,self.cur)\n timings=self.timings\n if fn in timings:\n cc,ns,tt,ct,callers=timings[fn]\n timings[fn]=cc,ns+1,tt,ct,callers\n else:\n timings[fn]=0,0,0,0,{}\n return 1\n \n def trace_dispatch_c_call(self,frame,t):\n fn=(\"\",0,self.c_func_name)\n self.cur=(t,0,0,fn,frame,self.cur)\n timings=self.timings\n if fn in timings:\n cc,ns,tt,ct,callers=timings[fn]\n timings[fn]=cc,ns+1,tt,ct,callers\n else:\n timings[fn]=0,0,0,0,{}\n return 1\n \n def trace_dispatch_return(self,frame,t):\n if frame is not self.cur[-2]:\n assert frame is self.cur[-2].f_back,(\"Bad return\",self.cur[-3])\n self.trace_dispatch_return(self.cur[-2],0)\n \n \n \n \n rpt,rit,ret,rfn,frame,rcur=self.cur\n rit=rit+t\n frame_total=rit+ret\n \n ppt,pit,pet,pfn,pframe,pcur=rcur\n self.cur=ppt,pit+rpt,pet+frame_total,pfn,pframe,pcur\n \n timings=self.timings\n cc,ns,tt,ct,callers=timings[rfn]\n if not ns:\n \n \n \n \n ct=ct+frame_total\n cc=cc+1\n \n if pfn in callers:\n callers[pfn]=callers[pfn]+1\n \n \n \n else:\n callers[pfn]=1\n \n timings[rfn]=cc,ns -1,tt+rit,ct,callers\n \n return 1\n \n \n dispatch={\n \"call\":trace_dispatch_call,\n \"exception\":trace_dispatch_exception,\n \"return\":trace_dispatch_return,\n \"c_call\":trace_dispatch_c_call,\n \"c_exception\":trace_dispatch_return,\n \"c_return\":trace_dispatch_return,\n }\n \n \n \n \n \n \n \n \n def set_cmd(self,cmd):\n if self.cur[-1]:return\n self.cmd=cmd\n self.simulate_call(cmd)\n \n class fake_code:\n def __init__(self,filename,line,name):\n self.co_filename=filename\n self.co_line=line\n self.co_name=name\n self.co_firstlineno=0\n \n def __repr__(self):\n return repr((self.co_filename,self.co_line,self.co_name))\n \n class fake_frame:\n def __init__(self,code,prior):\n self.f_code=code\n self.f_back=prior\n \n def simulate_call(self,name):\n code=self.fake_code('profile',0,name)\n if self.cur:\n pframe=self.cur[-2]\n else:\n pframe=None\n frame=self.fake_frame(code,pframe)\n self.dispatch['call'](self,frame,0)\n \n \n \n \n def simulate_cmd_complete(self):\n get_time=self.get_time\n t=get_time()-self.t\n while self.cur[-1]:\n \n \n self.dispatch['return'](self,self.cur[-2],t)\n t=0\n self.t=get_time()-t\n \n \n def print_stats(self,sort=-1):\n import pstats\n if not isinstance(sort,tuple):\n sort=(sort,)\n pstats.Stats(self).strip_dirs().sort_stats(*sort).print_stats()\n \n def dump_stats(self,file):\n with open(file,'wb')as f:\n self.create_stats()\n marshal.dump(self.stats,f)\n \n def create_stats(self):\n self.simulate_cmd_complete()\n self.snapshot_stats()\n \n def snapshot_stats(self):\n self.stats={}\n for func,(cc,ns,tt,ct,callers)in self.timings.items():\n callers=callers.copy()\n nc=0\n for callcnt in callers.values():\n nc +=callcnt\n self.stats[func]=cc,nc,tt,ct,callers\n \n \n \n \n \n def run(self,cmd):\n import __main__\n dict=__main__.__dict__\n return self.runctx(cmd,dict,dict)\n \n def runctx(self,cmd,globals,locals):\n self.set_cmd(cmd)\n sys.setprofile(self.dispatcher)\n try:\n exec(cmd,globals,locals)\n finally:\n sys.setprofile(None)\n return self\n \n \n def runcall(self,func,/,*args,**kw):\n self.set_cmd(repr(func))\n sys.setprofile(self.dispatcher)\n try:\n return func(*args,**kw)\n finally:\n sys.setprofile(None)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def calibrate(self,m,verbose=0):\n if self.__class__ is not Profile:\n raise TypeError(\"Subclasses must override .calibrate().\")\n \n saved_bias=self.bias\n self.bias=0\n try:\n return self._calibrate_inner(m,verbose)\n finally:\n self.bias=saved_bias\n \n def _calibrate_inner(self,m,verbose):\n get_time=self.get_time\n \n \n \n \n \n \n \n def f1(n):\n for i in range(n):\n x=1\n \n def f(m,f1=f1):\n for i in range(m):\n f1(100)\n \n f(m)\n \n \n t0=get_time()\n f(m)\n t1=get_time()\n elapsed_noprofile=t1 -t0\n if verbose:\n print(\"elapsed time without profiling =\",elapsed_noprofile)\n \n \n \n \n p=Profile()\n t0=get_time()\n p.runctx('f(m)',globals(),locals())\n t1=get_time()\n elapsed_profile=t1 -t0\n if verbose:\n print(\"elapsed time with profiling =\",elapsed_profile)\n \n \n total_calls=0.0\n reported_time=0.0\n for(filename,line,funcname),(cc,ns,tt,ct,callers)in\\\n p.timings.items():\n if funcname in(\"f\",\"f1\"):\n total_calls +=cc\n reported_time +=tt\n \n if verbose:\n print(\"'CPU seconds' profiler reported =\",reported_time)\n print(\"total # calls =\",total_calls)\n if total_calls !=m+1:\n raise ValueError(\"internal error: total calls = %d\"%total_calls)\n \n \n \n \n \n mean=(reported_time -elapsed_noprofile)/2.0 /total_calls\n if verbose:\n print(\"mean stopwatch overhead per profile event =\",mean)\n return mean\n \n \n \ndef main():\n import os\n from optparse import OptionParser\n \n usage=\"profile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ...\"\n parser=OptionParser(usage=usage)\n parser.allow_interspersed_args=False\n parser.add_option('-o','--outfile',dest=\"outfile\",\n help=\"Save stats to \",default=None)\n parser.add_option('-m',dest=\"module\",action=\"store_true\",\n help=\"Profile a library module.\",default=False)\n parser.add_option('-s','--sort',dest=\"sort\",\n help=\"Sort order when printing to stdout, based on pstats.Stats class\",\n default=-1)\n \n if not sys.argv[1:]:\n parser.print_usage()\n sys.exit(2)\n \n (options,args)=parser.parse_args()\n sys.argv[:]=args\n \n \n \n if options.outfile is not None:\n options.outfile=os.path.abspath(options.outfile)\n \n if len(args)>0:\n if options.module:\n import runpy\n code=\"run_module(modname, run_name='__main__')\"\n globs={\n 'run_module':runpy.run_module,\n 'modname':args[0]\n }\n else:\n progname=args[0]\n sys.path.insert(0,os.path.dirname(progname))\n with io.open_code(progname)as fp:\n code=compile(fp.read(),progname,'exec')\n spec=importlib.machinery.ModuleSpec(name='__main__',loader=None,\n origin=progname)\n globs={\n '__spec__':spec,\n '__file__':spec.origin,\n '__name__':spec.name,\n '__package__':None,\n '__cached__':None,\n }\n try:\n runctx(code,globs,None,options.outfile,options.sort)\n except BrokenPipeError as exc:\n \n sys.stdout=None\n sys.exit(exc.errno)\n else:\n parser.print_usage()\n return parser\n \n \nif __name__ =='__main__':\n main()\n", ["__main__", "importlib.machinery", "io", "marshal", "optparse", "os", "pstats", "runpy", "sys", "time"]], "pwd": [".py", "\ndef getpwuid():\n pass\n", []], "pyclbr": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport ast\nimport sys\nimport importlib.util\n\n__all__=[\"readmodule\",\"readmodule_ex\",\"Class\",\"Function\"]\n\n_modules={}\n\n\nclass _Object:\n ''\n def __init__(self,module,name,file,lineno,end_lineno,parent):\n self.module=module\n self.name=name\n self.file=file\n self.lineno=lineno\n self.end_lineno=end_lineno\n self.parent=parent\n self.children={}\n if parent is not None:\n parent.children[name]=self\n \n \n \nclass Function(_Object):\n ''\n def __init__(self,module,name,file,lineno,\n parent=None,is_async=False,*,end_lineno=None):\n super().__init__(module,name,file,lineno,end_lineno,parent)\n self.is_async=is_async\n if isinstance(parent,Class):\n parent.methods[name]=lineno\n \n \nclass Class(_Object):\n ''\n def __init__(self,module,name,super_,file,lineno,\n parent=None,*,end_lineno=None):\n super().__init__(module,name,file,lineno,end_lineno,parent)\n self.super=super_ or[]\n self.methods={}\n \n \n \n \ndef _nest_function(ob,func_name,lineno,end_lineno,is_async=False):\n ''\n return Function(ob.module,func_name,ob.file,lineno,\n parent=ob,is_async=is_async,end_lineno=end_lineno)\n \ndef _nest_class(ob,class_name,lineno,end_lineno,super=None):\n ''\n return Class(ob.module,class_name,super,ob.file,lineno,\n parent=ob,end_lineno=end_lineno)\n \n \ndef readmodule(module,path=None):\n ''\n\n\n \n \n res={}\n for key,value in _readmodule(module,path or[]).items():\n if isinstance(value,Class):\n res[key]=value\n return res\n \ndef readmodule_ex(module,path=None):\n ''\n\n\n\n\n \n return _readmodule(module,path or[])\n \n \ndef _readmodule(module,path,inpackage=None):\n ''\n\n\n\n\n\n \n \n if inpackage is not None:\n fullmodule=\"%s.%s\"%(inpackage,module)\n else:\n fullmodule=module\n \n \n if fullmodule in _modules:\n return _modules[fullmodule]\n \n \n tree={}\n \n \n if module in sys.builtin_module_names and inpackage is None:\n _modules[module]=tree\n return tree\n \n \n i=module.rfind('.')\n if i >=0:\n package=module[:i]\n submodule=module[i+1:]\n parent=_readmodule(package,path,inpackage)\n if inpackage is not None:\n package=\"%s.%s\"%(inpackage,package)\n if not '__path__'in parent:\n raise ImportError('No package named {}'.format(package))\n return _readmodule(submodule,parent['__path__'],package)\n \n \n f=None\n if inpackage is not None:\n search_path=path\n else:\n search_path=path+sys.path\n spec=importlib.util._find_spec_from_path(fullmodule,search_path)\n if spec is None:\n raise ModuleNotFoundError(f\"no module named {fullmodule !r}\",name=fullmodule)\n _modules[fullmodule]=tree\n \n if spec.submodule_search_locations is not None:\n tree['__path__']=spec.submodule_search_locations\n try:\n source=spec.loader.get_source(fullmodule)\n except(AttributeError,ImportError):\n \n return tree\n else:\n if source is None:\n return tree\n \n fname=spec.loader.get_filename(fullmodule)\n return _create_tree(fullmodule,path,fname,source,tree,inpackage)\n \n \nclass _ModuleBrowser(ast.NodeVisitor):\n def __init__(self,module,path,file,tree,inpackage):\n self.path=path\n self.tree=tree\n self.file=file\n self.module=module\n self.inpackage=inpackage\n self.stack=[]\n \n def visit_ClassDef(self,node):\n bases=[]\n for base in node.bases:\n name=ast.unparse(base)\n if name in self.tree:\n \n bases.append(self.tree[name])\n elif len(names :=name.split(\".\"))>1:\n \n \n *_,module,class_=names\n if module in _modules:\n bases.append(_modules[module].get(class_,name))\n else:\n bases.append(name)\n \n parent=self.stack[-1]if self.stack else None\n class_=Class(self.module,node.name,bases,self.file,node.lineno,\n parent=parent,end_lineno=node.end_lineno)\n if parent is None:\n self.tree[node.name]=class_\n self.stack.append(class_)\n self.generic_visit(node)\n self.stack.pop()\n \n def visit_FunctionDef(self,node,*,is_async=False):\n parent=self.stack[-1]if self.stack else None\n function=Function(self.module,node.name,self.file,node.lineno,\n parent,is_async,end_lineno=node.end_lineno)\n if parent is None:\n self.tree[node.name]=function\n self.stack.append(function)\n self.generic_visit(node)\n self.stack.pop()\n \n def visit_AsyncFunctionDef(self,node):\n self.visit_FunctionDef(node,is_async=True)\n \n def visit_Import(self,node):\n if node.col_offset !=0:\n return\n \n for module in node.names:\n try:\n try:\n _readmodule(module.name,self.path,self.inpackage)\n except ImportError:\n _readmodule(module.name,[])\n except(ImportError,SyntaxError):\n \n \n continue\n \n def visit_ImportFrom(self,node):\n if node.col_offset !=0:\n return\n try:\n module=\".\"*node.level\n if node.module:\n module +=node.module\n module=_readmodule(module,self.path,self.inpackage)\n except(ImportError,SyntaxError):\n return\n \n for name in node.names:\n if name.name in module:\n self.tree[name.asname or name.name]=module[name.name]\n elif name.name ==\"*\":\n for import_name,import_value in module.items():\n if import_name.startswith(\"_\"):\n continue\n self.tree[import_name]=import_value\n \n \ndef _create_tree(fullmodule,path,fname,source,tree,inpackage):\n mbrowser=_ModuleBrowser(fullmodule,path,fname,tree,inpackage)\n mbrowser.visit(ast.parse(source))\n return mbrowser.tree\n \n \ndef _main():\n ''\n import os\n try:\n mod=sys.argv[1]\n except:\n mod=__file__\n if os.path.exists(mod):\n path=[os.path.dirname(mod)]\n mod=os.path.basename(mod)\n if mod.lower().endswith(\".py\"):\n mod=mod[:-3]\n else:\n path=[]\n tree=readmodule_ex(mod,path)\n lineno_key=lambda a:getattr(a,'lineno',0)\n objs=sorted(tree.values(),key=lineno_key,reverse=True)\n indent_level=2\n while objs:\n obj=objs.pop()\n if isinstance(obj,list):\n \n continue\n if not hasattr(obj,'indent'):\n obj.indent=0\n \n if isinstance(obj,_Object):\n new_objs=sorted(obj.children.values(),\n key=lineno_key,reverse=True)\n for ob in new_objs:\n ob.indent=obj.indent+indent_level\n objs.extend(new_objs)\n if isinstance(obj,Class):\n print(\"{}class {} {} {}\"\n .format(' '*obj.indent,obj.name,obj.super,obj.lineno))\n elif isinstance(obj,Function):\n print(\"{}def {} {}\".format(' '*obj.indent,obj.name,obj.lineno))\n \nif __name__ ==\"__main__\":\n _main()\n", ["ast", "importlib.util", "os", "sys"]], "pydoc": [".py", "#!/usr/bin/env python3\n''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['help']\n__author__=\"Ka-Ping Yee \"\n__date__=\"26 February 2001\"\n\n__credits__=\"\"\"Guido van Rossum, for an excellent programming language.\nTommy Burnette, the original creator of manpy.\nPaul Prescod, for all his work on onlinehelp.\nRichard Chamberlain, for the first implementation of textdoc.\n\"\"\"\n\n\n\n\n\n\n\n\nimport __future__\nimport builtins\nimport importlib._bootstrap\nimport importlib._bootstrap_external\nimport importlib.machinery\nimport importlib.util\nimport inspect\nimport io\nimport os\nimport pkgutil\nimport platform\nimport re\nimport sys\nimport sysconfig\nimport time\nimport tokenize\nimport urllib.parse\nimport warnings\nfrom collections import deque\nfrom reprlib import Repr\nfrom traceback import format_exception_only\n\n\n\n\ndef pathdirs():\n ''\n dirs=[]\n normdirs=[]\n for dir in sys.path:\n dir=os.path.abspath(dir or '.')\n normdir=os.path.normcase(dir)\n if normdir not in normdirs and os.path.isdir(dir):\n dirs.append(dir)\n normdirs.append(normdir)\n return dirs\n \ndef _findclass(func):\n cls=sys.modules.get(func.__module__)\n if cls is None:\n return None\n for name in func.__qualname__.split('.')[:-1]:\n cls=getattr(cls,name)\n if not inspect.isclass(cls):\n return None\n return cls\n \ndef _finddoc(obj):\n if inspect.ismethod(obj):\n name=obj.__func__.__name__\n self=obj.__self__\n if(inspect.isclass(self)and\n getattr(getattr(self,name,None),'__func__')is obj.__func__):\n \n cls=self\n else:\n cls=self.__class__\n elif inspect.isfunction(obj):\n name=obj.__name__\n cls=_findclass(obj)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif inspect.isbuiltin(obj):\n name=obj.__name__\n self=obj.__self__\n if(inspect.isclass(self)and\n self.__qualname__+'.'+name ==obj.__qualname__):\n \n cls=self\n else:\n cls=self.__class__\n \n elif isinstance(obj,property):\n func=obj.fget\n name=func.__name__\n cls=_findclass(func)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif inspect.ismethoddescriptor(obj)or inspect.isdatadescriptor(obj):\n name=obj.__name__\n cls=obj.__objclass__\n if getattr(cls,name)is not obj:\n return None\n if inspect.ismemberdescriptor(obj):\n slots=getattr(cls,'__slots__',None)\n if isinstance(slots,dict)and name in slots:\n return slots[name]\n else:\n return None\n for base in cls.__mro__:\n try:\n doc=_getowndoc(getattr(base,name))\n except AttributeError:\n continue\n if doc is not None:\n return doc\n return None\n \ndef _getowndoc(obj):\n ''\n \n try:\n doc=object.__getattribute__(obj,'__doc__')\n if doc is None:\n return None\n if obj is not type:\n typedoc=type(obj).__doc__\n if isinstance(typedoc,str)and typedoc ==doc:\n return None\n return doc\n except AttributeError:\n return None\n \ndef _getdoc(object):\n ''\n\n\n\n \n doc=_getowndoc(object)\n if doc is None:\n try:\n doc=_finddoc(object)\n except(AttributeError,TypeError):\n return None\n if not isinstance(doc,str):\n return None\n return inspect.cleandoc(doc)\n \ndef getdoc(object):\n ''\n result=_getdoc(object)or inspect.getcomments(object)\n return result and re.sub('^ *\\n','',result.rstrip())or ''\n \ndef splitdoc(doc):\n ''\n lines=doc.strip().split('\\n')\n if len(lines)==1:\n return lines[0],''\n elif len(lines)>=2 and not lines[1].rstrip():\n return lines[0],'\\n'.join(lines[2:])\n return '','\\n'.join(lines)\n \ndef classname(object,modname):\n ''\n name=object.__name__\n if object.__module__ !=modname:\n name=object.__module__+'.'+name\n return name\n \ndef isdata(object):\n ''\n return not(inspect.ismodule(object)or inspect.isclass(object)or\n inspect.isroutine(object)or inspect.isframe(object)or\n inspect.istraceback(object)or inspect.iscode(object))\n \ndef replace(text,*pairs):\n ''\n while pairs:\n text=pairs[1].join(text.split(pairs[0]))\n pairs=pairs[2:]\n return text\n \ndef cram(text,maxlen):\n ''\n if len(text)>maxlen:\n pre=max(0,(maxlen -3)//2)\n post=max(0,maxlen -3 -pre)\n return text[:pre]+'...'+text[len(text)-post:]\n return text\n \n_re_stripid=re.compile(r' at 0x[0-9a-f]{6,16}(>+)$',re.IGNORECASE)\ndef stripid(text):\n ''\n \n return _re_stripid.sub(r'\\1',text)\n \ndef _is_bound_method(fn):\n ''\n\n\n \n if inspect.ismethod(fn):\n return True\n if inspect.isbuiltin(fn):\n self=getattr(fn,'__self__',None)\n return not(inspect.ismodule(self)or(self is None))\n return False\n \n \ndef allmethods(cl):\n methods={}\n for key,value in inspect.getmembers(cl,inspect.isroutine):\n methods[key]=1\n for base in cl.__bases__:\n methods.update(allmethods(base))\n for key in methods.keys():\n methods[key]=getattr(cl,key)\n return methods\n \ndef _split_list(s,predicate):\n ''\n\n\n\n\n \n \n yes=[]\n no=[]\n for x in s:\n if predicate(x):\n yes.append(x)\n else:\n no.append(x)\n return yes,no\n \n_future_feature_names=set(__future__.all_feature_names)\n\ndef visiblename(name,all=None,obj=None):\n ''\n \n \n if name in{'__author__','__builtins__','__cached__','__credits__',\n '__date__','__doc__','__file__','__spec__',\n '__loader__','__module__','__name__','__package__',\n '__path__','__qualname__','__slots__','__version__'}:\n return 0\n \n if name.startswith('__')and name.endswith('__'):return 1\n \n if name.startswith('_')and hasattr(obj,'_fields'):\n return True\n \n if obj is not __future__ and name in _future_feature_names:\n if isinstance(getattr(obj,name,None),__future__._Feature):\n return False\n if all is not None:\n \n return name in all\n else:\n return not name.startswith('_')\n \ndef classify_class_attrs(object):\n ''\n results=[]\n for(name,kind,cls,value)in inspect.classify_class_attrs(object):\n if inspect.isdatadescriptor(value):\n kind='data descriptor'\n if isinstance(value,property)and value.fset is None:\n kind='readonly property'\n results.append((name,kind,cls,value))\n return results\n \ndef sort_attributes(attrs,object):\n ''\n \n \n fields=getattr(object,'_fields',[])\n try:\n field_order={name:i -len(fields)for(i,name)in enumerate(fields)}\n except TypeError:\n field_order={}\n keyfunc=lambda attr:(field_order.get(attr[0],0),attr[0])\n attrs.sort(key=keyfunc)\n \n \n \ndef ispackage(path):\n ''\n if os.path.isdir(path):\n for ext in('.py','.pyc'):\n if os.path.isfile(os.path.join(path,'__init__'+ext)):\n return True\n return False\n \ndef source_synopsis(file):\n line=file.readline()\n while line[:1]=='#'or not line.strip():\n line=file.readline()\n if not line:break\n line=line.strip()\n if line[:4]=='r\"\"\"':line=line[1:]\n if line[:3]=='\"\"\"':\n line=line[3:]\n if line[-1:]=='\\\\':line=line[:-1]\n while not line.strip():\n line=file.readline()\n if not line:break\n result=line.split('\"\"\"')[0].strip()\n else:result=None\n return result\n \ndef synopsis(filename,cache={}):\n ''\n mtime=os.stat(filename).st_mtime\n lastupdate,result=cache.get(filename,(None,None))\n if lastupdate is None or lastupdate ','>')\n \n def repr(self,object):\n return Repr.repr(self,object)\n \n def repr1(self,x,level):\n if hasattr(type(x),'__name__'):\n methodname='repr_'+'_'.join(type(x).__name__.split())\n if hasattr(self,methodname):\n return getattr(self,methodname)(x,level)\n return self.escape(cram(stripid(repr(x)),self.maxother))\n \n def repr_string(self,x,level):\n test=cram(x,self.maxstring)\n testrepr=repr(test)\n if '\\\\'in test and '\\\\'not in replace(testrepr,r'\\\\',''):\n \n \n return 'r'+testrepr[0]+self.escape(test)+testrepr[0]\n return re.sub(r'((\\\\[\\\\abfnrtv\\'\"]|\\\\[0-9]..|\\\\x..|\\\\u....)+)',\n r'\\1',\n self.escape(testrepr))\n \n repr_str=repr_string\n \n def repr_instance(self,x,level):\n try:\n return self.escape(cram(stripid(repr(x)),self.maxstring))\n except:\n return self.escape('<%s instance>'%x.__class__.__name__)\n \n repr_unicode=repr_string\n \nclass HTMLDoc(Doc):\n ''\n \n \n \n _repr_instance=HTMLRepr()\n repr=_repr_instance.repr\n escape=_repr_instance.escape\n \n def page(self,title,contents):\n ''\n return '''\\\n\n\n\n\nPython: %s\n\n%s\n'''%(title,contents)\n \n def heading(self,title,extras=''):\n ''\n return '''\n\n\n\n
 
%s
%s
\n '''%(title,extras or ' ')\n \n def section(self,title,cls,contents,width=6,\n prelude='',marginalia=None,gap=' '):\n ''\n if marginalia is None:\n marginalia=''+' '*width+''\n result='''

\n\n\n\n '''%(cls,title)\n if prelude:\n result=result+'''\n\n\n'''%(cls,marginalia,cls,prelude,gap)\n else:\n result=result+'''\n'''%(cls,marginalia,gap)\n \n return result+'\\n
 
%s
%s%s
%s
%s%s%s
'%contents\n \n def bigsection(self,title,*args):\n ''\n title='%s'%title\n return self.section(title,*args)\n \n def preformat(self,text):\n ''\n text=self.escape(text.expandtabs())\n return replace(text,'\\n\\n','\\n \\n','\\n\\n','\\n \\n',\n ' ',' ','\\n','
\\n')\n \n def multicolumn(self,list,format):\n ''\n result=''\n rows=(len(list)+3)//4\n for col in range(4):\n result=result+''\n for i in range(rows *col,rows *col+rows):\n if i \\n'\n result=result+''\n return '%s
'%result\n \n def grey(self,text):return '%s'%text\n \n def namelink(self,name,*dicts):\n ''\n for dict in dicts:\n if name in dict:\n return '
%s'%(dict[name],name)\n return name\n \n def classlink(self,object,modname):\n ''\n name,module=object.__name__,sys.modules.get(object.__module__)\n if hasattr(module,name)and getattr(module,name)is object:\n return '%s'%(\n module.__name__,name,classname(object,modname))\n return classname(object,modname)\n \n def modulelink(self,object):\n ''\n return '%s'%(object.__name__,object.__name__)\n \n def modpkglink(self,modpkginfo):\n ''\n name,path,ispackage,shadowed=modpkginfo\n if shadowed:\n return self.grey(name)\n if path:\n url='%s.%s.html'%(path,name)\n else:\n url='%s.html'%name\n if ispackage:\n text='%s (package)'%name\n else:\n text=name\n return '%s'%(url,text)\n \n def filelink(self,url,path):\n ''\n return '%s'%(url,path)\n \n def markup(self,text,escape=None,funcs={},classes={},methods={}):\n ''\n \n escape=escape or self.escape\n results=[]\n here=0\n pattern=re.compile(r'\\b((http|https|ftp)://\\S+[\\w/]|'\n r'RFC[- ]?(\\d+)|'\n r'PEP[- ]?(\\d+)|'\n r'(self\\.)?(\\w+))')\n while match :=pattern.search(text,here):\n start,end=match.span()\n results.append(escape(text[here:start]))\n \n all,scheme,rfc,pep,selfdot,name=match.groups()\n if scheme:\n url=escape(all).replace('\"','"')\n results.append('%s'%(url,url))\n elif rfc:\n url='https://www.rfc-editor.org/rfc/rfc%d.txt'%int(rfc)\n results.append('%s'%(url,escape(all)))\n elif pep:\n url='https://peps.python.org/pep-%04d/'%int(pep)\n results.append('%s'%(url,escape(all)))\n elif selfdot:\n \n \n if text[end:end+1]=='(':\n results.append('self.'+self.namelink(name,methods))\n else:\n results.append('self.%s'%name)\n elif text[end:end+1]=='(':\n results.append(self.namelink(name,methods,funcs,classes))\n else:\n results.append(self.namelink(name,classes))\n here=end\n results.append(escape(text[here:]))\n return ''.join(results)\n \n \n \n def formattree(self,tree,modname,parent=None):\n ''\n result=''\n for entry in tree:\n if isinstance(entry,tuple):\n c,bases=entry\n result=result+'

'\n result=result+self.classlink(c,modname)\n if bases and bases !=(parent,):\n parents=[]\n for base in bases:\n parents.append(self.classlink(base,modname))\n result=result+'('+', '.join(parents)+')'\n result=result+'\\n
'\n elif isinstance(entry,list):\n result=result+'
\\n%s
\\n'%self.formattree(\n entry,modname,c)\n return '
\\n%s
\\n'%result\n \n def docmodule(self,object,name=None,mod=None,*ignored):\n ''\n name=object.__name__\n try:\n all=object.__all__\n except AttributeError:\n all=None\n parts=name.split('.')\n links=[]\n for i in range(len(parts)-1):\n links.append(\n '%s'%\n ('.'.join(parts[:i+1]),parts[i]))\n linkedname='.'.join(links+parts[-1:])\n head='%s'%linkedname\n try:\n path=inspect.getabsfile(object)\n url=urllib.parse.quote(path)\n filelink=self.filelink(url,path)\n except TypeError:\n filelink='(built-in)'\n info=[]\n if hasattr(object,'__version__'):\n version=str(object.__version__)\n if version[:11]=='$'+'Revision: 'and version[-1:]=='$':\n version=version[11:-1].strip()\n info.append('version %s'%self.escape(version))\n if hasattr(object,'__date__'):\n info.append(self.escape(str(object.__date__)))\n if info:\n head=head+' (%s)'%', '.join(info)\n docloc=self.getdocloc(object)\n if docloc is not None:\n docloc='
Module Reference'%locals()\n else:\n docloc=''\n result=self.heading(head,'index
'+filelink+docloc)\n \n modules=inspect.getmembers(object,inspect.ismodule)\n \n classes,cdict=[],{}\n for key,value in inspect.getmembers(object,inspect.isclass):\n \n if(all is not None or\n (inspect.getmodule(value)or object)is object):\n if visiblename(key,all,object):\n classes.append((key,value))\n cdict[key]=cdict[value]='#'+key\n for key,value in classes:\n for base in value.__bases__:\n key,modname=base.__name__,base.__module__\n module=sys.modules.get(modname)\n if modname !=name and module and hasattr(module,key):\n if getattr(module,key)is base:\n if not key in cdict:\n cdict[key]=cdict[base]=modname+'.html#'+key\n funcs,fdict=[],{}\n for key,value in inspect.getmembers(object,inspect.isroutine):\n \n if(all is not None or\n inspect.isbuiltin(value)or inspect.getmodule(value)is object):\n if visiblename(key,all,object):\n funcs.append((key,value))\n fdict[key]='#-'+key\n if inspect.isfunction(value):fdict[value]=fdict[key]\n data=[]\n for key,value in inspect.getmembers(object,isdata):\n if visiblename(key,all,object):\n data.append((key,value))\n \n doc=self.markup(getdoc(object),self.preformat,fdict,cdict)\n doc=doc and '%s'%doc\n result=result+'

%s

\\n'%doc\n \n if hasattr(object,'__path__'):\n modpkgs=[]\n for importer,modname,ispkg in pkgutil.iter_modules(object.__path__):\n modpkgs.append((modname,name,ispkg,0))\n modpkgs.sort()\n contents=self.multicolumn(modpkgs,self.modpkglink)\n result=result+self.bigsection(\n 'Package Contents','pkg-content',contents)\n elif modules:\n contents=self.multicolumn(\n modules,lambda t:self.modulelink(t[1]))\n result=result+self.bigsection(\n 'Modules','pkg-content',contents)\n \n if classes:\n classlist=[value for(key,value)in classes]\n contents=[\n self.formattree(inspect.getclasstree(classlist,1),name)]\n for key,value in classes:\n contents.append(self.document(value,key,name,fdict,cdict))\n result=result+self.bigsection(\n 'Classes','index',' '.join(contents))\n if funcs:\n contents=[]\n for key,value in funcs:\n contents.append(self.document(value,key,name,fdict,cdict))\n result=result+self.bigsection(\n 'Functions','functions',' '.join(contents))\n if data:\n contents=[]\n for key,value in data:\n contents.append(self.document(value,key))\n result=result+self.bigsection(\n 'Data','data','
\\n'.join(contents))\n if hasattr(object,'__author__'):\n contents=self.markup(str(object.__author__),self.preformat)\n result=result+self.bigsection('Author','author',contents)\n if hasattr(object,'__credits__'):\n contents=self.markup(str(object.__credits__),self.preformat)\n result=result+self.bigsection('Credits','credits',contents)\n \n return result\n \n def docclass(self,object,name=None,mod=None,funcs={},classes={},\n *ignored):\n ''\n realname=object.__name__\n name=name or realname\n bases=object.__bases__\n \n contents=[]\n push=contents.append\n \n \n class HorizontalRule:\n def __init__(self):\n self.needone=0\n def maybe(self):\n if self.needone:\n push('
\\n')\n self.needone=1\n hr=HorizontalRule()\n \n \n mro=deque(inspect.getmro(object))\n if len(mro)>2:\n hr.maybe()\n push('
Method resolution order:
\\n')\n for base in mro:\n push('
%s
\\n'%self.classlink(base,\n object.__module__))\n push('
\\n')\n \n def spill(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n try:\n value=getattr(object,name)\n except Exception:\n \n \n push(self.docdata(value,name,mod))\n else:\n push(self.document(value,name,mod,\n funcs,classes,mdict,object))\n push('\\n')\n return attrs\n \n def spilldescriptors(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n push(self.docdata(value,name,mod))\n return attrs\n \n def spilldata(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n base=self.docother(getattr(object,name),name,mod)\n doc=getdoc(value)\n if not doc:\n push('
%s
\\n'%base)\n else:\n doc=self.markup(getdoc(value),self.preformat,\n funcs,classes,mdict)\n doc='
%s'%doc\n push('
%s%s
\\n'%(base,doc))\n push('\\n')\n return attrs\n \n attrs=[(name,kind,cls,value)\n for name,kind,cls,value in classify_class_attrs(object)\n if visiblename(name,obj=object)]\n \n mdict={}\n for key,kind,homecls,value in attrs:\n mdict[key]=anchor='#'+name+'-'+key\n try:\n value=getattr(object,name)\n except Exception:\n \n \n pass\n try:\n \n \n mdict[value]=anchor\n except TypeError:\n pass\n \n while attrs:\n if mro:\n thisclass=mro.popleft()\n else:\n thisclass=attrs[0][2]\n attrs,inherited=_split_list(attrs,lambda t:t[2]is thisclass)\n \n if object is not builtins.object and thisclass is builtins.object:\n attrs=inherited\n continue\n elif thisclass is object:\n tag='defined here'\n else:\n tag='inherited from %s'%self.classlink(thisclass,\n object.__module__)\n tag +=':
\\n'\n \n sort_attributes(attrs,object)\n \n \n attrs=spill('Methods %s'%tag,attrs,\n lambda t:t[1]=='method')\n attrs=spill('Class methods %s'%tag,attrs,\n lambda t:t[1]=='class method')\n attrs=spill('Static methods %s'%tag,attrs,\n lambda t:t[1]=='static method')\n attrs=spilldescriptors(\"Readonly properties %s\"%tag,attrs,\n lambda t:t[1]=='readonly property')\n attrs=spilldescriptors('Data descriptors %s'%tag,attrs,\n lambda t:t[1]=='data descriptor')\n attrs=spilldata('Data and other attributes %s'%tag,attrs,\n lambda t:t[1]=='data')\n assert attrs ==[]\n attrs=inherited\n \n contents=''.join(contents)\n \n if name ==realname:\n title='class %s'%(\n name,realname)\n else:\n title='%s = class %s'%(\n name,name,realname)\n if bases:\n parents=[]\n for base in bases:\n parents.append(self.classlink(base,object.__module__))\n title=title+'(%s)'%', '.join(parents)\n \n decl=''\n try:\n signature=inspect.signature(object)\n except(ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if argspec and argspec !='()':\n decl=name+self.escape(argspec)+'\\n\\n'\n \n doc=getdoc(object)\n if decl:\n doc=decl+(doc or '')\n doc=self.markup(doc,self.preformat,funcs,classes,mdict)\n doc=doc and '%s
 
'%doc\n \n return self.section(title,'title',contents,3,doc)\n \n def formatvalue(self,object):\n ''\n return self.grey('='+self.repr(object))\n \n def docroutine(self,object,name=None,mod=None,\n funcs={},classes={},methods={},cl=None):\n ''\n realname=object.__name__\n name=name or realname\n anchor=(cl and cl.__name__ or '')+'-'+name\n note=''\n skipdocs=0\n if _is_bound_method(object):\n imclass=object.__self__.__class__\n if cl:\n if imclass is not cl:\n note=' from '+self.classlink(imclass,mod)\n else:\n if object.__self__ is not None:\n note=' method of %s instance'%self.classlink(\n object.__self__.__class__,mod)\n else:\n note=' unbound %s method'%self.classlink(imclass,mod)\n \n if(inspect.iscoroutinefunction(object)or\n inspect.isasyncgenfunction(object)):\n asyncqualifier='async '\n else:\n asyncqualifier=''\n \n if name ==realname:\n title='%s'%(anchor,realname)\n else:\n if cl and inspect.getattr_static(cl,realname,[])is object:\n reallink='%s'%(\n cl.__name__+'-'+realname,realname)\n skipdocs=1\n else:\n reallink=realname\n title='%s = %s'%(\n anchor,name,reallink)\n argspec=None\n if inspect.isroutine(object):\n try:\n signature=inspect.signature(object)\n except(ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if realname =='':\n title='%s lambda '%name\n \n \n \n argspec=argspec[1:-1]\n if not argspec:\n argspec='(...)'\n \n decl=asyncqualifier+title+self.escape(argspec)+(note and\n self.grey('%s'%note))\n \n if skipdocs:\n return '
%s
\\n'%decl\n else:\n doc=self.markup(\n getdoc(object),self.preformat,funcs,classes,methods)\n doc=doc and '
%s
'%doc\n return '
%s
%s
\\n'%(decl,doc)\n \n def docdata(self,object,name=None,mod=None,cl=None):\n ''\n results=[]\n push=results.append\n \n if name:\n push('
%s
\\n'%name)\n doc=self.markup(getdoc(object),self.preformat)\n if doc:\n push('
%s
\\n'%doc)\n push('
\\n')\n \n return ''.join(results)\n \n docproperty=docdata\n \n def docother(self,object,name=None,mod=None,*ignored):\n ''\n lhs=name and '%s = '%name or ''\n return lhs+self.repr(object)\n \n def index(self,dir,shadowed=None):\n ''\n modpkgs=[]\n if shadowed is None:shadowed={}\n for importer,name,ispkg in pkgutil.iter_modules([dir]):\n if any((0xD800 <=ord(ch)<=0xDFFF)for ch in name):\n \n continue\n modpkgs.append((name,'',ispkg,name in shadowed))\n shadowed[name]=1\n \n modpkgs.sort()\n contents=self.multicolumn(modpkgs,self.modpkglink)\n return self.bigsection(dir,'index',contents)\n \n \n \nclass TextRepr(Repr):\n ''\n def __init__(self):\n Repr.__init__(self)\n self.maxlist=self.maxtuple=20\n self.maxdict=10\n self.maxstring=self.maxother=100\n \n def repr1(self,x,level):\n if hasattr(type(x),'__name__'):\n methodname='repr_'+'_'.join(type(x).__name__.split())\n if hasattr(self,methodname):\n return getattr(self,methodname)(x,level)\n return cram(stripid(repr(x)),self.maxother)\n \n def repr_string(self,x,level):\n test=cram(x,self.maxstring)\n testrepr=repr(test)\n if '\\\\'in test and '\\\\'not in replace(testrepr,r'\\\\',''):\n \n \n return 'r'+testrepr[0]+test+testrepr[0]\n return testrepr\n \n repr_str=repr_string\n \n def repr_instance(self,x,level):\n try:\n return cram(stripid(repr(x)),self.maxstring)\n except:\n return '<%s instance>'%x.__class__.__name__\n \nclass TextDoc(Doc):\n ''\n \n \n \n _repr_instance=TextRepr()\n repr=_repr_instance.repr\n \n def bold(self,text):\n ''\n return ''.join(ch+'\\b'+ch for ch in text)\n \n def indent(self,text,prefix=' '):\n ''\n if not text:return ''\n lines=[(prefix+line).rstrip()for line in text.split('\\n')]\n return '\\n'.join(lines)\n \n def section(self,title,contents):\n ''\n clean_contents=self.indent(contents).rstrip()\n return self.bold(title)+'\\n'+clean_contents+'\\n\\n'\n \n \n \n def formattree(self,tree,modname,parent=None,prefix=''):\n ''\n result=''\n for entry in tree:\n if isinstance(entry,tuple):\n c,bases=entry\n result=result+prefix+classname(c,modname)\n if bases and bases !=(parent,):\n parents=(classname(c,modname)for c in bases)\n result=result+'(%s)'%', '.join(parents)\n result=result+'\\n'\n elif isinstance(entry,list):\n result=result+self.formattree(\n entry,modname,c,prefix+' ')\n return result\n \n def docmodule(self,object,name=None,mod=None):\n ''\n name=object.__name__\n synop,desc=splitdoc(getdoc(object))\n result=self.section('NAME',name+(synop and ' - '+synop))\n all=getattr(object,'__all__',None)\n docloc=self.getdocloc(object)\n if docloc is not None:\n result=result+self.section('MODULE REFERENCE',docloc+\"\"\"\n\nThe following documentation is automatically generated from the Python\nsource files. It may be incomplete, incorrect or include features that\nare considered implementation detail and may vary between Python\nimplementations. When in doubt, consult the module reference at the\nlocation listed above.\n\"\"\")\n \n if desc:\n result=result+self.section('DESCRIPTION',desc)\n \n classes=[]\n for key,value in inspect.getmembers(object,inspect.isclass):\n \n if(all is not None\n or(inspect.getmodule(value)or object)is object):\n if visiblename(key,all,object):\n classes.append((key,value))\n funcs=[]\n for key,value in inspect.getmembers(object,inspect.isroutine):\n \n if(all is not None or\n inspect.isbuiltin(value)or inspect.getmodule(value)is object):\n if visiblename(key,all,object):\n funcs.append((key,value))\n data=[]\n for key,value in inspect.getmembers(object,isdata):\n if visiblename(key,all,object):\n data.append((key,value))\n \n modpkgs=[]\n modpkgs_names=set()\n if hasattr(object,'__path__'):\n for importer,modname,ispkg in pkgutil.iter_modules(object.__path__):\n modpkgs_names.add(modname)\n if ispkg:\n modpkgs.append(modname+' (package)')\n else:\n modpkgs.append(modname)\n \n modpkgs.sort()\n result=result+self.section(\n 'PACKAGE CONTENTS','\\n'.join(modpkgs))\n \n \n submodules=[]\n for key,value in inspect.getmembers(object,inspect.ismodule):\n if value.__name__.startswith(name+'.')and key not in modpkgs_names:\n submodules.append(key)\n if submodules:\n submodules.sort()\n result=result+self.section(\n 'SUBMODULES','\\n'.join(submodules))\n \n if classes:\n classlist=[value for key,value in classes]\n contents=[self.formattree(\n inspect.getclasstree(classlist,1),name)]\n for key,value in classes:\n contents.append(self.document(value,key,name))\n result=result+self.section('CLASSES','\\n'.join(contents))\n \n if funcs:\n contents=[]\n for key,value in funcs:\n contents.append(self.document(value,key,name))\n result=result+self.section('FUNCTIONS','\\n'.join(contents))\n \n if data:\n contents=[]\n for key,value in data:\n contents.append(self.docother(value,key,name,maxlen=70))\n result=result+self.section('DATA','\\n'.join(contents))\n \n if hasattr(object,'__version__'):\n version=str(object.__version__)\n if version[:11]=='$'+'Revision: 'and version[-1:]=='$':\n version=version[11:-1].strip()\n result=result+self.section('VERSION',version)\n if hasattr(object,'__date__'):\n result=result+self.section('DATE',str(object.__date__))\n if hasattr(object,'__author__'):\n result=result+self.section('AUTHOR',str(object.__author__))\n if hasattr(object,'__credits__'):\n result=result+self.section('CREDITS',str(object.__credits__))\n try:\n file=inspect.getabsfile(object)\n except TypeError:\n file='(built-in)'\n result=result+self.section('FILE',file)\n return result\n \n def docclass(self,object,name=None,mod=None,*ignored):\n ''\n realname=object.__name__\n name=name or realname\n bases=object.__bases__\n \n def makename(c,m=object.__module__):\n return classname(c,m)\n \n if name ==realname:\n title='class '+self.bold(realname)\n else:\n title=self.bold(name)+' = class '+realname\n if bases:\n parents=map(makename,bases)\n title=title+'(%s)'%', '.join(parents)\n \n contents=[]\n push=contents.append\n \n try:\n signature=inspect.signature(object)\n except(ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if argspec and argspec !='()':\n push(name+argspec+'\\n')\n \n doc=getdoc(object)\n if doc:\n push(doc+'\\n')\n \n \n mro=deque(inspect.getmro(object))\n if len(mro)>2:\n push(\"Method resolution order:\")\n for base in mro:\n push(' '+makename(base))\n push('')\n \n \n subclasses=sorted(\n (str(cls.__name__)for cls in type.__subclasses__(object)\n if not cls.__name__.startswith(\"_\")and cls.__module__ ==\"builtins\"),\n key=str.lower\n )\n no_of_subclasses=len(subclasses)\n MAX_SUBCLASSES_TO_DISPLAY=4\n if subclasses:\n push(\"Built-in subclasses:\")\n for subclassname in subclasses[:MAX_SUBCLASSES_TO_DISPLAY]:\n push(' '+subclassname)\n if no_of_subclasses >MAX_SUBCLASSES_TO_DISPLAY:\n push(' ... and '+\n str(no_of_subclasses -MAX_SUBCLASSES_TO_DISPLAY)+\n ' other subclasses')\n push('')\n \n \n class HorizontalRule:\n def __init__(self):\n self.needone=0\n def maybe(self):\n if self.needone:\n push('-'*70)\n self.needone=1\n hr=HorizontalRule()\n \n def spill(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n try:\n value=getattr(object,name)\n except Exception:\n \n \n push(self.docdata(value,name,mod))\n else:\n push(self.document(value,\n name,mod,object))\n return attrs\n \n def spilldescriptors(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n push(self.docdata(value,name,mod))\n return attrs\n \n def spilldata(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n doc=getdoc(value)\n try:\n obj=getattr(object,name)\n except AttributeError:\n obj=homecls.__dict__[name]\n push(self.docother(obj,name,mod,maxlen=70,doc=doc)+\n '\\n')\n return attrs\n \n attrs=[(name,kind,cls,value)\n for name,kind,cls,value in classify_class_attrs(object)\n if visiblename(name,obj=object)]\n \n while attrs:\n if mro:\n thisclass=mro.popleft()\n else:\n thisclass=attrs[0][2]\n attrs,inherited=_split_list(attrs,lambda t:t[2]is thisclass)\n \n if object is not builtins.object and thisclass is builtins.object:\n attrs=inherited\n continue\n elif thisclass is object:\n tag=\"defined here\"\n else:\n tag=\"inherited from %s\"%classname(thisclass,\n object.__module__)\n \n sort_attributes(attrs,object)\n \n \n attrs=spill(\"Methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='method')\n attrs=spill(\"Class methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='class method')\n attrs=spill(\"Static methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='static method')\n attrs=spilldescriptors(\"Readonly properties %s:\\n\"%tag,attrs,\n lambda t:t[1]=='readonly property')\n attrs=spilldescriptors(\"Data descriptors %s:\\n\"%tag,attrs,\n lambda t:t[1]=='data descriptor')\n attrs=spilldata(\"Data and other attributes %s:\\n\"%tag,attrs,\n lambda t:t[1]=='data')\n \n assert attrs ==[]\n attrs=inherited\n \n contents='\\n'.join(contents)\n if not contents:\n return title+'\\n'\n return title+'\\n'+self.indent(contents.rstrip(),' | ')+'\\n'\n \n def formatvalue(self,object):\n ''\n return '='+self.repr(object)\n \n def docroutine(self,object,name=None,mod=None,cl=None):\n ''\n realname=object.__name__\n name=name or realname\n note=''\n skipdocs=0\n if _is_bound_method(object):\n imclass=object.__self__.__class__\n if cl:\n if imclass is not cl:\n note=' from '+classname(imclass,mod)\n else:\n if object.__self__ is not None:\n note=' method of %s instance'%classname(\n object.__self__.__class__,mod)\n else:\n note=' unbound %s method'%classname(imclass,mod)\n \n if(inspect.iscoroutinefunction(object)or\n inspect.isasyncgenfunction(object)):\n asyncqualifier='async '\n else:\n asyncqualifier=''\n \n if name ==realname:\n title=self.bold(realname)\n else:\n if cl and inspect.getattr_static(cl,realname,[])is object:\n skipdocs=1\n title=self.bold(name)+' = '+realname\n argspec=None\n \n if inspect.isroutine(object):\n try:\n signature=inspect.signature(object)\n except(ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if realname =='':\n title=self.bold(name)+' lambda '\n \n \n \n argspec=argspec[1:-1]\n if not argspec:\n argspec='(...)'\n decl=asyncqualifier+title+argspec+note\n \n if skipdocs:\n return decl+'\\n'\n else:\n doc=getdoc(object)or ''\n return decl+'\\n'+(doc and self.indent(doc).rstrip()+'\\n')\n \n def docdata(self,object,name=None,mod=None,cl=None):\n ''\n results=[]\n push=results.append\n \n if name:\n push(self.bold(name))\n push('\\n')\n doc=getdoc(object)or ''\n if doc:\n push(self.indent(doc))\n push('\\n')\n return ''.join(results)\n \n docproperty=docdata\n \n def docother(self,object,name=None,mod=None,parent=None,maxlen=None,doc=None):\n ''\n repr=self.repr(object)\n if maxlen:\n line=(name and name+' = 'or '')+repr\n chop=maxlen -len(line)\n if chop <0:repr=repr[:chop]+'...'\n line=(name and self.bold(name)+' = 'or '')+repr\n if not doc:\n doc=getdoc(object)\n if doc:\n line +='\\n'+self.indent(str(doc))+'\\n'\n return line\n \nclass _PlainTextDoc(TextDoc):\n ''\n def bold(self,text):\n return text\n \n \n \ndef pager(text):\n ''\n global pager\n pager=getpager()\n pager(text)\n \ndef getpager():\n ''\n if not hasattr(sys.stdin,\"isatty\"):\n return plainpager\n if not hasattr(sys.stdout,\"isatty\"):\n return plainpager\n if not sys.stdin.isatty()or not sys.stdout.isatty():\n return plainpager\n if sys.platform ==\"emscripten\":\n return plainpager\n use_pager=os.environ.get('MANPAGER')or os.environ.get('PAGER')\n if use_pager:\n if sys.platform =='win32':\n return lambda text:tempfilepager(plain(text),use_pager)\n elif os.environ.get('TERM')in('dumb','emacs'):\n return lambda text:pipepager(plain(text),use_pager)\n else:\n return lambda text:pipepager(text,use_pager)\n if os.environ.get('TERM')in('dumb','emacs'):\n return plainpager\n if sys.platform =='win32':\n return lambda text:tempfilepager(plain(text),'more <')\n if hasattr(os,'system')and os.system('(less) 2>/dev/null')==0:\n return lambda text:pipepager(text,'less')\n \n import tempfile\n (fd,filename)=tempfile.mkstemp()\n os.close(fd)\n try:\n if hasattr(os,'system')and os.system('more \"%s\"'%filename)==0:\n return lambda text:pipepager(text,'more')\n else:\n return ttypager\n finally:\n os.unlink(filename)\n \ndef plain(text):\n ''\n return re.sub('.\\b','',text)\n \ndef pipepager(text,cmd):\n ''\n import subprocess\n proc=subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE,\n errors='backslashreplace')\n try:\n with proc.stdin as pipe:\n try:\n pipe.write(text)\n except KeyboardInterrupt:\n \n \n pass\n except OSError:\n pass\n while True:\n try:\n proc.wait()\n break\n except KeyboardInterrupt:\n \n \n pass\n \ndef tempfilepager(text,cmd):\n ''\n import tempfile\n with tempfile.TemporaryDirectory()as tempdir:\n filename=os.path.join(tempdir,'pydoc.out')\n with open(filename,'w',errors='backslashreplace',\n encoding=os.device_encoding(0)if\n sys.platform =='win32'else None\n )as file:\n file.write(text)\n os.system(cmd+' \"'+filename+'\"')\n \ndef _escape_stdout(text):\n\n encoding=getattr(sys.stdout,'encoding',None)or 'utf-8'\n return text.encode(encoding,'backslashreplace').decode(encoding)\n \ndef ttypager(text):\n ''\n lines=plain(_escape_stdout(text)).split('\\n')\n try:\n import tty\n fd=sys.stdin.fileno()\n old=tty.tcgetattr(fd)\n tty.setcbreak(fd)\n getchar=lambda:sys.stdin.read(1)\n except(ImportError,AttributeError,io.UnsupportedOperation):\n tty=None\n getchar=lambda:sys.stdin.readline()[:-1][:1]\n \n try:\n try:\n h=int(os.environ.get('LINES',0))\n except ValueError:\n h=0\n if h <=1:\n h=25\n r=inc=h -1\n sys.stdout.write('\\n'.join(lines[:inc])+'\\n')\n while lines[r:]:\n sys.stdout.write('-- more --')\n sys.stdout.flush()\n c=getchar()\n \n if c in('q','Q'):\n sys.stdout.write('\\r \\r')\n break\n elif c in('\\r','\\n'):\n sys.stdout.write('\\r \\r'+lines[r]+'\\n')\n r=r+1\n continue\n if c in('b','B','\\x1b'):\n r=r -inc -inc\n if r <0:r=0\n sys.stdout.write('\\n'+'\\n'.join(lines[r:r+inc])+'\\n')\n r=r+inc\n \n finally:\n if tty:\n tty.tcsetattr(fd,tty.TCSAFLUSH,old)\n \ndef plainpager(text):\n ''\n sys.stdout.write(plain(_escape_stdout(text)))\n \ndef describe(thing):\n ''\n if inspect.ismodule(thing):\n if thing.__name__ in sys.builtin_module_names:\n return 'built-in module '+thing.__name__\n if hasattr(thing,'__path__'):\n return 'package '+thing.__name__\n else:\n return 'module '+thing.__name__\n if inspect.isbuiltin(thing):\n return 'built-in function '+thing.__name__\n if inspect.isgetsetdescriptor(thing):\n return 'getset descriptor %s.%s.%s'%(\n thing.__objclass__.__module__,thing.__objclass__.__name__,\n thing.__name__)\n if inspect.ismemberdescriptor(thing):\n return 'member descriptor %s.%s.%s'%(\n thing.__objclass__.__module__,thing.__objclass__.__name__,\n thing.__name__)\n if inspect.isclass(thing):\n return 'class '+thing.__name__\n if inspect.isfunction(thing):\n return 'function '+thing.__name__\n if inspect.ismethod(thing):\n return 'method '+thing.__name__\n return type(thing).__name__\n \ndef locate(path,forceload=0):\n ''\n parts=[part for part in path.split('.')if part]\n module,n=None,0\n while n >','&',\n '|','^','~','<','>','<=','>=','==','!=','<>'),\n 'COMPARISON':('<','>','<=','>=','==','!=','<>'),\n 'UNARY':('-','~'),\n 'AUGMENTEDASSIGNMENT':('+=','-=','*=','/=','%=','&=','|=',\n '^=','<<=','>>=','**=','//='),\n 'BITWISE':('<<','>>','&','|','^','~'),\n 'COMPLEX':('j','J')\n }\n symbols={\n '%':'OPERATORS FORMATTING',\n '**':'POWER',\n ',':'TUPLES LISTS FUNCTIONS',\n '.':'ATTRIBUTES FLOAT MODULES OBJECTS',\n '...':'ELLIPSIS',\n ':':'SLICINGS DICTIONARYLITERALS',\n '@':'def class',\n '\\\\':'STRINGS',\n '_':'PRIVATENAMES',\n '__':'PRIVATENAMES SPECIALMETHODS',\n '`':'BACKQUOTES',\n '(':'TUPLES FUNCTIONS CALLS',\n ')':'TUPLES FUNCTIONS CALLS',\n '[':'LISTS SUBSCRIPTS SLICINGS',\n ']':'LISTS SUBSCRIPTS SLICINGS'\n }\n for topic,symbols_ in _symbols_inverse.items():\n for symbol in symbols_:\n topics=symbols.get(symbol,topic)\n if topic not in topics:\n topics=topics+' '+topic\n symbols[symbol]=topics\n del topic,symbols_,symbol,topics\n \n topics={\n 'TYPES':('types','STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '\n 'FUNCTIONS CLASSES MODULES FILES inspect'),\n 'STRINGS':('strings','str UNICODE SEQUENCES STRINGMETHODS '\n 'FORMATTING TYPES'),\n 'STRINGMETHODS':('string-methods','STRINGS FORMATTING'),\n 'FORMATTING':('formatstrings','OPERATORS'),\n 'UNICODE':('strings','encodings unicode SEQUENCES STRINGMETHODS '\n 'FORMATTING TYPES'),\n 'NUMBERS':('numbers','INTEGER FLOAT COMPLEX TYPES'),\n 'INTEGER':('integers','int range'),\n 'FLOAT':('floating','float math'),\n 'COMPLEX':('imaginary','complex cmath'),\n 'SEQUENCES':('typesseq','STRINGMETHODS FORMATTING range LISTS'),\n 'MAPPINGS':'DICTIONARIES',\n 'FUNCTIONS':('typesfunctions','def TYPES'),\n 'METHODS':('typesmethods','class def CLASSES TYPES'),\n 'CODEOBJECTS':('bltin-code-objects','compile FUNCTIONS TYPES'),\n 'TYPEOBJECTS':('bltin-type-objects','types TYPES'),\n 'FRAMEOBJECTS':'TYPES',\n 'TRACEBACKS':'TYPES',\n 'NONE':('bltin-null-object',''),\n 'ELLIPSIS':('bltin-ellipsis-object','SLICINGS'),\n 'SPECIALATTRIBUTES':('specialattrs',''),\n 'CLASSES':('types','class SPECIALMETHODS PRIVATENAMES'),\n 'MODULES':('typesmodules','import'),\n 'PACKAGES':'import',\n 'EXPRESSIONS':('operator-summary','lambda or and not in is BOOLEAN '\n 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '\n 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '\n 'LISTS DICTIONARIES'),\n 'OPERATORS':'EXPRESSIONS',\n 'PRECEDENCE':'EXPRESSIONS',\n 'OBJECTS':('objects','TYPES'),\n 'SPECIALMETHODS':('specialnames','BASICMETHODS ATTRIBUTEMETHODS '\n 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '\n 'NUMBERMETHODS CLASSES'),\n 'BASICMETHODS':('customization','hash repr str SPECIALMETHODS'),\n 'ATTRIBUTEMETHODS':('attribute-access','ATTRIBUTES SPECIALMETHODS'),\n 'CALLABLEMETHODS':('callable-types','CALLS SPECIALMETHODS'),\n 'SEQUENCEMETHODS':('sequence-types','SEQUENCES SEQUENCEMETHODS '\n 'SPECIALMETHODS'),\n 'MAPPINGMETHODS':('sequence-types','MAPPINGS SPECIALMETHODS'),\n 'NUMBERMETHODS':('numeric-types','NUMBERS AUGMENTEDASSIGNMENT '\n 'SPECIALMETHODS'),\n 'EXECUTION':('execmodel','NAMESPACES DYNAMICFEATURES EXCEPTIONS'),\n 'NAMESPACES':('naming','global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),\n 'DYNAMICFEATURES':('dynamic-features',''),\n 'SCOPING':'NAMESPACES',\n 'FRAMES':'NAMESPACES',\n 'EXCEPTIONS':('exceptions','try except finally raise'),\n 'CONVERSIONS':('conversions',''),\n 'IDENTIFIERS':('identifiers','keywords SPECIALIDENTIFIERS'),\n 'SPECIALIDENTIFIERS':('id-classes',''),\n 'PRIVATENAMES':('atom-identifiers',''),\n 'LITERALS':('atom-literals','STRINGS NUMBERS TUPLELITERALS '\n 'LISTLITERALS DICTIONARYLITERALS'),\n 'TUPLES':'SEQUENCES',\n 'TUPLELITERALS':('exprlists','TUPLES LITERALS'),\n 'LISTS':('typesseq-mutable','LISTLITERALS'),\n 'LISTLITERALS':('lists','LISTS LITERALS'),\n 'DICTIONARIES':('typesmapping','DICTIONARYLITERALS'),\n 'DICTIONARYLITERALS':('dict','DICTIONARIES LITERALS'),\n 'ATTRIBUTES':('attribute-references','getattr hasattr setattr ATTRIBUTEMETHODS'),\n 'SUBSCRIPTS':('subscriptions','SEQUENCEMETHODS'),\n 'SLICINGS':('slicings','SEQUENCEMETHODS'),\n 'CALLS':('calls','EXPRESSIONS'),\n 'POWER':('power','EXPRESSIONS'),\n 'UNARY':('unary','EXPRESSIONS'),\n 'BINARY':('binary','EXPRESSIONS'),\n 'SHIFTING':('shifting','EXPRESSIONS'),\n 'BITWISE':('bitwise','EXPRESSIONS'),\n 'COMPARISON':('comparisons','EXPRESSIONS BASICMETHODS'),\n 'BOOLEAN':('booleans','EXPRESSIONS TRUTHVALUE'),\n 'ASSERTION':'assert',\n 'ASSIGNMENT':('assignment','AUGMENTEDASSIGNMENT'),\n 'AUGMENTEDASSIGNMENT':('augassign','NUMBERMETHODS'),\n 'DELETION':'del',\n 'RETURNING':'return',\n 'IMPORTING':'import',\n 'CONDITIONAL':'if',\n 'LOOPING':('compound','for while break continue'),\n 'TRUTHVALUE':('truth','if while and or not BASICMETHODS'),\n 'DEBUGGING':('debugger','pdb'),\n 'CONTEXTMANAGERS':('context-managers','with'),\n }\n \n def __init__(self,input=None,output=None):\n self._input=input\n self._output=output\n \n @property\n def input(self):\n return self._input or sys.stdin\n \n @property\n def output(self):\n return self._output or sys.stdout\n \n def __repr__(self):\n if inspect.stack()[1][3]=='?':\n self()\n return ''\n return '<%s.%s instance>'%(self.__class__.__module__,\n self.__class__.__qualname__)\n \n _GoInteractive=object()\n def __call__(self,request=_GoInteractive):\n if request is not self._GoInteractive:\n try:\n self.help(request)\n except ImportError as err:\n self.output.write(f'{err}\\n')\n else:\n self.intro()\n self.interact()\n self.output.write('''\nYou are now leaving help and returning to the Python interpreter.\nIf you want to ask for help on a particular object directly from the\ninterpreter, you can type \"help(object)\". Executing \"help('string')\"\nhas the same effect as typing a particular string at the help> prompt.\n''')\n \n def interact(self):\n self.output.write('\\n')\n while True:\n try:\n request=self.getline('help> ')\n if not request:break\n except(KeyboardInterrupt,EOFError):\n break\n request=request.strip()\n \n \n \n if(len(request)>2 and request[0]==request[-1]in(\"'\",'\"')\n and request[0]not in request[1:-1]):\n request=request[1:-1]\n if request.lower()in('q','quit'):break\n if request =='help':\n self.intro()\n else:\n self.help(request)\n \n def getline(self,prompt):\n ''\n if self.input is sys.stdin:\n return input(prompt)\n else:\n self.output.write(prompt)\n self.output.flush()\n return self.input.readline()\n \n def help(self,request):\n if isinstance(request,str):\n request=request.strip()\n if request =='keywords':self.listkeywords()\n elif request =='symbols':self.listsymbols()\n elif request =='topics':self.listtopics()\n elif request =='modules':self.listmodules()\n elif request[:8]=='modules ':\n self.listmodules(request.split()[1])\n elif request in self.symbols:self.showsymbol(request)\n elif request in['True','False','None']:\n \n doc(eval(request),'Help on %s:')\n elif request in self.keywords:self.showtopic(request)\n elif request in self.topics:self.showtopic(request)\n elif request:doc(request,'Help on %s:',output=self._output)\n else:doc(str,'Help on %s:',output=self._output)\n elif isinstance(request,Helper):self()\n else:doc(request,'Help on %s:',output=self._output)\n self.output.write('\\n')\n \n def intro(self):\n self.output.write('''\nWelcome to Python {0}'s help utility!\n\nIf this is your first time using Python, you should definitely check out\nthe tutorial on the internet at https://docs.python.org/{0}/tutorial/.\n\nEnter the name of any module, keyword, or topic to get help on writing\nPython programs and using Python modules. To quit this help utility and\nreturn to the interpreter, just type \"quit\".\n\nTo get a list of available modules, keywords, symbols, or topics, type\n\"modules\", \"keywords\", \"symbols\", or \"topics\". Each module also comes\nwith a one-line summary of what it does; to list the modules whose name\nor summary contain a given string such as \"spam\", type \"modules spam\".\n'''.format('%d.%d'%sys.version_info[:2]))\n \n def list(self,items,columns=4,width=80):\n items=list(sorted(items))\n colw=width //columns\n rows=(len(items)+columns -1)//columns\n for row in range(rows):\n for col in range(columns):\n i=col *rows+row\n if i =0:\n callback(None,modname,desc)\n \n for importer,modname,ispkg in pkgutil.walk_packages(onerror=onerror):\n if self.quit:\n break\n \n if key is None:\n callback(None,modname,'')\n else:\n try:\n spec=importer.find_spec(modname)\n except SyntaxError:\n \n continue\n loader=spec.loader\n if hasattr(loader,'get_source'):\n try:\n source=loader.get_source(modname)\n except Exception:\n if onerror:\n onerror(modname)\n continue\n desc=source_synopsis(io.StringIO(source))or ''\n if hasattr(loader,'get_filename'):\n path=loader.get_filename(modname)\n else:\n path=None\n else:\n try:\n module=importlib._bootstrap._load(spec)\n except ImportError:\n if onerror:\n onerror(modname)\n continue\n desc=module.__doc__.splitlines()[0]if module.__doc__ else ''\n path=getattr(module,'__file__',None)\n name=modname+' - '+desc\n if name.lower().find(key)>=0:\n callback(path,modname,desc)\n \n if completer:\n completer()\n \ndef apropos(key):\n ''\n def callback(path,modname,desc):\n if modname[-9:]=='.__init__':\n modname=modname[:-9]+' (package)'\n print(modname,desc and '- '+desc)\n def onerror(modname):\n pass\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n ModuleScanner().run(callback,key,onerror=onerror)\n \n \n \ndef _start_server(urlhandler,hostname,port):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n import http.server\n import email.message\n import select\n import threading\n \n class DocHandler(http.server.BaseHTTPRequestHandler):\n \n def do_GET(self):\n ''\n\n\n\n \n if self.path.endswith('.css'):\n content_type='text/css'\n else:\n content_type='text/html'\n self.send_response(200)\n self.send_header('Content-Type','%s; charset=UTF-8'%content_type)\n self.end_headers()\n self.wfile.write(self.urlhandler(\n self.path,content_type).encode('utf-8'))\n \n def log_message(self,*args):\n \n pass\n \n class DocServer(http.server.HTTPServer):\n \n def __init__(self,host,port,callback):\n self.host=host\n self.address=(self.host,port)\n self.callback=callback\n self.base.__init__(self,self.address,self.handler)\n self.quit=False\n \n def serve_until_quit(self):\n while not self.quit:\n rd,wr,ex=select.select([self.socket.fileno()],[],[],1)\n if rd:\n self.handle_request()\n self.server_close()\n \n def server_activate(self):\n self.base.server_activate(self)\n if self.callback:\n self.callback(self)\n \n class ServerThread(threading.Thread):\n \n def __init__(self,urlhandler,host,port):\n self.urlhandler=urlhandler\n self.host=host\n self.port=int(port)\n threading.Thread.__init__(self)\n self.serving=False\n self.error=None\n \n def run(self):\n ''\n try:\n DocServer.base=http.server.HTTPServer\n DocServer.handler=DocHandler\n DocHandler.MessageClass=email.message.Message\n DocHandler.urlhandler=staticmethod(self.urlhandler)\n docsvr=DocServer(self.host,self.port,self.ready)\n self.docserver=docsvr\n docsvr.serve_until_quit()\n except Exception as err:\n self.error=err\n \n def ready(self,server):\n self.serving=True\n self.host=server.host\n self.port=server.server_port\n self.url='http://%s:%d/'%(self.host,self.port)\n \n def stop(self):\n ''\n self.docserver.quit=True\n self.join()\n \n \n self.docserver=None\n self.serving=False\n self.url=None\n \n thread=ServerThread(urlhandler,hostname,port)\n thread.start()\n \n \n while not thread.error and not thread.serving:\n time.sleep(.01)\n return thread\n \n \ndef _url_handler(url,content_type=\"text/html\"):\n ''\n\n\n\n\n\n\n \n class _HTMLDoc(HTMLDoc):\n \n def page(self,title,contents):\n ''\n css_path=\"pydoc_data/_pydoc.css\"\n css_link=(\n ''%\n css_path)\n return '''\\\n\n\n\n\nPydoc: %s\n%s%s
%s
\n'''%(title,css_link,html_navbar(),contents)\n \n \n html=_HTMLDoc()\n \n def html_navbar():\n version=html.escape(\"%s [%s, %s]\"%(platform.python_version(),\n platform.python_build()[0],\n platform.python_compiler()))\n return \"\"\"\n
\n Python %s
%s\n
\n
\n \n
\n
\n \n \n
 \n
\n \n \n
\n
\n
\n \"\"\"%(version,html.escape(platform.platform(terse=True)))\n \n def html_index():\n ''\n \n def bltinlink(name):\n return '%s'%(name,name)\n \n heading=html.heading(\n 'Index of Modules'\n )\n names=[name for name in sys.builtin_module_names\n if name !='__main__']\n contents=html.multicolumn(names,bltinlink)\n contents=[heading,'

'+html.bigsection(\n 'Built-in Modules','index',contents)]\n \n seen={}\n for dir in sys.path:\n contents.append(html.index(dir,seen))\n \n contents.append(\n '

pydoc by Ka-Ping Yee'\n '<ping@lfw.org>

')\n return 'Index of Modules',''.join(contents)\n \n def html_search(key):\n ''\n \n search_result=[]\n \n def callback(path,modname,desc):\n if modname[-9:]=='.__init__':\n modname=modname[:-9]+' (package)'\n search_result.append((modname,desc and '- '+desc))\n \n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n def onerror(modname):\n pass\n ModuleScanner().run(callback,key,onerror=onerror)\n \n \n def bltinlink(name):\n return '%s'%(name,name)\n \n results=[]\n heading=html.heading(\n 'Search Results',\n )\n for name,desc in search_result:\n results.append(bltinlink(name)+desc)\n contents=heading+html.bigsection(\n 'key = %s'%key,'index','
'.join(results))\n return 'Search Results',contents\n \n def html_topics():\n ''\n \n def bltinlink(name):\n return '%s'%(name,name)\n \n heading=html.heading(\n 'INDEX',\n )\n names=sorted(Helper.topics.keys())\n \n contents=html.multicolumn(names,bltinlink)\n contents=heading+html.bigsection(\n 'Topics','index',contents)\n return 'Topics',contents\n \n def html_keywords():\n ''\n heading=html.heading(\n 'INDEX',\n )\n names=sorted(Helper.keywords.keys())\n \n def bltinlink(name):\n return '%s'%(name,name)\n \n contents=html.multicolumn(names,bltinlink)\n contents=heading+html.bigsection(\n 'Keywords','index',contents)\n return 'Keywords',contents\n \n def html_topicpage(topic):\n ''\n buf=io.StringIO()\n htmlhelp=Helper(buf,buf)\n contents,xrefs=htmlhelp._gettopic(topic)\n if topic in htmlhelp.keywords:\n title='KEYWORD'\n else:\n title='TOPIC'\n heading=html.heading(\n '%s'%title,\n )\n contents='
%s
'%html.markup(contents)\n contents=html.bigsection(topic,'index',contents)\n if xrefs:\n xrefs=sorted(xrefs.split())\n \n def bltinlink(name):\n return '%s'%(name,name)\n \n xrefs=html.multicolumn(xrefs,bltinlink)\n xrefs=html.section('Related help topics: ','index',xrefs)\n return('%s %s'%(title,topic),\n ''.join((heading,contents,xrefs)))\n \n def html_getobj(url):\n obj=locate(url,forceload=1)\n if obj is None and url !='None':\n raise ValueError('could not find object')\n title=describe(obj)\n content=html.document(obj,url)\n return title,content\n \n def html_error(url,exc):\n heading=html.heading(\n 'Error',\n )\n contents='
'.join(html.escape(line)for line in\n format_exception_only(type(exc),exc))\n contents=heading+html.bigsection(url,'error',contents)\n return \"Error - %s\"%url,contents\n \n def get_html_page(url):\n ''\n complete_url=url\n if url.endswith('.html'):\n url=url[:-5]\n try:\n if url in(\"\",\"index\"):\n title,content=html_index()\n elif url ==\"topics\":\n title,content=html_topics()\n elif url ==\"keywords\":\n title,content=html_keywords()\n elif '='in url:\n op,_,url=url.partition('=')\n if op ==\"search?key\":\n title,content=html_search(url)\n elif op ==\"topic?key\":\n \n try:\n title,content=html_topicpage(url)\n except ValueError:\n title,content=html_getobj(url)\n elif op ==\"get?key\":\n \n if url in(\"\",\"index\"):\n title,content=html_index()\n else:\n try:\n title,content=html_getobj(url)\n except ValueError:\n title,content=html_topicpage(url)\n else:\n raise ValueError('bad pydoc url')\n else:\n title,content=html_getobj(url)\n except Exception as exc:\n \n title,content=html_error(complete_url,exc)\n return html.page(title,content)\n \n if url.startswith('/'):\n url=url[1:]\n if content_type =='text/css':\n path_here=os.path.dirname(os.path.realpath(__file__))\n css_path=os.path.join(path_here,url)\n with open(css_path)as fp:\n return ''.join(fp.readlines())\n elif content_type =='text/html':\n return get_html_page(url)\n \n raise TypeError('unknown content type %r for url %s'%(content_type,url))\n \n \ndef browse(port=0,*,open_browser=True,hostname='localhost'):\n ''\n\n\n\n \n import webbrowser\n serverthread=_start_server(_url_handler,hostname,port)\n if serverthread.error:\n print(serverthread.error)\n return\n if serverthread.serving:\n server_help_msg='Server commands: [b]rowser, [q]uit'\n if open_browser:\n webbrowser.open(serverthread.url)\n try:\n print('Server ready at',serverthread.url)\n print(server_help_msg)\n while serverthread.serving:\n cmd=input('server> ')\n cmd=cmd.lower()\n if cmd =='q':\n break\n elif cmd =='b':\n webbrowser.open(serverthread.url)\n else:\n print(server_help_msg)\n except(KeyboardInterrupt,EOFError):\n print()\n finally:\n if serverthread.serving:\n serverthread.stop()\n print('Server stopped')\n \n \n \n \ndef ispath(x):\n return isinstance(x,str)and x.find(os.sep)>=0\n \ndef _get_revised_path(given_path,argv0):\n ''\n\n\n\n\n \n \n \n \n \n \n \n if ''in given_path or os.curdir in given_path or os.getcwd()in given_path:\n return None\n \n \n \n stdlib_dir=os.path.dirname(__file__)\n script_dir=os.path.dirname(argv0)\n revised_path=given_path.copy()\n if script_dir in given_path and not os.path.samefile(script_dir,stdlib_dir):\n revised_path.remove(script_dir)\n revised_path.insert(0,os.getcwd())\n return revised_path\n \n \n \ndef _adjust_cli_sys_path():\n ''\n\n\n \n revised_path=_get_revised_path(sys.path,sys.argv[0])\n if revised_path is not None:\n sys.path[:]=revised_path\n \n \ndef cli():\n ''\n import getopt\n class BadUsage(Exception):pass\n \n _adjust_cli_sys_path()\n \n try:\n opts,args=getopt.getopt(sys.argv[1:],'bk:n:p:w')\n writing=False\n start_server=False\n open_browser=False\n port=0\n hostname='localhost'\n for opt,val in opts:\n if opt =='-b':\n start_server=True\n open_browser=True\n if opt =='-k':\n apropos(val)\n return\n if opt =='-p':\n start_server=True\n port=val\n if opt =='-w':\n writing=True\n if opt =='-n':\n start_server=True\n hostname=val\n \n if start_server:\n browse(port,hostname=hostname,open_browser=open_browser)\n return\n \n if not args:raise BadUsage\n for arg in args:\n if ispath(arg)and not os.path.exists(arg):\n print('file %r does not exist'%arg)\n sys.exit(1)\n try:\n if ispath(arg)and os.path.isfile(arg):\n arg=importfile(arg)\n if writing:\n if ispath(arg)and os.path.isdir(arg):\n writedocs(arg)\n else:\n writedoc(arg)\n else:\n help.help(arg)\n except(ImportError,ErrorDuringImport)as value:\n print(value)\n sys.exit(1)\n \n except(getopt.error,BadUsage):\n cmd=os.path.splitext(os.path.basename(sys.argv[0]))[0]\n print(\"\"\"pydoc - the Python documentation tool\n\n{cmd} ...\n Show text documentation on something. may be the name of a\n Python keyword, topic, function, module, or package, or a dotted\n reference to a class or function within a module or module in a\n package. If contains a '{sep}', it is used as the path to a\n Python source file to document. If name is 'keywords', 'topics',\n or 'modules', a listing of these things is displayed.\n\n{cmd} -k \n Search for a keyword in the synopsis lines of all available modules.\n\n{cmd} -n \n Start an HTTP server with the given hostname (default: localhost).\n\n{cmd} -p \n Start an HTTP server on the given port on the local machine. Port\n number 0 can be used to get an arbitrary unused port.\n\n{cmd} -b\n Start an HTTP server on an arbitrary unused port and open a web browser\n to interactively browse documentation. This option can be used in\n combination with -n and/or -p.\n\n{cmd} -w ...\n Write out the HTML documentation for a module to a file in the current\n directory. If contains a '{sep}', it is treated as a filename; if\n it names a directory, documentation is written for all the contents.\n\"\"\".format(cmd=cmd,sep=os.sep))\n \nif __name__ =='__main__':\n cli()\n", ["__future__", "builtins", "collections", "email.message", "getopt", "http.server", "importlib._bootstrap", "importlib._bootstrap_external", "importlib.machinery", "importlib.util", "inspect", "io", "os", "pkgutil", "platform", "pydoc_data.topics", "re", "reprlib", "select", "subprocess", "sys", "sysconfig", "tempfile", "textwrap", "threading", "time", "tokenize", "traceback", "tty", "urllib.parse", "warnings", "webbrowser"]], "py_compile": [".py", "''\n\n\n\n\nimport enum\nimport importlib._bootstrap_external\nimport importlib.machinery\nimport importlib.util\nimport os\nimport os.path\nimport sys\nimport traceback\n\n__all__=[\"compile\",\"main\",\"PyCompileError\",\"PycInvalidationMode\"]\n\n\nclass PyCompileError(Exception):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,exc_type,exc_value,file,msg=''):\n exc_type_name=exc_type.__name__\n if exc_type is SyntaxError:\n tbtext=''.join(traceback.format_exception_only(\n exc_type,exc_value))\n errmsg=tbtext.replace('File \"\"','File \"%s\"'%file)\n else:\n errmsg=\"Sorry: %s: %s\"%(exc_type_name,exc_value)\n \n Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)\n \n self.exc_type_name=exc_type_name\n self.exc_value=exc_value\n self.file=file\n self.msg=msg or errmsg\n \n def __str__(self):\n return self.msg\n \n \nclass PycInvalidationMode(enum.Enum):\n TIMESTAMP=1\n CHECKED_HASH=2\n UNCHECKED_HASH=3\n \n \ndef _get_default_invalidation_mode():\n if os.environ.get('SOURCE_DATE_EPOCH'):\n return PycInvalidationMode.CHECKED_HASH\n else:\n return PycInvalidationMode.TIMESTAMP\n \n \ndef compile(file,cfile=None,dfile=None,doraise=False,optimize=-1,\ninvalidation_mode=None,quiet=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if invalidation_mode is None:\n invalidation_mode=_get_default_invalidation_mode()\n if cfile is None:\n if optimize >=0:\n optimization=optimize if optimize >=1 else ''\n cfile=importlib.util.cache_from_source(file,\n optimization=optimization)\n else:\n cfile=importlib.util.cache_from_source(file)\n if os.path.islink(cfile):\n msg=('{} is a symlink and will be changed into a regular file if '\n 'import writes a byte-compiled file to it')\n raise FileExistsError(msg.format(cfile))\n elif os.path.exists(cfile)and not os.path.isfile(cfile):\n msg=('{} is a non-regular file and will be changed into a regular '\n 'one if import writes a byte-compiled file to it')\n raise FileExistsError(msg.format(cfile))\n loader=importlib.machinery.SourceFileLoader('',file)\n source_bytes=loader.get_data(file)\n try:\n code=loader.source_to_code(source_bytes,dfile or file,\n _optimize=optimize)\n except Exception as err:\n py_exc=PyCompileError(err.__class__,err,dfile or file)\n if quiet <2:\n if doraise:\n raise py_exc\n else:\n sys.stderr.write(py_exc.msg+'\\n')\n return\n try:\n dirname=os.path.dirname(cfile)\n if dirname:\n os.makedirs(dirname)\n except FileExistsError:\n pass\n if invalidation_mode ==PycInvalidationMode.TIMESTAMP:\n source_stats=loader.path_stats(file)\n bytecode=importlib._bootstrap_external._code_to_timestamp_pyc(\n code,source_stats['mtime'],source_stats['size'])\n else:\n source_hash=importlib.util.source_hash(source_bytes)\n bytecode=importlib._bootstrap_external._code_to_hash_pyc(\n code,\n source_hash,\n (invalidation_mode ==PycInvalidationMode.CHECKED_HASH),\n )\n mode=importlib._bootstrap_external._calc_mode(file)\n importlib._bootstrap_external._write_atomic(cfile,bytecode,mode)\n return cfile\n \n \ndef main():\n import argparse\n \n description='A simple command-line interface for py_compile module.'\n parser=argparse.ArgumentParser(description=description)\n parser.add_argument(\n '-q','--quiet',\n action='store_true',\n help='Suppress error output',\n )\n parser.add_argument(\n 'filenames',\n nargs='+',\n help='Files to compile',\n )\n args=parser.parse_args()\n if args.filenames ==['-']:\n filenames=[filename.rstrip('\\n')for filename in sys.stdin.readlines()]\n else:\n filenames=args.filenames\n for filename in filenames:\n try:\n compile(filename,doraise=True)\n except PyCompileError as error:\n if args.quiet:\n parser.exit(1)\n else:\n parser.exit(1,error.msg)\n except OSError as error:\n if args.quiet:\n parser.exit(1)\n else:\n parser.exit(1,str(error))\n \n \nif __name__ ==\"__main__\":\n main()\n", ["argparse", "enum", "importlib._bootstrap_external", "importlib.machinery", "importlib.util", "os", "os.path", "sys", "traceback"]], "queue": [".py", "''\n\nimport threading\nimport types\nfrom collections import deque\nfrom heapq import heappush,heappop\nfrom time import monotonic as time\ntry:\n from _queue import SimpleQueue\nexcept ImportError:\n SimpleQueue=None\n \n__all__=[\n'Empty',\n'Full',\n'ShutDown',\n'Queue',\n'PriorityQueue',\n'LifoQueue',\n'SimpleQueue',\n]\n\n\ntry:\n from _queue import Empty\nexcept ImportError:\n class Empty(Exception):\n ''\n pass\n \nclass Full(Exception):\n ''\n pass\n \n \nclass ShutDown(Exception):\n ''\n \n \nclass Queue:\n ''\n\n\n \n \n def __init__(self,maxsize=0):\n self.maxsize=maxsize\n self._init(maxsize)\n \n \n \n \n \n self.mutex=threading.Lock()\n \n \n \n self.not_empty=threading.Condition(self.mutex)\n \n \n \n self.not_full=threading.Condition(self.mutex)\n \n \n \n self.all_tasks_done=threading.Condition(self.mutex)\n self.unfinished_tasks=0\n \n \n self.is_shutdown=False\n \n def task_done(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n with self.all_tasks_done:\n unfinished=self.unfinished_tasks -1\n if unfinished <=0:\n if unfinished <0:\n raise ValueError('task_done() called too many times')\n self.all_tasks_done.notify_all()\n self.unfinished_tasks=unfinished\n \n def join(self):\n ''\n\n\n\n\n\n\n \n with self.all_tasks_done:\n while self.unfinished_tasks:\n self.all_tasks_done.wait()\n \n def qsize(self):\n ''\n with self.mutex:\n return self._qsize()\n \n def empty(self):\n ''\n\n\n\n\n\n\n\n\n \n with self.mutex:\n return not self._qsize()\n \n def full(self):\n ''\n\n\n\n\n\n \n with self.mutex:\n return 0 0:\n if not block:\n if self._qsize()>=self.maxsize:\n raise Full\n elif timeout is None:\n while self._qsize()>=self.maxsize:\n self.not_full.wait()\n if self.is_shutdown:\n raise ShutDown\n elif timeout <0:\n raise ValueError(\"'timeout' must be a non-negative number\")\n else:\n endtime=time()+timeout\n while self._qsize()>=self.maxsize:\n remaining=endtime -time()\n if remaining <=0.0:\n raise Full\n self.not_full.wait(remaining)\n if self.is_shutdown:\n raise ShutDown\n self._put(item)\n self.unfinished_tasks +=1\n self.not_empty.notify()\n \n def get(self,block=True,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n with self.not_empty:\n if self.is_shutdown and not self._qsize():\n raise ShutDown\n if not block:\n if not self._qsize():\n raise Empty\n elif timeout is None:\n while not self._qsize():\n self.not_empty.wait()\n if self.is_shutdown and not self._qsize():\n raise ShutDown\n elif timeout <0:\n raise ValueError(\"'timeout' must be a non-negative number\")\n else:\n endtime=time()+timeout\n while not self._qsize():\n remaining=endtime -time()\n if remaining <=0.0:\n raise Empty\n self.not_empty.wait(remaining)\n if self.is_shutdown and not self._qsize():\n raise ShutDown\n item=self._get()\n self.not_full.notify()\n return item\n \n def put_nowait(self,item):\n ''\n\n\n\n \n return self.put(item,block=False)\n \n def get_nowait(self):\n ''\n\n\n\n \n return self.get(block=False)\n \n def shutdown(self,immediate=False):\n ''\n\n\n\n\n\n\n\n \n with self.mutex:\n self.is_shutdown=True\n if immediate:\n while self._qsize():\n self._get()\n if self.unfinished_tasks >0:\n self.unfinished_tasks -=1\n \n self.all_tasks_done.notify_all()\n \n self.not_empty.notify_all()\n self.not_full.notify_all()\n \n \n \n \n \n \n def _init(self,maxsize):\n self.queue=deque()\n \n def _qsize(self):\n return len(self.queue)\n \n \n def _put(self,item):\n self.queue.append(item)\n \n \n def _get(self):\n return self.queue.popleft()\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \nclass PriorityQueue(Queue):\n ''\n\n\n \n \n def _init(self,maxsize):\n self.queue=[]\n \n def _qsize(self):\n return len(self.queue)\n \n def _put(self,item):\n heappush(self.queue,item)\n \n def _get(self):\n return heappop(self.queue)\n \n \nclass LifoQueue(Queue):\n ''\n \n def _init(self,maxsize):\n self.queue=[]\n \n def _qsize(self):\n return len(self.queue)\n \n def _put(self,item):\n self.queue.append(item)\n \n def _get(self):\n return self.queue.pop()\n \n \nclass _PySimpleQueue:\n ''\n\n\n \n \n \n \n \n \n def __init__(self):\n self._queue=deque()\n self._count=threading.Semaphore(0)\n \n def put(self,item,block=True,timeout=None):\n ''\n\n\n\n \n self._queue.append(item)\n self._count.release()\n \n def get(self,block=True,timeout=None):\n ''\n\n\n\n\n\n\n\n\n \n if timeout is not None and timeout <0:\n raise ValueError(\"'timeout' must be a non-negative number\")\n if not self._count.acquire(block,timeout):\n raise Empty\n return self._queue.popleft()\n \n def put_nowait(self,item):\n ''\n\n\n\n \n return self.put(item,block=False)\n \n def get_nowait(self):\n ''\n\n\n\n \n return self.get(block=False)\n \n def empty(self):\n ''\n return len(self._queue)==0\n \n def qsize(self):\n ''\n return len(self._queue)\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \nif SimpleQueue is None:\n SimpleQueue=_PySimpleQueue\n", ["_queue", "collections", "heapq", "threading", "time", "types"]], "quopri": [".py", "#! /usr/bin/env python3\n\n\"\"\"Conversions to/from quoted-printable transport encoding as per RFC 1521.\"\"\"\n\n\n\n__all__=[\"encode\",\"decode\",\"encodestring\",\"decodestring\"]\n\nESCAPE=b'='\nMAXLINESIZE=76\nHEX=b'0123456789ABCDEF'\nEMPTYSTRING=b''\n\ntry:\n from binascii import a2b_qp,b2a_qp\nexcept ImportError:\n a2b_qp=None\n b2a_qp=None\n \n \ndef needsquoting(c,quotetabs,header):\n ''\n\n\n\n\n \n assert isinstance(c,bytes)\n if c in b' \\t':\n return quotetabs\n \n if c ==b'_':\n return header\n return c ==ESCAPE or not(b' '<=c <=b'~')\n \ndef quote(c):\n ''\n assert isinstance(c,bytes)and len(c)==1\n c=ord(c)\n return ESCAPE+bytes((HEX[c //16],HEX[c %16]))\n \n \n \ndef encode(input,output,quotetabs,header=False):\n ''\n\n\n\n\n\n \n \n if b2a_qp is not None:\n data=input.read()\n odata=b2a_qp(data,quotetabs=quotetabs,header=header)\n output.write(odata)\n return\n \n def write(s,output=output,lineEnd=b'\\n'):\n \n \n if s and s[-1:]in b' \\t':\n output.write(s[:-1]+quote(s[-1:])+lineEnd)\n elif s ==b'.':\n output.write(quote(s)+lineEnd)\n else:\n output.write(s+lineEnd)\n \n prevline=None\n while line :=input.readline():\n outline=[]\n \n stripped=b''\n if line[-1:]==b'\\n':\n line=line[:-1]\n stripped=b'\\n'\n \n for c in line:\n c=bytes((c,))\n if needsquoting(c,quotetabs,header):\n c=quote(c)\n if header and c ==b' ':\n outline.append(b'_')\n else:\n outline.append(c)\n \n if prevline is not None:\n write(prevline)\n \n \n thisline=EMPTYSTRING.join(outline)\n while len(thisline)>MAXLINESIZE:\n \n \n write(thisline[:MAXLINESIZE -1],lineEnd=b'=\\n')\n thisline=thisline[MAXLINESIZE -1:]\n \n prevline=thisline\n \n if prevline is not None:\n write(prevline,lineEnd=stripped)\n \ndef encodestring(s,quotetabs=False,header=False):\n if b2a_qp is not None:\n return b2a_qp(s,quotetabs=quotetabs,header=header)\n from io import BytesIO\n infp=BytesIO(s)\n outfp=BytesIO()\n encode(infp,outfp,quotetabs,header)\n return outfp.getvalue()\n \n \n \ndef decode(input,output,header=False):\n ''\n\n \n \n if a2b_qp is not None:\n data=input.read()\n odata=a2b_qp(data,header=header)\n output.write(odata)\n return\n \n new=b''\n while line :=input.readline():\n i,n=0,len(line)\n if n >0 and line[n -1:n]==b'\\n':\n partial=0 ;n=n -1\n \n while n >0 and line[n -1:n]in b\" \\t\\r\":\n n=n -1\n else:\n partial=1\n while i =n:\n r=getrandbits(k)\n return r\n \n def _randbelow_without_getrandbits(self,n,maxsize=1 <=maxsize:\n _warn(\"Underlying random() generator does not supply \\n\"\n \"enough bits to choose from a population range this large.\\n\"\n \"To remove the range limitation, add a getrandbits() method.\")\n return _floor(random()*n)\n rem=maxsize %n\n limit=(maxsize -rem)/maxsize\n r=random()\n while r >=limit:\n r=random()\n return _floor(r *maxsize)%n\n \n _randbelow=_randbelow_with_getrandbits\n \n \n \n \n \n \n \n \n \n \n \n \n def randbytes(self,n):\n ''\n return self.getrandbits(n *8).to_bytes(n,'little')\n \n \n \n \n def randrange(self,start,stop=None,step=_ONE):\n ''\n\n\n\n\n \n \n \n \n istart=_index(start)\n if stop is None:\n \n \n if step is not _ONE:\n raise TypeError(\"Missing a non-None stop argument\")\n if istart >0:\n return self._randbelow(istart)\n raise ValueError(\"empty range for randrange()\")\n \n \n istop=_index(stop)\n width=istop -istart\n istep=_index(step)\n \n if istep ==1:\n if width >0:\n return istart+self._randbelow(width)\n raise ValueError(f\"empty range in randrange({start}, {stop})\")\n \n \n if istep >0:\n n=(width+istep -1)//istep\n elif istep <0:\n n=(width+istep+1)//istep\n else:\n raise ValueError(\"zero step for randrange()\")\n if n <=0:\n raise ValueError(f\"empty range in randrange({start}, {stop}, {step})\")\n return istart+istep *self._randbelow(n)\n \n def randint(self,a,b):\n ''\n \n \n return self.randrange(a,b+1)\n \n \n \n \n def choice(self,seq):\n ''\n \n \n \n if not len(seq):\n raise IndexError('Cannot choose from an empty sequence')\n return seq[self._randbelow(len(seq))]\n \n def shuffle(self,x):\n ''\n \n randbelow=self._randbelow\n for i in reversed(range(1,len(x))):\n \n j=randbelow(i+1)\n x[i],x[j]=x[j],x[i]\n \n def sample(self,population,k,*,counts=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if not isinstance(population,_Sequence):\n raise TypeError(\"Population must be a sequence. \"\n \"For dicts or sets, use sorted(d).\")\n n=len(population)\n if counts is not None:\n cum_counts=list(_accumulate(counts))\n if len(cum_counts)!=n:\n raise ValueError('The number of counts does not match the population')\n total=cum_counts.pop()\n if not isinstance(total,int):\n raise TypeError('Counts must be integers')\n if total <=0:\n raise ValueError('Total of counts must be greater than zero')\n selections=self.sample(range(total),k=k)\n bisect=_bisect\n return[population[bisect(cum_counts,s)]for s in selections]\n randbelow=self._randbelow\n if not 0 <=k <=n:\n raise ValueError(\"Sample larger than population or is negative\")\n result=[None]*k\n setsize=21\n if k >5:\n setsize +=4 **_ceil(_log(k *3,4))\n if n <=setsize:\n \n \n pool=list(population)\n for i in range(k):\n j=randbelow(n -i)\n result[i]=pool[j]\n pool[j]=pool[n -i -1]\n else:\n selected=set()\n selected_add=selected.add\n for i in range(k):\n j=randbelow(n)\n while j in selected:\n j=randbelow(n)\n selected_add(j)\n result[i]=population[j]\n return result\n \n def choices(self,population,weights=None,*,cum_weights=None,k=1):\n ''\n\n\n\n\n \n random=self.random\n n=len(population)\n if cum_weights is None:\n if weights is None:\n floor=_floor\n n +=0.0\n return[population[floor(random()*n)]for i in _repeat(None,k)]\n try:\n cum_weights=list(_accumulate(weights))\n except TypeError:\n if not isinstance(weights,int):\n raise\n k=weights\n raise TypeError(\n f'The number of choices must be a keyword argument: {k=}'\n )from None\n elif weights is not None:\n raise TypeError('Cannot specify both weights and cumulative weights')\n if len(cum_weights)!=n:\n raise ValueError('The number of weights does not match the population')\n total=cum_weights[-1]+0.0\n if total <=0.0:\n raise ValueError('Total of weights must be greater than zero')\n if not _isfinite(total):\n raise ValueError('Total of weights must be finite')\n bisect=_bisect\n hi=n -1\n return[population[bisect(cum_weights,random()*total,0,hi)]\n for i in _repeat(None,k)]\n \n \n \n \n def uniform(self,a,b):\n ''\n return a+(b -a)*self.random()\n \n def triangular(self,low=0.0,high=1.0,mode=None):\n ''\n\n\n\n\n\n\n \n u=self.random()\n try:\n c=0.5 if mode is None else(mode -low)/(high -low)\n except ZeroDivisionError:\n return low\n if u >c:\n u=1.0 -u\n c=1.0 -c\n low,high=high,low\n return low+(high -low)*_sqrt(u *c)\n \n def normalvariate(self,mu=0.0,sigma=1.0):\n ''\n\n\n\n \n \n \n \n \n \n random=self.random\n while True:\n u1=random()\n u2=1.0 -random()\n z=NV_MAGICCONST *(u1 -0.5)/u2\n zz=z *z /4.0\n if zz <=-_log(u2):\n break\n return mu+z *sigma\n \n def gauss(self,mu=0.0,sigma=1.0):\n ''\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n random=self.random\n z=self.gauss_next\n self.gauss_next=None\n if z is None:\n x2pi=random()*TWOPI\n g2rad=_sqrt(-2.0 *_log(1.0 -random()))\n z=_cos(x2pi)*g2rad\n self.gauss_next=_sin(x2pi)*g2rad\n \n return mu+z *sigma\n \n def lognormvariate(self,mu,sigma):\n ''\n\n\n\n\n\n \n return _exp(self.normalvariate(mu,sigma))\n \n def expovariate(self,lambd=1.0):\n ''\n\n\n\n\n\n\n\n \n \n \n \n \n \n return -_log(1.0 -self.random())/lambd\n \n def vonmisesvariate(self,mu,kappa):\n ''\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n random=self.random\n if kappa <=1e-6:\n return TWOPI *random()\n \n s=0.5 /kappa\n r=s+_sqrt(1.0+s *s)\n \n while True:\n u1=random()\n z=_cos(_pi *u1)\n \n d=z /(r+z)\n u2=random()\n if u2 <1.0 -d *d or u2 <=(1.0 -d)*_exp(d):\n break\n \n q=1.0 /r\n f=(q+z)/(1.0+q *z)\n u3=random()\n if u3 >0.5:\n theta=(mu+_acos(f))%TWOPI\n else:\n theta=(mu -_acos(f))%TWOPI\n \n return theta\n \n def gammavariate(self,alpha,beta):\n ''\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n if alpha <=0.0 or beta <=0.0:\n raise ValueError('gammavariate: alpha and beta must be > 0.0')\n \n random=self.random\n if alpha >1.0:\n \n \n \n \n \n ainv=_sqrt(2.0 *alpha -1.0)\n bbb=alpha -LOG4\n ccc=alpha+ainv\n \n while True:\n u1=random()\n if not 1e-7 =0.0 or r >=_log(z):\n return x *beta\n \n elif alpha ==1.0:\n \n return -_log(1.0 -random())*beta\n \n else:\n \n \n while True:\n u=random()\n b=(_e+alpha)/_e\n p=b *u\n if p <=1.0:\n x=p **(1.0 /alpha)\n else:\n x=-_log((b -p)/alpha)\n u1=random()\n if p >1.0:\n if u1 <=x **(alpha -1.0):\n break\n elif u1 <=_exp(-x):\n break\n return x *beta\n \n def betavariate(self,alpha,beta):\n ''\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n y=self.gammavariate(alpha,1.0)\n if y:\n return y /(y+self.gammavariate(beta,1.0))\n return 0.0\n \n def paretovariate(self,alpha):\n ''\n \n \n u=1.0 -self.random()\n return u **(-1.0 /alpha)\n \n def weibullvariate(self,alpha,beta):\n ''\n\n\n\n \n \n \n u=1.0 -self.random()\n return alpha *(-_log(u))**(1.0 /beta)\n \n \n \n \n def binomialvariate(self,n=1,p=0.5):\n ''\n\n\n\n\n\n\n\n\n \n \n if n <0:\n raise ValueError(\"n must be non-negative\")\n if p <=0.0 or p >=1.0:\n if p ==0.0:\n return 0\n if p ==1.0:\n return n\n raise ValueError(\"p must be in the range 0.0 <= p <= 1.0\")\n \n random=self.random\n \n \n if n ==1:\n return _index(random()0.5:\n return n -self.binomialvariate(n,1.0 -p)\n \n if n *p <10.0:\n \n \n x=y=0\n c=_log2(1.0 -p)\n if not c:\n return x\n while True:\n y +=_floor(_log2(random())/c)+1\n if y >n:\n return x\n x +=1\n \n \n \n assert n *p >=10.0 and p <=0.5\n setup_complete=False\n \n spq=_sqrt(n *p *(1.0 -p))\n b=1.15+2.53 *spq\n a=-0.0873+0.0248 *b+0.01 *p\n c=n *p+0.5\n vr=0.92 -4.2 /b\n \n while True:\n \n u=random()\n u -=0.5\n us=0.5 -_fabs(u)\n k=_floor((2.0 *a /us+b)*u+c)\n if k <0 or k >n:\n continue\n \n \n \n v=random()\n if us >=0.07 and v <=vr:\n return k\n \n \n \n \n if not setup_complete:\n alpha=(2.83+5.1 /b)*spq\n lpq=_log(p /(1.0 -p))\n m=_floor((n+1)*p)\n h=_lgamma(m+1)+_lgamma(n -m+1)\n setup_complete=True\n v *=alpha /(a /(us *us)+b)\n if _log(v)<=h -_lgamma(k+1)-_lgamma(n -k+1)+(k -m)*lpq:\n return k\n \n \n \n \n \n \nclass SystemRandom(Random):\n ''\n\n\n\n\n\n \n \n def random(self):\n ''\n return(int.from_bytes(_urandom(7))>>3)*RECIP_BPF\n \n def getrandbits(self,k):\n ''\n if k <0:\n raise ValueError('number of bits must be non-negative')\n numbytes=(k+7)//8\n x=int.from_bytes(_urandom(numbytes))\n return x >>(numbytes *8 -k)\n \n def randbytes(self,n):\n ''\n \n \n return _urandom(n)\n \n def seed(self,*args,**kwds):\n ''\n return None\n \n def _notimplemented(self,*args,**kwds):\n ''\n raise NotImplementedError('System entropy source does not have state.')\n getstate=setstate=_notimplemented\n \n \n \n \n \n \n \n \n \n_inst=Random()\nseed=_inst.seed\nrandom=_inst.random\nuniform=_inst.uniform\ntriangular=_inst.triangular\nrandint=_inst.randint\nchoice=_inst.choice\nrandrange=_inst.randrange\nsample=_inst.sample\nshuffle=_inst.shuffle\nchoices=_inst.choices\nnormalvariate=_inst.normalvariate\nlognormvariate=_inst.lognormvariate\nexpovariate=_inst.expovariate\nvonmisesvariate=_inst.vonmisesvariate\ngammavariate=_inst.gammavariate\ngauss=_inst.gauss\nbetavariate=_inst.betavariate\nbinomialvariate=_inst.binomialvariate\nparetovariate=_inst.paretovariate\nweibullvariate=_inst.weibullvariate\ngetstate=_inst.getstate\nsetstate=_inst.setstate\ngetrandbits=_inst.getrandbits\nrandbytes=_inst.randbytes\n\n\n\n\n\ndef _test_generator(n,func,args):\n from statistics import stdev,fmean as mean\n from time import perf_counter\n \n t0=perf_counter()\n data=[func(*args)for i in _repeat(None,n)]\n t1=perf_counter()\n \n xbar=mean(data)\n sigma=stdev(data,xbar)\n low=min(data)\n high=max(data)\n \n print(f'{t1 -t0:.3f} sec, {n} times {func.__name__}{args !r}')\n print('avg %g, stddev %g, min %g, max %g\\n'%(xbar,sigma,low,high))\n \n \ndef _test(N=10_000):\n _test_generator(N,random,())\n _test_generator(N,normalvariate,(0.0,1.0))\n _test_generator(N,lognormvariate,(0.0,1.0))\n _test_generator(N,vonmisesvariate,(0.0,1.0))\n _test_generator(N,binomialvariate,(15,0.60))\n _test_generator(N,binomialvariate,(100,0.75))\n _test_generator(N,gammavariate,(0.01,1.0))\n _test_generator(N,gammavariate,(0.1,1.0))\n _test_generator(N,gammavariate,(0.1,2.0))\n _test_generator(N,gammavariate,(0.5,1.0))\n _test_generator(N,gammavariate,(0.9,1.0))\n _test_generator(N,gammavariate,(1.0,1.0))\n _test_generator(N,gammavariate,(2.0,1.0))\n _test_generator(N,gammavariate,(20.0,1.0))\n _test_generator(N,gammavariate,(200.0,1.0))\n _test_generator(N,gauss,(0.0,1.0))\n _test_generator(N,betavariate,(3.0,3.0))\n _test_generator(N,triangular,(0.0,1.0,1.0 /3.0))\n \n \n \n \n \nif hasattr(_os,\"fork\"):\n _os.register_at_fork(after_in_child=_inst.seed)\n \n \nif __name__ =='__main__':\n _test()\n \n", ["_collections_abc", "_random", "_sha512", "bisect", "hashlib", "itertools", "math", "operator", "os", "statistics", "time", "warnings"]], "re": [".py", "import enum\n\n\nclass _compiler:\n SRE_FLAG_IGNORECASE=2\n SRE_FLAG_LOCALE=4\n SRE_FLAG_MULTILINE=8\n SRE_FLAG_DOTALL=16\n SRE_FLAG_UNICODE=32\n SRE_FLAG_VERBOSE=64\n SRE_FLAG_DEBUG=128\n SRE_FLAG_ASCII=256\n SRE_INFO_PREFIX=1\n SRE_INFO_LITERAL=2\n SRE_INFO_CHARSET=4\n \n@enum.global_enum\n@enum._simple_enum(enum.IntFlag,boundary=enum.KEEP)\nclass RegexFlag:\n NOFLAG=0\n ASCII=A=_compiler.SRE_FLAG_ASCII\n IGNORECASE=I=_compiler.SRE_FLAG_IGNORECASE\n LOCALE=L=_compiler.SRE_FLAG_LOCALE\n UNICODE=U=_compiler.SRE_FLAG_UNICODE\n MULTILINE=M=_compiler.SRE_FLAG_MULTILINE\n DOTALL=S=_compiler.SRE_FLAG_DOTALL\n VERBOSE=X=_compiler.SRE_FLAG_VERBOSE\n \n \n DEBUG=_compiler.SRE_FLAG_DEBUG\n __str__=object.__str__\n _numeric_repr_=hex\n \n \nfrom python_re import *\nfrom browser import console\n\n\nimport python_re\n_compile=python_re._compile\n_reconstructor=python_re._reconstructor\n\npython_re._reconstructor.__module__='re'\n", ["browser", "enum", "python_re"]], "re1": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nr\"\"\"Support for regular expressions (RE).\n\nThis module provides regular expression matching operations similar to\nthose found in Perl. It supports both 8-bit and Unicode strings; both\nthe pattern and the strings being processed can contain null bytes and\ncharacters outside the US ASCII range.\n\nRegular expressions can contain both special and ordinary characters.\nMost ordinary characters, like \"A\", \"a\", or \"0\", are the simplest\nregular expressions; they simply match themselves. You can\nconcatenate ordinary characters, so last matches the string 'last'.\n\nThe special characters are:\n \".\" Matches any character except a newline.\n \"^\" Matches the start of the string.\n \"$\" Matches the end of the string or just before the newline at\n the end of the string.\n \"*\" Matches 0 or more (greedy) repetitions of the preceding RE.\n Greedy means that it will match as many repetitions as possible.\n \"+\" Matches 1 or more (greedy) repetitions of the preceding RE.\n \"?\" Matches 0 or 1 (greedy) of the preceding RE.\n *?,+?,?? Non-greedy versions of the previous three special characters.\n {m,n} Matches from m to n repetitions of the preceding RE.\n {m,n}? Non-greedy version of the above.\n \"\\\\\" Either escapes special characters or signals a special sequence.\n [] Indicates a set of characters.\n A \"^\" as the first character indicates a complementing set.\n \"|\" A|B, creates an RE that will match either A or B.\n (...) Matches the RE inside the parentheses.\n The contents can be retrieved or matched later in the string.\n (?aiLmsux) The letters set the corresponding flags defined below.\n (?:...) Non-grouping version of regular parentheses.\n (?P...) The substring matched by the group is accessible by name.\n (?P=name) Matches the text matched earlier by the group named name.\n (?#...) A comment; ignored.\n (?=...) Matches if ... matches next, but doesn't consume the string.\n (?!...) Matches if ... doesn't match next.\n (?<=...) Matches if preceded by ... (must be fixed length).\n (?1:\n res=f'~({res})'\n else:\n res=f'~{res}'\n return res\n __str__=object.__str__\nglobals().update(RegexFlag.__members__)\n\n\nerror=sre_compile.error\n\n\n\n\ndef match(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).match(string)\n \ndef fullmatch(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).fullmatch(string)\n \ndef search(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).search(string)\n \ndef sub(pattern,repl,string,count=0,flags=0):\n ''\n\n\n\n\n \n return _compile(pattern,flags).sub(repl,string,count)\n \ndef subn(pattern,repl,string,count=0,flags=0):\n ''\n\n\n\n\n\n\n \n return _compile(pattern,flags).subn(repl,string,count)\n \ndef split(pattern,string,maxsplit=0,flags=0):\n ''\n\n\n\n\n\n \n return _compile(pattern,flags).split(string,maxsplit)\n \ndef findall(pattern,string,flags=0):\n ''\n\n\n\n\n\n \n return _compile(pattern,flags).findall(string)\n \ndef finditer(pattern,string,flags=0):\n ''\n\n\n \n return _compile(pattern,flags).finditer(string)\n \ndef compile(pattern,flags=0):\n ''\n return _compile(pattern,flags)\n \ndef purge():\n ''\n _cache.clear()\n _compile_repl.cache_clear()\n \ndef template(pattern,flags=0):\n ''\n return _compile(pattern,flags |T)\n \n \n \n \n \n \n_special_chars_map={i:'\\\\'+chr(i)for i in b'()[]{}?*+-|^$\\\\.&~# \\t\\n\\r\\v\\f'}\n\ndef escape(pattern):\n ''\n\n \n if isinstance(pattern,str):\n return pattern.translate(_special_chars_map)\n else:\n pattern=str(pattern,'latin1')\n return pattern.translate(_special_chars_map).encode('latin1')\n \nPattern=type(sre_compile.compile('',0))\nMatch=type(sre_compile.compile('',0).match(''))\n\n\n\n\n_cache={}\n\n_MAXCACHE=512\ndef _compile(pattern,flags):\n\n if isinstance(flags,RegexFlag):\n flags=flags.value\n try:\n return _cache[type(pattern),pattern,flags]\n except KeyError:\n pass\n if isinstance(pattern,Pattern):\n if flags:\n raise ValueError(\n \"cannot process flags argument with a compiled pattern\")\n return pattern\n if not sre_compile.isstring(pattern):\n raise TypeError(\"first argument must be string or compiled pattern\")\n p=sre_compile.compile(pattern,flags)\n if not(flags&DEBUG):\n if len(_cache)>=_MAXCACHE:\n \n try:\n del _cache[next(iter(_cache))]\n except(StopIteration,RuntimeError,KeyError):\n pass\n _cache[type(pattern),pattern,flags]=p\n return p\n \n@functools.lru_cache(_MAXCACHE)\ndef _compile_repl(repl,pattern):\n\n return sre_parse.parse_template(repl,pattern)\n \ndef _expand(pattern,match,template):\n\n template=sre_parse.parse_template(template,pattern)\n return sre_parse.expand_template(template,match)\n \ndef _subx(pattern,template):\n\n template=_compile_repl(template,pattern)\n if not template[0]and len(template[1])==1:\n \n return template[1][0]\n def filter(match,template=template):\n return sre_parse.expand_template(template,match)\n return filter\n \n \n \nimport copyreg\n\ndef _pickle(p):\n return _compile,(p.pattern,p.flags)\n \ncopyreg.pickle(Pattern,_pickle,_compile)\n\n\n\n\nclass Scanner:\n def __init__(self,lexicon,flags=0):\n from sre_constants import BRANCH,SUBPATTERN\n if isinstance(flags,RegexFlag):\n flags=flags.value\n self.lexicon=lexicon\n \n p=[]\n s=sre_parse.State()\n s.flags=flags\n for phrase,action in lexicon:\n gid=s.opengroup()\n p.append(sre_parse.SubPattern(s,[\n (SUBPATTERN,(gid,0,0,sre_parse.parse(phrase,flags))),\n ]))\n s.closegroup(gid,p[-1])\n p=sre_parse.SubPattern(s,[(BRANCH,(None,p))])\n self.scanner=sre_compile.compile(p)\n def scan(self,string):\n result=[]\n append=result.append\n match=self.scanner.scanner(string).match\n i=0\n while True:\n m=match()\n if not m:\n break\n j=m.end()\n if i ==j:\n break\n action=self.lexicon[m.lastindex -1][1]\n if callable(action):\n self.match=m\n action=action(self,m.group())\n if action is not None:\n append(action)\n i=j\n return result,string[i:]\n", ["_locale", "copyreg", "enum", "functools", "sre_compile", "sre_constants", "sre_parse"]], "reprlib": [".py", "''\n\n__all__=[\"Repr\",\"repr\",\"recursive_repr\"]\n\nimport builtins\nfrom itertools import islice\nfrom _thread import get_ident\n\ndef recursive_repr(fillvalue='...'):\n ''\n \n def decorating_function(user_function):\n repr_running=set()\n \n def wrapper(self):\n key=id(self),get_ident()\n if key in repr_running:\n return fillvalue\n repr_running.add(key)\n try:\n result=user_function(self)\n finally:\n repr_running.discard(key)\n return result\n \n \n wrapper.__module__=getattr(user_function,'__module__')\n wrapper.__doc__=getattr(user_function,'__doc__')\n wrapper.__name__=getattr(user_function,'__name__')\n wrapper.__qualname__=getattr(user_function,'__qualname__')\n wrapper.__annotations__=getattr(user_function,'__annotations__',{})\n wrapper.__type_params__=getattr(user_function,'__type_params__',())\n wrapper.__wrapped__=user_function\n return wrapper\n \n return decorating_function\n \nclass Repr:\n\n def __init__(\n self,*,maxlevel=6,maxtuple=6,maxlist=6,maxarray=5,maxdict=4,\n maxset=6,maxfrozenset=6,maxdeque=6,maxstring=30,maxlong=40,\n maxother=30,fillvalue='...',indent=None,\n ):\n self.maxlevel=maxlevel\n self.maxtuple=maxtuple\n self.maxlist=maxlist\n self.maxarray=maxarray\n self.maxdict=maxdict\n self.maxset=maxset\n self.maxfrozenset=maxfrozenset\n self.maxdeque=maxdeque\n self.maxstring=maxstring\n self.maxlong=maxlong\n self.maxother=maxother\n self.fillvalue=fillvalue\n self.indent=indent\n \n def repr(self,x):\n return self.repr1(x,self.maxlevel)\n \n def repr1(self,x,level):\n typename=type(x).__name__\n if ' 'in typename:\n parts=typename.split()\n typename='_'.join(parts)\n if hasattr(self,'repr_'+typename):\n return getattr(self,'repr_'+typename)(x,level)\n else:\n return self.repr_instance(x,level)\n \n def _join(self,pieces,level):\n if self.indent is None:\n return ', '.join(pieces)\n if not pieces:\n return ''\n indent=self.indent\n if isinstance(indent,int):\n if indent <0:\n raise ValueError(\n f'Repr.indent cannot be negative int (was {indent !r})'\n )\n indent *=' '\n try:\n sep=',\\n'+(self.maxlevel -level+1)*indent\n except TypeError as error:\n raise TypeError(\n f'Repr.indent must be a str, int or None, not {type(indent)}'\n )from error\n return sep.join(('',*pieces,''))[1:-len(indent)or None]\n \n def _repr_iterable(self,x,level,left,right,maxiter,trail=''):\n n=len(x)\n if level <=0 and n:\n s=self.fillvalue\n else:\n newlevel=level -1\n repr1=self.repr1\n pieces=[repr1(elem,newlevel)for elem in islice(x,maxiter)]\n if n >maxiter:\n pieces.append(self.fillvalue)\n s=self._join(pieces,level)\n if n ==1 and trail and self.indent is None:\n right=trail+right\n return '%s%s%s'%(left,s,right)\n \n def repr_tuple(self,x,level):\n return self._repr_iterable(x,level,'(',')',self.maxtuple,',')\n \n def repr_list(self,x,level):\n return self._repr_iterable(x,level,'[',']',self.maxlist)\n \n def repr_array(self,x,level):\n if not x:\n return \"array('%s')\"%x.typecode\n header=\"array('%s', [\"%x.typecode\n return self._repr_iterable(x,level,header,'])',self.maxarray)\n \n def repr_set(self,x,level):\n if not x:\n return 'set()'\n x=_possibly_sorted(x)\n return self._repr_iterable(x,level,'{','}',self.maxset)\n \n def repr_frozenset(self,x,level):\n if not x:\n return 'frozenset()'\n x=_possibly_sorted(x)\n return self._repr_iterable(x,level,'frozenset({','})',\n self.maxfrozenset)\n \n def repr_deque(self,x,level):\n return self._repr_iterable(x,level,'deque([','])',self.maxdeque)\n \n def repr_dict(self,x,level):\n n=len(x)\n if n ==0:\n return '{}'\n if level <=0:\n return '{'+self.fillvalue+'}'\n newlevel=level -1\n repr1=self.repr1\n pieces=[]\n for key in islice(_possibly_sorted(x),self.maxdict):\n keyrepr=repr1(key,newlevel)\n valrepr=repr1(x[key],newlevel)\n pieces.append('%s: %s'%(keyrepr,valrepr))\n if n >self.maxdict:\n pieces.append(self.fillvalue)\n s=self._join(pieces,level)\n return '{%s}'%(s,)\n \n def repr_str(self,x,level):\n s=builtins.repr(x[:self.maxstring])\n if len(s)>self.maxstring:\n i=max(0,(self.maxstring -3)//2)\n j=max(0,self.maxstring -3 -i)\n s=builtins.repr(x[:i]+x[len(x)-j:])\n s=s[:i]+self.fillvalue+s[len(s)-j:]\n return s\n \n def repr_int(self,x,level):\n s=builtins.repr(x)\n if len(s)>self.maxlong:\n i=max(0,(self.maxlong -3)//2)\n j=max(0,self.maxlong -3 -i)\n s=s[:i]+self.fillvalue+s[len(s)-j:]\n return s\n \n def repr_instance(self,x,level):\n try:\n s=builtins.repr(x)\n \n \n except Exception:\n return '<%s instance at %#x>'%(x.__class__.__name__,id(x))\n if len(s)>self.maxother:\n i=max(0,(self.maxother -3)//2)\n j=max(0,self.maxother -3 -i)\n s=s[:i]+self.fillvalue+s[len(s)-j:]\n return s\n \n \ndef _possibly_sorted(x):\n\n\n\n try:\n return sorted(x)\n except Exception:\n return list(x)\n \naRepr=Repr()\nrepr=aRepr.repr\n", ["_thread", "builtins", "itertools"]], "secrets": [".py", "''\n\n\n\n\n\n\n\n__all__=['choice','randbelow','randbits','SystemRandom',\n'token_bytes','token_hex','token_urlsafe',\n'compare_digest',\n]\n\n\nimport base64\n\nfrom hmac import compare_digest\nfrom random import SystemRandom\n\n_sysrand=SystemRandom()\n\nrandbits=_sysrand.getrandbits\nchoice=_sysrand.choice\n\ndef randbelow(exclusive_upper_bound):\n ''\n if exclusive_upper_bound <=0:\n raise ValueError(\"Upper bound must be positive.\")\n return _sysrand._randbelow(exclusive_upper_bound)\n \nDEFAULT_ENTROPY=32\n\ndef token_bytes(nbytes=None):\n ''\n\n\n\n\n\n\n\n \n if nbytes is None:\n nbytes=DEFAULT_ENTROPY\n return _sysrand.randbytes(nbytes)\n \ndef token_hex(nbytes=None):\n ''\n\n\n\n\n\n\n\n\n \n return token_bytes(nbytes).hex()\n \ndef token_urlsafe(nbytes=None):\n ''\n\n\n\n\n\n\n\n \n tok=token_bytes(nbytes)\n return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')\n", ["base64", "hmac", "random"]], "select": [".py", "''\n\n\n\n\nimport errno\nimport os\n\nclass error(Exception):\n pass\n \nALL=None\n\n_exception_map={}\n\ndef _map_exception(exc,circumstance=ALL):\n try:\n mapped_exception=_exception_map[(exc.__class__,circumstance)]\n mapped_exception.java_exception=exc\n return mapped_exception\n except KeyError:\n return error(-1,'Unmapped java exception: <%s:%s>'%(exc.toString(),circumstance))\n \nPOLLIN=1\nPOLLOUT=2\n\n\n\n\n\nPOLLPRI=4\nPOLLERR=8\nPOLLHUP=16\nPOLLNVAL=32\n\ndef _getselectable(selectable_object):\n try:\n channel=selectable_object.getchannel()\n except:\n try:\n channel=selectable_object.fileno().getChannel()\n except:\n raise TypeError(\"Object '%s' is not watchable\"%selectable_object,\n errno.ENOTSOCK)\n \n return channel\n \n \nclass Selector:\n\n def close(self):\n pass\n \n def keys(self):\n return[]\n \n def select(self,timeout=None):\n return[]\n \n def selectedKeys(self):\n class SelectedKeys:\n def iterator(self):\n return[]\n return SelectedKeys()\n \n def selectNow(self,timeout=None):\n return[]\n \nclass poll:\n\n def __init__(self):\n self.selector=Selector()\n self.chanmap={}\n self.unconnected_sockets=[]\n \n def _register_channel(self,socket_object,channel,mask):\n jmask=0\n if mask&POLLIN:\n \n if channel.validOps()&OP_ACCEPT:\n jmask=OP_ACCEPT\n else:\n jmask=OP_READ\n if mask&POLLOUT:\n if channel.validOps()&OP_WRITE:\n jmask |=OP_WRITE\n if channel.validOps()&OP_CONNECT:\n jmask |=OP_CONNECT\n selectionkey=channel.register(self.selector,jmask)\n self.chanmap[channel]=(socket_object,selectionkey)\n \n def _check_unconnected_sockets(self):\n temp_list=[]\n for socket_object,mask in self.unconnected_sockets:\n channel=_getselectable(socket_object)\n if channel is not None:\n self._register_channel(socket_object,channel,mask)\n else:\n temp_list.append((socket_object,mask))\n self.unconnected_sockets=temp_list\n \n def register(self,socket_object,mask=POLLIN |POLLOUT |POLLPRI):\n try:\n channel=_getselectable(socket_object)\n if channel is None:\n \n \n self.unconnected_sockets.append((socket_object,mask))\n return\n self._register_channel(socket_object,channel,mask)\n except BaseException as exc:\n raise _map_exception(exc)\n \n def unregister(self,socket_object):\n try:\n channel=_getselectable(socket_object)\n self.chanmap[channel][1].cancel()\n del self.chanmap[channel]\n except BaseException as exc:\n raise _map_exception(exc)\n \n def _dopoll(self,timeout):\n if timeout is None or timeout <0:\n self.selector.select()\n else:\n try:\n timeout=int(timeout)\n if not timeout:\n self.selector.selectNow()\n else:\n \n self.selector.select(timeout)\n except ValueError as vx:\n raise error(\"poll timeout must be a number of milliseconds or None\",errno.EINVAL)\n \n return self.selector.selectedKeys()\n \n def poll(self,timeout=None):\n return[]\n \n def _deregister_all(self):\n try:\n for k in self.selector.keys():\n k.cancel()\n \n self.selector.selectNow()\n except BaseException as exc:\n raise _map_exception(exc)\n \n def close(self):\n try:\n self._deregister_all()\n self.selector.close()\n except BaseException as exc:\n raise _map_exception(exc)\n \ndef _calcselecttimeoutvalue(value):\n if value is None:\n return None\n try:\n floatvalue=float(value)\n except Exception as x:\n raise TypeError(\"Select timeout value must be a number or None\")\n if value <0:\n raise error(\"Select timeout value cannot be negative\",errno.EINVAL)\n if floatvalue <0.000001:\n return 0\n return int(floatvalue *1000)\n \n \n \n \nclass poll_object_cache:\n\n def __init__(self):\n self.is_windows=os.name =='nt'\n if self.is_windows:\n self.poll_object_queue=Queue.Queue()\n import atexit\n atexit.register(self.finalize)\n \n def get_poll_object(self):\n if not self.is_windows:\n return poll()\n try:\n return self.poll_object_queue.get(False)\n except Queue.Empty:\n return poll()\n \n def release_poll_object(self,pobj):\n if self.is_windows:\n pobj._deregister_all()\n self.poll_object_queue.put(pobj)\n else:\n pobj.close()\n \n def finalize(self):\n if self.is_windows:\n while True:\n try:\n p=self.poll_object_queue.get(False)\n p.close()\n except Queue.Empty:\n return\n \n_poll_object_cache=poll_object_cache()\n\ndef native_select(read_fd_list,write_fd_list,outofband_fd_list,timeout=None):\n timeout=_calcselecttimeoutvalue(timeout)\n \n pobj=_poll_object_cache.get_poll_object()\n try:\n registered_for_read={}\n \n for fd in read_fd_list:\n pobj.register(fd,POLLIN)\n registered_for_read[fd]=1\n \n for fd in write_fd_list:\n if fd in registered_for_read:\n \n pobj.register(fd,POLLIN |POLLOUT)\n else:\n pobj.register(fd,POLLOUT)\n results=pobj.poll(timeout)\n \n read_ready_list,write_ready_list,oob_ready_list=[],[],[]\n for fd,mask in results:\n if mask&POLLIN:\n read_ready_list.append(fd)\n if mask&POLLOUT:\n write_ready_list.append(fd)\n return read_ready_list,write_ready_list,oob_ready_list\n finally:\n _poll_object_cache.release_poll_object(pobj)\n \nselect=native_select\n\ndef cpython_compatible_select(read_fd_list,write_fd_list,outofband_fd_list,timeout=None):\n\n\n modified_channels=[]\n try:\n for socket_list in[read_fd_list,write_fd_list,outofband_fd_list]:\n for s in socket_list:\n channel=_getselectable(s)\n if channel.isBlocking():\n modified_channels.append(channel)\n channel.configureBlocking(0)\n return native_select(read_fd_list,write_fd_list,outofband_fd_list,timeout)\n finally:\n for channel in modified_channels:\n channel.configureBlocking(1)\n", ["atexit", "errno", "os"]], "selectors": [".py", "''\n\n\n\n\n\n\nfrom abc import ABCMeta,abstractmethod\nfrom collections import namedtuple\nfrom collections.abc import Mapping\nimport math\nimport select\nimport sys\n\n\n\nEVENT_READ=(1 <<0)\nEVENT_WRITE=(1 <<1)\n\n\ndef _fileobj_to_fd(fileobj):\n ''\n\n\n\n\n\n\n\n\n\n \n if isinstance(fileobj,int):\n fd=fileobj\n else:\n try:\n fd=int(fileobj.fileno())\n except(AttributeError,TypeError,ValueError):\n raise ValueError(\"Invalid file object: \"\n \"{!r}\".format(fileobj))from None\n if fd <0:\n raise ValueError(\"Invalid file descriptor: {}\".format(fd))\n return fd\n \n \nSelectorKey=namedtuple('SelectorKey',['fileobj','fd','events','data'])\n\nSelectorKey.__doc__=\"\"\"SelectorKey(fileobj, fd, events, data)\n\n Object used to associate a file object to its backing\n file descriptor, selected event mask, and attached data.\n\"\"\"\nSelectorKey.fileobj.__doc__='File object registered.'\nSelectorKey.fd.__doc__='Underlying file descriptor.'\nSelectorKey.events.__doc__='Events that must be waited for on this file object.'\nSelectorKey.data.__doc__=('''Optional opaque data associated to this file object.\nFor example, this could be used to store a per-client session ID.''')\n\n\nclass _SelectorMapping(Mapping):\n ''\n \n def __init__(self,selector):\n self._selector=selector\n \n def __len__(self):\n return len(self._selector._fd_to_key)\n \n def get(self,fileobj,default=None):\n fd=self._selector._fileobj_lookup(fileobj)\n return self._selector._fd_to_key.get(fd,default)\n \n def __getitem__(self,fileobj):\n fd=self._selector._fileobj_lookup(fileobj)\n key=self._selector._fd_to_key.get(fd)\n if key is None:\n raise KeyError(\"{!r} is not registered\".format(fileobj))\n return key\n \n def __iter__(self):\n return iter(self._selector._fd_to_key)\n \n \nclass BaseSelector(metaclass=ABCMeta):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n @abstractmethod\n def register(self,fileobj,events,data=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def unregister(self,fileobj):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def modify(self,fileobj,events,data=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self.unregister(fileobj)\n return self.register(fileobj,events,data)\n \n @abstractmethod\n def select(self,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def close(self):\n ''\n\n\n \n pass\n \n def get_key(self,fileobj):\n ''\n\n\n\n \n mapping=self.get_map()\n if mapping is None:\n raise RuntimeError('Selector is closed')\n try:\n return mapping[fileobj]\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n \n @abstractmethod\n def get_map(self):\n ''\n raise NotImplementedError\n \n def __enter__(self):\n return self\n \n def __exit__(self,*args):\n self.close()\n \n \nclass _BaseSelectorImpl(BaseSelector):\n ''\n \n def __init__(self):\n \n self._fd_to_key={}\n \n self._map=_SelectorMapping(self)\n \n def _fileobj_lookup(self,fileobj):\n ''\n\n\n\n\n\n\n \n try:\n return _fileobj_to_fd(fileobj)\n except ValueError:\n \n for key in self._fd_to_key.values():\n if key.fileobj is fileobj:\n return key.fd\n \n raise\n \n def register(self,fileobj,events,data=None):\n if(not events)or(events&~(EVENT_READ |EVENT_WRITE)):\n raise ValueError(\"Invalid events: {!r}\".format(events))\n \n key=SelectorKey(fileobj,self._fileobj_lookup(fileobj),events,data)\n \n if key.fd in self._fd_to_key:\n raise KeyError(\"{!r} (FD {}) is already registered\"\n .format(fileobj,key.fd))\n \n self._fd_to_key[key.fd]=key\n return key\n \n def unregister(self,fileobj):\n try:\n key=self._fd_to_key.pop(self._fileobj_lookup(fileobj))\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n return key\n \n def modify(self,fileobj,events,data=None):\n try:\n key=self._fd_to_key[self._fileobj_lookup(fileobj)]\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n if events !=key.events:\n self.unregister(fileobj)\n key=self.register(fileobj,events,data)\n elif data !=key.data:\n \n key=key._replace(data=data)\n self._fd_to_key[key.fd]=key\n return key\n \n def close(self):\n self._fd_to_key.clear()\n self._map=None\n \n def get_map(self):\n return self._map\n \n \n \nclass SelectSelector(_BaseSelectorImpl):\n ''\n \n def __init__(self):\n super().__init__()\n self._readers=set()\n self._writers=set()\n \n def register(self,fileobj,events,data=None):\n key=super().register(fileobj,events,data)\n if events&EVENT_READ:\n self._readers.add(key.fd)\n if events&EVENT_WRITE:\n self._writers.add(key.fd)\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n self._readers.discard(key.fd)\n self._writers.discard(key.fd)\n return key\n \n if sys.platform =='win32':\n def _select(self,r,w,_,timeout=None):\n r,w,x=select.select(r,w,w,timeout)\n return r,w+x,[]\n else:\n _select=select.select\n \n def select(self,timeout=None):\n timeout=None if timeout is None else max(timeout,0)\n ready=[]\n try:\n r,w,_=self._select(self._readers,self._writers,[],timeout)\n except InterruptedError:\n return ready\n r=frozenset(r)\n w=frozenset(w)\n rw=r |w\n fd_to_key_get=self._fd_to_key.get\n for fd in rw:\n key=fd_to_key_get(fd)\n if key:\n events=((fd in r and EVENT_READ)\n |(fd in w and EVENT_WRITE))\n ready.append((key,events&key.events))\n return ready\n \n \nclass _PollLikeSelector(_BaseSelectorImpl):\n ''\n _selector_cls=None\n _EVENT_READ=None\n _EVENT_WRITE=None\n \n def __init__(self):\n super().__init__()\n self._selector=self._selector_cls()\n \n def register(self,fileobj,events,data=None):\n key=super().register(fileobj,events,data)\n poller_events=((events&EVENT_READ and self._EVENT_READ)\n |(events&EVENT_WRITE and self._EVENT_WRITE))\n try:\n self._selector.register(key.fd,poller_events)\n except:\n super().unregister(fileobj)\n raise\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n try:\n self._selector.unregister(key.fd)\n except OSError:\n \n \n pass\n return key\n \n def modify(self,fileobj,events,data=None):\n try:\n key=self._fd_to_key[self._fileobj_lookup(fileobj)]\n except KeyError:\n raise KeyError(f\"{fileobj !r} is not registered\")from None\n \n changed=False\n if events !=key.events:\n selector_events=((events&EVENT_READ and self._EVENT_READ)\n |(events&EVENT_WRITE and self._EVENT_WRITE))\n try:\n self._selector.modify(key.fd,selector_events)\n except:\n super().unregister(fileobj)\n raise\n changed=True\n if data !=key.data:\n changed=True\n \n if changed:\n key=key._replace(events=events,data=data)\n self._fd_to_key[key.fd]=key\n return key\n \n def select(self,timeout=None):\n \n \n if timeout is None:\n timeout=None\n elif timeout <=0:\n timeout=0\n else:\n \n \n timeout=math.ceil(timeout *1e3)\n ready=[]\n try:\n fd_event_list=self._selector.poll(timeout)\n except InterruptedError:\n return ready\n \n fd_to_key_get=self._fd_to_key.get\n for fd,event in fd_event_list:\n key=fd_to_key_get(fd)\n if key:\n events=((event&~self._EVENT_READ and EVENT_WRITE)\n |(event&~self._EVENT_WRITE and EVENT_READ))\n ready.append((key,events&key.events))\n return ready\n \n \nif hasattr(select,'poll'):\n\n class PollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.poll\n _EVENT_READ=select.POLLIN\n _EVENT_WRITE=select.POLLOUT\n \n \nif hasattr(select,'epoll'):\n\n _NOT_EPOLLIN=~select.EPOLLIN\n _NOT_EPOLLOUT=~select.EPOLLOUT\n \n class EpollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.epoll\n _EVENT_READ=select.EPOLLIN\n _EVENT_WRITE=select.EPOLLOUT\n \n def fileno(self):\n return self._selector.fileno()\n \n def select(self,timeout=None):\n if timeout is None:\n timeout=-1\n elif timeout <=0:\n timeout=0\n else:\n \n \n timeout=math.ceil(timeout *1e3)*1e-3\n \n \n \n \n max_ev=len(self._fd_to_key)or 1\n \n ready=[]\n try:\n fd_event_list=self._selector.poll(timeout,max_ev)\n except InterruptedError:\n return ready\n \n fd_to_key=self._fd_to_key\n for fd,event in fd_event_list:\n key=fd_to_key.get(fd)\n if key:\n events=((event&_NOT_EPOLLIN and EVENT_WRITE)\n |(event&_NOT_EPOLLOUT and EVENT_READ))\n ready.append((key,events&key.events))\n return ready\n \n def close(self):\n self._selector.close()\n super().close()\n \n \nif hasattr(select,'devpoll'):\n\n class DevpollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.devpoll\n _EVENT_READ=select.POLLIN\n _EVENT_WRITE=select.POLLOUT\n \n def fileno(self):\n return self._selector.fileno()\n \n def close(self):\n self._selector.close()\n super().close()\n \n \nif hasattr(select,'kqueue'):\n\n class KqueueSelector(_BaseSelectorImpl):\n ''\n \n def __init__(self):\n super().__init__()\n self._selector=select.kqueue()\n self._max_events=0\n \n def fileno(self):\n return self._selector.fileno()\n \n def register(self,fileobj,events,data=None):\n key=super().register(fileobj,events,data)\n try:\n if events&EVENT_READ:\n kev=select.kevent(key.fd,select.KQ_FILTER_READ,\n select.KQ_EV_ADD)\n self._selector.control([kev],0,0)\n self._max_events +=1\n if events&EVENT_WRITE:\n kev=select.kevent(key.fd,select.KQ_FILTER_WRITE,\n select.KQ_EV_ADD)\n self._selector.control([kev],0,0)\n self._max_events +=1\n except:\n super().unregister(fileobj)\n raise\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n if key.events&EVENT_READ:\n kev=select.kevent(key.fd,select.KQ_FILTER_READ,\n select.KQ_EV_DELETE)\n self._max_events -=1\n try:\n self._selector.control([kev],0,0)\n except OSError:\n \n \n pass\n if key.events&EVENT_WRITE:\n kev=select.kevent(key.fd,select.KQ_FILTER_WRITE,\n select.KQ_EV_DELETE)\n self._max_events -=1\n try:\n self._selector.control([kev],0,0)\n except OSError:\n \n pass\n return key\n \n def select(self,timeout=None):\n timeout=None if timeout is None else max(timeout,0)\n \n \n \n max_ev=self._max_events or 1\n ready=[]\n try:\n kev_list=self._selector.control(None,max_ev,timeout)\n except InterruptedError:\n return ready\n \n fd_to_key_get=self._fd_to_key.get\n for kev in kev_list:\n fd=kev.ident\n flag=kev.filter\n key=fd_to_key_get(fd)\n if key:\n events=((flag ==select.KQ_FILTER_READ and EVENT_READ)\n |(flag ==select.KQ_FILTER_WRITE and EVENT_WRITE))\n ready.append((key,events&key.events))\n return ready\n \n def close(self):\n self._selector.close()\n super().close()\n \n \ndef _can_use(method):\n ''\n \n \n selector=getattr(select,method,None)\n if selector is None:\n \n return False\n \n \n try:\n selector_obj=selector()\n if method =='poll':\n \n selector_obj.poll(0)\n else:\n \n selector_obj.close()\n return True\n except OSError:\n return False\n \n \n \n \n \nif _can_use('kqueue'):\n DefaultSelector=KqueueSelector\nelif _can_use('epoll'):\n DefaultSelector=EpollSelector\nelif _can_use('devpoll'):\n DefaultSelector=DevpollSelector\nelif _can_use('poll'):\n DefaultSelector=PollSelector\nelse:\n DefaultSelector=SelectSelector\n", ["abc", "collections", "collections.abc", "math", "select", "sys"]], "shlex": [".py", "''\n\n\n\n\n\n\n\n\nimport os\nimport re\nimport sys\nfrom collections import deque\n\nfrom io import StringIO\n\n__all__=[\"shlex\",\"split\",\"quote\",\"join\"]\n\nclass shlex:\n ''\n def __init__(self,instream=None,infile=None,posix=False,\n punctuation_chars=False):\n if isinstance(instream,str):\n instream=StringIO(instream)\n if instream is not None:\n self.instream=instream\n self.infile=infile\n else:\n self.instream=sys.stdin\n self.infile=None\n self.posix=posix\n if posix:\n self.eof=None\n else:\n self.eof=''\n self.commenters='#'\n self.wordchars=('abcdfeghijklmnopqrstuvwxyz'\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')\n if self.posix:\n self.wordchars +=('\u00df\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef\u00f0\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u00f9\u00fa\u00fb\u00fc\u00fd\u00fe\u00ff'\n '\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf\u00d0\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d8\u00d9\u00da\u00db\u00dc\u00dd\u00de')\n self.whitespace=' \\t\\r\\n'\n self.whitespace_split=False\n self.quotes='\\'\"'\n self.escape='\\\\'\n self.escapedquotes='\"'\n self.state=' '\n self.pushback=deque()\n self.lineno=1\n self.debug=0\n self.token=''\n self.filestack=deque()\n self.source=None\n if not punctuation_chars:\n punctuation_chars=''\n elif punctuation_chars is True:\n punctuation_chars='();<>|&'\n self._punctuation_chars=punctuation_chars\n if punctuation_chars:\n \n self._pushback_chars=deque()\n \n self.wordchars +='~-./*?='\n \n t=self.wordchars.maketrans(dict.fromkeys(punctuation_chars))\n self.wordchars=self.wordchars.translate(t)\n \n @property\n def punctuation_chars(self):\n return self._punctuation_chars\n \n def push_token(self,tok):\n ''\n if self.debug >=1:\n print(\"shlex: pushing token \"+repr(tok))\n self.pushback.appendleft(tok)\n \n def push_source(self,newstream,newfile=None):\n ''\n if isinstance(newstream,str):\n newstream=StringIO(newstream)\n self.filestack.appendleft((self.infile,self.instream,self.lineno))\n self.infile=newfile\n self.instream=newstream\n self.lineno=1\n if self.debug:\n if newfile is not None:\n print('shlex: pushing to file %s'%(self.infile,))\n else:\n print('shlex: pushing to stream %s'%(self.instream,))\n \n def pop_source(self):\n ''\n self.instream.close()\n (self.infile,self.instream,self.lineno)=self.filestack.popleft()\n if self.debug:\n print('shlex: popping to %s, line %d'\\\n %(self.instream,self.lineno))\n self.state=' '\n \n def get_token(self):\n ''\n if self.pushback:\n tok=self.pushback.popleft()\n if self.debug >=1:\n print(\"shlex: popping token \"+repr(tok))\n return tok\n \n raw=self.read_token()\n \n if self.source is not None:\n while raw ==self.source:\n spec=self.sourcehook(self.read_token())\n if spec:\n (newfile,newstream)=spec\n self.push_source(newstream,newfile)\n raw=self.get_token()\n \n while raw ==self.eof:\n if not self.filestack:\n return self.eof\n else:\n self.pop_source()\n raw=self.get_token()\n \n if self.debug >=1:\n if raw !=self.eof:\n print(\"shlex: token=\"+repr(raw))\n else:\n print(\"shlex: token=EOF\")\n return raw\n \n def read_token(self):\n quoted=False\n escapedstate=' '\n while True:\n if self.punctuation_chars and self._pushback_chars:\n nextchar=self._pushback_chars.pop()\n else:\n nextchar=self.instream.read(1)\n if nextchar =='\\n':\n self.lineno +=1\n if self.debug >=3:\n print(\"shlex: in state %r I see character: %r\"%(self.state,\n nextchar))\n if self.state is None:\n self.token=''\n break\n elif self.state ==' ':\n if not nextchar:\n self.state=None\n break\n elif nextchar in self.whitespace:\n if self.debug >=2:\n print(\"shlex: I see whitespace in whitespace state\")\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n elif nextchar in self.commenters:\n self.instream.readline()\n self.lineno +=1\n elif self.posix and nextchar in self.escape:\n escapedstate='a'\n self.state=nextchar\n elif nextchar in self.wordchars:\n self.token=nextchar\n self.state='a'\n elif nextchar in self.punctuation_chars:\n self.token=nextchar\n self.state='c'\n elif nextchar in self.quotes:\n if not self.posix:\n self.token=nextchar\n self.state=nextchar\n elif self.whitespace_split:\n self.token=nextchar\n self.state='a'\n else:\n self.token=nextchar\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n elif self.state in self.quotes:\n quoted=True\n if not nextchar:\n if self.debug >=2:\n print(\"shlex: I see EOF in quotes state\")\n \n raise ValueError(\"No closing quotation\")\n if nextchar ==self.state:\n if not self.posix:\n self.token +=nextchar\n self.state=' '\n break\n else:\n self.state='a'\n elif(self.posix and nextchar in self.escape and self.state\n in self.escapedquotes):\n escapedstate=self.state\n self.state=nextchar\n else:\n self.token +=nextchar\n elif self.state in self.escape:\n if not nextchar:\n if self.debug >=2:\n print(\"shlex: I see EOF in escape state\")\n \n raise ValueError(\"No escaped character\")\n \n \n if(escapedstate in self.quotes and\n nextchar !=self.state and nextchar !=escapedstate):\n self.token +=self.state\n self.token +=nextchar\n self.state=escapedstate\n elif self.state in('a','c'):\n if not nextchar:\n self.state=None\n break\n elif nextchar in self.whitespace:\n if self.debug >=2:\n print(\"shlex: I see whitespace in word state\")\n self.state=' '\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n elif nextchar in self.commenters:\n self.instream.readline()\n self.lineno +=1\n if self.posix:\n self.state=' '\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n elif self.state =='c':\n if nextchar in self.punctuation_chars:\n self.token +=nextchar\n else:\n if nextchar not in self.whitespace:\n self._pushback_chars.append(nextchar)\n self.state=' '\n break\n elif self.posix and nextchar in self.quotes:\n self.state=nextchar\n elif self.posix and nextchar in self.escape:\n escapedstate='a'\n self.state=nextchar\n elif(nextchar in self.wordchars or nextchar in self.quotes\n or(self.whitespace_split and\n nextchar not in self.punctuation_chars)):\n self.token +=nextchar\n else:\n if self.punctuation_chars:\n self._pushback_chars.append(nextchar)\n else:\n self.pushback.appendleft(nextchar)\n if self.debug >=2:\n print(\"shlex: I see punctuation in word state\")\n self.state=' '\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n result=self.token\n self.token=''\n if self.posix and not quoted and result =='':\n result=None\n if self.debug >1:\n if result:\n print(\"shlex: raw token=\"+repr(result))\n else:\n print(\"shlex: raw token=EOF\")\n return result\n \n def sourcehook(self,newfile):\n ''\n if newfile[0]=='\"':\n newfile=newfile[1:-1]\n \n if isinstance(self.infile,str)and not os.path.isabs(newfile):\n newfile=os.path.join(os.path.dirname(self.infile),newfile)\n return(newfile,open(newfile,\"r\"))\n \n def error_leader(self,infile=None,lineno=None):\n ''\n if infile is None:\n infile=self.infile\n if lineno is None:\n lineno=self.lineno\n return \"\\\"%s\\\", line %d: \"%(infile,lineno)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n token=self.get_token()\n if token ==self.eof:\n raise StopIteration\n return token\n \ndef split(s,comments=False,posix=True):\n ''\n if s is None:\n raise ValueError(\"s argument must not be None\")\n lex=shlex(s,posix=posix)\n lex.whitespace_split=True\n if not comments:\n lex.commenters=''\n return list(lex)\n \n \ndef join(split_command):\n ''\n return ' '.join(quote(arg)for arg in split_command)\n \n \n_find_unsafe=re.compile(r'[^\\w@%+=:,./-]',re.ASCII).search\n\ndef quote(s):\n ''\n if not s:\n return \"''\"\n if _find_unsafe(s)is None:\n return s\n \n \n \n return \"'\"+s.replace(\"'\",\"'\\\"'\\\"'\")+\"'\"\n \n \ndef _print_tokens(lexer):\n while tt :=lexer.get_token():\n print(\"Token: \"+repr(tt))\n \nif __name__ =='__main__':\n if len(sys.argv)==1:\n _print_tokens(shlex())\n else:\n fn=sys.argv[1]\n with open(fn)as f:\n _print_tokens(shlex(f,fn))\n", ["collections", "io", "os", "re", "sys"]], "shutil": [".py", "''\n\n\n\n\n\nimport os\nimport sys\nimport stat\nimport fnmatch\nimport collections\nimport errno\n\ntry:\n import zlib\n del zlib\n _ZLIB_SUPPORTED=True\nexcept ImportError:\n _ZLIB_SUPPORTED=False\n \ntry:\n import bz2\n del bz2\n _BZ2_SUPPORTED=True\nexcept ImportError:\n _BZ2_SUPPORTED=False\n \ntry:\n import lzma\n del lzma\n _LZMA_SUPPORTED=True\nexcept ImportError:\n _LZMA_SUPPORTED=False\n \n_WINDOWS=os.name =='nt'\nposix=nt=None\nif os.name =='posix':\n import posix\nelif _WINDOWS:\n import nt\n \nif sys.platform =='win32':\n import _winapi\nelse:\n _winapi=None\n \nCOPY_BUFSIZE=1024 *1024 if _WINDOWS else 64 *1024\n\n\n_USE_CP_SENDFILE=(hasattr(os,\"sendfile\")\nand sys.platform.startswith((\"linux\",\"android\")))\n_HAS_FCOPYFILE=posix and hasattr(posix,\"_fcopyfile\")\n\n\n_WIN_DEFAULT_PATHEXT=\".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC\"\n\n__all__=[\"copyfileobj\",\"copyfile\",\"copymode\",\"copystat\",\"copy\",\"copy2\",\n\"copytree\",\"move\",\"rmtree\",\"Error\",\"SpecialFileError\",\n\"ExecError\",\"make_archive\",\"get_archive_formats\",\n\"register_archive_format\",\"unregister_archive_format\",\n\"get_unpack_formats\",\"register_unpack_format\",\n\"unregister_unpack_format\",\"unpack_archive\",\n\"ignore_patterns\",\"chown\",\"which\",\"get_terminal_size\",\n\"SameFileError\"]\n\n\nclass Error(OSError):\n pass\n \nclass SameFileError(Error):\n ''\n \nclass SpecialFileError(OSError):\n ''\n \n \nclass ExecError(OSError):\n ''\n \nclass ReadError(OSError):\n ''\n \nclass RegistryError(Exception):\n ''\n \n \nclass _GiveupOnFastCopy(Exception):\n ''\n\n \n \ndef _fastcopy_fcopyfile(fsrc,fdst,flags):\n ''\n\n \n try:\n infd=fsrc.fileno()\n outfd=fdst.fileno()\n except Exception as err:\n raise _GiveupOnFastCopy(err)\n \n try:\n posix._fcopyfile(infd,outfd,flags)\n except OSError as err:\n err.filename=fsrc.name\n err.filename2=fdst.name\n if err.errno in{errno.EINVAL,errno.ENOTSUP}:\n raise _GiveupOnFastCopy(err)\n else:\n raise err from None\n \ndef _fastcopy_sendfile(fsrc,fdst):\n ''\n\n\n \n \n \n \n \n \n \n \n \n \n global _USE_CP_SENDFILE\n try:\n infd=fsrc.fileno()\n outfd=fdst.fileno()\n except Exception as err:\n raise _GiveupOnFastCopy(err)\n \n \n \n \n \n \n try:\n blocksize=max(os.fstat(infd).st_size,2 **23)\n except OSError:\n blocksize=2 **27\n \n \n if sys.maxsize <2 **32:\n blocksize=min(blocksize,2 **30)\n \n offset=0\n while True:\n try:\n sent=os.sendfile(outfd,infd,offset,blocksize)\n except OSError as err:\n \n err.filename=fsrc.name\n err.filename2=fdst.name\n \n if err.errno ==errno.ENOTSOCK:\n \n \n \n _USE_CP_SENDFILE=False\n raise _GiveupOnFastCopy(err)\n \n if err.errno ==errno.ENOSPC:\n raise err from None\n \n \n if offset ==0 and os.lseek(outfd,0,os.SEEK_CUR)==0:\n raise _GiveupOnFastCopy(err)\n \n raise err\n else:\n if sent ==0:\n break\n offset +=sent\n \ndef _copyfileobj_readinto(fsrc,fdst,length=COPY_BUFSIZE):\n ''\n\n\n \n \n fsrc_readinto=fsrc.readinto\n fdst_write=fdst.write\n with memoryview(bytearray(length))as mv:\n while True:\n n=fsrc_readinto(mv)\n if not n:\n break\n elif n 0:\n _copyfileobj_readinto(fsrc,fdst,min(file_size,COPY_BUFSIZE))\n return dst\n \n copyfileobj(fsrc,fdst)\n \n \n except IsADirectoryError as e:\n if not os.path.exists(dst):\n raise FileNotFoundError(f'Directory does not exist: {dst}')from e\n else:\n raise\n \n return dst\n \ndef copymode(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n \n sys.audit(\"shutil.copymode\",src,dst)\n \n if not follow_symlinks and _islink(src)and os.path.islink(dst):\n if hasattr(os,'lchmod'):\n stat_func,chmod_func=os.lstat,os.lchmod\n else:\n return\n else:\n stat_func=_stat\n if os.name =='nt'and os.path.islink(dst):\n def chmod_func(*args):\n os.chmod(*args,follow_symlinks=True)\n else:\n chmod_func=os.chmod\n \n st=stat_func(src)\n chmod_func(dst,stat.S_IMODE(st.st_mode))\n \nif hasattr(os,'listxattr'):\n def _copyxattr(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n \n \n try:\n names=os.listxattr(src,follow_symlinks=follow_symlinks)\n except OSError as e:\n if e.errno not in(errno.ENOTSUP,errno.ENODATA,errno.EINVAL):\n raise\n return\n for name in names:\n try:\n value=os.getxattr(src,name,follow_symlinks=follow_symlinks)\n os.setxattr(dst,name,value,follow_symlinks=follow_symlinks)\n except OSError as e:\n if e.errno not in(errno.EPERM,errno.ENOTSUP,errno.ENODATA,\n errno.EINVAL,errno.EACCES):\n raise\nelse:\n def _copyxattr(*args,**kwargs):\n pass\n \ndef copystat(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.copystat\",src,dst)\n \n def _nop(*args,ns=None,follow_symlinks=None):\n pass\n \n \n follow=follow_symlinks or not(_islink(src)and os.path.islink(dst))\n if follow:\n \n def lookup(name):\n return getattr(os,name,_nop)\n else:\n \n \n def lookup(name):\n fn=getattr(os,name,_nop)\n if fn in os.supports_follow_symlinks:\n return fn\n return _nop\n \n if isinstance(src,os.DirEntry):\n st=src.stat(follow_symlinks=follow)\n else:\n st=lookup(\"stat\")(src,follow_symlinks=follow)\n mode=stat.S_IMODE(st.st_mode)\n lookup(\"utime\")(dst,ns=(st.st_atime_ns,st.st_mtime_ns),\n follow_symlinks=follow)\n \n \n _copyxattr(src,dst,follow_symlinks=follow)\n try:\n lookup(\"chmod\")(dst,mode,follow_symlinks=follow)\n except NotImplementedError:\n \n \n \n \n \n \n \n \n \n \n pass\n if hasattr(st,'st_flags'):\n try:\n lookup(\"chflags\")(dst,st.st_flags,follow_symlinks=follow)\n except OSError as why:\n for err in 'EOPNOTSUPP','ENOTSUP':\n if hasattr(errno,err)and why.errno ==getattr(errno,err):\n break\n else:\n raise\n \ndef copy(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n\n\n\n\n \n if os.path.isdir(dst):\n dst=os.path.join(dst,os.path.basename(src))\n copyfile(src,dst,follow_symlinks=follow_symlinks)\n copymode(src,dst,follow_symlinks=follow_symlinks)\n return dst\n \ndef copy2(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n\n\n\n \n if os.path.isdir(dst):\n dst=os.path.join(dst,os.path.basename(src))\n \n if hasattr(_winapi,\"CopyFile2\"):\n src_=os.fsdecode(src)\n dst_=os.fsdecode(dst)\n flags=_winapi.COPY_FILE_ALLOW_DECRYPTED_DESTINATION\n if not follow_symlinks:\n flags |=_winapi.COPY_FILE_COPY_SYMLINK\n try:\n _winapi.CopyFile2(src_,dst_,flags)\n return dst\n except OSError as exc:\n if(exc.winerror ==_winapi.ERROR_PRIVILEGE_NOT_HELD\n and not follow_symlinks):\n \n \n pass\n elif exc.winerror ==_winapi.ERROR_ACCESS_DENIED:\n \n \n pass\n else:\n raise\n \n copyfile(src,dst,follow_symlinks=follow_symlinks)\n copystat(src,dst,follow_symlinks=follow_symlinks)\n return dst\n \ndef ignore_patterns(*patterns):\n ''\n\n\n \n def _ignore_patterns(path,names):\n ignored_names=[]\n for pattern in patterns:\n ignored_names.extend(fnmatch.filter(names,pattern))\n return set(ignored_names)\n return _ignore_patterns\n \ndef _copytree(entries,src,dst,symlinks,ignore,copy_function,\nignore_dangling_symlinks,dirs_exist_ok=False):\n if ignore is not None:\n ignored_names=ignore(os.fspath(src),[x.name for x in entries])\n else:\n ignored_names=()\n \n os.makedirs(dst,exist_ok=dirs_exist_ok)\n errors=[]\n use_srcentry=copy_function is copy2 or copy_function is copy\n \n for srcentry in entries:\n if srcentry.name in ignored_names:\n continue\n srcname=os.path.join(src,srcentry.name)\n dstname=os.path.join(dst,srcentry.name)\n srcobj=srcentry if use_srcentry else srcname\n try:\n is_symlink=srcentry.is_symlink()\n if is_symlink and os.name =='nt':\n \n \n lstat=srcentry.stat(follow_symlinks=False)\n if lstat.st_reparse_tag ==stat.IO_REPARSE_TAG_MOUNT_POINT:\n is_symlink=False\n if is_symlink:\n linkto=os.readlink(srcname)\n if symlinks:\n \n \n \n os.symlink(linkto,dstname)\n copystat(srcobj,dstname,follow_symlinks=not symlinks)\n else:\n \n if not os.path.exists(linkto)and ignore_dangling_symlinks:\n continue\n \n if srcentry.is_dir():\n copytree(srcobj,dstname,symlinks,ignore,\n copy_function,ignore_dangling_symlinks,\n dirs_exist_ok)\n else:\n copy_function(srcobj,dstname)\n elif srcentry.is_dir():\n copytree(srcobj,dstname,symlinks,ignore,copy_function,\n ignore_dangling_symlinks,dirs_exist_ok)\n else:\n \n copy_function(srcobj,dstname)\n \n \n except Error as err:\n errors.extend(err.args[0])\n except OSError as why:\n errors.append((srcname,dstname,str(why)))\n try:\n copystat(src,dst)\n except OSError as why:\n \n if getattr(why,'winerror',None)is None:\n errors.append((src,dst,str(why)))\n if errors:\n raise Error(errors)\n return dst\n \ndef copytree(src,dst,symlinks=False,ignore=None,copy_function=copy2,\nignore_dangling_symlinks=False,dirs_exist_ok=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.copytree\",src,dst)\n with os.scandir(src)as itr:\n entries=list(itr)\n return _copytree(entries=entries,src=src,dst=dst,symlinks=symlinks,\n ignore=ignore,copy_function=copy_function,\n ignore_dangling_symlinks=ignore_dangling_symlinks,\n dirs_exist_ok=dirs_exist_ok)\n \nif hasattr(os.stat_result,'st_file_attributes'):\n def _rmtree_islink(st):\n return(stat.S_ISLNK(st.st_mode)or\n (st.st_file_attributes&stat.FILE_ATTRIBUTE_REPARSE_POINT\n and st.st_reparse_tag ==stat.IO_REPARSE_TAG_MOUNT_POINT))\nelse:\n def _rmtree_islink(st):\n return stat.S_ISLNK(st.st_mode)\n \n \ndef _rmtree_unsafe(path,onexc):\n try:\n with os.scandir(path)as scandir_it:\n entries=list(scandir_it)\n except FileNotFoundError:\n return\n except OSError as err:\n onexc(os.scandir,path,err)\n entries=[]\n for entry in entries:\n fullname=entry.path\n try:\n is_dir=entry.is_dir(follow_symlinks=False)\n except FileNotFoundError:\n continue\n except OSError:\n is_dir=False\n \n if is_dir and not entry.is_junction():\n try:\n if entry.is_symlink():\n \n \n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.path.islink,fullname,err)\n continue\n _rmtree_unsafe(fullname,onexc)\n else:\n try:\n os.unlink(fullname)\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.unlink,fullname,err)\n try:\n os.rmdir(path)\n except FileNotFoundError:\n pass\n except OSError as err:\n onexc(os.rmdir,path,err)\n \n \ndef _rmtree_safe_fd(topfd,path,onexc):\n try:\n with os.scandir(topfd)as scandir_it:\n entries=list(scandir_it)\n except FileNotFoundError:\n return\n except OSError as err:\n err.filename=path\n onexc(os.scandir,path,err)\n return\n for entry in entries:\n fullname=os.path.join(path,entry.name)\n try:\n is_dir=entry.is_dir(follow_symlinks=False)\n except FileNotFoundError:\n continue\n except OSError:\n is_dir=False\n else:\n if is_dir:\n try:\n orig_st=entry.stat(follow_symlinks=False)\n is_dir=stat.S_ISDIR(orig_st.st_mode)\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.lstat,fullname,err)\n continue\n if is_dir:\n try:\n dirfd=os.open(entry.name,os.O_RDONLY |os.O_NONBLOCK,dir_fd=topfd)\n dirfd_closed=False\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.open,fullname,err)\n else:\n try:\n if os.path.samestat(orig_st,os.fstat(dirfd)):\n _rmtree_safe_fd(dirfd,fullname,onexc)\n try:\n os.close(dirfd)\n except OSError as err:\n \n dirfd_closed=True\n onexc(os.close,fullname,err)\n dirfd_closed=True\n try:\n os.rmdir(entry.name,dir_fd=topfd)\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.rmdir,fullname,err)\n else:\n try:\n \n \n \n raise OSError(\"Cannot call rmtree on a symbolic \"\n \"link\")\n except OSError as err:\n onexc(os.path.islink,fullname,err)\n finally:\n if not dirfd_closed:\n try:\n os.close(dirfd)\n except OSError as err:\n onexc(os.close,fullname,err)\n else:\n try:\n os.unlink(entry.name,dir_fd=topfd)\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.unlink,fullname,err)\n \n_use_fd_functions=({os.open,os.stat,os.unlink,os.rmdir}<=\nos.supports_dir_fd and\nos.scandir in os.supports_fd and\nos.stat in os.supports_follow_symlinks)\n\ndef rmtree(path,ignore_errors=False,onerror=None,*,onexc=None,dir_fd=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n sys.audit(\"shutil.rmtree\",path,dir_fd)\n if ignore_errors:\n def onexc(*args):\n pass\n elif onerror is None and onexc is None:\n def onexc(*args):\n raise\n elif onexc is None:\n if onerror is None:\n def onexc(*args):\n raise\n else:\n \n def onexc(*args):\n func,path,exc=args\n if exc is None:\n exc_info=None,None,None\n else:\n exc_info=type(exc),exc,exc.__traceback__\n return onerror(func,path,exc_info)\n \n if _use_fd_functions:\n \n if isinstance(path,bytes):\n path=os.fsdecode(path)\n \n \n try:\n orig_st=os.lstat(path,dir_fd=dir_fd)\n except OSError as err:\n onexc(os.lstat,path,err)\n return\n try:\n fd=os.open(path,os.O_RDONLY |os.O_NONBLOCK,dir_fd=dir_fd)\n fd_closed=False\n except OSError as err:\n onexc(os.open,path,err)\n return\n try:\n if os.path.samestat(orig_st,os.fstat(fd)):\n _rmtree_safe_fd(fd,path,onexc)\n try:\n os.close(fd)\n except OSError as err:\n \n fd_closed=True\n onexc(os.close,path,err)\n fd_closed=True\n try:\n os.rmdir(path,dir_fd=dir_fd)\n except OSError as err:\n onexc(os.rmdir,path,err)\n else:\n try:\n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except OSError as err:\n onexc(os.path.islink,path,err)\n finally:\n if not fd_closed:\n try:\n os.close(fd)\n except OSError as err:\n onexc(os.close,path,err)\n else:\n if dir_fd is not None:\n raise NotImplementedError(\"dir_fd unavailable on this platform\")\n try:\n st=os.lstat(path)\n except OSError as err:\n onexc(os.lstat,path,err)\n return\n try:\n if _rmtree_islink(st):\n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except OSError as err:\n onexc(os.path.islink,path,err)\n \n return\n return _rmtree_unsafe(path,onexc)\n \n \n \nrmtree.avoids_symlink_attacks=_use_fd_functions\n\ndef _basename(path):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n path=os.fspath(path)\n sep=os.path.sep+(os.path.altsep or '')\n return os.path.basename(path.rstrip(sep))\n \ndef move(src,dst,copy_function=copy2):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.move\",src,dst)\n real_dst=dst\n if os.path.isdir(dst):\n if _samefile(src,dst)and not os.path.islink(src):\n \n \n os.rename(src,dst)\n return\n \n \n \n real_dst=os.path.join(dst,_basename(src))\n \n if os.path.exists(real_dst):\n raise Error(\"Destination path '%s' already exists\"%real_dst)\n try:\n os.rename(src,real_dst)\n except OSError:\n if os.path.islink(src):\n linkto=os.readlink(src)\n os.symlink(linkto,real_dst)\n os.unlink(src)\n elif os.path.isdir(src):\n if _destinsrc(src,dst):\n raise Error(\"Cannot move a directory '%s' into itself\"\n \" '%s'.\"%(src,dst))\n if(_is_immutable(src)\n or(not os.access(src,os.W_OK)and os.listdir(src)\n and sys.platform =='darwin')):\n raise PermissionError(\"Cannot move the non-empty directory \"\n \"'%s': Lacking write permission to '%s'.\"\n %(src,src))\n copytree(src,real_dst,copy_function=copy_function,\n symlinks=True)\n rmtree(src)\n else:\n copy_function(src,real_dst)\n os.unlink(src)\n return real_dst\n \ndef _destinsrc(src,dst):\n src=os.path.abspath(src)\n dst=os.path.abspath(dst)\n if not src.endswith(os.path.sep):\n src +=os.path.sep\n if not dst.endswith(os.path.sep):\n dst +=os.path.sep\n return dst.startswith(src)\n \ndef _is_immutable(src):\n st=_stat(src)\n immutable_states=[stat.UF_IMMUTABLE,stat.SF_IMMUTABLE]\n return hasattr(st,'st_flags')and st.st_flags in immutable_states\n \ndef _get_gid(name):\n ''\n if name is None:\n return None\n \n try:\n from grp import getgrnam\n except ImportError:\n return None\n \n try:\n result=getgrnam(name)\n except KeyError:\n result=None\n if result is not None:\n return result[2]\n return None\n \ndef _get_uid(name):\n ''\n if name is None:\n return None\n \n try:\n from pwd import getpwnam\n except ImportError:\n return None\n \n try:\n result=getpwnam(name)\n except KeyError:\n result=None\n if result is not None:\n return result[2]\n return None\n \ndef _make_tarball(base_name,base_dir,compress=\"gzip\",verbose=0,dry_run=0,\nowner=None,group=None,logger=None,root_dir=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if compress is None:\n tar_compression=''\n elif _ZLIB_SUPPORTED and compress =='gzip':\n tar_compression='gz'\n elif _BZ2_SUPPORTED and compress =='bzip2':\n tar_compression='bz2'\n elif _LZMA_SUPPORTED and compress =='xz':\n tar_compression='xz'\n else:\n raise ValueError(\"bad value for 'compress', or compression format not \"\n \"supported : {0}\".format(compress))\n \n import tarfile\n \n compress_ext='.'+tar_compression if compress else ''\n archive_name=base_name+'.tar'+compress_ext\n archive_dir=os.path.dirname(archive_name)\n \n if archive_dir and not os.path.exists(archive_dir):\n if logger is not None:\n logger.info(\"creating %s\",archive_dir)\n if not dry_run:\n os.makedirs(archive_dir)\n \n \n if logger is not None:\n logger.info('Creating tar archive')\n \n uid=_get_uid(owner)\n gid=_get_gid(group)\n \n def _set_uid_gid(tarinfo):\n if gid is not None:\n tarinfo.gid=gid\n tarinfo.gname=group\n if uid is not None:\n tarinfo.uid=uid\n tarinfo.uname=owner\n return tarinfo\n \n if not dry_run:\n tar=tarfile.open(archive_name,'w|%s'%tar_compression)\n arcname=base_dir\n if root_dir is not None:\n base_dir=os.path.join(root_dir,base_dir)\n try:\n tar.add(base_dir,arcname,filter=_set_uid_gid)\n finally:\n tar.close()\n \n if root_dir is not None:\n archive_name=os.path.abspath(archive_name)\n return archive_name\n \ndef _make_zipfile(base_name,base_dir,verbose=0,dry_run=0,\nlogger=None,owner=None,group=None,root_dir=None):\n ''\n\n\n\n \n import zipfile\n \n zip_filename=base_name+\".zip\"\n archive_dir=os.path.dirname(base_name)\n \n if archive_dir and not os.path.exists(archive_dir):\n if logger is not None:\n logger.info(\"creating %s\",archive_dir)\n if not dry_run:\n os.makedirs(archive_dir)\n \n if logger is not None:\n logger.info(\"creating '%s' and adding '%s' to it\",\n zip_filename,base_dir)\n \n if not dry_run:\n with zipfile.ZipFile(zip_filename,\"w\",\n compression=zipfile.ZIP_DEFLATED)as zf:\n arcname=os.path.normpath(base_dir)\n if root_dir is not None:\n base_dir=os.path.join(root_dir,base_dir)\n base_dir=os.path.normpath(base_dir)\n if arcname !=os.curdir:\n zf.write(base_dir,arcname)\n if logger is not None:\n logger.info(\"adding '%s'\",base_dir)\n for dirpath,dirnames,filenames in os.walk(base_dir):\n arcdirpath=dirpath\n if root_dir is not None:\n arcdirpath=os.path.relpath(arcdirpath,root_dir)\n arcdirpath=os.path.normpath(arcdirpath)\n for name in sorted(dirnames):\n path=os.path.join(dirpath,name)\n arcname=os.path.join(arcdirpath,name)\n zf.write(path,arcname)\n if logger is not None:\n logger.info(\"adding '%s'\",path)\n for name in filenames:\n path=os.path.join(dirpath,name)\n path=os.path.normpath(path)\n if os.path.isfile(path):\n arcname=os.path.join(arcdirpath,name)\n zf.write(path,arcname)\n if logger is not None:\n logger.info(\"adding '%s'\",path)\n \n if root_dir is not None:\n zip_filename=os.path.abspath(zip_filename)\n return zip_filename\n \n_make_tarball.supports_root_dir=True\n_make_zipfile.supports_root_dir=True\n\n\n\n\n\n_ARCHIVE_FORMATS={\n'tar':(_make_tarball,[('compress',None)],\n\"uncompressed tar file\"),\n}\n\nif _ZLIB_SUPPORTED:\n _ARCHIVE_FORMATS['gztar']=(_make_tarball,[('compress','gzip')],\n \"gzip'ed tar-file\")\n _ARCHIVE_FORMATS['zip']=(_make_zipfile,[],\"ZIP file\")\n \nif _BZ2_SUPPORTED:\n _ARCHIVE_FORMATS['bztar']=(_make_tarball,[('compress','bzip2')],\n \"bzip2'ed tar-file\")\n \nif _LZMA_SUPPORTED:\n _ARCHIVE_FORMATS['xztar']=(_make_tarball,[('compress','xz')],\n \"xz'ed tar-file\")\n \ndef get_archive_formats():\n ''\n\n\n \n formats=[(name,registry[2])for name,registry in\n _ARCHIVE_FORMATS.items()]\n formats.sort()\n return formats\n \ndef register_archive_format(name,function,extra_args=None,description=''):\n ''\n\n\n\n\n\n\n \n if extra_args is None:\n extra_args=[]\n if not callable(function):\n raise TypeError('The %s object is not callable'%function)\n if not isinstance(extra_args,(tuple,list)):\n raise TypeError('extra_args needs to be a sequence')\n for element in extra_args:\n if not isinstance(element,(tuple,list))or len(element)!=2:\n raise TypeError('extra_args elements are : (arg_name, value)')\n \n _ARCHIVE_FORMATS[name]=(function,extra_args,description)\n \ndef unregister_archive_format(name):\n del _ARCHIVE_FORMATS[name]\n \ndef make_archive(base_name,format,root_dir=None,base_dir=None,verbose=0,\ndry_run=0,owner=None,group=None,logger=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.make_archive\",base_name,format,root_dir,base_dir)\n try:\n format_info=_ARCHIVE_FORMATS[format]\n except KeyError:\n raise ValueError(\"unknown archive format '%s'\"%format)from None\n \n kwargs={'dry_run':dry_run,'logger':logger,\n 'owner':owner,'group':group}\n \n func=format_info[0]\n for arg,val in format_info[1]:\n kwargs[arg]=val\n \n if base_dir is None:\n base_dir=os.curdir\n \n supports_root_dir=getattr(func,'supports_root_dir',False)\n save_cwd=None\n if root_dir is not None:\n stmd=os.stat(root_dir).st_mode\n if not stat.S_ISDIR(stmd):\n raise NotADirectoryError(errno.ENOTDIR,'Not a directory',root_dir)\n \n if supports_root_dir:\n \n base_name=os.fspath(base_name)\n kwargs['root_dir']=root_dir\n else:\n save_cwd=os.getcwd()\n if logger is not None:\n logger.debug(\"changing into '%s'\",root_dir)\n base_name=os.path.abspath(base_name)\n if not dry_run:\n os.chdir(root_dir)\n \n try:\n filename=func(base_name,base_dir,**kwargs)\n finally:\n if save_cwd is not None:\n if logger is not None:\n logger.debug(\"changing back to '%s'\",save_cwd)\n os.chdir(save_cwd)\n \n return filename\n \n \ndef get_unpack_formats():\n ''\n\n\n\n \n formats=[(name,info[0],info[3])for name,info in\n _UNPACK_FORMATS.items()]\n formats.sort()\n return formats\n \ndef _check_unpack_options(extensions,function,extra_args):\n ''\n \n existing_extensions={}\n for name,info in _UNPACK_FORMATS.items():\n for ext in info[0]:\n existing_extensions[ext]=name\n \n for extension in extensions:\n if extension in existing_extensions:\n msg='%s is already registered for \"%s\"'\n raise RegistryError(msg %(extension,\n existing_extensions[extension]))\n \n if not callable(function):\n raise TypeError('The registered function must be a callable')\n \n \ndef register_unpack_format(name,extensions,function,extra_args=None,\ndescription=''):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if extra_args is None:\n extra_args=[]\n _check_unpack_options(extensions,function,extra_args)\n _UNPACK_FORMATS[name]=extensions,function,extra_args,description\n \ndef unregister_unpack_format(name):\n ''\n del _UNPACK_FORMATS[name]\n \ndef _ensure_directory(path):\n ''\n dirname=os.path.dirname(path)\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n \ndef _unpack_zipfile(filename,extract_dir):\n ''\n \n import zipfile\n \n if not zipfile.is_zipfile(filename):\n raise ReadError(\"%s is not a zip file\"%filename)\n \n zip=zipfile.ZipFile(filename)\n try:\n for info in zip.infolist():\n name=info.filename\n \n \n if name.startswith('/')or '..'in name:\n continue\n \n targetpath=os.path.join(extract_dir,*name.split('/'))\n if not targetpath:\n continue\n \n _ensure_directory(targetpath)\n if not name.endswith('/'):\n \n with zip.open(name,'r')as source,\\\n open(targetpath,'wb')as target:\n copyfileobj(source,target)\n finally:\n zip.close()\n \ndef _unpack_tarfile(filename,extract_dir,*,filter=None):\n ''\n \n import tarfile\n try:\n tarobj=tarfile.open(filename)\n except tarfile.TarError:\n raise ReadError(\n \"%s is not a compressed or uncompressed tar file\"%filename)\n try:\n tarobj.extractall(extract_dir,filter=filter)\n finally:\n tarobj.close()\n \n \n \n \n \n \n_UNPACK_FORMATS={\n'tar':(['.tar'],_unpack_tarfile,[],\"uncompressed tar file\"),\n'zip':(['.zip'],_unpack_zipfile,[],\"ZIP file\"),\n}\n\nif _ZLIB_SUPPORTED:\n _UNPACK_FORMATS['gztar']=(['.tar.gz','.tgz'],_unpack_tarfile,[],\n \"gzip'ed tar-file\")\n \nif _BZ2_SUPPORTED:\n _UNPACK_FORMATS['bztar']=(['.tar.bz2','.tbz2'],_unpack_tarfile,[],\n \"bzip2'ed tar-file\")\n \nif _LZMA_SUPPORTED:\n _UNPACK_FORMATS['xztar']=(['.tar.xz','.txz'],_unpack_tarfile,[],\n \"xz'ed tar-file\")\n \ndef _find_unpack_format(filename):\n for name,info in _UNPACK_FORMATS.items():\n for extension in info[0]:\n if filename.endswith(extension):\n return name\n return None\n \ndef unpack_archive(filename,extract_dir=None,format=None,*,filter=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.unpack_archive\",filename,extract_dir,format)\n \n if extract_dir is None:\n extract_dir=os.getcwd()\n \n extract_dir=os.fspath(extract_dir)\n filename=os.fspath(filename)\n \n if filter is None:\n filter_kwargs={}\n else:\n filter_kwargs={'filter':filter}\n if format is not None:\n try:\n format_info=_UNPACK_FORMATS[format]\n except KeyError:\n raise ValueError(\"Unknown unpack format '{0}'\".format(format))from None\n \n func=format_info[1]\n func(filename,extract_dir,**dict(format_info[2]),**filter_kwargs)\n else:\n \n format=_find_unpack_format(filename)\n if format is None:\n raise ReadError(\"Unknown archive format '{0}'\".format(filename))\n \n func=_UNPACK_FORMATS[format][1]\n kwargs=dict(_UNPACK_FORMATS[format][2])|filter_kwargs\n func(filename,extract_dir,**kwargs)\n \n \nif hasattr(os,'statvfs'):\n\n __all__.append('disk_usage')\n _ntuple_diskusage=collections.namedtuple('usage','total used free')\n _ntuple_diskusage.total.__doc__='Total space in bytes'\n _ntuple_diskusage.used.__doc__='Used space in bytes'\n _ntuple_diskusage.free.__doc__='Free space in bytes'\n \n def disk_usage(path):\n ''\n\n\n\n \n st=os.statvfs(path)\n free=st.f_bavail *st.f_frsize\n total=st.f_blocks *st.f_frsize\n used=(st.f_blocks -st.f_bfree)*st.f_frsize\n return _ntuple_diskusage(total,used,free)\n \nelif _WINDOWS:\n\n __all__.append('disk_usage')\n _ntuple_diskusage=collections.namedtuple('usage','total used free')\n \n def disk_usage(path):\n ''\n\n\n\n \n total,free=nt._getdiskusage(path)\n used=total -free\n return _ntuple_diskusage(total,used,free)\n \n \ndef chown(path,user=None,group=None,*,dir_fd=None,follow_symlinks=True):\n ''\n\n\n\n\n\n\n\n\n\n\n \n sys.audit('shutil.chown',path,user,group)\n \n if user is None and group is None:\n raise ValueError(\"user and/or group must be set\")\n \n _user=user\n _group=group\n \n \n if user is None:\n _user=-1\n \n elif isinstance(user,str):\n _user=_get_uid(user)\n if _user is None:\n raise LookupError(\"no such user: {!r}\".format(user))\n \n if group is None:\n _group=-1\n elif not isinstance(group,int):\n _group=_get_gid(group)\n if _group is None:\n raise LookupError(\"no such group: {!r}\".format(group))\n \n os.chown(path,_user,_group,dir_fd=dir_fd,\n follow_symlinks=follow_symlinks)\n \ndef get_terminal_size(fallback=(80,24)):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n try:\n columns=int(os.environ['COLUMNS'])\n except(KeyError,ValueError):\n columns=0\n \n try:\n lines=int(os.environ['LINES'])\n except(KeyError,ValueError):\n lines=0\n \n \n if columns <=0 or lines <=0:\n try:\n size=os.get_terminal_size(sys.__stdout__.fileno())\n except(AttributeError,ValueError,OSError):\n \n \n size=os.terminal_size(fallback)\n if columns <=0:\n columns=size.columns or fallback[0]\n if lines <=0:\n lines=size.lines or fallback[1]\n \n return os.terminal_size((columns,lines))\n \n \n \n \n \ndef _access_check(fn,mode):\n return(os.path.exists(fn)and os.access(fn,mode)\n and not os.path.isdir(fn))\n \n \ndef _win_path_needs_curdir(cmd,mode):\n ''\n\n\n\n \n return(not(mode&os.X_OK))or _winapi.NeedCurrentDirectoryForExePath(\n os.fsdecode(cmd))\n \n \ndef which(cmd,mode=os.F_OK |os.X_OK,path=None):\n ''\n\n\n\n\n\n\n\n \n use_bytes=isinstance(cmd,bytes)\n \n \n \n \n dirname,cmd=os.path.split(cmd)\n if dirname:\n path=[dirname]\n else:\n if path is None:\n path=os.environ.get(\"PATH\",None)\n if path is None:\n try:\n path=os.confstr(\"CS_PATH\")\n except(AttributeError,ValueError):\n \n path=os.defpath\n \n \n \n \n \n if not path:\n return None\n \n if use_bytes:\n path=os.fsencode(path)\n path=path.split(os.fsencode(os.pathsep))\n else:\n path=os.fsdecode(path)\n path=path.split(os.pathsep)\n \n if sys.platform ==\"win32\"and _win_path_needs_curdir(cmd,mode):\n curdir=os.curdir\n if use_bytes:\n curdir=os.fsencode(curdir)\n path.insert(0,curdir)\n \n if sys.platform ==\"win32\":\n \n pathext_source=os.getenv(\"PATHEXT\")or _WIN_DEFAULT_PATHEXT\n pathext=[ext for ext in pathext_source.split(os.pathsep)if ext]\n \n if use_bytes:\n pathext=[os.fsencode(ext)for ext in pathext]\n \n files=([cmd]+[cmd+ext for ext in pathext])\n \n \n \n \n \n \n suffix=os.path.splitext(files[0])[1].upper()\n if mode&os.X_OK and not any(suffix ==ext.upper()for ext in pathext):\n files.append(files.pop(0))\n else:\n \n \n files=[cmd]\n \n seen=set()\n for dir in path:\n normdir=os.path.normcase(dir)\n if not normdir in seen:\n seen.add(normdir)\n for thefile in files:\n name=os.path.join(dir,thefile)\n if _access_check(name,mode):\n return name\n return None\n", ["_winapi", "bz2", "collections", "errno", "fnmatch", "grp", "lzma", "nt", "os", "posix", "pwd", "stat", "sys", "tarfile", "zipfile", "zlib"]], "signal": [".py", "import _signal\nfrom _signal import *\nfrom enum import IntEnum as _IntEnum\n\n_globals=globals()\n\n_IntEnum._convert_(\n'Signals',__name__,\nlambda name:\nname.isupper()\nand(name.startswith('SIG')and not name.startswith('SIG_'))\nor name.startswith('CTRL_'))\n\n_IntEnum._convert_(\n'Handlers',__name__,\nlambda name:name in('SIG_DFL','SIG_IGN'))\n\nif 'pthread_sigmask'in _globals:\n _IntEnum._convert_(\n 'Sigmasks',__name__,\n lambda name:name in('SIG_BLOCK','SIG_UNBLOCK','SIG_SETMASK'))\n \n \ndef _int_to_enum(value,enum_klass):\n ''\n\n \n if not isinstance(value,int):\n return value\n try:\n return enum_klass(value)\n except ValueError:\n return value\n \n \ndef _enum_to_int(value):\n ''\n\n \n try:\n return int(value)\n except(ValueError,TypeError):\n return value\n \n \n \n \n \n \ndef _wraps(wrapped):\n def decorator(wrapper):\n wrapper.__doc__=wrapped.__doc__\n return wrapper\n return decorator\n \n@_wraps(_signal.signal)\ndef signal(signalnum,handler):\n handler=_signal.signal(_enum_to_int(signalnum),_enum_to_int(handler))\n return _int_to_enum(handler,Handlers)\n \n \n@_wraps(_signal.getsignal)\ndef getsignal(signalnum):\n handler=_signal.getsignal(signalnum)\n return _int_to_enum(handler,Handlers)\n \n \nif 'pthread_sigmask'in _globals:\n @_wraps(_signal.pthread_sigmask)\n def pthread_sigmask(how,mask):\n sigs_set=_signal.pthread_sigmask(how,mask)\n return set(_int_to_enum(x,Signals)for x in sigs_set)\n \n \nif 'sigpending'in _globals:\n @_wraps(_signal.sigpending)\n def sigpending():\n return{_int_to_enum(x,Signals)for x in _signal.sigpending()}\n \n \nif 'sigwait'in _globals:\n @_wraps(_signal.sigwait)\n def sigwait(sigset):\n retsig=_signal.sigwait(sigset)\n return _int_to_enum(retsig,Signals)\n \n \nif 'valid_signals'in _globals:\n @_wraps(_signal.valid_signals)\n def valid_signals():\n return{_int_to_enum(x,Signals)for x in _signal.valid_signals()}\n \n \ndel _globals,_wraps\n", ["_signal", "enum"]], "site": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport os\nimport builtins\nimport _sitebuiltins\nimport io\nimport stat\n\n\nPREFIXES=[sys.prefix,sys.exec_prefix]\n\n\nENABLE_USER_SITE=None\n\n\n\n\nUSER_SITE=None\nUSER_BASE=None\n\n\ndef _trace(message):\n if sys.flags.verbose:\n print(message,file=sys.stderr)\n \n \ndef makepath(*paths):\n dir=os.path.join(*paths)\n try:\n dir=os.path.abspath(dir)\n except OSError:\n pass\n return dir,os.path.normcase(dir)\n \n \ndef abs_paths():\n ''\n for m in set(sys.modules.values()):\n loader_module=None\n try:\n loader_module=m.__loader__.__module__\n except AttributeError:\n try:\n loader_module=m.__spec__.loader.__module__\n except AttributeError:\n pass\n if loader_module not in{'_frozen_importlib','_frozen_importlib_external'}:\n continue\n try:\n m.__file__=os.path.abspath(m.__file__)\n except(AttributeError,OSError,TypeError):\n pass\n try:\n m.__cached__=os.path.abspath(m.__cached__)\n except(AttributeError,OSError,TypeError):\n pass\n \n \ndef removeduppaths():\n ''\n \n \n \n L=[]\n known_paths=set()\n for dir in sys.path:\n \n \n \n dir,dircase=makepath(dir)\n if dircase not in known_paths:\n L.append(dir)\n known_paths.add(dircase)\n sys.path[:]=L\n return known_paths\n \n \ndef _init_pathinfo():\n ''\n d=set()\n for item in sys.path:\n try:\n if os.path.exists(item):\n _,itemcase=makepath(item)\n d.add(itemcase)\n except TypeError:\n continue\n return d\n \n \ndef addpackage(sitedir,name,known_paths):\n ''\n\n\n \n if known_paths is None:\n known_paths=_init_pathinfo()\n reset=True\n else:\n reset=False\n fullname=os.path.join(sitedir,name)\n try:\n st=os.lstat(fullname)\n except OSError:\n return\n if((getattr(st,'st_flags',0)&stat.UF_HIDDEN)or\n (getattr(st,'st_file_attributes',0)&stat.FILE_ATTRIBUTE_HIDDEN)):\n _trace(f\"Skipping hidden .pth file: {fullname !r}\")\n return\n _trace(f\"Processing .pth file: {fullname !r}\")\n try:\n with io.open_code(fullname)as f:\n pth_content=f.read()\n except OSError:\n return\n \n try:\n pth_content=pth_content.decode()\n except UnicodeDecodeError:\n \n \n import locale\n pth_content=pth_content.decode(locale.getencoding())\n _trace(f\"Cannot read {fullname !r} as UTF-8. \"\n f\"Using fallback encoding {locale.getencoding()!r}\")\n \n for n,line in enumerate(pth_content.splitlines(),1):\n if line.startswith(\"#\"):\n continue\n if line.strip()==\"\":\n continue\n try:\n if line.startswith((\"import \",\"import\\t\")):\n exec(line)\n continue\n line=line.rstrip()\n dir,dircase=makepath(sitedir,line)\n if dircase not in known_paths and os.path.exists(dir):\n sys.path.append(dir)\n known_paths.add(dircase)\n except Exception as exc:\n print(f\"Error processing line {n:d} of {fullname}:\\n\",\n file=sys.stderr)\n import traceback\n for record in traceback.format_exception(exc):\n for line in record.splitlines():\n print(' '+line,file=sys.stderr)\n print(\"\\nRemainder of file ignored\",file=sys.stderr)\n break\n if reset:\n known_paths=None\n return known_paths\n \n \ndef addsitedir(sitedir,known_paths=None):\n ''\n \n _trace(f\"Adding directory: {sitedir !r}\")\n if known_paths is None:\n known_paths=_init_pathinfo()\n reset=True\n else:\n reset=False\n sitedir,sitedircase=makepath(sitedir)\n if not sitedircase in known_paths:\n sys.path.append(sitedir)\n known_paths.add(sitedircase)\n try:\n names=os.listdir(sitedir)\n except OSError:\n return\n names=[name for name in names\n if name.endswith(\".pth\")and not name.startswith(\".\")]\n for name in sorted(names):\n addpackage(sitedir,name,known_paths)\n if reset:\n known_paths=None\n return known_paths\n \n \ndef check_enableusersite():\n ''\n\n\n\n\n\n\n\n \n if sys.flags.no_user_site:\n return False\n \n if hasattr(os,\"getuid\")and hasattr(os,\"geteuid\"):\n \n if os.geteuid()!=os.getuid():\n return None\n if hasattr(os,\"getgid\")and hasattr(os,\"getegid\"):\n \n if os.getegid()!=os.getgid():\n return None\n \n return True\n \n \n \n \n \n \n \n \n \ndef _get_implementation():\n return 'Python'\n \n \ndef _getuserbase():\n env_base=os.environ.get(\"PYTHONUSERBASE\",None)\n if env_base:\n return env_base\n \n \n if sys.platform in{\"emscripten\",\"ios\",\"tvos\",\"vxworks\",\"wasi\",\"watchos\"}:\n return None\n \n def joinuser(*args):\n return os.path.expanduser(os.path.join(*args))\n \n if os.name ==\"nt\":\n base=os.environ.get(\"APPDATA\")or \"~\"\n return joinuser(base,_get_implementation())\n \n if sys.platform ==\"darwin\"and sys._framework:\n return joinuser(\"~\",\"Library\",sys._framework,\n \"%d.%d\"%sys.version_info[:2])\n \n return joinuser(\"~\",\".local\")\n \n \n \ndef _get_path(userbase):\n version=sys.version_info\n \n implementation=_get_implementation()\n implementation_lower=implementation.lower()\n if os.name =='nt':\n ver_nodot=sys.winver.replace('.','')\n return f'{userbase}\\\\{implementation}{ver_nodot}\\\\site-packages'\n \n if sys.platform =='darwin'and sys._framework:\n return f'{userbase}/lib/{implementation_lower}/site-packages'\n \n return f'{userbase}/lib/python{version[0]}.{version[1]}/site-packages'\n \n \ndef getuserbase():\n ''\n\n\n\n\n \n global USER_BASE\n if USER_BASE is None:\n USER_BASE=_getuserbase()\n return USER_BASE\n \n \ndef getusersitepackages():\n ''\n\n\n\n \n global USER_SITE,ENABLE_USER_SITE\n userbase=getuserbase()\n \n if USER_SITE is None:\n if userbase is None:\n ENABLE_USER_SITE=False\n else:\n USER_SITE=_get_path(userbase)\n \n return USER_SITE\n \ndef addusersitepackages(known_paths):\n ''\n\n\n\n \n \n \n _trace(\"Processing user site-packages\")\n user_site=getusersitepackages()\n \n if ENABLE_USER_SITE and os.path.isdir(user_site):\n addsitedir(user_site,known_paths)\n return known_paths\n \ndef getsitepackages(prefixes=None):\n ''\n\n\n\n\n \n sitepackages=[]\n seen=set()\n \n if prefixes is None:\n prefixes=PREFIXES\n \n for prefix in prefixes:\n if not prefix or prefix in seen:\n continue\n seen.add(prefix)\n \n implementation=_get_implementation().lower()\n ver=sys.version_info\n if os.sep =='/':\n libdirs=[sys.platlibdir]\n if sys.platlibdir !=\"lib\":\n libdirs.append(\"lib\")\n \n for libdir in libdirs:\n path=os.path.join(prefix,libdir,\n f\"{implementation}{ver[0]}.{ver[1]}\",\n \"site-packages\")\n sitepackages.append(path)\n else:\n sitepackages.append(prefix)\n sitepackages.append(os.path.join(prefix,\"Lib\",\"site-packages\"))\n return sitepackages\n \ndef addsitepackages(known_paths,prefixes=None):\n ''\n _trace(\"Processing global site-packages\")\n for sitedir in getsitepackages(prefixes):\n if os.path.isdir(sitedir):\n addsitedir(sitedir,known_paths)\n \n return known_paths\n \ndef setquit():\n ''\n\n\n\n\n \n if os.sep =='\\\\':\n eof='Ctrl-Z plus Return'\n else:\n eof='Ctrl-D (i.e. EOF)'\n \n builtins.quit=_sitebuiltins.Quitter('quit',eof)\n builtins.exit=_sitebuiltins.Quitter('exit',eof)\n \n \ndef setcopyright():\n ''\n builtins.copyright=_sitebuiltins._Printer(\"copyright\",sys.copyright)\n builtins.credits=_sitebuiltins._Printer(\"credits\",\"\"\"\\\n Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\n for supporting Python development. See www.python.org for more information.\"\"\")\n files,dirs=[],[]\n \n \n here=getattr(sys,'_stdlib_dir',None)\n if not here and hasattr(os,'__file__'):\n here=os.path.dirname(os.__file__)\n if here:\n files.extend([\"LICENSE.txt\",\"LICENSE\"])\n dirs.extend([os.path.join(here,os.pardir),here,os.curdir])\n builtins.license=_sitebuiltins._Printer(\n \"license\",\n \"See https://www.python.org/psf/license/\",\n files,dirs)\n \n \ndef sethelper():\n builtins.help=_sitebuiltins._Helper()\n \n \ndef gethistoryfile():\n ''\n\n\n \n if not sys.flags.ignore_environment:\n history=os.environ.get(\"PYTHON_HISTORY\")\n if history:\n return history\n return os.path.join(os.path.expanduser('~'),\n '.python_history')\n \n \ndef enablerlcompleter():\n ''\n\n \n sys.__interactivehook__=register_readline\n \n \ndef register_readline():\n ''\n\n\n\n\n\n \n import atexit\n try:\n import readline\n import rlcompleter\n import _pyrepl.readline\n import _pyrepl.unix_console\n except ImportError:\n return\n \n \n \n if readline.backend =='editline':\n readline.parse_and_bind('bind ^I rl_complete')\n else:\n readline.parse_and_bind('tab: complete')\n \n try:\n readline.read_init_file()\n except OSError:\n \n \n \n \n pass\n \n if readline.get_current_history_length()==0:\n \n \n \n \n \n \n history=gethistoryfile()\n try:\n if os.getenv(\"PYTHON_BASIC_REPL\"):\n readline.read_history_file(history)\n else:\n _pyrepl.readline.read_history_file(history)\n except(OSError,*_pyrepl.unix_console._error):\n pass\n \n def write_history():\n try:\n if os.getenv(\"PYTHON_BASIC_REPL\"):\n readline.write_history_file(history)\n else:\n _pyrepl.readline.write_history_file(history)\n except(FileNotFoundError,PermissionError):\n \n \n pass\n \n atexit.register(write_history)\n \n \ndef venv(known_paths):\n global PREFIXES,ENABLE_USER_SITE\n \n env=os.environ\n if sys.platform =='darwin'and '__PYVENV_LAUNCHER__'in env:\n executable=sys._base_executable=os.environ['__PYVENV_LAUNCHER__']\n else:\n executable=sys.executable\n exe_dir=os.path.dirname(os.path.abspath(executable))\n site_prefix=os.path.dirname(exe_dir)\n sys._home=None\n conf_basename='pyvenv.cfg'\n candidate_conf=next(\n (\n conffile for conffile in(\n os.path.join(exe_dir,conf_basename),\n os.path.join(site_prefix,conf_basename)\n )\n if os.path.isfile(conffile)\n ),\n None\n )\n \n if candidate_conf:\n virtual_conf=candidate_conf\n system_site=\"true\"\n \n \n with open(virtual_conf,encoding='utf-8')as f:\n for line in f:\n if '='in line:\n key,_,value=line.partition('=')\n key=key.strip().lower()\n value=value.strip()\n if key =='include-system-site-packages':\n system_site=value.lower()\n elif key =='home':\n sys._home=value\n \n sys.prefix=sys.exec_prefix=site_prefix\n \n \n addsitepackages(known_paths,[sys.prefix])\n \n \n \n if system_site ==\"true\":\n PREFIXES.insert(0,sys.prefix)\n else:\n PREFIXES=[sys.prefix]\n ENABLE_USER_SITE=False\n \n return known_paths\n \n \ndef execsitecustomize():\n ''\n try:\n try:\n import sitecustomize\n except ImportError as exc:\n if exc.name =='sitecustomize':\n pass\n else:\n raise\n except Exception as err:\n if sys.flags.verbose:\n sys.excepthook(*sys.exc_info())\n else:\n sys.stderr.write(\n \"Error in sitecustomize; set PYTHONVERBOSE for traceback:\\n\"\n \"%s: %s\\n\"%\n (err.__class__.__name__,err))\n \n \ndef execusercustomize():\n ''\n try:\n try:\n import usercustomize\n except ImportError as exc:\n if exc.name =='usercustomize':\n pass\n else:\n raise\n except Exception as err:\n if sys.flags.verbose:\n sys.excepthook(*sys.exc_info())\n else:\n sys.stderr.write(\n \"Error in usercustomize; set PYTHONVERBOSE for traceback:\\n\"\n \"%s: %s\\n\"%\n (err.__class__.__name__,err))\n \n \ndef main():\n ''\n\n\n\n \n global ENABLE_USER_SITE\n \n orig_path=sys.path[:]\n known_paths=removeduppaths()\n if orig_path !=sys.path:\n \n \n abs_paths()\n \n known_paths=venv(known_paths)\n if ENABLE_USER_SITE is None:\n ENABLE_USER_SITE=check_enableusersite()\n known_paths=addusersitepackages(known_paths)\n known_paths=addsitepackages(known_paths)\n setquit()\n setcopyright()\n sethelper()\n if not sys.flags.isolated:\n enablerlcompleter()\n execsitecustomize()\n if ENABLE_USER_SITE:\n execusercustomize()\n \n \n \nif not sys.flags.no_site:\n main()\n \ndef _script():\n help=\"\"\"\\\n %s [--user-base] [--user-site]\n\n Without arguments print some useful information\n With arguments print the value of USER_BASE and/or USER_SITE separated\n by '%s'.\n\n Exit codes with --user-base or --user-site:\n 0 - user site directory is enabled\n 1 - user site directory is disabled by user\n 2 - user site directory is disabled by super user\n or for security reasons\n >2 - unknown error\n \"\"\"\n args=sys.argv[1:]\n if not args:\n user_base=getuserbase()\n user_site=getusersitepackages()\n print(\"sys.path = [\")\n for dir in sys.path:\n print(\" %r,\"%(dir,))\n print(\"]\")\n def exists(path):\n if path is not None and os.path.isdir(path):\n return \"exists\"\n else:\n return \"doesn't exist\"\n print(f\"USER_BASE: {user_base !r} ({exists(user_base)})\")\n print(f\"USER_SITE: {user_site !r} ({exists(user_site)})\")\n print(f\"ENABLE_USER_SITE: {ENABLE_USER_SITE !r}\")\n sys.exit(0)\n \n buffer=[]\n if '--user-base'in args:\n buffer.append(USER_BASE)\n if '--user-site'in args:\n buffer.append(USER_SITE)\n \n if buffer:\n print(os.pathsep.join(buffer))\n if ENABLE_USER_SITE:\n sys.exit(0)\n elif ENABLE_USER_SITE is False:\n sys.exit(1)\n elif ENABLE_USER_SITE is None:\n sys.exit(2)\n else:\n sys.exit(3)\n else:\n import textwrap\n print(textwrap.dedent(help %(sys.argv[0],os.pathsep)))\n sys.exit(10)\n \nif __name__ =='__main__':\n _script()\n", ["_pyrepl.readline", "_pyrepl.unix_console", "_sitebuiltins", "atexit", "builtins", "io", "locale", "os", "readline", "rlcompleter", "sitecustomize", "stat", "sys", "textwrap", "traceback", "usercustomize"]], "socket": [".py", "\n\n\n\"\"\"\\\nThis module provides socket operations and some related functions.\nOn Unix, it supports IP (Internet Protocol) and Unix domain sockets.\nOn other systems, it only supports IP. Functions specific for a\nsocket are available as methods of the socket object.\n\nFunctions:\n\nsocket() -- create a new socket object\nsocketpair() -- create a pair of new socket objects [*]\nfromfd() -- create a socket object from an open file descriptor [*]\nsend_fds() -- Send file descriptor to the socket.\nrecv_fds() -- Receive file descriptors from the socket.\nfromshare() -- create a socket object from data received from socket.share() [*]\ngethostname() -- return the current hostname\ngethostbyname() -- map a hostname to its IP number\ngethostbyaddr() -- map an IP number or hostname to DNS info\ngetservbyname() -- map a service name and a protocol name to a port number\ngetprotobyname() -- map a protocol name (e.g. 'tcp') to a number\nntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order\nhtons(), htonl() -- convert 16, 32 bit int from host to network byte order\ninet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format\ninet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)\nsocket.getdefaulttimeout() -- get the default timeout value\nsocket.setdefaulttimeout() -- set the default timeout value\ncreate_connection() -- connects to an address, with an optional timeout and\n optional source address.\n\n [*] not available on all platforms!\n\nSpecial objects:\n\nSocketType -- type object for socket objects\nerror -- exception raised for I/O errors\nhas_ipv6 -- boolean value indicating if IPv6 is supported\n\nIntEnum constants:\n\nAF_INET, AF_UNIX -- socket domains (first argument to socket() call)\nSOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)\n\nInteger constants:\n\nMany other constants may be defined; these may be used in calls to\nthe setsockopt() and getsockopt() methods.\n\"\"\"\n\nimport _socket\nfrom _socket import *\n\nimport os,sys,io,selectors\nfrom enum import IntEnum,IntFlag\n\ntry:\n import errno\nexcept ImportError:\n errno=None\nEBADF=getattr(errno,'EBADF',9)\nEAGAIN=getattr(errno,'EAGAIN',11)\nEWOULDBLOCK=getattr(errno,'EWOULDBLOCK',11)\n\n__all__=[\"fromfd\",\"getfqdn\",\"create_connection\",\"create_server\",\n\"has_dualstack_ipv6\",\"AddressFamily\",\"SocketKind\"]\n__all__.extend(os._get_exports_list(_socket))\n\n\n\n\n\n\n\nIntEnum._convert_(\n'AddressFamily',\n__name__,\nlambda C:C.isupper()and C.startswith('AF_'))\n\nIntEnum._convert_(\n'SocketKind',\n__name__,\nlambda C:C.isupper()and C.startswith('SOCK_'))\n\nIntFlag._convert_(\n'MsgFlag',\n__name__,\nlambda C:C.isupper()and C.startswith('MSG_'))\n\nIntFlag._convert_(\n'AddressInfo',\n__name__,\nlambda C:C.isupper()and C.startswith('AI_'))\n\n_LOCALHOST='127.0.0.1'\n_LOCALHOST_V6='::1'\n\n\ndef _intenum_converter(value,enum_klass):\n ''\n\n\n \n try:\n return enum_klass(value)\n except ValueError:\n return value\n \n \n \nif sys.platform.lower().startswith(\"win\"):\n errorTab={}\n errorTab[6]=\"Specified event object handle is invalid.\"\n errorTab[8]=\"Insufficient memory available.\"\n errorTab[87]=\"One or more parameters are invalid.\"\n errorTab[995]=\"Overlapped operation aborted.\"\n errorTab[996]=\"Overlapped I/O event object not in signaled state.\"\n errorTab[997]=\"Overlapped operation will complete later.\"\n errorTab[10004]=\"The operation was interrupted.\"\n errorTab[10009]=\"A bad file handle was passed.\"\n errorTab[10013]=\"Permission denied.\"\n errorTab[10014]=\"A fault occurred on the network??\"\n errorTab[10022]=\"An invalid operation was attempted.\"\n errorTab[10024]=\"Too many open files.\"\n errorTab[10035]=\"The socket operation would block.\"\n errorTab[10036]=\"A blocking operation is already in progress.\"\n errorTab[10037]=\"Operation already in progress.\"\n errorTab[10038]=\"Socket operation on nonsocket.\"\n errorTab[10039]=\"Destination address required.\"\n errorTab[10040]=\"Message too long.\"\n errorTab[10041]=\"Protocol wrong type for socket.\"\n errorTab[10042]=\"Bad protocol option.\"\n errorTab[10043]=\"Protocol not supported.\"\n errorTab[10044]=\"Socket type not supported.\"\n errorTab[10045]=\"Operation not supported.\"\n errorTab[10046]=\"Protocol family not supported.\"\n errorTab[10047]=\"Address family not supported by protocol family.\"\n errorTab[10048]=\"The network address is in use.\"\n errorTab[10049]=\"Cannot assign requested address.\"\n errorTab[10050]=\"Network is down.\"\n errorTab[10051]=\"Network is unreachable.\"\n errorTab[10052]=\"Network dropped connection on reset.\"\n errorTab[10053]=\"Software caused connection abort.\"\n errorTab[10054]=\"The connection has been reset.\"\n errorTab[10055]=\"No buffer space available.\"\n errorTab[10056]=\"Socket is already connected.\"\n errorTab[10057]=\"Socket is not connected.\"\n errorTab[10058]=\"The network has been shut down.\"\n errorTab[10059]=\"Too many references.\"\n errorTab[10060]=\"The operation timed out.\"\n errorTab[10061]=\"Connection refused.\"\n errorTab[10062]=\"Cannot translate name.\"\n errorTab[10063]=\"The name is too long.\"\n errorTab[10064]=\"The host is down.\"\n errorTab[10065]=\"The host is unreachable.\"\n errorTab[10066]=\"Directory not empty.\"\n errorTab[10067]=\"Too many processes.\"\n errorTab[10068]=\"User quota exceeded.\"\n errorTab[10069]=\"Disk quota exceeded.\"\n errorTab[10070]=\"Stale file handle reference.\"\n errorTab[10071]=\"Item is remote.\"\n errorTab[10091]=\"Network subsystem is unavailable.\"\n errorTab[10092]=\"Winsock.dll version out of range.\"\n errorTab[10093]=\"Successful WSAStartup not yet performed.\"\n errorTab[10101]=\"Graceful shutdown in progress.\"\n errorTab[10102]=\"No more results from WSALookupServiceNext.\"\n errorTab[10103]=\"Call has been canceled.\"\n errorTab[10104]=\"Procedure call table is invalid.\"\n errorTab[10105]=\"Service provider is invalid.\"\n errorTab[10106]=\"Service provider failed to initialize.\"\n errorTab[10107]=\"System call failure.\"\n errorTab[10108]=\"Service not found.\"\n errorTab[10109]=\"Class type not found.\"\n errorTab[10110]=\"No more results from WSALookupServiceNext.\"\n errorTab[10111]=\"Call was canceled.\"\n errorTab[10112]=\"Database query was refused.\"\n errorTab[11001]=\"Host not found.\"\n errorTab[11002]=\"Nonauthoritative host not found.\"\n errorTab[11003]=\"This is a nonrecoverable error.\"\n errorTab[11004]=\"Valid name, no data record requested type.\"\n errorTab[11005]=\"QoS receivers.\"\n errorTab[11006]=\"QoS senders.\"\n errorTab[11007]=\"No QoS senders.\"\n errorTab[11008]=\"QoS no receivers.\"\n errorTab[11009]=\"QoS request confirmed.\"\n errorTab[11010]=\"QoS admission error.\"\n errorTab[11011]=\"QoS policy failure.\"\n errorTab[11012]=\"QoS bad style.\"\n errorTab[11013]=\"QoS bad object.\"\n errorTab[11014]=\"QoS traffic control error.\"\n errorTab[11015]=\"QoS generic error.\"\n errorTab[11016]=\"QoS service type error.\"\n errorTab[11017]=\"QoS flowspec error.\"\n errorTab[11018]=\"Invalid QoS provider buffer.\"\n errorTab[11019]=\"Invalid QoS filter style.\"\n errorTab[11020]=\"Invalid QoS filter style.\"\n errorTab[11021]=\"Incorrect QoS filter count.\"\n errorTab[11022]=\"Invalid QoS object length.\"\n errorTab[11023]=\"Incorrect QoS flow count.\"\n errorTab[11024]=\"Unrecognized QoS object.\"\n errorTab[11025]=\"Invalid QoS policy object.\"\n errorTab[11026]=\"Invalid QoS flow descriptor.\"\n errorTab[11027]=\"Invalid QoS provider-specific flowspec.\"\n errorTab[11028]=\"Invalid QoS provider-specific filterspec.\"\n errorTab[11029]=\"Invalid QoS shape discard mode object.\"\n errorTab[11030]=\"Invalid QoS shaping rate object.\"\n errorTab[11031]=\"Reserved policy QoS element type.\"\n __all__.append(\"errorTab\")\n \n \nclass _GiveupOnSendfile(Exception):pass\n\n\nclass socket(_socket.socket):\n\n ''\n \n __slots__=[\"__weakref__\",\"_io_refs\",\"_closed\"]\n \n def __init__(self,family=-1,type=-1,proto=-1,fileno=None):\n \n \n \n \n if fileno is None:\n if family ==-1:\n family=AF_INET\n if type ==-1:\n type=SOCK_STREAM\n if proto ==-1:\n proto=0\n _socket.socket.__init__(self,family,type,proto,fileno)\n self._io_refs=0\n self._closed=False\n \n def __enter__(self):\n return self\n \n def __exit__(self,*args):\n if not self._closed:\n self.close()\n \n def __repr__(self):\n ''\n\n \n closed=getattr(self,'_closed',False)\n s=\"<%s.%s%s fd=%i, family=%s, type=%s, proto=%i\"\\\n %(self.__class__.__module__,\n self.__class__.__qualname__,\n \" [closed]\"if closed else \"\",\n self.fileno(),\n self.family,\n self.type,\n self.proto)\n if not closed:\n try:\n laddr=self.getsockname()\n if laddr:\n s +=\", laddr=%s\"%str(laddr)\n except error:\n pass\n try:\n raddr=self.getpeername()\n if raddr:\n s +=\", raddr=%s\"%str(raddr)\n except error:\n pass\n s +='>'\n return s\n \n def __getstate__(self):\n raise TypeError(f\"cannot pickle {self.__class__.__name__ !r} object\")\n \n def dup(self):\n ''\n\n\n\n \n fd=dup(self.fileno())\n sock=self.__class__(self.family,self.type,self.proto,fileno=fd)\n sock.settimeout(self.gettimeout())\n return sock\n \n def accept(self):\n ''\n\n\n\n\n \n fd,addr=self._accept()\n sock=socket(self.family,self.type,self.proto,fileno=fd)\n \n \n \n if getdefaulttimeout()is None and self.gettimeout():\n sock.setblocking(True)\n return sock,addr\n \n def makefile(self,mode=\"r\",buffering=None,*,\n encoding=None,errors=None,newline=None):\n ''\n\n\n\n \n \n if not set(mode)<={\"r\",\"w\",\"b\"}:\n raise ValueError(\"invalid mode %r (only r, w, b allowed)\"%(mode,))\n writing=\"w\"in mode\n reading=\"r\"in mode or not writing\n assert reading or writing\n binary=\"b\"in mode\n rawmode=\"\"\n if reading:\n rawmode +=\"r\"\n if writing:\n rawmode +=\"w\"\n raw=SocketIO(self,rawmode)\n self._io_refs +=1\n if buffering is None:\n buffering=-1\n if buffering <0:\n buffering=io.DEFAULT_BUFFER_SIZE\n if buffering ==0:\n if not binary:\n raise ValueError(\"unbuffered streams must be binary\")\n return raw\n if reading and writing:\n buffer=io.BufferedRWPair(raw,raw,buffering)\n elif reading:\n buffer=io.BufferedReader(raw,buffering)\n else:\n assert writing\n buffer=io.BufferedWriter(raw,buffering)\n if binary:\n return buffer\n encoding=io.text_encoding(encoding)\n text=io.TextIOWrapper(buffer,encoding,errors,newline)\n text.mode=mode\n return text\n \n if hasattr(os,'sendfile'):\n \n def _sendfile_use_sendfile(self,file,offset=0,count=None):\n self._check_sendfile_params(file,offset,count)\n sockno=self.fileno()\n try:\n fileno=file.fileno()\n except(AttributeError,io.UnsupportedOperation)as err:\n raise _GiveupOnSendfile(err)\n try:\n fsize=os.fstat(fileno).st_size\n except OSError as err:\n raise _GiveupOnSendfile(err)\n if not fsize:\n return 0\n \n blocksize=min(count or fsize,2 **30)\n timeout=self.gettimeout()\n if timeout ==0:\n raise ValueError(\"non-blocking sockets are not supported\")\n \n \n \n if hasattr(selectors,'PollSelector'):\n selector=selectors.PollSelector()\n else:\n selector=selectors.SelectSelector()\n selector.register(sockno,selectors.EVENT_WRITE)\n \n total_sent=0\n \n selector_select=selector.select\n os_sendfile=os.sendfile\n try:\n while True:\n if timeout and not selector_select(timeout):\n raise TimeoutError('timed out')\n if count:\n blocksize=count -total_sent\n if blocksize <=0:\n break\n try:\n sent=os_sendfile(sockno,fileno,offset,blocksize)\n except BlockingIOError:\n if not timeout:\n \n \n selector_select()\n continue\n except OSError as err:\n if total_sent ==0:\n \n \n \n \n raise _GiveupOnSendfile(err)\n raise err from None\n else:\n if sent ==0:\n break\n offset +=sent\n total_sent +=sent\n return total_sent\n finally:\n if total_sent >0 and hasattr(file,'seek'):\n file.seek(offset)\n else:\n def _sendfile_use_sendfile(self,file,offset=0,count=None):\n raise _GiveupOnSendfile(\n \"os.sendfile() not available on this platform\")\n \n def _sendfile_use_send(self,file,offset=0,count=None):\n self._check_sendfile_params(file,offset,count)\n if self.gettimeout()==0:\n raise ValueError(\"non-blocking sockets are not supported\")\n if offset:\n file.seek(offset)\n blocksize=min(count,8192)if count else 8192\n total_sent=0\n \n file_read=file.read\n sock_send=self.send\n try:\n while True:\n if count:\n blocksize=min(count -total_sent,blocksize)\n if blocksize <=0:\n break\n data=memoryview(file_read(blocksize))\n if not data:\n break\n while True:\n try:\n sent=sock_send(data)\n except BlockingIOError:\n continue\n else:\n total_sent +=sent\n if sent 0 and hasattr(file,'seek'):\n file.seek(offset+total_sent)\n \n def _check_sendfile_params(self,file,offset,count):\n if 'b'not in getattr(file,'mode','b'):\n raise ValueError(\"file should be opened in binary mode\")\n if not self.type&SOCK_STREAM:\n raise ValueError(\"only SOCK_STREAM type sockets are supported\")\n if count is not None:\n if not isinstance(count,int):\n raise TypeError(\n \"count must be a positive integer (got {!r})\".format(count))\n if count <=0:\n raise ValueError(\n \"count must be a positive integer (got {!r})\".format(count))\n \n def sendfile(self,file,offset=0,count=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return self._sendfile_use_sendfile(file,offset,count)\n except _GiveupOnSendfile:\n return self._sendfile_use_send(file,offset,count)\n \n def _decref_socketios(self):\n if self._io_refs >0:\n self._io_refs -=1\n if self._closed:\n self.close()\n \n def _real_close(self,_ss=_socket.socket):\n \n _ss.close(self)\n \n def close(self):\n \n self._closed=True\n if self._io_refs <=0:\n self._real_close()\n \n def detach(self):\n ''\n\n\n\n\n \n self._closed=True\n return super().detach()\n \n @property\n def family(self):\n ''\n \n return _intenum_converter(super().family,AddressFamily)\n \n @property\n def type(self):\n ''\n \n return _intenum_converter(super().type,SocketKind)\n \n if os.name =='nt':\n def get_inheritable(self):\n return os.get_handle_inheritable(self.fileno())\n def set_inheritable(self,inheritable):\n os.set_handle_inheritable(self.fileno(),inheritable)\n else:\n def get_inheritable(self):\n return os.get_inheritable(self.fileno())\n def set_inheritable(self,inheritable):\n os.set_inheritable(self.fileno(),inheritable)\n get_inheritable.__doc__=\"Get the inheritable flag of the socket\"\n set_inheritable.__doc__=\"Set the inheritable flag of the socket\"\n \ndef fromfd(fd,family,type,proto=0):\n ''\n\n\n\n \n nfd=dup(fd)\n return socket(family,type,proto,nfd)\n \nif hasattr(_socket.socket,\"sendmsg\"):\n import array\n \n def send_fds(sock,buffers,fds,flags=0,address=None):\n ''\n\n\n \n return sock.sendmsg(buffers,[(_socket.SOL_SOCKET,\n _socket.SCM_RIGHTS,array.array(\"i\",fds))])\n __all__.append(\"send_fds\")\n \nif hasattr(_socket.socket,\"recvmsg\"):\n import array\n \n def recv_fds(sock,bufsize,maxfds,flags=0):\n ''\n\n\n\n\n \n \n fds=array.array(\"i\")\n msg,ancdata,flags,addr=sock.recvmsg(bufsize,\n _socket.CMSG_LEN(maxfds *fds.itemsize))\n for cmsg_level,cmsg_type,cmsg_data in ancdata:\n if(cmsg_level ==_socket.SOL_SOCKET and cmsg_type ==_socket.SCM_RIGHTS):\n fds.frombytes(cmsg_data[:\n len(cmsg_data)-(len(cmsg_data)%fds.itemsize)])\n \n return msg,list(fds),flags,addr\n __all__.append(\"recv_fds\")\n \nif hasattr(_socket.socket,\"share\"):\n def fromshare(info):\n ''\n\n\n\n \n return socket(0,0,0,info)\n __all__.append(\"fromshare\")\n \nif hasattr(_socket,\"socketpair\"):\n\n def socketpair(family=None,type=SOCK_STREAM,proto=0):\n ''\n\n\n\n\n\n \n if family is None:\n try:\n family=AF_UNIX\n except NameError:\n family=AF_INET\n a,b=_socket.socketpair(family,type,proto)\n a=socket(family,type,proto,a.detach())\n b=socket(family,type,proto,b.detach())\n return a,b\n \nelse:\n\n\n def socketpair(family=AF_INET,type=SOCK_STREAM,proto=0):\n if family ==AF_INET:\n host=_LOCALHOST\n elif family ==AF_INET6:\n host=_LOCALHOST_V6\n else:\n raise ValueError(\"Only AF_INET and AF_INET6 socket address families \"\n \"are supported\")\n if type !=SOCK_STREAM:\n raise ValueError(\"Only SOCK_STREAM socket type is supported\")\n if proto !=0:\n raise ValueError(\"Only protocol zero is supported\")\n \n \n \n lsock=socket(family,type,proto)\n try:\n lsock.bind((host,0))\n lsock.listen()\n \n addr,port=lsock.getsockname()[:2]\n csock=socket(family,type,proto)\n try:\n csock.setblocking(False)\n try:\n csock.connect((addr,port))\n except(BlockingIOError,InterruptedError):\n pass\n csock.setblocking(True)\n ssock,_=lsock.accept()\n except:\n csock.close()\n raise\n finally:\n lsock.close()\n return(ssock,csock)\n __all__.append(\"socketpair\")\n \nsocketpair.__doc__=\"\"\"socketpair([family[, type[, proto]]]) -> (socket object, socket object)\nCreate a pair of socket objects from the sockets returned by the platform\nsocketpair() function.\nThe arguments are the same as for socket() except the default family is AF_UNIX\nif defined on the platform; otherwise, the default is AF_INET.\n\"\"\"\n\n_blocking_errnos={EAGAIN,EWOULDBLOCK}\n\nclass SocketIO(io.RawIOBase):\n\n ''\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n def __init__(self,sock,mode):\n if mode not in(\"r\",\"w\",\"rw\",\"rb\",\"wb\",\"rwb\"):\n raise ValueError(\"invalid mode: %r\"%mode)\n io.RawIOBase.__init__(self)\n self._sock=sock\n if \"b\"not in mode:\n mode +=\"b\"\n self._mode=mode\n self._reading=\"r\"in mode\n self._writing=\"w\"in mode\n self._timeout_occurred=False\n \n def readinto(self,b):\n ''\n\n\n\n\n\n \n self._checkClosed()\n self._checkReadable()\n if self._timeout_occurred:\n raise OSError(\"cannot read from timed out object\")\n while True:\n try:\n return self._sock.recv_into(b)\n except timeout:\n self._timeout_occurred=True\n raise\n except error as e:\n if e.errno in _blocking_errnos:\n return None\n raise\n \n def write(self,b):\n ''\n\n\n\n \n self._checkClosed()\n self._checkWritable()\n try:\n return self._sock.send(b)\n except error as e:\n \n if e.errno in _blocking_errnos:\n return None\n raise\n \n def readable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return self._reading\n \n def writable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return self._writing\n \n def seekable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return super().seekable()\n \n def fileno(self):\n ''\n \n self._checkClosed()\n return self._sock.fileno()\n \n @property\n def name(self):\n if not self.closed:\n return self.fileno()\n else:\n return -1\n \n @property\n def mode(self):\n return self._mode\n \n def close(self):\n ''\n\n \n if self.closed:\n return\n io.RawIOBase.close(self)\n self._sock._decref_socketios()\n self._sock=None\n \n \ndef getfqdn(name=''):\n ''\n\n\n\n\n\n\n\n \n name=name.strip()\n if not name or name =='0.0.0.0':\n name=gethostname()\n try:\n hostname,aliases,ipaddrs=gethostbyaddr(name)\n except error:\n pass\n else:\n aliases.insert(0,hostname)\n for name in aliases:\n if '.'in name:\n break\n else:\n name=hostname\n return name\n \n \n_GLOBAL_DEFAULT_TIMEOUT=object()\n\ndef create_connection(address,timeout=_GLOBAL_DEFAULT_TIMEOUT,\nsource_address=None,*,all_errors=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n host,port=address\n exceptions=[]\n for res in getaddrinfo(host,port,0,SOCK_STREAM):\n af,socktype,proto,canonname,sa=res\n sock=None\n try:\n sock=socket(af,socktype,proto)\n if timeout is not _GLOBAL_DEFAULT_TIMEOUT:\n sock.settimeout(timeout)\n if source_address:\n sock.bind(source_address)\n sock.connect(sa)\n \n exceptions.clear()\n return sock\n \n except error as exc:\n if not all_errors:\n exceptions.clear()\n exceptions.append(exc)\n if sock is not None:\n sock.close()\n \n if len(exceptions):\n try:\n if not all_errors:\n raise exceptions[0]\n raise ExceptionGroup(\"create_connection failed\",exceptions)\n finally:\n \n exceptions.clear()\n else:\n raise error(\"getaddrinfo returns an empty list\")\n \n \ndef has_dualstack_ipv6():\n ''\n\n \n if not has_ipv6\\\n or not hasattr(_socket,'IPPROTO_IPV6')\\\n or not hasattr(_socket,'IPV6_V6ONLY'):\n return False\n try:\n with socket(AF_INET6,SOCK_STREAM)as sock:\n sock.setsockopt(IPPROTO_IPV6,IPV6_V6ONLY,0)\n return True\n except error:\n return False\n \n \ndef create_server(address,*,family=AF_INET,backlog=None,reuse_port=False,\ndualstack_ipv6=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if reuse_port and not hasattr(_socket,\"SO_REUSEPORT\"):\n raise ValueError(\"SO_REUSEPORT not supported on this platform\")\n if dualstack_ipv6:\n if not has_dualstack_ipv6():\n raise ValueError(\"dualstack_ipv6 not supported on this platform\")\n if family !=AF_INET6:\n raise ValueError(\"dualstack_ipv6 requires AF_INET6 family\")\n sock=socket(family,SOCK_STREAM)\n try:\n \n \n \n \n \n \n \n \n \n if os.name not in('nt','cygwin')and\\\n hasattr(_socket,'SO_REUSEADDR'):\n try:\n sock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)\n except error:\n \n \n pass\n if reuse_port:\n sock.setsockopt(SOL_SOCKET,SO_REUSEPORT,1)\n if has_ipv6 and family ==AF_INET6:\n if dualstack_ipv6:\n sock.setsockopt(IPPROTO_IPV6,IPV6_V6ONLY,0)\n elif hasattr(_socket,\"IPV6_V6ONLY\")and\\\n hasattr(_socket,\"IPPROTO_IPV6\"):\n sock.setsockopt(IPPROTO_IPV6,IPV6_V6ONLY,1)\n try:\n sock.bind(address)\n except error as err:\n msg='%s (while attempting to bind on address %r)'%\\\n (err.strerror,address)\n raise error(err.errno,msg)from None\n if backlog is None:\n sock.listen()\n else:\n sock.listen(backlog)\n return sock\n except error:\n sock.close()\n raise\n \n \ndef getaddrinfo(host,port,family=0,type=0,proto=0,flags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n addrlist=[]\n for res in _socket.getaddrinfo(host,port,family,type,proto,flags):\n af,socktype,proto,canonname,sa=res\n addrlist.append((_intenum_converter(af,AddressFamily),\n _intenum_converter(socktype,SocketKind),\n proto,canonname,sa))\n return addrlist\n", ["_socket", "array", "enum", "errno", "io", "os", "selectors", "sys"]], "sre_compile": [".py", "import warnings\nwarnings.warn(f\"module {__name__ !r} is deprecated\",\nDeprecationWarning,\nstacklevel=2)\n\nfrom re import _compiler as _\nglobals().update({k:v for k,v in vars(_).items()if k[:2]!='__'})\n", ["re", "warnings"]], "sre_constants": [".py", "import warnings\nwarnings.warn(f\"module {__name__ !r} is deprecated\",\nDeprecationWarning,\nstacklevel=2)\n\nfrom re import _constants as _\nglobals().update({k:v for k,v in vars(_).items()if k[:2]!='__'})\n", ["re", "warnings"]], "sre_parse": [".py", "import warnings\nwarnings.warn(f\"module {__name__ !r} is deprecated\",\nDeprecationWarning,\nstacklevel=2)\n\nfrom re import _parser as _\nglobals().update({k:v for k,v in vars(_).items()if k[:2]!='__'})\n", ["re", "warnings"]], "stat": [".py", "''\n\n\n\nimport sys\n\n\n\nST_MODE=0\nST_INO=1\nST_DEV=2\nST_NLINK=3\nST_UID=4\nST_GID=5\nST_SIZE=6\nST_ATIME=7\nST_MTIME=8\nST_CTIME=9\n\n\n\ndef S_IMODE(mode):\n ''\n\n \n return mode&0o7777\n \ndef S_IFMT(mode):\n ''\n\n \n return mode&0o170000\n \n \n \n \nS_IFDIR=0o040000\nS_IFCHR=0o020000\nS_IFBLK=0o060000\nS_IFREG=0o100000\nS_IFIFO=0o010000\nS_IFLNK=0o120000\nS_IFSOCK=0o140000\n\nS_IFDOOR=0\nS_IFPORT=0\nS_IFWHT=0\n\n\n\ndef S_ISDIR(mode):\n ''\n return S_IFMT(mode)==S_IFDIR\n \ndef S_ISCHR(mode):\n ''\n return S_IFMT(mode)==S_IFCHR\n \ndef S_ISBLK(mode):\n ''\n return S_IFMT(mode)==S_IFBLK\n \ndef S_ISREG(mode):\n ''\n return S_IFMT(mode)==S_IFREG\n \ndef S_ISFIFO(mode):\n ''\n return S_IFMT(mode)==S_IFIFO\n \ndef S_ISLNK(mode):\n ''\n return S_IFMT(mode)==S_IFLNK\n \ndef S_ISSOCK(mode):\n ''\n return S_IFMT(mode)==S_IFSOCK\n \ndef S_ISDOOR(mode):\n ''\n return False\n \ndef S_ISPORT(mode):\n ''\n return False\n \ndef S_ISWHT(mode):\n ''\n return False\n \n \n \nS_ISUID=0o4000\nS_ISGID=0o2000\nS_ENFMT=S_ISGID\nS_ISVTX=0o1000\nS_IREAD=0o0400\nS_IWRITE=0o0200\nS_IEXEC=0o0100\nS_IRWXU=0o0700\nS_IRUSR=0o0400\nS_IWUSR=0o0200\nS_IXUSR=0o0100\nS_IRWXG=0o0070\nS_IRGRP=0o0040\nS_IWGRP=0o0020\nS_IXGRP=0o0010\nS_IRWXO=0o0007\nS_IROTH=0o0004\nS_IWOTH=0o0002\nS_IXOTH=0o0001\n\n\nUF_SETTABLE=0x0000ffff\nUF_NODUMP=0x00000001\nUF_IMMUTABLE=0x00000002\nUF_APPEND=0x00000004\nUF_OPAQUE=0x00000008\nUF_NOUNLINK=0x00000010\nUF_COMPRESSED=0x00000020\nUF_TRACKED=0x00000040\nUF_DATAVAULT=0x00000080\nUF_HIDDEN=0x00008000\nSF_SETTABLE=0xffff0000\nSF_ARCHIVED=0x00010000\nSF_IMMUTABLE=0x00020000\nSF_APPEND=0x00040000\nSF_RESTRICTED=0x00080000\nSF_NOUNLINK=0x00100000\nSF_SNAPSHOT=0x00200000\nSF_FIRMLINK=0x00800000\nSF_DATALESS=0x40000000\n\n\n_filemode_table=(\n\n\n((S_IFLNK,\"l\"),\n(S_IFSOCK,\"s\"),\n(S_IFREG,\"-\"),\n(S_IFBLK,\"b\"),\n(S_IFDIR,\"d\"),\n(S_IFCHR,\"c\"),\n(S_IFIFO,\"p\")),\n\n((S_IRUSR,\"r\"),),\n((S_IWUSR,\"w\"),),\n((S_IXUSR |S_ISUID,\"s\"),\n(S_ISUID,\"S\"),\n(S_IXUSR,\"x\")),\n\n((S_IRGRP,\"r\"),),\n((S_IWGRP,\"w\"),),\n((S_IXGRP |S_ISGID,\"s\"),\n(S_ISGID,\"S\"),\n(S_IXGRP,\"x\")),\n\n((S_IROTH,\"r\"),),\n((S_IWOTH,\"w\"),),\n((S_IXOTH |S_ISVTX,\"t\"),\n(S_ISVTX,\"T\"),\n(S_IXOTH,\"x\"))\n)\n\ndef filemode(mode):\n ''\n perm=[]\n for index,table in enumerate(_filemode_table):\n for bit,char in table:\n if mode&bit ==bit:\n perm.append(char)\n break\n else:\n if index ==0:\n \n perm.append(\"?\")\n else:\n perm.append(\"-\")\n return \"\".join(perm)\n \n \n \n \n \nFILE_ATTRIBUTE_ARCHIVE=32\nFILE_ATTRIBUTE_COMPRESSED=2048\nFILE_ATTRIBUTE_DEVICE=64\nFILE_ATTRIBUTE_DIRECTORY=16\nFILE_ATTRIBUTE_ENCRYPTED=16384\nFILE_ATTRIBUTE_HIDDEN=2\nFILE_ATTRIBUTE_INTEGRITY_STREAM=32768\nFILE_ATTRIBUTE_NORMAL=128\nFILE_ATTRIBUTE_NOT_CONTENT_INDEXED=8192\nFILE_ATTRIBUTE_NO_SCRUB_DATA=131072\nFILE_ATTRIBUTE_OFFLINE=4096\nFILE_ATTRIBUTE_READONLY=1\nFILE_ATTRIBUTE_REPARSE_POINT=1024\nFILE_ATTRIBUTE_SPARSE_FILE=512\nFILE_ATTRIBUTE_SYSTEM=4\nFILE_ATTRIBUTE_TEMPORARY=256\nFILE_ATTRIBUTE_VIRTUAL=65536\n\n\n\ntry:\n from _stat import *\nexcept ImportError:\n pass\n", ["_stat", "sys"]], "statistics": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\n'NormalDist',\n'StatisticsError',\n'correlation',\n'covariance',\n'fmean',\n'geometric_mean',\n'harmonic_mean',\n'kde',\n'kde_random',\n'linear_regression',\n'mean',\n'median',\n'median_grouped',\n'median_high',\n'median_low',\n'mode',\n'multimode',\n'pstdev',\n'pvariance',\n'quantiles',\n'stdev',\n'variance',\n]\n\nimport math\nimport numbers\nimport random\nimport sys\n\nfrom fractions import Fraction\nfrom decimal import Decimal\nfrom itertools import count,groupby,repeat\nfrom bisect import bisect_left,bisect_right\nfrom math import hypot,sqrt,fabs,exp,erf,tau,log,fsum,sumprod\nfrom math import isfinite,isinf,pi,cos,sin,tan,cosh,asin,atan,acos\nfrom functools import reduce\nfrom operator import itemgetter\nfrom collections import Counter,namedtuple,defaultdict\n\n_SQRT2=sqrt(2.0)\n_random=random\n\n\n\nclass StatisticsError(ValueError):\n pass\n \n \n \n \ndef _sum(data):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n count=0\n types=set()\n types_add=types.add\n partials={}\n partials_get=partials.get\n for typ,values in groupby(data,type):\n types_add(typ)\n for n,d in map(_exact_ratio,values):\n count +=1\n partials[d]=partials_get(d,0)+n\n if None in partials:\n \n \n total=partials[None]\n assert not _isfinite(total)\n else:\n \n total=sum(Fraction(n,d)for d,n in partials.items())\n T=reduce(_coerce,types,int)\n return(T,total,count)\n \n \ndef _ss(data,c=None):\n ''\n\n\n\n\n\n\n \n if c is not None:\n T,ssd,count=_sum((d :=x -c)*d for x in data)\n return(T,ssd,c,count)\n count=0\n types=set()\n types_add=types.add\n sx_partials=defaultdict(int)\n sxx_partials=defaultdict(int)\n for typ,values in groupby(data,type):\n types_add(typ)\n for n,d in map(_exact_ratio,values):\n count +=1\n sx_partials[d]+=n\n sxx_partials[d]+=n *n\n if not count:\n ssd=c=Fraction(0)\n elif None in sx_partials:\n \n \n ssd=c=sx_partials[None]\n assert not _isfinite(ssd)\n else:\n sx=sum(Fraction(n,d)for d,n in sx_partials.items())\n sxx=sum(Fraction(n,d *d)for d,n in sxx_partials.items())\n \n \n ssd=(count *sxx -sx *sx)/count\n c=sx /count\n T=reduce(_coerce,types,int)\n return(T,ssd,c,count)\n \n \ndef _isfinite(x):\n try:\n return x.is_finite()\n except AttributeError:\n return math.isfinite(x)\n \n \ndef _coerce(T,S):\n ''\n\n\n\n \n \n assert T is not bool,\"initial type T is bool\"\n \n \n \n if T is S:return T\n \n if S is int or S is bool:return T\n if T is int:return S\n \n if issubclass(S,T):return S\n if issubclass(T,S):return T\n \n if issubclass(T,int):return S\n if issubclass(S,int):return T\n \n if issubclass(T,Fraction)and issubclass(S,float):\n return S\n if issubclass(T,float)and issubclass(S,Fraction):\n return T\n \n msg=\"don't know how to coerce %s and %s\"\n raise TypeError(msg %(T.__name__,S.__name__))\n \n \ndef _exact_ratio(x):\n ''\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n try:\n return x.as_integer_ratio()\n except AttributeError:\n pass\n except(OverflowError,ValueError):\n \n assert not _isfinite(x)\n return(x,None)\n try:\n \n return(x.numerator,x.denominator)\n except AttributeError:\n msg=f\"can't convert type '{type(x).__name__}' to numerator/denominator\"\n raise TypeError(msg)\n \n \ndef _convert(value,T):\n ''\n if type(value)is T:\n \n \n return value\n if issubclass(T,int)and value.denominator !=1:\n T=float\n try:\n \n return T(value)\n except TypeError:\n if issubclass(T,Decimal):\n return T(value.numerator)/T(value.denominator)\n else:\n raise\n \n \ndef _fail_neg(values,errmsg='negative value'):\n ''\n for x in values:\n if x <0:\n raise StatisticsError(errmsg)\n yield x\n \n \ndef _rank(data,/,*,key=None,reverse=False,ties='average',start=1)->list[float]:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n if ties !='average':\n raise ValueError(f'Unknown tie resolution method: {ties !r}')\n if key is not None:\n data=map(key,data)\n val_pos=sorted(zip(data,count()),reverse=reverse)\n i=start -1\n result=[0]*len(val_pos)\n for _,g in groupby(val_pos,key=itemgetter(0)):\n group=list(g)\n size=len(group)\n rank=i+(size+1)/2\n for value,orig_pos in group:\n result[orig_pos]=rank\n i +=size\n return result\n \n \ndef _integer_sqrt_of_frac_rto(n:int,m:int)->int:\n ''\n \n a=math.isqrt(n //m)\n return a |(a *a *m !=n)\n \n \n \n \n_sqrt_bit_width:int=2 *sys.float_info.mant_dig+3\n\n\ndef _float_sqrt_of_frac(n:int,m:int)->float:\n ''\n \n q=(n.bit_length()-m.bit_length()-_sqrt_bit_width)//2\n if q >=0:\n numerator=_integer_sqrt_of_frac_rto(n,m <<2 *q)<Decimal:\n ''\n \n \n \n if n <=0:\n if not n:\n return Decimal('0.0')\n n,m=-n,-m\n \n root=(Decimal(n)/Decimal(m)).sqrt()\n nr,dr=root.as_integer_ratio()\n \n plus=root.next_plus()\n np,dp=plus.as_integer_ratio()\n \n if 4 *n *(dr *dp)**2 >m *(dr *np+dp *nr)**2:\n return plus\n \n minus=root.next_minus()\n nm,dm=minus.as_integer_ratio()\n \n if 4 *n *(dr *dm)**2 0.0 or math.isnan(x):\n yield x\n elif x ==0.0:\n found_zero=True\n else:\n raise StatisticsError('No negative inputs allowed',x)\n total=fsum(map(log,count_positive(data)))\n if not n:\n raise StatisticsError('Must have a non-empty dataset')\n if math.isnan(total):\n return math.nan\n if found_zero:\n return math.nan if total ==math.inf else 0.0\n return exp(total /n)\n \n \ndef harmonic_mean(data,weights=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if iter(data)is data:\n data=list(data)\n errmsg='harmonic mean does not support negative values'\n n=len(data)\n if n <1:\n raise StatisticsError('harmonic_mean requires at least one data point')\n elif n ==1 and weights is None:\n x=data[0]\n if isinstance(x,(numbers.Real,Decimal)):\n if x <0:\n raise StatisticsError(errmsg)\n return x\n else:\n raise TypeError('unsupported type')\n if weights is None:\n weights=repeat(1,n)\n sum_weights=n\n else:\n if iter(weights)is weights:\n weights=list(weights)\n if len(weights)!=n:\n raise StatisticsError('Number of weights does not match data size')\n _,sum_weights,_=_sum(w for w in _fail_neg(weights,errmsg))\n try:\n data=_fail_neg(data,errmsg)\n T,total,count=_sum(w /x if w else 0 for w,x in zip(weights,data))\n except ZeroDivisionError:\n return 0\n if total <=0:\n raise StatisticsError('Weighted sum must be positive')\n return _convert(sum_weights /total,T)\n \n \ndef median(data):\n ''\n\n\n\n\n\n\n\n\n\n\n \n data=sorted(data)\n n=len(data)\n if n ==0:\n raise StatisticsError(\"no median for empty data\")\n if n %2 ==1:\n return data[n //2]\n else:\n i=n //2\n return(data[i -1]+data[i])/2\n \n \ndef median_low(data):\n ''\n\n\n\n\n\n\n\n\n\n \n data=sorted(data)\n n=len(data)\n if n ==0:\n raise StatisticsError(\"no median for empty data\")\n if n %2 ==1:\n return data[n //2]\n else:\n return data[n //2 -1]\n \n \ndef median_high(data):\n ''\n\n\n\n\n\n\n\n\n\n \n data=sorted(data)\n n=len(data)\n if n ==0:\n raise StatisticsError(\"no median for empty data\")\n return data[n //2]\n \n \ndef median_grouped(data,interval=1.0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n data=sorted(data)\n n=len(data)\n if not n:\n raise StatisticsError(\"no median for empty data\")\n \n \n \n x=data[n //2]\n \n \n \n i=bisect_left(data,x)\n j=bisect_right(data,x,lo=i)\n \n \n try:\n interval=float(interval)\n x=float(x)\n except ValueError:\n raise TypeError(f'Value cannot be converted to a float')\n \n \n \n L=x -interval /2.0\n cf=i\n f=j -i\n return L+interval *(n /2 -cf)/f\n \n \ndef mode(data):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n pairs=Counter(iter(data)).most_common(1)\n try:\n return pairs[0][0]\n except IndexError:\n raise StatisticsError('no mode for empty data')from None\n \n \ndef multimode(data):\n ''\n\n\n\n\n\n\n\n\n\n\n \n counts=Counter(iter(data))\n if not counts:\n return[]\n maxcount=max(counts.values())\n return[value for value,count in counts.items()if count ==maxcount]\n \n \ndef kde(data,h,kernel='normal',*,cumulative=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n n=len(data)\n if not n:\n raise StatisticsError('Empty data sequence')\n \n if not isinstance(data[0],(int,float)):\n raise TypeError('Data sequence must contain ints or floats')\n \n if h <=0.0:\n raise StatisticsError(f'Bandwidth h must be positive, not {h=!r}')\n \n match kernel:\n \n case 'normal'|'gauss':\n sqrt2pi=sqrt(2 *pi)\n sqrt2=sqrt(2)\n K=lambda t:exp(-1 /2 *t *t)/sqrt2pi\n W=lambda t:1 /2 *(1.0+erf(t /sqrt2))\n support=None\n \n case 'logistic':\n \n K=lambda t:1 /2 /(1.0+cosh(t))\n W=lambda t:1.0 -1.0 /(exp(t)+1.0)\n support=None\n \n case 'sigmoid':\n \n c1=1 /pi\n c2=2 /pi\n K=lambda t:c1 /cosh(t)\n W=lambda t:c2 *atan(exp(t))\n support=None\n \n case 'rectangular'|'uniform':\n K=lambda t:1 /2\n W=lambda t:1 /2 *t+1 /2\n support=1.0\n \n case 'triangular':\n K=lambda t:1.0 -abs(t)\n W=lambda t:t *t *(1 /2 if t <0.0 else -1 /2)+t+1 /2\n support=1.0\n \n case 'parabolic'|'epanechnikov':\n K=lambda t:3 /4 *(1.0 -t *t)\n W=lambda t:-1 /4 *t **3+3 /4 *t+1 /2\n support=1.0\n \n case 'quartic'|'biweight':\n K=lambda t:15 /16 *(1.0 -t *t)**2\n W=lambda t:3 /16 *t **5 -5 /8 *t **3+15 /16 *t+1 /2\n support=1.0\n \n case 'triweight':\n K=lambda t:35 /32 *(1.0 -t *t)**3\n W=lambda t:35 /32 *(-1 /7 *t **7+3 /5 *t **5 -t **3+t)+1 /2\n support=1.0\n \n case 'cosine':\n c1=pi /4\n c2=pi /2\n K=lambda t:c1 *cos(c2 *t)\n W=lambda t:1 /2 *sin(c2 *t)+1 /2\n support=1.0\n \n case _:\n raise StatisticsError(f'Unknown kernel name: {kernel !r}')\n \n if support is None:\n \n def pdf(x):\n n=len(data)\n return sum(K((x -x_i)/h)for x_i in data)/(n *h)\n \n def cdf(x):\n n=len(data)\n return sum(W((x -x_i)/h)for x_i in data)/n\n \n else:\n \n sample=sorted(data)\n bandwidth=h *support\n \n def pdf(x):\n nonlocal n,sample\n if len(data)!=n:\n sample=sorted(data)\n n=len(data)\n i=bisect_left(sample,x -bandwidth)\n j=bisect_right(sample,x+bandwidth)\n supported=sample[i:j]\n return sum(K((x -x_i)/h)for x_i in supported)/(n *h)\n \n def cdf(x):\n nonlocal n,sample\n if len(data)!=n:\n sample=sorted(data)\n n=len(data)\n i=bisect_left(sample,x -bandwidth)\n j=bisect_right(sample,x+bandwidth)\n supported=sample[i:j]\n return sum((W((x -x_i)/h)for x_i in supported),i)/n\n \n if cumulative:\n cdf.__doc__=f'CDF estimate with {h=!r} and {kernel=!r}'\n return cdf\n \n else:\n pdf.__doc__=f'PDF estimate with {h=!r} and {kernel=!r}'\n return pdf\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef quantiles(data,*,n=4,method='exclusive'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if n <1:\n raise StatisticsError('n must be at least 1')\n data=sorted(data)\n ld=len(data)\n if ld <2:\n if ld ==1:\n return data *(n -1)\n raise StatisticsError('must have at least one data point')\n \n if method =='inclusive':\n m=ld -1\n result=[]\n for i in range(1,n):\n j,delta=divmod(i *m,n)\n interpolated=(data[j]*(n -delta)+data[j+1]*delta)/n\n result.append(interpolated)\n return result\n \n if method =='exclusive':\n m=ld+1\n result=[]\n for i in range(1,n):\n j=i *m //n\n j=1 if j <1 else ld -1 if j >ld -1 else j\n delta=i *m -j *n\n interpolated=(data[j -1]*(n -delta)+data[j]*delta)/n\n result.append(interpolated)\n return result\n \n raise ValueError(f'Unknown method: {method !r}')\n \n \n \n \n \n \n \n \ndef variance(data,xbar=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n T,ss,c,n=_ss(data,xbar)\n if n <2:\n raise StatisticsError('variance requires at least two data points')\n return _convert(ss /(n -1),T)\n \n \ndef pvariance(data,mu=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n T,ss,c,n=_ss(data,mu)\n if n <1:\n raise StatisticsError('pvariance requires at least one data point')\n return _convert(ss /n,T)\n \n \ndef stdev(data,xbar=None):\n ''\n\n\n\n\n\n\n \n T,ss,c,n=_ss(data,xbar)\n if n <2:\n raise StatisticsError('stdev requires at least two data points')\n mss=ss /(n -1)\n if issubclass(T,Decimal):\n return _decimal_sqrt_of_frac(mss.numerator,mss.denominator)\n return _float_sqrt_of_frac(mss.numerator,mss.denominator)\n \n \ndef pstdev(data,mu=None):\n ''\n\n\n\n\n\n\n \n T,ss,c,n=_ss(data,mu)\n if n <1:\n raise StatisticsError('pstdev requires at least one data point')\n mss=ss /n\n if issubclass(T,Decimal):\n return _decimal_sqrt_of_frac(mss.numerator,mss.denominator)\n return _float_sqrt_of_frac(mss.numerator,mss.denominator)\n \n \ndef _mean_stdev(data):\n ''\n T,ss,xbar,n=_ss(data)\n if n <2:\n raise StatisticsError('stdev requires at least two data points')\n mss=ss /(n -1)\n try:\n return float(xbar),_float_sqrt_of_frac(mss.numerator,mss.denominator)\n except AttributeError:\n \n return float(xbar),float(xbar)/float(ss)\n \ndef _sqrtprod(x:float,y:float)->float:\n ''\n h=sqrt(x *y)\n if not isfinite(h):\n if isinf(h)and not isinf(x)and not isinf(y):\n \n scale=2.0 **-512\n return _sqrtprod(scale *x,scale *y)/scale\n return h\n if not h:\n if x and y:\n \n \n scale=2.0 **537\n return _sqrtprod(scale *x,scale *y)/scale\n return h\n \n \n d=sumprod((x,h),(y,-h))\n return h+d /(2.0 *h)\n \n \n \n \n \n \n \n \n \ndef covariance(x,y,/):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n n=len(x)\n if len(y)!=n:\n raise StatisticsError('covariance requires that both inputs have same number of data points')\n if n <2:\n raise StatisticsError('covariance requires at least two data points')\n xbar=fsum(x)/n\n ybar=fsum(y)/n\n sxy=sumprod((xi -xbar for xi in x),(yi -ybar for yi in y))\n return sxy /(n -1)\n \n \ndef correlation(x,y,/,*,method='linear'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n n=len(x)\n if len(y)!=n:\n raise StatisticsError('correlation requires that both inputs have same number of data points')\n if n <2:\n raise StatisticsError('correlation requires at least two data points')\n if method not in{'linear','ranked'}:\n raise ValueError(f'Unknown method: {method !r}')\n if method =='ranked':\n start=(n -1)/-2\n x=_rank(x,start=start)\n y=_rank(y,start=start)\n else:\n xbar=fsum(x)/n\n ybar=fsum(y)/n\n x=[xi -xbar for xi in x]\n y=[yi -ybar for yi in y]\n sxy=sumprod(x,y)\n sxx=sumprod(x,x)\n syy=sumprod(y,y)\n try:\n return sxy /_sqrtprod(sxx,syy)\n except ZeroDivisionError:\n raise StatisticsError('at least one of the inputs is constant')\n \n \nLinearRegression=namedtuple('LinearRegression',('slope','intercept'))\n\n\ndef linear_regression(x,y,/,*,proportional=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n n=len(x)\n if len(y)!=n:\n raise StatisticsError('linear regression requires that both inputs have same number of data points')\n if n <2:\n raise StatisticsError('linear regression requires at least two data points')\n if not proportional:\n xbar=fsum(x)/n\n ybar=fsum(y)/n\n x=[xi -xbar for xi in x]\n y=(yi -ybar for yi in y)\n sxy=sumprod(x,y)+0.0\n sxx=sumprod(x,x)\n try:\n slope=sxy /sxx\n except ZeroDivisionError:\n raise StatisticsError('x is constant')\n intercept=0.0 if proportional else ybar -slope *xbar\n return LinearRegression(slope=slope,intercept=intercept)\n \n \n \n \n \ndef _normal_dist_inv_cdf(p,mu,sigma):\n\n\n\n\n\n q=p -0.5\n if fabs(q)<=0.425:\n r=0.180625 -q *q\n \n num=(((((((2.50908_09287_30122_6727e+3 *r+\n 3.34305_75583_58812_8105e+4)*r+\n 6.72657_70927_00870_0853e+4)*r+\n 4.59219_53931_54987_1457e+4)*r+\n 1.37316_93765_50946_1125e+4)*r+\n 1.97159_09503_06551_4427e+3)*r+\n 1.33141_66789_17843_7745e+2)*r+\n 3.38713_28727_96366_6080e+0)*q\n den=(((((((5.22649_52788_52854_5610e+3 *r+\n 2.87290_85735_72194_2674e+4)*r+\n 3.93078_95800_09271_0610e+4)*r+\n 2.12137_94301_58659_5867e+4)*r+\n 5.39419_60214_24751_1077e+3)*r+\n 6.87187_00749_20579_0830e+2)*r+\n 4.23133_30701_60091_1252e+1)*r+\n 1.0)\n x=num /den\n return mu+(x *sigma)\n r=p if q <=0.0 else 1.0 -p\n r=sqrt(-log(r))\n if r <=5.0:\n r=r -1.6\n \n num=(((((((7.74545_01427_83414_07640e-4 *r+\n 2.27238_44989_26918_45833e-2)*r+\n 2.41780_72517_74506_11770e-1)*r+\n 1.27045_82524_52368_38258e+0)*r+\n 3.64784_83247_63204_60504e+0)*r+\n 5.76949_72214_60691_40550e+0)*r+\n 4.63033_78461_56545_29590e+0)*r+\n 1.42343_71107_49683_57734e+0)\n den=(((((((1.05075_00716_44416_84324e-9 *r+\n 5.47593_80849_95344_94600e-4)*r+\n 1.51986_66563_61645_71966e-2)*r+\n 1.48103_97642_74800_74590e-1)*r+\n 6.89767_33498_51000_04550e-1)*r+\n 1.67638_48301_83803_84940e+0)*r+\n 2.05319_16266_37758_82187e+0)*r+\n 1.0)\n else:\n r=r -5.0\n \n num=(((((((2.01033_43992_92288_13265e-7 *r+\n 2.71155_55687_43487_57815e-5)*r+\n 1.24266_09473_88078_43860e-3)*r+\n 2.65321_89526_57612_30930e-2)*r+\n 2.96560_57182_85048_91230e-1)*r+\n 1.78482_65399_17291_33580e+0)*r+\n 5.46378_49111_64114_36990e+0)*r+\n 6.65790_46435_01103_77720e+0)\n den=(((((((2.04426_31033_89939_78564e-15 *r+\n 1.42151_17583_16445_88870e-7)*r+\n 1.84631_83175_10054_68180e-5)*r+\n 7.86869_13114_56132_59100e-4)*r+\n 1.48753_61290_85061_48525e-2)*r+\n 1.36929_88092_27358_05310e-1)*r+\n 5.99832_20655_58879_37690e-1)*r+\n 1.0)\n x=num /den\n if q <0.0:\n x=-x\n return mu+(x *sigma)\n \n \n \ntry:\n from _statistics import _normal_dist_inv_cdf\nexcept ImportError:\n pass\n \n \nclass NormalDist:\n ''\n \n \n \n __slots__={\n '_mu':'Arithmetic mean of a normal distribution',\n '_sigma':'Standard deviation of a normal distribution',\n }\n \n def __init__(self,mu=0.0,sigma=1.0):\n ''\n if sigma <0.0:\n raise StatisticsError('sigma must be non-negative')\n self._mu=float(mu)\n self._sigma=float(sigma)\n \n @classmethod\n def from_samples(cls,data):\n ''\n return cls(*_mean_stdev(data))\n \n def samples(self,n,*,seed=None):\n ''\n rnd=random.random if seed is None else random.Random(seed).random\n inv_cdf=_normal_dist_inv_cdf\n mu=self._mu\n sigma=self._sigma\n return[inv_cdf(rnd(),mu,sigma)for _ in repeat(None,n)]\n \n def pdf(self,x):\n ''\n variance=self._sigma *self._sigma\n if not variance:\n raise StatisticsError('pdf() not defined when sigma is zero')\n diff=x -self._mu\n return exp(diff *diff /(-2.0 *variance))/sqrt(tau *variance)\n \n def cdf(self,x):\n ''\n if not self._sigma:\n raise StatisticsError('cdf() not defined when sigma is zero')\n return 0.5 *(1.0+erf((x -self._mu)/(self._sigma *_SQRT2)))\n \n def inv_cdf(self,p):\n ''\n\n\n\n\n\n\n\n \n if p <=0.0 or p >=1.0:\n raise StatisticsError('p must be in the range 0.0 < p < 1.0')\n return _normal_dist_inv_cdf(p,self._mu,self._sigma)\n \n def quantiles(self,n=4):\n ''\n\n\n\n\n\n\n \n return[self.inv_cdf(i /n)for i in range(1,n)]\n \n def overlap(self,other):\n ''\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n if not isinstance(other,NormalDist):\n raise TypeError('Expected another NormalDist instance')\n X,Y=self,other\n if(Y._sigma,Y._mu)<(X._sigma,X._mu):\n X,Y=Y,X\n X_var,Y_var=X.variance,Y.variance\n if not X_var or not Y_var:\n raise StatisticsError('overlap() not defined when sigma is zero')\n dv=Y_var -X_var\n dm=fabs(Y._mu -X._mu)\n if not dv:\n return 1.0 -erf(dm /(2.0 *X._sigma *_SQRT2))\n a=X._mu *Y_var -Y._mu *X_var\n b=X._sigma *Y._sigma *sqrt(dm *dm+dv *log(Y_var /X_var))\n x1=(a+b)/dv\n x2=(a -b)/dv\n return 1.0 -(fabs(Y.cdf(x1)-X.cdf(x1))+fabs(Y.cdf(x2)-X.cdf(x2)))\n \n def zscore(self,x):\n ''\n\n\n\n \n \n if not self._sigma:\n raise StatisticsError('zscore() not defined when sigma is zero')\n return(x -self._mu)/self._sigma\n \n @property\n def mean(self):\n ''\n return self._mu\n \n @property\n def median(self):\n ''\n return self._mu\n \n @property\n def mode(self):\n ''\n\n\n\n \n return self._mu\n \n @property\n def stdev(self):\n ''\n return self._sigma\n \n @property\n def variance(self):\n ''\n return self._sigma *self._sigma\n \n def __add__(x1,x2):\n ''\n\n\n\n\n\n\n\n \n if isinstance(x2,NormalDist):\n return NormalDist(x1._mu+x2._mu,hypot(x1._sigma,x2._sigma))\n return NormalDist(x1._mu+x2,x1._sigma)\n \n def __sub__(x1,x2):\n ''\n\n\n\n\n\n\n\n \n if isinstance(x2,NormalDist):\n return NormalDist(x1._mu -x2._mu,hypot(x1._sigma,x2._sigma))\n return NormalDist(x1._mu -x2,x1._sigma)\n \n def __mul__(x1,x2):\n ''\n\n\n\n \n return NormalDist(x1._mu *x2,x1._sigma *fabs(x2))\n \n def __truediv__(x1,x2):\n ''\n\n\n\n \n return NormalDist(x1._mu /x2,x1._sigma /fabs(x2))\n \n def __pos__(x1):\n ''\n return NormalDist(x1._mu,x1._sigma)\n \n def __neg__(x1):\n ''\n return NormalDist(-x1._mu,x1._sigma)\n \n __radd__=__add__\n \n def __rsub__(x1,x2):\n ''\n return -(x1 -x2)\n \n __rmul__=__mul__\n \n def __eq__(x1,x2):\n ''\n if not isinstance(x2,NormalDist):\n return NotImplemented\n return x1._mu ==x2._mu and x1._sigma ==x2._sigma\n \n def __hash__(self):\n ''\n return hash((self._mu,self._sigma))\n \n def __repr__(self):\n return f'{type(self).__name__}(mu={self._mu !r}, sigma={self._sigma !r})'\n \n def __getstate__(self):\n return self._mu,self._sigma\n \n def __setstate__(self,state):\n self._mu,self._sigma=state\n \n \n \n \ndef _newton_raphson(f_inv_estimate,f,f_prime,tolerance=1e-12):\n def f_inv(y):\n ''\n x=f_inv_estimate(y)\n while abs(diff :=f(x)-y)>tolerance:\n x -=diff /f_prime(x)\n return x\n return f_inv\n \ndef _quartic_invcdf_estimate(p):\n sign,p=(1.0,p)if p <=1 /2 else(-1.0,1.0 -p)\n x=(2.0 *p)**0.4258865685331 -1.0\n if p >=0.004 <0.499:\n x +=0.026818732 *sin(7.101753784 *p+2.73230839482953)\n return x *sign\n \n_quartic_invcdf=_newton_raphson(\nf_inv_estimate=_quartic_invcdf_estimate,\nf=lambda t:3 /16 *t **5 -5 /8 *t **3+15 /16 *t+1 /2,\nf_prime=lambda t:15 /16 *(1.0 -t *t)**2)\n\ndef _triweight_invcdf_estimate(p):\n sign,p=(1.0,p)if p <=1 /2 else(-1.0,1.0 -p)\n x=(2.0 *p)**0.3400218741872791 -1.0\n return x *sign\n \n_triweight_invcdf=_newton_raphson(\nf_inv_estimate=_triweight_invcdf_estimate,\nf=lambda t:35 /32 *(-1 /7 *t **7+3 /5 *t **5 -t **3+t)+1 /2,\nf_prime=lambda t:35 /32 *(1.0 -t *t)**3)\n\n_kernel_invcdfs={\n'normal':NormalDist().inv_cdf,\n'logistic':lambda p:log(p /(1 -p)),\n'sigmoid':lambda p:log(tan(p *pi /2)),\n'rectangular':lambda p:2 *p -1,\n'parabolic':lambda p:2 *cos((acos(2 *p -1)+pi)/3),\n'quartic':_quartic_invcdf,\n'triweight':_triweight_invcdf,\n'triangular':lambda p:sqrt(2 *p)-1 if p <1 /2 else 1 -sqrt(2 -2 *p),\n'cosine':lambda p:2 *asin(2 *p -1)/pi,\n}\n_kernel_invcdfs['gauss']=_kernel_invcdfs['normal']\n_kernel_invcdfs['uniform']=_kernel_invcdfs['rectangular']\n_kernel_invcdfs['epanechnikov']=_kernel_invcdfs['parabolic']\n_kernel_invcdfs['biweight']=_kernel_invcdfs['quartic']\n\ndef kde_random(data,h,kernel='normal',*,seed=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n n=len(data)\n if not n:\n raise StatisticsError('Empty data sequence')\n \n if not isinstance(data[0],(int,float)):\n raise TypeError('Data sequence must contain ints or floats')\n \n if h <=0.0:\n raise StatisticsError(f'Bandwidth h must be positive, not {h=!r}')\n \n kernel_invcdf=_kernel_invcdfs.get(kernel)\n if kernel_invcdf is None:\n raise StatisticsError(f'Unknown kernel name: {kernel !r}')\n \n prng=_random.Random(seed)\n random=prng.random\n choice=prng.choice\n \n def rand():\n return choice(data)+h *kernel_invcdf(random())\n \n rand.__doc__=f'Random KDE selection with {h=!r} and {kernel=!r}'\n \n return rand\n", ["_statistics", "bisect", "collections", "decimal", "fractions", "functools", "itertools", "math", "numbers", "operator", "random", "sys"]], "string": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\"ascii_letters\",\"ascii_lowercase\",\"ascii_uppercase\",\"capwords\",\n\"digits\",\"hexdigits\",\"octdigits\",\"printable\",\"punctuation\",\n\"whitespace\",\"Formatter\",\"Template\"]\n\nimport _string\n\n\nwhitespace=' \\t\\n\\r\\v\\f'\nascii_lowercase='abcdefghijklmnopqrstuvwxyz'\nascii_uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nascii_letters=ascii_lowercase+ascii_uppercase\ndigits='0123456789'\nhexdigits=digits+'abcdef'+'ABCDEF'\noctdigits='01234567'\npunctuation=r\"\"\"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\"\"\nprintable=digits+ascii_letters+punctuation+whitespace\n\n\n\n\ndef capwords(s,sep=None):\n ''\n\n\n\n\n\n\n\n\n \n return(sep or ' ').join(map(str.capitalize,s.split(sep)))\n \n \n \nimport re as _re\nfrom collections import ChainMap as _ChainMap\n\n_sentinel_dict={}\n\nclass Template:\n ''\n \n delimiter='$'\n \n \n \n \n idpattern=r'(?a:[_a-z][_a-z0-9]*)'\n braceidpattern=None\n flags=_re.IGNORECASE\n \n def __init_subclass__(cls):\n super().__init_subclass__()\n if 'pattern'in cls.__dict__:\n pattern=cls.pattern\n else:\n delim=_re.escape(cls.delimiter)\n id=cls.idpattern\n bid=cls.braceidpattern or cls.idpattern\n pattern=fr\"\"\"\n {delim}(?:\n (?P{delim}) | # Escape sequence of two delimiters\n (?P{id}) | # delimiter and a Python identifier\n {{(?P{bid})}} | # delimiter and a braced identifier\n (?P) # Other ill-formed delimiter exprs\n )\n \"\"\"\n cls.pattern=_re.compile(pattern,cls.flags |_re.VERBOSE)\n \n def __init__(self,template):\n self.template=template\n \n \n \n def _invalid(self,mo):\n i=mo.start('invalid')\n lines=self.template[:i].splitlines(keepends=True)\n if not lines:\n colno=1\n lineno=1\n else:\n colno=i -len(''.join(lines[:-1]))\n lineno=len(lines)\n raise ValueError('Invalid placeholder in string: line %d, col %d'%\n (lineno,colno))\n \n def substitute(self,mapping=_sentinel_dict,/,**kws):\n if mapping is _sentinel_dict:\n mapping=kws\n elif kws:\n mapping=_ChainMap(kws,mapping)\n \n def convert(mo):\n \n named=mo.group('named')or mo.group('braced')\n if named is not None:\n return str(mapping[named])\n if mo.group('escaped')is not None:\n return self.delimiter\n if mo.group('invalid')is not None:\n self._invalid(mo)\n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return self.pattern.sub(convert,self.template)\n \n def safe_substitute(self,mapping=_sentinel_dict,/,**kws):\n if mapping is _sentinel_dict:\n mapping=kws\n elif kws:\n mapping=_ChainMap(kws,mapping)\n \n def convert(mo):\n named=mo.group('named')or mo.group('braced')\n if named is not None:\n try:\n return str(mapping[named])\n except KeyError:\n return mo.group()\n if mo.group('escaped')is not None:\n return self.delimiter\n if mo.group('invalid')is not None:\n return mo.group()\n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return self.pattern.sub(convert,self.template)\n \n def is_valid(self):\n for mo in self.pattern.finditer(self.template):\n if mo.group('invalid')is not None:\n return False\n if(mo.group('named')is None\n and mo.group('braced')is None\n and mo.group('escaped')is None):\n \n \n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return True\n \n def get_identifiers(self):\n ids=[]\n for mo in self.pattern.finditer(self.template):\n named=mo.group('named')or mo.group('braced')\n if named is not None and named not in ids:\n \n ids.append(named)\n elif(named is None\n and mo.group('invalid')is None\n and mo.group('escaped')is None):\n \n \n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return ids\n \n \n \nTemplate.__init_subclass__()\n\n\n\n\n\n\n\n\n\n\n\n\nclass Formatter:\n def format(self,format_string,/,*args,**kwargs):\n return self.vformat(format_string,args,kwargs)\n \n def vformat(self,format_string,args,kwargs):\n used_args=set()\n result,_=self._vformat(format_string,args,kwargs,used_args,2)\n self.check_unused_args(used_args,args,kwargs)\n return result\n \n def _vformat(self,format_string,args,kwargs,used_args,recursion_depth,\n auto_arg_index=0):\n if recursion_depth <0:\n raise ValueError('Max string recursion exceeded')\n result=[]\n for literal_text,field_name,format_spec,conversion in\\\n self.parse(format_string):\n \n \n if literal_text:\n result.append(literal_text)\n \n \n if field_name is not None:\n \n \n \n \n if field_name =='':\n if auto_arg_index is False:\n raise ValueError('cannot switch from manual field '\n 'specification to automatic field '\n 'numbering')\n field_name=str(auto_arg_index)\n auto_arg_index +=1\n elif field_name.isdigit():\n if auto_arg_index:\n raise ValueError('cannot switch from manual field '\n 'specification to automatic field '\n 'numbering')\n \n \n auto_arg_index=False\n \n \n \n obj,arg_used=self.get_field(field_name,args,kwargs)\n used_args.add(arg_used)\n \n \n obj=self.convert_field(obj,conversion)\n \n \n format_spec,auto_arg_index=self._vformat(\n format_spec,args,kwargs,\n used_args,recursion_depth -1,\n auto_arg_index=auto_arg_index)\n \n \n result.append(self.format_field(obj,format_spec))\n \n return ''.join(result),auto_arg_index\n \n \n def get_value(self,key,args,kwargs):\n if isinstance(key,int):\n return args[key]\n else:\n return kwargs[key]\n \n \n def check_unused_args(self,used_args,args,kwargs):\n pass\n \n \n def format_field(self,value,format_spec):\n return format(value,format_spec)\n \n \n def convert_field(self,value,conversion):\n \n if conversion is None:\n return value\n elif conversion =='s':\n return str(value)\n elif conversion =='r':\n return repr(value)\n elif conversion =='a':\n return ascii(value)\n raise ValueError(\"Unknown conversion specifier {0!s}\".format(conversion))\n \n \n \n \n \n \n \n \n \n def parse(self,format_string):\n return _string.formatter_parser(format_string)\n \n \n \n \n \n \n \n def get_field(self,field_name,args,kwargs):\n first,rest=_string.formatter_field_name_split(field_name)\n \n obj=self.get_value(first,args,kwargs)\n \n \n \n for is_attr,i in rest:\n if is_attr:\n obj=getattr(obj,i)\n else:\n obj=obj[i]\n \n return obj,first\n", ["_string", "collections", "re"]], "stringprep": [".py", "\n''\n\n\n\n\n\nfrom unicodedata import ucd_3_2_0 as unicodedata\n\nassert unicodedata.unidata_version =='3.2.0'\n\ndef in_table_a1(code):\n if unicodedata.category(code)!='Cn':return False\n c=ord(code)\n if 0xFDD0 <=c <0xFDF0:return False\n return(c&0xFFFF)not in(0xFFFE,0xFFFF)\n \n \nb1_set=set([173,847,6150,6155,6156,6157,8203,8204,8205,8288,65279]+list(range(65024,65040)))\ndef in_table_b1(code):\n return ord(code)in b1_set\n \n \nb3_exceptions={\n0xb5:'\\u03bc',0xdf:'ss',0x130:'i\\u0307',0x149:'\\u02bcn',\n0x17f:'s',0x1f0:'j\\u030c',0x345:'\\u03b9',0x37a:' \\u03b9',\n0x390:'\\u03b9\\u0308\\u0301',0x3b0:'\\u03c5\\u0308\\u0301',0x3c2:'\\u03c3',0x3d0:'\\u03b2',\n0x3d1:'\\u03b8',0x3d2:'\\u03c5',0x3d3:'\\u03cd',0x3d4:'\\u03cb',\n0x3d5:'\\u03c6',0x3d6:'\\u03c0',0x3f0:'\\u03ba',0x3f1:'\\u03c1',\n0x3f2:'\\u03c3',0x3f5:'\\u03b5',0x587:'\\u0565\\u0582',0x1e96:'h\\u0331',\n0x1e97:'t\\u0308',0x1e98:'w\\u030a',0x1e99:'y\\u030a',0x1e9a:'a\\u02be',\n0x1e9b:'\\u1e61',0x1f50:'\\u03c5\\u0313',0x1f52:'\\u03c5\\u0313\\u0300',0x1f54:'\\u03c5\\u0313\\u0301',\n0x1f56:'\\u03c5\\u0313\\u0342',0x1f80:'\\u1f00\\u03b9',0x1f81:'\\u1f01\\u03b9',0x1f82:'\\u1f02\\u03b9',\n0x1f83:'\\u1f03\\u03b9',0x1f84:'\\u1f04\\u03b9',0x1f85:'\\u1f05\\u03b9',0x1f86:'\\u1f06\\u03b9',\n0x1f87:'\\u1f07\\u03b9',0x1f88:'\\u1f00\\u03b9',0x1f89:'\\u1f01\\u03b9',0x1f8a:'\\u1f02\\u03b9',\n0x1f8b:'\\u1f03\\u03b9',0x1f8c:'\\u1f04\\u03b9',0x1f8d:'\\u1f05\\u03b9',0x1f8e:'\\u1f06\\u03b9',\n0x1f8f:'\\u1f07\\u03b9',0x1f90:'\\u1f20\\u03b9',0x1f91:'\\u1f21\\u03b9',0x1f92:'\\u1f22\\u03b9',\n0x1f93:'\\u1f23\\u03b9',0x1f94:'\\u1f24\\u03b9',0x1f95:'\\u1f25\\u03b9',0x1f96:'\\u1f26\\u03b9',\n0x1f97:'\\u1f27\\u03b9',0x1f98:'\\u1f20\\u03b9',0x1f99:'\\u1f21\\u03b9',0x1f9a:'\\u1f22\\u03b9',\n0x1f9b:'\\u1f23\\u03b9',0x1f9c:'\\u1f24\\u03b9',0x1f9d:'\\u1f25\\u03b9',0x1f9e:'\\u1f26\\u03b9',\n0x1f9f:'\\u1f27\\u03b9',0x1fa0:'\\u1f60\\u03b9',0x1fa1:'\\u1f61\\u03b9',0x1fa2:'\\u1f62\\u03b9',\n0x1fa3:'\\u1f63\\u03b9',0x1fa4:'\\u1f64\\u03b9',0x1fa5:'\\u1f65\\u03b9',0x1fa6:'\\u1f66\\u03b9',\n0x1fa7:'\\u1f67\\u03b9',0x1fa8:'\\u1f60\\u03b9',0x1fa9:'\\u1f61\\u03b9',0x1faa:'\\u1f62\\u03b9',\n0x1fab:'\\u1f63\\u03b9',0x1fac:'\\u1f64\\u03b9',0x1fad:'\\u1f65\\u03b9',0x1fae:'\\u1f66\\u03b9',\n0x1faf:'\\u1f67\\u03b9',0x1fb2:'\\u1f70\\u03b9',0x1fb3:'\\u03b1\\u03b9',0x1fb4:'\\u03ac\\u03b9',\n0x1fb6:'\\u03b1\\u0342',0x1fb7:'\\u03b1\\u0342\\u03b9',0x1fbc:'\\u03b1\\u03b9',0x1fbe:'\\u03b9',\n0x1fc2:'\\u1f74\\u03b9',0x1fc3:'\\u03b7\\u03b9',0x1fc4:'\\u03ae\\u03b9',0x1fc6:'\\u03b7\\u0342',\n0x1fc7:'\\u03b7\\u0342\\u03b9',0x1fcc:'\\u03b7\\u03b9',0x1fd2:'\\u03b9\\u0308\\u0300',0x1fd3:'\\u03b9\\u0308\\u0301',\n0x1fd6:'\\u03b9\\u0342',0x1fd7:'\\u03b9\\u0308\\u0342',0x1fe2:'\\u03c5\\u0308\\u0300',0x1fe3:'\\u03c5\\u0308\\u0301',\n0x1fe4:'\\u03c1\\u0313',0x1fe6:'\\u03c5\\u0342',0x1fe7:'\\u03c5\\u0308\\u0342',0x1ff2:'\\u1f7c\\u03b9',\n0x1ff3:'\\u03c9\\u03b9',0x1ff4:'\\u03ce\\u03b9',0x1ff6:'\\u03c9\\u0342',0x1ff7:'\\u03c9\\u0342\\u03b9',\n0x1ffc:'\\u03c9\\u03b9',0x20a8:'rs',0x2102:'c',0x2103:'\\xb0c',\n0x2107:'\\u025b',0x2109:'\\xb0f',0x210b:'h',0x210c:'h',\n0x210d:'h',0x2110:'i',0x2111:'i',0x2112:'l',\n0x2115:'n',0x2116:'no',0x2119:'p',0x211a:'q',\n0x211b:'r',0x211c:'r',0x211d:'r',0x2120:'sm',\n0x2121:'tel',0x2122:'tm',0x2124:'z',0x2128:'z',\n0x212c:'b',0x212d:'c',0x2130:'e',0x2131:'f',\n0x2133:'m',0x213e:'\\u03b3',0x213f:'\\u03c0',0x2145:'d',\n0x3371:'hpa',0x3373:'au',0x3375:'ov',0x3380:'pa',\n0x3381:'na',0x3382:'\\u03bca',0x3383:'ma',0x3384:'ka',\n0x3385:'kb',0x3386:'mb',0x3387:'gb',0x338a:'pf',\n0x338b:'nf',0x338c:'\\u03bcf',0x3390:'hz',0x3391:'khz',\n0x3392:'mhz',0x3393:'ghz',0x3394:'thz',0x33a9:'pa',\n0x33aa:'kpa',0x33ab:'mpa',0x33ac:'gpa',0x33b4:'pv',\n0x33b5:'nv',0x33b6:'\\u03bcv',0x33b7:'mv',0x33b8:'kv',\n0x33b9:'mv',0x33ba:'pw',0x33bb:'nw',0x33bc:'\\u03bcw',\n0x33bd:'mw',0x33be:'kw',0x33bf:'mw',0x33c0:'k\\u03c9',\n0x33c1:'m\\u03c9',0x33c3:'bq',0x33c6:'c\\u2215kg',0x33c7:'co.',\n0x33c8:'db',0x33c9:'gy',0x33cb:'hp',0x33cd:'kk',\n0x33ce:'km',0x33d7:'ph',0x33d9:'ppm',0x33da:'pr',\n0x33dc:'sv',0x33dd:'wb',0xfb00:'ff',0xfb01:'fi',\n0xfb02:'fl',0xfb03:'ffi',0xfb04:'ffl',0xfb05:'st',\n0xfb06:'st',0xfb13:'\\u0574\\u0576',0xfb14:'\\u0574\\u0565',0xfb15:'\\u0574\\u056b',\n0xfb16:'\\u057e\\u0576',0xfb17:'\\u0574\\u056d',0x1d400:'a',0x1d401:'b',\n0x1d402:'c',0x1d403:'d',0x1d404:'e',0x1d405:'f',\n0x1d406:'g',0x1d407:'h',0x1d408:'i',0x1d409:'j',\n0x1d40a:'k',0x1d40b:'l',0x1d40c:'m',0x1d40d:'n',\n0x1d40e:'o',0x1d40f:'p',0x1d410:'q',0x1d411:'r',\n0x1d412:'s',0x1d413:'t',0x1d414:'u',0x1d415:'v',\n0x1d416:'w',0x1d417:'x',0x1d418:'y',0x1d419:'z',\n0x1d434:'a',0x1d435:'b',0x1d436:'c',0x1d437:'d',\n0x1d438:'e',0x1d439:'f',0x1d43a:'g',0x1d43b:'h',\n0x1d43c:'i',0x1d43d:'j',0x1d43e:'k',0x1d43f:'l',\n0x1d440:'m',0x1d441:'n',0x1d442:'o',0x1d443:'p',\n0x1d444:'q',0x1d445:'r',0x1d446:'s',0x1d447:'t',\n0x1d448:'u',0x1d449:'v',0x1d44a:'w',0x1d44b:'x',\n0x1d44c:'y',0x1d44d:'z',0x1d468:'a',0x1d469:'b',\n0x1d46a:'c',0x1d46b:'d',0x1d46c:'e',0x1d46d:'f',\n0x1d46e:'g',0x1d46f:'h',0x1d470:'i',0x1d471:'j',\n0x1d472:'k',0x1d473:'l',0x1d474:'m',0x1d475:'n',\n0x1d476:'o',0x1d477:'p',0x1d478:'q',0x1d479:'r',\n0x1d47a:'s',0x1d47b:'t',0x1d47c:'u',0x1d47d:'v',\n0x1d47e:'w',0x1d47f:'x',0x1d480:'y',0x1d481:'z',\n0x1d49c:'a',0x1d49e:'c',0x1d49f:'d',0x1d4a2:'g',\n0x1d4a5:'j',0x1d4a6:'k',0x1d4a9:'n',0x1d4aa:'o',\n0x1d4ab:'p',0x1d4ac:'q',0x1d4ae:'s',0x1d4af:'t',\n0x1d4b0:'u',0x1d4b1:'v',0x1d4b2:'w',0x1d4b3:'x',\n0x1d4b4:'y',0x1d4b5:'z',0x1d4d0:'a',0x1d4d1:'b',\n0x1d4d2:'c',0x1d4d3:'d',0x1d4d4:'e',0x1d4d5:'f',\n0x1d4d6:'g',0x1d4d7:'h',0x1d4d8:'i',0x1d4d9:'j',\n0x1d4da:'k',0x1d4db:'l',0x1d4dc:'m',0x1d4dd:'n',\n0x1d4de:'o',0x1d4df:'p',0x1d4e0:'q',0x1d4e1:'r',\n0x1d4e2:'s',0x1d4e3:'t',0x1d4e4:'u',0x1d4e5:'v',\n0x1d4e6:'w',0x1d4e7:'x',0x1d4e8:'y',0x1d4e9:'z',\n0x1d504:'a',0x1d505:'b',0x1d507:'d',0x1d508:'e',\n0x1d509:'f',0x1d50a:'g',0x1d50d:'j',0x1d50e:'k',\n0x1d50f:'l',0x1d510:'m',0x1d511:'n',0x1d512:'o',\n0x1d513:'p',0x1d514:'q',0x1d516:'s',0x1d517:'t',\n0x1d518:'u',0x1d519:'v',0x1d51a:'w',0x1d51b:'x',\n0x1d51c:'y',0x1d538:'a',0x1d539:'b',0x1d53b:'d',\n0x1d53c:'e',0x1d53d:'f',0x1d53e:'g',0x1d540:'i',\n0x1d541:'j',0x1d542:'k',0x1d543:'l',0x1d544:'m',\n0x1d546:'o',0x1d54a:'s',0x1d54b:'t',0x1d54c:'u',\n0x1d54d:'v',0x1d54e:'w',0x1d54f:'x',0x1d550:'y',\n0x1d56c:'a',0x1d56d:'b',0x1d56e:'c',0x1d56f:'d',\n0x1d570:'e',0x1d571:'f',0x1d572:'g',0x1d573:'h',\n0x1d574:'i',0x1d575:'j',0x1d576:'k',0x1d577:'l',\n0x1d578:'m',0x1d579:'n',0x1d57a:'o',0x1d57b:'p',\n0x1d57c:'q',0x1d57d:'r',0x1d57e:'s',0x1d57f:'t',\n0x1d580:'u',0x1d581:'v',0x1d582:'w',0x1d583:'x',\n0x1d584:'y',0x1d585:'z',0x1d5a0:'a',0x1d5a1:'b',\n0x1d5a2:'c',0x1d5a3:'d',0x1d5a4:'e',0x1d5a5:'f',\n0x1d5a6:'g',0x1d5a7:'h',0x1d5a8:'i',0x1d5a9:'j',\n0x1d5aa:'k',0x1d5ab:'l',0x1d5ac:'m',0x1d5ad:'n',\n0x1d5ae:'o',0x1d5af:'p',0x1d5b0:'q',0x1d5b1:'r',\n0x1d5b2:'s',0x1d5b3:'t',0x1d5b4:'u',0x1d5b5:'v',\n0x1d5b6:'w',0x1d5b7:'x',0x1d5b8:'y',0x1d5b9:'z',\n0x1d5d4:'a',0x1d5d5:'b',0x1d5d6:'c',0x1d5d7:'d',\n0x1d5d8:'e',0x1d5d9:'f',0x1d5da:'g',0x1d5db:'h',\n0x1d5dc:'i',0x1d5dd:'j',0x1d5de:'k',0x1d5df:'l',\n0x1d5e0:'m',0x1d5e1:'n',0x1d5e2:'o',0x1d5e3:'p',\n0x1d5e4:'q',0x1d5e5:'r',0x1d5e6:'s',0x1d5e7:'t',\n0x1d5e8:'u',0x1d5e9:'v',0x1d5ea:'w',0x1d5eb:'x',\n0x1d5ec:'y',0x1d5ed:'z',0x1d608:'a',0x1d609:'b',\n0x1d60a:'c',0x1d60b:'d',0x1d60c:'e',0x1d60d:'f',\n0x1d60e:'g',0x1d60f:'h',0x1d610:'i',0x1d611:'j',\n0x1d612:'k',0x1d613:'l',0x1d614:'m',0x1d615:'n',\n0x1d616:'o',0x1d617:'p',0x1d618:'q',0x1d619:'r',\n0x1d61a:'s',0x1d61b:'t',0x1d61c:'u',0x1d61d:'v',\n0x1d61e:'w',0x1d61f:'x',0x1d620:'y',0x1d621:'z',\n0x1d63c:'a',0x1d63d:'b',0x1d63e:'c',0x1d63f:'d',\n0x1d640:'e',0x1d641:'f',0x1d642:'g',0x1d643:'h',\n0x1d644:'i',0x1d645:'j',0x1d646:'k',0x1d647:'l',\n0x1d648:'m',0x1d649:'n',0x1d64a:'o',0x1d64b:'p',\n0x1d64c:'q',0x1d64d:'r',0x1d64e:'s',0x1d64f:'t',\n0x1d650:'u',0x1d651:'v',0x1d652:'w',0x1d653:'x',\n0x1d654:'y',0x1d655:'z',0x1d670:'a',0x1d671:'b',\n0x1d672:'c',0x1d673:'d',0x1d674:'e',0x1d675:'f',\n0x1d676:'g',0x1d677:'h',0x1d678:'i',0x1d679:'j',\n0x1d67a:'k',0x1d67b:'l',0x1d67c:'m',0x1d67d:'n',\n0x1d67e:'o',0x1d67f:'p',0x1d680:'q',0x1d681:'r',\n0x1d682:'s',0x1d683:'t',0x1d684:'u',0x1d685:'v',\n0x1d686:'w',0x1d687:'x',0x1d688:'y',0x1d689:'z',\n0x1d6a8:'\\u03b1',0x1d6a9:'\\u03b2',0x1d6aa:'\\u03b3',0x1d6ab:'\\u03b4',\n0x1d6ac:'\\u03b5',0x1d6ad:'\\u03b6',0x1d6ae:'\\u03b7',0x1d6af:'\\u03b8',\n0x1d6b0:'\\u03b9',0x1d6b1:'\\u03ba',0x1d6b2:'\\u03bb',0x1d6b3:'\\u03bc',\n0x1d6b4:'\\u03bd',0x1d6b5:'\\u03be',0x1d6b6:'\\u03bf',0x1d6b7:'\\u03c0',\n0x1d6b8:'\\u03c1',0x1d6b9:'\\u03b8',0x1d6ba:'\\u03c3',0x1d6bb:'\\u03c4',\n0x1d6bc:'\\u03c5',0x1d6bd:'\\u03c6',0x1d6be:'\\u03c7',0x1d6bf:'\\u03c8',\n0x1d6c0:'\\u03c9',0x1d6d3:'\\u03c3',0x1d6e2:'\\u03b1',0x1d6e3:'\\u03b2',\n0x1d6e4:'\\u03b3',0x1d6e5:'\\u03b4',0x1d6e6:'\\u03b5',0x1d6e7:'\\u03b6',\n0x1d6e8:'\\u03b7',0x1d6e9:'\\u03b8',0x1d6ea:'\\u03b9',0x1d6eb:'\\u03ba',\n0x1d6ec:'\\u03bb',0x1d6ed:'\\u03bc',0x1d6ee:'\\u03bd',0x1d6ef:'\\u03be',\n0x1d6f0:'\\u03bf',0x1d6f1:'\\u03c0',0x1d6f2:'\\u03c1',0x1d6f3:'\\u03b8',\n0x1d6f4:'\\u03c3',0x1d6f5:'\\u03c4',0x1d6f6:'\\u03c5',0x1d6f7:'\\u03c6',\n0x1d6f8:'\\u03c7',0x1d6f9:'\\u03c8',0x1d6fa:'\\u03c9',0x1d70d:'\\u03c3',\n0x1d71c:'\\u03b1',0x1d71d:'\\u03b2',0x1d71e:'\\u03b3',0x1d71f:'\\u03b4',\n0x1d720:'\\u03b5',0x1d721:'\\u03b6',0x1d722:'\\u03b7',0x1d723:'\\u03b8',\n0x1d724:'\\u03b9',0x1d725:'\\u03ba',0x1d726:'\\u03bb',0x1d727:'\\u03bc',\n0x1d728:'\\u03bd',0x1d729:'\\u03be',0x1d72a:'\\u03bf',0x1d72b:'\\u03c0',\n0x1d72c:'\\u03c1',0x1d72d:'\\u03b8',0x1d72e:'\\u03c3',0x1d72f:'\\u03c4',\n0x1d730:'\\u03c5',0x1d731:'\\u03c6',0x1d732:'\\u03c7',0x1d733:'\\u03c8',\n0x1d734:'\\u03c9',0x1d747:'\\u03c3',0x1d756:'\\u03b1',0x1d757:'\\u03b2',\n0x1d758:'\\u03b3',0x1d759:'\\u03b4',0x1d75a:'\\u03b5',0x1d75b:'\\u03b6',\n0x1d75c:'\\u03b7',0x1d75d:'\\u03b8',0x1d75e:'\\u03b9',0x1d75f:'\\u03ba',\n0x1d760:'\\u03bb',0x1d761:'\\u03bc',0x1d762:'\\u03bd',0x1d763:'\\u03be',\n0x1d764:'\\u03bf',0x1d765:'\\u03c0',0x1d766:'\\u03c1',0x1d767:'\\u03b8',\n0x1d768:'\\u03c3',0x1d769:'\\u03c4',0x1d76a:'\\u03c5',0x1d76b:'\\u03c6',\n0x1d76c:'\\u03c7',0x1d76d:'\\u03c8',0x1d76e:'\\u03c9',0x1d781:'\\u03c3',\n0x1d790:'\\u03b1',0x1d791:'\\u03b2',0x1d792:'\\u03b3',0x1d793:'\\u03b4',\n0x1d794:'\\u03b5',0x1d795:'\\u03b6',0x1d796:'\\u03b7',0x1d797:'\\u03b8',\n0x1d798:'\\u03b9',0x1d799:'\\u03ba',0x1d79a:'\\u03bb',0x1d79b:'\\u03bc',\n0x1d79c:'\\u03bd',0x1d79d:'\\u03be',0x1d79e:'\\u03bf',0x1d79f:'\\u03c0',\n0x1d7a0:'\\u03c1',0x1d7a1:'\\u03b8',0x1d7a2:'\\u03c3',0x1d7a3:'\\u03c4',\n0x1d7a4:'\\u03c5',0x1d7a5:'\\u03c6',0x1d7a6:'\\u03c7',0x1d7a7:'\\u03c8',\n0x1d7a8:'\\u03c9',0x1d7bb:'\\u03c3',}\n\ndef map_table_b3(code):\n r=b3_exceptions.get(ord(code))\n if r is not None:return r\n return code.lower()\n \n \ndef map_table_b2(a):\n al=map_table_b3(a)\n b=unicodedata.normalize(\"NFKC\",al)\n bl=\"\".join([map_table_b3(ch)for ch in b])\n c=unicodedata.normalize(\"NFKC\",bl)\n if b !=c:\n return c\n else:\n return al\n \n \ndef in_table_c11(code):\n return code ==\" \"\n \n \ndef in_table_c12(code):\n return unicodedata.category(code)==\"Zs\"and code !=\" \"\n \ndef in_table_c11_c12(code):\n return unicodedata.category(code)==\"Zs\"\n \n \ndef in_table_c21(code):\n return ord(code)<128 and unicodedata.category(code)==\"Cc\"\n \nc22_specials=set([1757,1807,6158,8204,8205,8232,8233,65279]+list(range(8288,8292))+list(range(8298,8304))+list(range(65529,65533))+list(range(119155,119163)))\ndef in_table_c22(code):\n c=ord(code)\n if c <128:return False\n if unicodedata.category(code)==\"Cc\":return True\n return c in c22_specials\n \ndef in_table_c21_c22(code):\n return unicodedata.category(code)==\"Cc\"or\\\n ord(code)in c22_specials\n \n \ndef in_table_c3(code):\n return unicodedata.category(code)==\"Co\"\n \n \ndef in_table_c4(code):\n c=ord(code)\n if c <0xFDD0:return False\n if c <0xFDF0:return True\n return(ord(code)&0xFFFF)in(0xFFFE,0xFFFF)\n \n \ndef in_table_c5(code):\n return unicodedata.category(code)==\"Cs\"\n \n \nc6_set=set(range(65529,65534))\ndef in_table_c6(code):\n return ord(code)in c6_set\n \n \nc7_set=set(range(12272,12284))\ndef in_table_c7(code):\n return ord(code)in c7_set\n \n \nc8_set=set([832,833,8206,8207]+list(range(8234,8239))+list(range(8298,8304)))\ndef in_table_c8(code):\n return ord(code)in c8_set\n \n \nc9_set=set([917505]+list(range(917536,917632)))\ndef in_table_c9(code):\n return ord(code)in c9_set\n \n \ndef in_table_d1(code):\n return unicodedata.bidirectional(code)in(\"R\",\"AL\")\n \n \ndef in_table_d2(code):\n return unicodedata.bidirectional(code)==\"L\"\n", ["unicodedata"]], "struct": [".py", "__all__=[\n\n'calcsize','pack','pack_into','unpack','unpack_from',\n'iter_unpack',\n\n\n'Struct',\n\n\n'error'\n]\n\nfrom _struct import *\nfrom _struct import _clearcache\nfrom _struct import __doc__\n", ["_struct"]], "subprocess": [".py", "\n\n\n\n\n\n\n\nr\"\"\"Subprocesses with accessible I/O streams\n\nThis module allows you to spawn processes, connect to their\ninput/output/error pipes, and obtain their return codes.\n\nFor a complete description of this module see the Python documentation.\n\nMain API\n========\nrun(...): Runs a command, waits for it to complete, then returns a\n CompletedProcess instance.\nPopen(...): A class for flexibly executing a command in a new process\n\nConstants\n---------\nDEVNULL: Special value that indicates that os.devnull should be used\nPIPE: Special value that indicates a pipe should be created\nSTDOUT: Special value that indicates that stderr should go to stdout\n\n\nOlder API\n=========\ncall(...): Runs a command, waits for it to complete, then returns\n the return code.\ncheck_call(...): Same as call() but raises CalledProcessError()\n if return code is not 0\ncheck_output(...): Same as check_call() but returns the contents of\n stdout instead of a return code\ngetoutput(...): Runs a command in the shell, waits for it to complete,\n then returns the output\ngetstatusoutput(...): Runs a command in the shell, waits for it to complete,\n then returns a (exitcode, output) tuple\n\"\"\"\n\nimport builtins\nimport errno\nimport io\nimport locale\nimport os\nimport time\nimport signal\nimport sys\nimport threading\nimport warnings\nimport contextlib\nfrom time import monotonic as _time\nimport types\n\ntry:\n import fcntl\nexcept ImportError:\n fcntl=None\n \n \n__all__=[\"Popen\",\"PIPE\",\"STDOUT\",\"call\",\"check_call\",\"getstatusoutput\",\n\"getoutput\",\"check_output\",\"run\",\"CalledProcessError\",\"DEVNULL\",\n\"SubprocessError\",\"TimeoutExpired\",\"CompletedProcess\"]\n\n\n\n\ntry:\n import msvcrt\nexcept ModuleNotFoundError:\n _mswindows=False\nelse:\n _mswindows=True\n \n \n_can_fork_exec=sys.platform not in{\"emscripten\",\"wasi\",\"ios\",\"tvos\",\"watchos\"}\n\nif _mswindows:\n import _winapi\n from _winapi import(CREATE_NEW_CONSOLE,CREATE_NEW_PROCESS_GROUP,\n STD_INPUT_HANDLE,STD_OUTPUT_HANDLE,\n STD_ERROR_HANDLE,SW_HIDE,\n STARTF_USESTDHANDLES,STARTF_USESHOWWINDOW,\n STARTF_FORCEONFEEDBACK,STARTF_FORCEOFFFEEDBACK,\n ABOVE_NORMAL_PRIORITY_CLASS,BELOW_NORMAL_PRIORITY_CLASS,\n HIGH_PRIORITY_CLASS,IDLE_PRIORITY_CLASS,\n NORMAL_PRIORITY_CLASS,REALTIME_PRIORITY_CLASS,\n CREATE_NO_WINDOW,DETACHED_PROCESS,\n CREATE_DEFAULT_ERROR_MODE,CREATE_BREAKAWAY_FROM_JOB)\n \n __all__.extend([\"CREATE_NEW_CONSOLE\",\"CREATE_NEW_PROCESS_GROUP\",\n \"STD_INPUT_HANDLE\",\"STD_OUTPUT_HANDLE\",\n \"STD_ERROR_HANDLE\",\"SW_HIDE\",\n \"STARTF_USESTDHANDLES\",\"STARTF_USESHOWWINDOW\",\n \"STARTF_FORCEONFEEDBACK\",\"STARTF_FORCEOFFFEEDBACK\",\n \"STARTUPINFO\",\n \"ABOVE_NORMAL_PRIORITY_CLASS\",\"BELOW_NORMAL_PRIORITY_CLASS\",\n \"HIGH_PRIORITY_CLASS\",\"IDLE_PRIORITY_CLASS\",\n \"NORMAL_PRIORITY_CLASS\",\"REALTIME_PRIORITY_CLASS\",\n \"CREATE_NO_WINDOW\",\"DETACHED_PROCESS\",\n \"CREATE_DEFAULT_ERROR_MODE\",\"CREATE_BREAKAWAY_FROM_JOB\"])\nelse:\n if _can_fork_exec:\n from _posixsubprocess import fork_exec as _fork_exec\n \n class _del_safe:\n waitpid=os.waitpid\n waitstatus_to_exitcode=os.waitstatus_to_exitcode\n WIFSTOPPED=os.WIFSTOPPED\n WSTOPSIG=os.WSTOPSIG\n WNOHANG=os.WNOHANG\n ECHILD=errno.ECHILD\n else:\n class _del_safe:\n waitpid=None\n waitstatus_to_exitcode=None\n WIFSTOPPED=None\n WSTOPSIG=None\n WNOHANG=None\n ECHILD=errno.ECHILD\n \n import select\n import selectors\n \n \n \nclass SubprocessError(Exception):pass\n\n\nclass CalledProcessError(SubprocessError):\n ''\n\n\n\n\n \n def __init__(self,returncode,cmd,output=None,stderr=None):\n self.returncode=returncode\n self.cmd=cmd\n self.output=output\n self.stderr=stderr\n \n def __str__(self):\n if self.returncode and self.returncode <0:\n try:\n return \"Command '%s' died with %r.\"%(\n self.cmd,signal.Signals(-self.returncode))\n except ValueError:\n return \"Command '%s' died with unknown signal %d.\"%(\n self.cmd,-self.returncode)\n else:\n return \"Command '%s' returned non-zero exit status %d.\"%(\n self.cmd,self.returncode)\n \n @property\n def stdout(self):\n ''\n return self.output\n \n @stdout.setter\n def stdout(self,value):\n \n \n self.output=value\n \n \nclass TimeoutExpired(SubprocessError):\n ''\n\n\n\n\n \n def __init__(self,cmd,timeout,output=None,stderr=None):\n self.cmd=cmd\n self.timeout=timeout\n self.output=output\n self.stderr=stderr\n \n def __str__(self):\n return(\"Command '%s' timed out after %s seconds\"%\n (self.cmd,self.timeout))\n \n @property\n def stdout(self):\n return self.output\n \n @stdout.setter\n def stdout(self,value):\n \n \n self.output=value\n \n \nif _mswindows:\n class STARTUPINFO:\n def __init__(self,*,dwFlags=0,hStdInput=None,hStdOutput=None,\n hStdError=None,wShowWindow=0,lpAttributeList=None):\n self.dwFlags=dwFlags\n self.hStdInput=hStdInput\n self.hStdOutput=hStdOutput\n self.hStdError=hStdError\n self.wShowWindow=wShowWindow\n self.lpAttributeList=lpAttributeList or{\"handle_list\":[]}\n \n def copy(self):\n attr_list=self.lpAttributeList.copy()\n if 'handle_list'in attr_list:\n attr_list['handle_list']=list(attr_list['handle_list'])\n \n return STARTUPINFO(dwFlags=self.dwFlags,\n hStdInput=self.hStdInput,\n hStdOutput=self.hStdOutput,\n hStdError=self.hStdError,\n wShowWindow=self.wShowWindow,\n lpAttributeList=attr_list)\n \n \n class Handle(int):\n closed=False\n \n def Close(self,CloseHandle=_winapi.CloseHandle):\n if not self.closed:\n self.closed=True\n CloseHandle(self)\n \n def Detach(self):\n if not self.closed:\n self.closed=True\n return int(self)\n raise ValueError(\"already closed\")\n \n def __repr__(self):\n return \"%s(%d)\"%(self.__class__.__name__,int(self))\n \n __del__=Close\nelse:\n\n\n\n _PIPE_BUF=getattr(select,'PIPE_BUF',512)\n \n \n \n \n if hasattr(selectors,'PollSelector'):\n _PopenSelector=selectors.PollSelector\n else:\n _PopenSelector=selectors.SelectSelector\n \n \nif _mswindows:\n\n\n\n\n\n\n\n\n _active=None\n \n def _cleanup():\n pass\nelse:\n\n\n\n\n _active=[]\n \n def _cleanup():\n if _active is None:\n return\n for inst in _active[:]:\n res=inst._internal_poll(_deadstate=sys.maxsize)\n if res is not None:\n try:\n _active.remove(inst)\n except ValueError:\n \n \n pass\n \nPIPE=-1\nSTDOUT=-2\nDEVNULL=-3\n\n\n\n\n\n\ndef _optim_args_from_interpreter_flags():\n ''\n \n args=[]\n value=sys.flags.optimize\n if value >0:\n args.append('-'+'O'*value)\n return args\n \n \ndef _args_from_interpreter_flags():\n ''\n \n flag_opt_map={\n 'debug':'d',\n \n \n 'dont_write_bytecode':'B',\n 'no_site':'S',\n 'verbose':'v',\n 'bytes_warning':'b',\n 'quiet':'q',\n \n }\n args=_optim_args_from_interpreter_flags()\n for flag,opt in flag_opt_map.items():\n v=getattr(sys.flags,flag)\n if v >0:\n args.append('-'+opt *v)\n \n if sys.flags.isolated:\n args.append('-I')\n else:\n if sys.flags.ignore_environment:\n args.append('-E')\n if sys.flags.no_user_site:\n args.append('-s')\n if sys.flags.safe_path:\n args.append('-P')\n \n \n warnopts=sys.warnoptions[:]\n xoptions=getattr(sys,'_xoptions',{})\n bytes_warning=sys.flags.bytes_warning\n dev_mode=sys.flags.dev_mode\n \n if bytes_warning >1:\n warnopts.remove(\"error::BytesWarning\")\n elif bytes_warning:\n warnopts.remove(\"default::BytesWarning\")\n if dev_mode:\n warnopts.remove('default')\n for opt in warnopts:\n args.append('-W'+opt)\n \n \n if dev_mode:\n args.extend(('-X','dev'))\n for opt in('faulthandler','tracemalloc','importtime',\n 'frozen_modules','showrefcount','utf8','gil'):\n if opt in xoptions:\n value=xoptions[opt]\n if value is True:\n arg=opt\n else:\n arg='%s=%s'%(opt,value)\n args.extend(('-X',arg))\n \n return args\n \n \ndef _text_encoding():\n\n\n if sys.flags.warn_default_encoding:\n f=sys._getframe()\n filename=f.f_code.co_filename\n stacklevel=2\n while f :=f.f_back:\n if f.f_code.co_filename !=filename:\n break\n stacklevel +=1\n warnings.warn(\"'encoding' argument not specified.\",\n EncodingWarning,stacklevel)\n \n if sys.flags.utf8_mode:\n return \"utf-8\"\n else:\n return locale.getencoding()\n \n \ndef call(*popenargs,timeout=None,**kwargs):\n ''\n\n\n\n\n\n \n with Popen(*popenargs,**kwargs)as p:\n try:\n return p.wait(timeout=timeout)\n except:\n p.kill()\n \n raise\n \n \ndef check_call(*popenargs,**kwargs):\n ''\n\n\n\n\n\n\n\n \n retcode=call(*popenargs,**kwargs)\n if retcode:\n cmd=kwargs.get(\"args\")\n if cmd is None:\n cmd=popenargs[0]\n raise CalledProcessError(retcode,cmd)\n return 0\n \n \ndef check_output(*popenargs,timeout=None,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n for kw in('stdout','check'):\n if kw in kwargs:\n raise ValueError(f'{kw} argument not allowed, it will be overridden.')\n \n if 'input'in kwargs and kwargs['input']is None:\n \n \n if kwargs.get('universal_newlines')or kwargs.get('text')or kwargs.get('encoding')\\\n or kwargs.get('errors'):\n empty=''\n else:\n empty=b''\n kwargs['input']=empty\n \n return run(*popenargs,stdout=PIPE,timeout=timeout,check=True,\n **kwargs).stdout\n \n \nclass CompletedProcess(object):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,args,returncode,stdout=None,stderr=None):\n self.args=args\n self.returncode=returncode\n self.stdout=stdout\n self.stderr=stderr\n \n def __repr__(self):\n args=['args={!r}'.format(self.args),\n 'returncode={!r}'.format(self.returncode)]\n if self.stdout is not None:\n args.append('stdout={!r}'.format(self.stdout))\n if self.stderr is not None:\n args.append('stderr={!r}'.format(self.stderr))\n return \"{}({})\".format(type(self).__name__,', '.join(args))\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \n def check_returncode(self):\n ''\n if self.returncode:\n raise CalledProcessError(self.returncode,self.args,self.stdout,\n self.stderr)\n \n \ndef run(*popenargs,\ninput=None,capture_output=False,timeout=None,check=False,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if input is not None:\n if kwargs.get('stdin')is not None:\n raise ValueError('stdin and input arguments may not both be used.')\n kwargs['stdin']=PIPE\n \n if capture_output:\n if kwargs.get('stdout')is not None or kwargs.get('stderr')is not None:\n raise ValueError('stdout and stderr arguments may not be used '\n 'with capture_output.')\n kwargs['stdout']=PIPE\n kwargs['stderr']=PIPE\n \n with Popen(*popenargs,**kwargs)as process:\n try:\n stdout,stderr=process.communicate(input,timeout=timeout)\n except TimeoutExpired as exc:\n process.kill()\n if _mswindows:\n \n \n \n \n \n exc.stdout,exc.stderr=process.communicate()\n else:\n \n \n process.wait()\n raise\n except:\n process.kill()\n \n raise\n retcode=process.poll()\n if check and retcode:\n raise CalledProcessError(retcode,process.args,\n output=stdout,stderr=stderr)\n return CompletedProcess(process.args,retcode,stdout,stderr)\n \n \ndef list2cmdline(seq):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n result=[]\n needquote=False\n for arg in map(os.fsdecode,seq):\n bs_buf=[]\n \n \n if result:\n result.append(' ')\n \n needquote=(\" \"in arg)or(\"\\t\"in arg)or not arg\n if needquote:\n result.append('\"')\n \n for c in arg:\n if c =='\\\\':\n \n bs_buf.append(c)\n elif c =='\"':\n \n result.append('\\\\'*len(bs_buf)*2)\n bs_buf=[]\n result.append('\\\\\"')\n else:\n \n if bs_buf:\n result.extend(bs_buf)\n bs_buf=[]\n result.append(c)\n \n \n if bs_buf:\n result.extend(bs_buf)\n \n if needquote:\n result.extend(bs_buf)\n result.append('\"')\n \n return ''.join(result)\n \n \n \n \n \ndef getstatusoutput(cmd,*,encoding=None,errors=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n data=check_output(cmd,shell=True,text=True,stderr=STDOUT,\n encoding=encoding,errors=errors)\n exitcode=0\n except CalledProcessError as ex:\n data=ex.output\n exitcode=ex.returncode\n if data[-1:]=='\\n':\n data=data[:-1]\n return exitcode,data\n \ndef getoutput(cmd,*,encoding=None,errors=None):\n ''\n\n\n\n\n\n\n\n \n return getstatusoutput(cmd,encoding=encoding,errors=errors)[1]\n \n \n \ndef _use_posix_spawn():\n ''\n\n\n\n\n\n\n\n\n\n\n \n if _mswindows or not hasattr(os,'posix_spawn'):\n \n return False\n \n if sys.platform in('darwin','sunos5'):\n \n \n return True\n \n \n try:\n ver=os.confstr('CS_GNU_LIBC_VERSION')\n \n parts=ver.split(maxsplit=1)\n if len(parts)!=2:\n \n raise ValueError\n libc=parts[0]\n version=tuple(map(int,parts[1].split('.')))\n \n if sys.platform =='linux'and libc =='glibc'and version >=(2,24):\n \n \n return True\n \n \n \n except(AttributeError,ValueError,OSError):\n \n pass\n \n \n return False\n \n \n \n \n_USE_POSIX_SPAWN=_use_posix_spawn()\n_USE_VFORK=True\n_HAVE_POSIX_SPAWN_CLOSEFROM=hasattr(os,'POSIX_SPAWN_CLOSEFROM')\n\n\nclass Popen:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n _child_created=False\n \n def __init__(self,args,bufsize=-1,executable=None,\n stdin=None,stdout=None,stderr=None,\n preexec_fn=None,close_fds=True,\n shell=False,cwd=None,env=None,universal_newlines=None,\n startupinfo=None,creationflags=0,\n restore_signals=True,start_new_session=False,\n pass_fds=(),*,user=None,group=None,extra_groups=None,\n encoding=None,errors=None,text=None,umask=-1,pipesize=-1,\n process_group=None):\n ''\n if not _can_fork_exec:\n raise OSError(\n errno.ENOTSUP,f\"{sys.platform} does not support processes.\"\n )\n \n _cleanup()\n \n \n \n \n \n self._waitpid_lock=threading.Lock()\n \n self._input=None\n self._communication_started=False\n if bufsize is None:\n bufsize=-1\n if not isinstance(bufsize,int):\n raise TypeError(\"bufsize must be an integer\")\n \n if stdout is STDOUT:\n raise ValueError(\"STDOUT can only be used for stderr\")\n \n if pipesize is None:\n pipesize=-1\n if not isinstance(pipesize,int):\n raise TypeError(\"pipesize must be an integer\")\n \n if _mswindows:\n if preexec_fn is not None:\n raise ValueError(\"preexec_fn is not supported on Windows \"\n \"platforms\")\n else:\n \n if pass_fds and not close_fds:\n warnings.warn(\"pass_fds overriding close_fds.\",RuntimeWarning)\n close_fds=True\n if startupinfo is not None:\n raise ValueError(\"startupinfo is only supported on Windows \"\n \"platforms\")\n if creationflags !=0:\n raise ValueError(\"creationflags is only supported on Windows \"\n \"platforms\")\n \n self.args=args\n self.stdin=None\n self.stdout=None\n self.stderr=None\n self.pid=None\n self.returncode=None\n self.encoding=encoding\n self.errors=errors\n self.pipesize=pipesize\n \n \n if(text is not None and universal_newlines is not None\n and bool(universal_newlines)!=bool(text)):\n raise SubprocessError('Cannot disambiguate when both text '\n 'and universal_newlines are supplied but '\n 'different. Pass one or the other.')\n \n self.text_mode=encoding or errors or text or universal_newlines\n if self.text_mode and encoding is None:\n self.encoding=encoding=_text_encoding()\n \n \n \n \n self._sigint_wait_secs=0.25\n \n self._closed_child_pipe_fds=False\n \n if self.text_mode:\n if bufsize ==1:\n line_buffering=True\n \n \n bufsize=-1\n else:\n line_buffering=False\n \n if process_group is None:\n process_group=-1\n \n gid=None\n if group is not None:\n if not hasattr(os,'setregid'):\n raise ValueError(\"The 'group' parameter is not supported on the \"\n \"current platform\")\n \n elif isinstance(group,str):\n try:\n import grp\n except ImportError:\n raise ValueError(\"The group parameter cannot be a string \"\n \"on systems without the grp module\")\n \n gid=grp.getgrnam(group).gr_gid\n elif isinstance(group,int):\n gid=group\n else:\n raise TypeError(\"Group must be a string or an integer, not {}\"\n .format(type(group)))\n \n if gid <0:\n raise ValueError(f\"Group ID cannot be negative, got {gid}\")\n \n gids=None\n if extra_groups is not None:\n if not hasattr(os,'setgroups'):\n raise ValueError(\"The 'extra_groups' parameter is not \"\n \"supported on the current platform\")\n \n elif isinstance(extra_groups,str):\n raise ValueError(\"Groups must be a list, not a string\")\n \n gids=[]\n for extra_group in extra_groups:\n if isinstance(extra_group,str):\n try:\n import grp\n except ImportError:\n raise ValueError(\"Items in extra_groups cannot be \"\n \"strings on systems without the \"\n \"grp module\")\n \n gids.append(grp.getgrnam(extra_group).gr_gid)\n elif isinstance(extra_group,int):\n gids.append(extra_group)\n else:\n raise TypeError(\"Items in extra_groups must be a string \"\n \"or integer, not {}\"\n .format(type(extra_group)))\n \n \n \n for gid_check in gids:\n if gid_check <0:\n raise ValueError(f\"Group ID cannot be negative, got {gid_check}\")\n \n uid=None\n if user is not None:\n if not hasattr(os,'setreuid'):\n raise ValueError(\"The 'user' parameter is not supported on \"\n \"the current platform\")\n \n elif isinstance(user,str):\n try:\n import pwd\n except ImportError:\n raise ValueError(\"The user parameter cannot be a string \"\n \"on systems without the pwd module\")\n uid=pwd.getpwnam(user).pw_uid\n elif isinstance(user,int):\n uid=user\n else:\n raise TypeError(\"User must be a string or an integer\")\n \n if uid <0:\n raise ValueError(f\"User ID cannot be negative, got {uid}\")\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n (p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)=self._get_handles(stdin,stdout,stderr)\n \n \n \n \n \n \n \n if _mswindows:\n if p2cwrite !=-1:\n p2cwrite=msvcrt.open_osfhandle(p2cwrite.Detach(),0)\n if c2pread !=-1:\n c2pread=msvcrt.open_osfhandle(c2pread.Detach(),0)\n if errread !=-1:\n errread=msvcrt.open_osfhandle(errread.Detach(),0)\n \n try:\n if p2cwrite !=-1:\n self.stdin=io.open(p2cwrite,'wb',bufsize)\n if self.text_mode:\n self.stdin=io.TextIOWrapper(self.stdin,write_through=True,\n line_buffering=line_buffering,\n encoding=encoding,errors=errors)\n if c2pread !=-1:\n self.stdout=io.open(c2pread,'rb',bufsize)\n if self.text_mode:\n self.stdout=io.TextIOWrapper(self.stdout,\n encoding=encoding,errors=errors)\n if errread !=-1:\n self.stderr=io.open(errread,'rb',bufsize)\n if self.text_mode:\n self.stderr=io.TextIOWrapper(self.stderr,\n encoding=encoding,errors=errors)\n \n self._execute_child(args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n restore_signals,\n gid,gids,uid,umask,\n start_new_session,process_group)\n except:\n \n for f in filter(None,(self.stdin,self.stdout,self.stderr)):\n try:\n f.close()\n except OSError:\n pass\n \n if not self._closed_child_pipe_fds:\n to_close=[]\n if stdin ==PIPE:\n to_close.append(p2cread)\n if stdout ==PIPE:\n to_close.append(c2pwrite)\n if stderr ==PIPE:\n to_close.append(errwrite)\n if hasattr(self,'_devnull'):\n to_close.append(self._devnull)\n for fd in to_close:\n try:\n if _mswindows and isinstance(fd,Handle):\n fd.Close()\n else:\n os.close(fd)\n except OSError:\n pass\n \n raise\n \n def __repr__(self):\n obj_repr=(\n f\"<{self.__class__.__name__}: \"\n f\"returncode: {self.returncode} args: {self.args !r}>\"\n )\n if len(obj_repr)>80:\n obj_repr=obj_repr[:76]+\"...>\"\n return obj_repr\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n @property\n def universal_newlines(self):\n \n \n return self.text_mode\n \n @universal_newlines.setter\n def universal_newlines(self,universal_newlines):\n self.text_mode=bool(universal_newlines)\n \n def _translate_newlines(self,data,encoding,errors):\n data=data.decode(encoding,errors)\n return data.replace(\"\\r\\n\",\"\\n\").replace(\"\\r\",\"\\n\")\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,value,traceback):\n if self.stdout:\n self.stdout.close()\n if self.stderr:\n self.stderr.close()\n try:\n if self.stdin:\n self.stdin.close()\n finally:\n if exc_type ==KeyboardInterrupt:\n \n \n \n \n \n \n \n if self._sigint_wait_secs >0:\n try:\n self._wait(timeout=self._sigint_wait_secs)\n except TimeoutExpired:\n pass\n self._sigint_wait_secs=0\n return\n \n \n self.wait()\n \n def __del__(self,_maxsize=sys.maxsize,_warn=warnings.warn):\n if not self._child_created:\n \n return\n if self.returncode is None:\n \n \n _warn(\"subprocess %s is still running\"%self.pid,\n ResourceWarning,source=self)\n \n self._internal_poll(_deadstate=_maxsize)\n if self.returncode is None and _active is not None:\n \n _active.append(self)\n \n def _get_devnull(self):\n if not hasattr(self,'_devnull'):\n self._devnull=os.open(os.devnull,os.O_RDWR)\n return self._devnull\n \n def _stdin_write(self,input):\n if input:\n try:\n self.stdin.write(input)\n except BrokenPipeError:\n pass\n except OSError as exc:\n if exc.errno ==errno.EINVAL:\n \n \n \n pass\n else:\n raise\n \n try:\n self.stdin.close()\n except BrokenPipeError:\n pass\n except OSError as exc:\n if exc.errno ==errno.EINVAL:\n pass\n else:\n raise\n \n def communicate(self,input=None,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if self._communication_started and input:\n raise ValueError(\"Cannot send input after starting communication\")\n \n \n \n \n if(timeout is None and not self._communication_started and\n [self.stdin,self.stdout,self.stderr].count(None)>=2):\n stdout=None\n stderr=None\n if self.stdin:\n self._stdin_write(input)\n elif self.stdout:\n stdout=self.stdout.read()\n self.stdout.close()\n elif self.stderr:\n stderr=self.stderr.read()\n self.stderr.close()\n self.wait()\n else:\n if timeout is not None:\n endtime=_time()+timeout\n else:\n endtime=None\n \n try:\n stdout,stderr=self._communicate(input,endtime,timeout)\n except KeyboardInterrupt:\n \n \n if timeout is not None:\n sigint_timeout=min(self._sigint_wait_secs,\n self._remaining_time(endtime))\n else:\n sigint_timeout=self._sigint_wait_secs\n self._sigint_wait_secs=0\n try:\n self._wait(timeout=sigint_timeout)\n except TimeoutExpired:\n pass\n raise\n \n finally:\n self._communication_started=True\n \n sts=self.wait(timeout=self._remaining_time(endtime))\n \n return(stdout,stderr)\n \n \n def poll(self):\n ''\n \n return self._internal_poll()\n \n \n def _remaining_time(self,endtime):\n ''\n if endtime is None:\n return None\n else:\n return endtime -_time()\n \n \n def _check_timeout(self,endtime,orig_timeout,stdout_seq,stderr_seq,\n skip_check_and_raise=False):\n ''\n if endtime is None:\n return\n if skip_check_and_raise or _time()>endtime:\n raise TimeoutExpired(\n self.args,orig_timeout,\n output=b''.join(stdout_seq)if stdout_seq else None,\n stderr=b''.join(stderr_seq)if stderr_seq else None)\n \n \n def wait(self,timeout=None):\n ''\n if timeout is not None:\n endtime=_time()+timeout\n try:\n return self._wait(timeout=timeout)\n except KeyboardInterrupt:\n \n \n \n \n if timeout is not None:\n sigint_timeout=min(self._sigint_wait_secs,\n self._remaining_time(endtime))\n else:\n sigint_timeout=self._sigint_wait_secs\n self._sigint_wait_secs=0\n try:\n self._wait(timeout=sigint_timeout)\n except TimeoutExpired:\n pass\n raise\n \n def _close_pipe_fds(self,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite):\n \n devnull_fd=getattr(self,'_devnull',None)\n \n with contextlib.ExitStack()as stack:\n if _mswindows:\n if p2cread !=-1:\n stack.callback(p2cread.Close)\n if c2pwrite !=-1:\n stack.callback(c2pwrite.Close)\n if errwrite !=-1:\n stack.callback(errwrite.Close)\n else:\n if p2cread !=-1 and p2cwrite !=-1 and p2cread !=devnull_fd:\n stack.callback(os.close,p2cread)\n if c2pwrite !=-1 and c2pread !=-1 and c2pwrite !=devnull_fd:\n stack.callback(os.close,c2pwrite)\n if errwrite !=-1 and errread !=-1 and errwrite !=devnull_fd:\n stack.callback(os.close,errwrite)\n \n if devnull_fd is not None:\n stack.callback(os.close,devnull_fd)\n \n \n self._closed_child_pipe_fds=True\n \n @contextlib.contextmanager\n def _on_error_fd_closer(self):\n ''\n to_close=[]\n try:\n yield to_close\n except:\n if hasattr(self,'_devnull'):\n to_close.append(self._devnull)\n del self._devnull\n for fd in to_close:\n try:\n if _mswindows and isinstance(fd,Handle):\n fd.Close()\n else:\n os.close(fd)\n except OSError:\n pass\n raise\n \n if _mswindows:\n \n \n \n def _get_handles(self,stdin,stdout,stderr):\n ''\n\n \n if stdin is None and stdout is None and stderr is None:\n return(-1,-1,-1,-1,-1,-1)\n \n p2cread,p2cwrite=-1,-1\n c2pread,c2pwrite=-1,-1\n errread,errwrite=-1,-1\n \n with self._on_error_fd_closer()as err_close_fds:\n if stdin is None:\n p2cread=_winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)\n if p2cread is None:\n p2cread,_=_winapi.CreatePipe(None,0)\n p2cread=Handle(p2cread)\n err_close_fds.append(p2cread)\n _winapi.CloseHandle(_)\n elif stdin ==PIPE:\n p2cread,p2cwrite=_winapi.CreatePipe(None,0)\n p2cread,p2cwrite=Handle(p2cread),Handle(p2cwrite)\n err_close_fds.extend((p2cread,p2cwrite))\n elif stdin ==DEVNULL:\n p2cread=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stdin,int):\n p2cread=msvcrt.get_osfhandle(stdin)\n else:\n \n p2cread=msvcrt.get_osfhandle(stdin.fileno())\n p2cread=self._make_inheritable(p2cread)\n \n if stdout is None:\n c2pwrite=_winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)\n if c2pwrite is None:\n _,c2pwrite=_winapi.CreatePipe(None,0)\n c2pwrite=Handle(c2pwrite)\n err_close_fds.append(c2pwrite)\n _winapi.CloseHandle(_)\n elif stdout ==PIPE:\n c2pread,c2pwrite=_winapi.CreatePipe(None,0)\n c2pread,c2pwrite=Handle(c2pread),Handle(c2pwrite)\n err_close_fds.extend((c2pread,c2pwrite))\n elif stdout ==DEVNULL:\n c2pwrite=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stdout,int):\n c2pwrite=msvcrt.get_osfhandle(stdout)\n else:\n \n c2pwrite=msvcrt.get_osfhandle(stdout.fileno())\n c2pwrite=self._make_inheritable(c2pwrite)\n \n if stderr is None:\n errwrite=_winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)\n if errwrite is None:\n _,errwrite=_winapi.CreatePipe(None,0)\n errwrite=Handle(errwrite)\n err_close_fds.append(errwrite)\n _winapi.CloseHandle(_)\n elif stderr ==PIPE:\n errread,errwrite=_winapi.CreatePipe(None,0)\n errread,errwrite=Handle(errread),Handle(errwrite)\n err_close_fds.extend((errread,errwrite))\n elif stderr ==STDOUT:\n errwrite=c2pwrite\n elif stderr ==DEVNULL:\n errwrite=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stderr,int):\n errwrite=msvcrt.get_osfhandle(stderr)\n else:\n \n errwrite=msvcrt.get_osfhandle(stderr.fileno())\n errwrite=self._make_inheritable(errwrite)\n \n return(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n def _make_inheritable(self,handle):\n ''\n h=_winapi.DuplicateHandle(\n _winapi.GetCurrentProcess(),handle,\n _winapi.GetCurrentProcess(),0,1,\n _winapi.DUPLICATE_SAME_ACCESS)\n return Handle(h)\n \n \n def _filter_handle_list(self,handle_list):\n ''\n\n \n \n \n \n return list({handle for handle in handle_list\n if handle&0x3 !=0x3\n or _winapi.GetFileType(handle)!=\n _winapi.FILE_TYPE_CHAR})\n \n \n def _execute_child(self,args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n unused_restore_signals,\n unused_gid,unused_gids,unused_uid,\n unused_umask,\n unused_start_new_session,unused_process_group):\n ''\n \n assert not pass_fds,\"pass_fds not supported on Windows.\"\n \n if isinstance(args,str):\n pass\n elif isinstance(args,bytes):\n if shell:\n raise TypeError('bytes args is not allowed on Windows')\n args=list2cmdline([args])\n elif isinstance(args,os.PathLike):\n if shell:\n raise TypeError('path-like args is not allowed when '\n 'shell is true')\n args=list2cmdline([args])\n else:\n args=list2cmdline(args)\n \n if executable is not None:\n executable=os.fsdecode(executable)\n \n \n if startupinfo is None:\n startupinfo=STARTUPINFO()\n else:\n \n \n startupinfo=startupinfo.copy()\n \n use_std_handles=-1 not in(p2cread,c2pwrite,errwrite)\n if use_std_handles:\n startupinfo.dwFlags |=_winapi.STARTF_USESTDHANDLES\n startupinfo.hStdInput=p2cread\n startupinfo.hStdOutput=c2pwrite\n startupinfo.hStdError=errwrite\n \n attribute_list=startupinfo.lpAttributeList\n have_handle_list=bool(attribute_list and\n \"handle_list\"in attribute_list and\n attribute_list[\"handle_list\"])\n \n \n if have_handle_list or(use_std_handles and close_fds):\n if attribute_list is None:\n attribute_list=startupinfo.lpAttributeList={}\n handle_list=attribute_list[\"handle_list\"]=\\\n list(attribute_list.get(\"handle_list\",[]))\n \n if use_std_handles:\n handle_list +=[int(p2cread),int(c2pwrite),int(errwrite)]\n \n handle_list[:]=self._filter_handle_list(handle_list)\n \n if handle_list:\n if not close_fds:\n warnings.warn(\"startupinfo.lpAttributeList['handle_list'] \"\n \"overriding close_fds\",RuntimeWarning)\n \n \n \n \n close_fds=False\n \n if shell:\n startupinfo.dwFlags |=_winapi.STARTF_USESHOWWINDOW\n startupinfo.wShowWindow=_winapi.SW_HIDE\n if not executable:\n \n \n \n \n \n comspec=os.environ.get('ComSpec')\n if not comspec:\n system_root=os.environ.get('SystemRoot','')\n comspec=os.path.join(system_root,'System32','cmd.exe')\n if not os.path.isabs(comspec):\n raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set')\n if os.path.isabs(comspec):\n executable=comspec\n else:\n comspec=executable\n \n args='{} /c \"{}\"'.format(comspec,args)\n \n if cwd is not None:\n cwd=os.fsdecode(cwd)\n \n sys.audit(\"subprocess.Popen\",executable,args,cwd,env)\n \n \n try:\n hp,ht,pid,tid=_winapi.CreateProcess(executable,args,\n \n None,None,\n int(not close_fds),\n creationflags,\n env,\n cwd,\n startupinfo)\n finally:\n \n \n \n \n \n \n self._close_pipe_fds(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n self._child_created=True\n self._handle=Handle(hp)\n self.pid=pid\n _winapi.CloseHandle(ht)\n \n def _internal_poll(self,_deadstate=None,\n _WaitForSingleObject=_winapi.WaitForSingleObject,\n _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,\n _GetExitCodeProcess=_winapi.GetExitCodeProcess):\n ''\n\n\n\n\n\n \n if self.returncode is None:\n if _WaitForSingleObject(self._handle,0)==_WAIT_OBJECT_0:\n self.returncode=_GetExitCodeProcess(self._handle)\n return self.returncode\n \n \n def _wait(self,timeout):\n ''\n if timeout is None:\n timeout_millis=_winapi.INFINITE\n elif timeout <=0:\n timeout_millis=0\n else:\n timeout_millis=int(timeout *1000)\n if self.returncode is None:\n \n result=_winapi.WaitForSingleObject(self._handle,\n timeout_millis)\n if result ==_winapi.WAIT_TIMEOUT:\n raise TimeoutExpired(self.args,timeout)\n self.returncode=_winapi.GetExitCodeProcess(self._handle)\n return self.returncode\n \n \n def _readerthread(self,fh,buffer):\n buffer.append(fh.read())\n fh.close()\n \n \n def _communicate(self,input,endtime,orig_timeout):\n \n \n if self.stdout and not hasattr(self,\"_stdout_buff\"):\n self._stdout_buff=[]\n self.stdout_thread=\\\n threading.Thread(target=self._readerthread,\n args=(self.stdout,self._stdout_buff))\n self.stdout_thread.daemon=True\n self.stdout_thread.start()\n if self.stderr and not hasattr(self,\"_stderr_buff\"):\n self._stderr_buff=[]\n self.stderr_thread=\\\n threading.Thread(target=self._readerthread,\n args=(self.stderr,self._stderr_buff))\n self.stderr_thread.daemon=True\n self.stderr_thread.start()\n \n if self.stdin:\n self._stdin_write(input)\n \n \n \n \n if self.stdout is not None:\n self.stdout_thread.join(self._remaining_time(endtime))\n if self.stdout_thread.is_alive():\n raise TimeoutExpired(self.args,orig_timeout)\n if self.stderr is not None:\n self.stderr_thread.join(self._remaining_time(endtime))\n if self.stderr_thread.is_alive():\n raise TimeoutExpired(self.args,orig_timeout)\n \n \n \n stdout=None\n stderr=None\n if self.stdout:\n stdout=self._stdout_buff\n self.stdout.close()\n if self.stderr:\n stderr=self._stderr_buff\n self.stderr.close()\n \n \n stdout=stdout[0]if stdout else None\n stderr=stderr[0]if stderr else None\n \n return(stdout,stderr)\n \n def send_signal(self,sig):\n ''\n \n if self.returncode is not None:\n return\n if sig ==signal.SIGTERM:\n self.terminate()\n elif sig ==signal.CTRL_C_EVENT:\n os.kill(self.pid,signal.CTRL_C_EVENT)\n elif sig ==signal.CTRL_BREAK_EVENT:\n os.kill(self.pid,signal.CTRL_BREAK_EVENT)\n else:\n raise ValueError(\"Unsupported signal: {}\".format(sig))\n \n def terminate(self):\n ''\n \n if self.returncode is not None:\n return\n try:\n _winapi.TerminateProcess(self._handle,1)\n except PermissionError:\n \n \n rc=_winapi.GetExitCodeProcess(self._handle)\n if rc ==_winapi.STILL_ACTIVE:\n raise\n self.returncode=rc\n \n kill=terminate\n \n else:\n \n \n \n def _get_handles(self,stdin,stdout,stderr):\n ''\n\n \n p2cread,p2cwrite=-1,-1\n c2pread,c2pwrite=-1,-1\n errread,errwrite=-1,-1\n \n with self._on_error_fd_closer()as err_close_fds:\n if stdin is None:\n pass\n elif stdin ==PIPE:\n p2cread,p2cwrite=os.pipe()\n err_close_fds.extend((p2cread,p2cwrite))\n if self.pipesize >0 and hasattr(fcntl,\"F_SETPIPE_SZ\"):\n fcntl.fcntl(p2cwrite,fcntl.F_SETPIPE_SZ,self.pipesize)\n elif stdin ==DEVNULL:\n p2cread=self._get_devnull()\n elif isinstance(stdin,int):\n p2cread=stdin\n else:\n \n p2cread=stdin.fileno()\n \n if stdout is None:\n pass\n elif stdout ==PIPE:\n c2pread,c2pwrite=os.pipe()\n err_close_fds.extend((c2pread,c2pwrite))\n if self.pipesize >0 and hasattr(fcntl,\"F_SETPIPE_SZ\"):\n fcntl.fcntl(c2pwrite,fcntl.F_SETPIPE_SZ,self.pipesize)\n elif stdout ==DEVNULL:\n c2pwrite=self._get_devnull()\n elif isinstance(stdout,int):\n c2pwrite=stdout\n else:\n \n c2pwrite=stdout.fileno()\n \n if stderr is None:\n pass\n elif stderr ==PIPE:\n errread,errwrite=os.pipe()\n err_close_fds.extend((errread,errwrite))\n if self.pipesize >0 and hasattr(fcntl,\"F_SETPIPE_SZ\"):\n fcntl.fcntl(errwrite,fcntl.F_SETPIPE_SZ,self.pipesize)\n elif stderr ==STDOUT:\n if c2pwrite !=-1:\n errwrite=c2pwrite\n else:\n errwrite=sys.__stdout__.fileno()\n elif stderr ==DEVNULL:\n errwrite=self._get_devnull()\n elif isinstance(stderr,int):\n errwrite=stderr\n else:\n \n errwrite=stderr.fileno()\n \n return(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n def _posix_spawn(self,args,executable,env,restore_signals,close_fds,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite):\n ''\n kwargs={}\n if restore_signals:\n \n sigset=[]\n for signame in('SIGPIPE','SIGXFZ','SIGXFSZ'):\n signum=getattr(signal,signame,None)\n if signum is not None:\n sigset.append(signum)\n kwargs['setsigdef']=sigset\n \n file_actions=[]\n for fd in(p2cwrite,c2pread,errread):\n if fd !=-1:\n file_actions.append((os.POSIX_SPAWN_CLOSE,fd))\n for fd,fd2 in(\n (p2cread,0),\n (c2pwrite,1),\n (errwrite,2),\n ):\n if fd !=-1:\n file_actions.append((os.POSIX_SPAWN_DUP2,fd,fd2))\n \n if close_fds:\n file_actions.append((os.POSIX_SPAWN_CLOSEFROM,3))\n \n if file_actions:\n kwargs['file_actions']=file_actions\n \n self.pid=os.posix_spawn(executable,args,env,**kwargs)\n self._child_created=True\n \n self._close_pipe_fds(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n def _execute_child(self,args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n restore_signals,\n gid,gids,uid,umask,\n start_new_session,process_group):\n ''\n \n if isinstance(args,(str,bytes)):\n args=[args]\n elif isinstance(args,os.PathLike):\n if shell:\n raise TypeError('path-like args is not allowed when '\n 'shell is true')\n args=[args]\n else:\n args=list(args)\n \n if shell:\n \n unix_shell=('/system/bin/sh'if\n hasattr(sys,'getandroidapilevel')else '/bin/sh')\n args=[unix_shell,\"-c\"]+args\n if executable:\n args[0]=executable\n \n if executable is None:\n executable=args[0]\n \n sys.audit(\"subprocess.Popen\",executable,args,cwd,env)\n \n if(_USE_POSIX_SPAWN\n and os.path.dirname(executable)\n and preexec_fn is None\n and(not close_fds or _HAVE_POSIX_SPAWN_CLOSEFROM)\n and not pass_fds\n and cwd is None\n and(p2cread ==-1 or p2cread >2)\n and(c2pwrite ==-1 or c2pwrite >2)\n and(errwrite ==-1 or errwrite >2)\n and not start_new_session\n and process_group ==-1\n and gid is None\n and gids is None\n and uid is None\n and umask <0):\n self._posix_spawn(args,executable,env,restore_signals,close_fds,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n return\n \n orig_executable=executable\n \n \n \n \n errpipe_read,errpipe_write=os.pipe()\n \n low_fds_to_close=[]\n while errpipe_write <3:\n low_fds_to_close.append(errpipe_write)\n errpipe_write=os.dup(errpipe_write)\n for low_fd in low_fds_to_close:\n os.close(low_fd)\n try:\n try:\n \n \n \n \n \n if env is not None:\n env_list=[]\n for k,v in env.items():\n k=os.fsencode(k)\n if b'='in k:\n raise ValueError(\"illegal environment variable name\")\n env_list.append(k+b'='+os.fsencode(v))\n else:\n env_list=None\n executable=os.fsencode(executable)\n if os.path.dirname(executable):\n executable_list=(executable,)\n else:\n \n executable_list=tuple(\n os.path.join(os.fsencode(dir),executable)\n for dir in os.get_exec_path(env))\n fds_to_keep=set(pass_fds)\n fds_to_keep.add(errpipe_write)\n self.pid=_fork_exec(\n args,executable_list,\n close_fds,tuple(sorted(map(int,fds_to_keep))),\n cwd,env_list,\n p2cread,p2cwrite,c2pread,c2pwrite,\n errread,errwrite,\n errpipe_read,errpipe_write,\n restore_signals,start_new_session,\n process_group,gid,gids,uid,umask,\n preexec_fn,_USE_VFORK)\n self._child_created=True\n finally:\n \n os.close(errpipe_write)\n \n self._close_pipe_fds(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n \n errpipe_data=bytearray()\n while True:\n part=os.read(errpipe_read,50000)\n errpipe_data +=part\n if not part or len(errpipe_data)>50000:\n break\n finally:\n \n os.close(errpipe_read)\n \n if errpipe_data:\n try:\n pid,sts=os.waitpid(self.pid,0)\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n else:\n self.returncode=sys.maxsize\n except ChildProcessError:\n pass\n \n try:\n exception_name,hex_errno,err_msg=(\n errpipe_data.split(b':',2))\n \n \n \n err_msg=err_msg.decode()\n except ValueError:\n exception_name=b'SubprocessError'\n hex_errno=b'0'\n err_msg='Bad exception data from child: {!r}'.format(\n bytes(errpipe_data))\n child_exception_type=getattr(\n builtins,exception_name.decode('ascii'),\n SubprocessError)\n if issubclass(child_exception_type,OSError)and hex_errno:\n errno_num=int(hex_errno,16)\n if err_msg ==\"noexec:chdir\":\n err_msg=\"\"\n \n err_filename=cwd\n elif err_msg ==\"noexec\":\n err_msg=\"\"\n err_filename=None\n else:\n err_filename=orig_executable\n if errno_num !=0:\n err_msg=os.strerror(errno_num)\n if err_filename is not None:\n raise child_exception_type(errno_num,err_msg,err_filename)\n else:\n raise child_exception_type(errno_num,err_msg)\n raise child_exception_type(err_msg)\n \n \n def _handle_exitstatus(self,sts,_del_safe=_del_safe):\n ''\n \n \n if _del_safe.WIFSTOPPED(sts):\n self.returncode=-_del_safe.WSTOPSIG(sts)\n else:\n self.returncode=_del_safe.waitstatus_to_exitcode(sts)\n \n def _internal_poll(self,_deadstate=None,_del_safe=_del_safe):\n ''\n\n\n\n\n\n \n if self.returncode is None:\n if not self._waitpid_lock.acquire(False):\n \n \n return None\n try:\n if self.returncode is not None:\n return self.returncode\n pid,sts=_del_safe.waitpid(self.pid,_del_safe.WNOHANG)\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n except OSError as e:\n if _deadstate is not None:\n self.returncode=_deadstate\n elif e.errno ==_del_safe.ECHILD:\n \n \n \n \n \n self.returncode=0\n finally:\n self._waitpid_lock.release()\n return self.returncode\n \n \n def _try_wait(self,wait_flags):\n ''\n try:\n (pid,sts)=os.waitpid(self.pid,wait_flags)\n except ChildProcessError:\n \n \n \n pid=self.pid\n sts=0\n return(pid,sts)\n \n \n def _wait(self,timeout):\n ''\n if self.returncode is not None:\n return self.returncode\n \n if timeout is not None:\n endtime=_time()+timeout\n \n \n delay=0.0005\n while True:\n if self._waitpid_lock.acquire(False):\n try:\n if self.returncode is not None:\n break\n (pid,sts)=self._try_wait(os.WNOHANG)\n assert pid ==self.pid or pid ==0\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n break\n finally:\n self._waitpid_lock.release()\n remaining=self._remaining_time(endtime)\n if remaining <=0:\n raise TimeoutExpired(self.args,timeout)\n delay=min(delay *2,remaining,.05)\n time.sleep(delay)\n else:\n while self.returncode is None:\n with self._waitpid_lock:\n if self.returncode is not None:\n break\n (pid,sts)=self._try_wait(0)\n \n \n \n if pid ==self.pid:\n self._handle_exitstatus(sts)\n return self.returncode\n \n \n def _communicate(self,input,endtime,orig_timeout):\n if self.stdin and not self._communication_started:\n \n \n try:\n self.stdin.flush()\n except BrokenPipeError:\n pass\n if not input:\n try:\n self.stdin.close()\n except BrokenPipeError:\n pass\n \n stdout=None\n stderr=None\n \n \n if not self._communication_started:\n self._fileobj2output={}\n if self.stdout:\n self._fileobj2output[self.stdout]=[]\n if self.stderr:\n self._fileobj2output[self.stderr]=[]\n \n if self.stdout:\n stdout=self._fileobj2output[self.stdout]\n if self.stderr:\n stderr=self._fileobj2output[self.stderr]\n \n self._save_input(input)\n \n if self._input:\n input_view=memoryview(self._input)\n \n with _PopenSelector()as selector:\n if self.stdin and input:\n selector.register(self.stdin,selectors.EVENT_WRITE)\n if self.stdout and not self.stdout.closed:\n selector.register(self.stdout,selectors.EVENT_READ)\n if self.stderr and not self.stderr.closed:\n selector.register(self.stderr,selectors.EVENT_READ)\n \n while selector.get_map():\n timeout=self._remaining_time(endtime)\n if timeout is not None and timeout <0:\n self._check_timeout(endtime,orig_timeout,\n stdout,stderr,\n skip_check_and_raise=True)\n raise RuntimeError(\n '_check_timeout(..., skip_check_and_raise=True) '\n 'failed to raise TimeoutExpired.')\n \n ready=selector.select(timeout)\n self._check_timeout(endtime,orig_timeout,stdout,stderr)\n \n \n \n \n for key,events in ready:\n if key.fileobj is self.stdin:\n chunk=input_view[self._input_offset:\n self._input_offset+_PIPE_BUF]\n try:\n self._input_offset +=os.write(key.fd,chunk)\n except BrokenPipeError:\n selector.unregister(key.fileobj)\n key.fileobj.close()\n else:\n if self._input_offset >=len(self._input):\n selector.unregister(key.fileobj)\n key.fileobj.close()\n elif key.fileobj in(self.stdout,self.stderr):\n data=os.read(key.fd,32768)\n if not data:\n selector.unregister(key.fileobj)\n key.fileobj.close()\n self._fileobj2output[key.fileobj].append(data)\n \n self.wait(timeout=self._remaining_time(endtime))\n \n \n if stdout is not None:\n stdout=b''.join(stdout)\n if stderr is not None:\n stderr=b''.join(stderr)\n \n \n \n if self.text_mode:\n if stdout is not None:\n stdout=self._translate_newlines(stdout,\n self.stdout.encoding,\n self.stdout.errors)\n if stderr is not None:\n stderr=self._translate_newlines(stderr,\n self.stderr.encoding,\n self.stderr.errors)\n \n return(stdout,stderr)\n \n \n def _save_input(self,input):\n \n \n \n if self.stdin and self._input is None:\n self._input_offset=0\n self._input=input\n if input is not None and self.text_mode:\n self._input=self._input.encode(self.stdin.encoding,\n self.stdin.errors)\n \n \n def send_signal(self,sig):\n ''\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n self.poll()\n if self.returncode is not None:\n \n return\n \n \n \n \n try:\n os.kill(self.pid,sig)\n except ProcessLookupError:\n \n pass\n \n def terminate(self):\n ''\n \n self.send_signal(signal.SIGTERM)\n \n def kill(self):\n ''\n \n self.send_signal(signal.SIGKILL)\n", ["_posixsubprocess", "_winapi", "builtins", "contextlib", "errno", "fcntl", "grp", "io", "locale", "msvcrt", "os", "pwd", "select", "selectors", "signal", "sys", "threading", "time", "types", "warnings"]], "symtable": [".py", "''\n\nimport _symtable\nfrom _symtable import(USE,DEF_GLOBAL,DEF_NONLOCAL,DEF_LOCAL,DEF_PARAM,\nDEF_IMPORT,DEF_BOUND,DEF_ANNOT,SCOPE_OFF,SCOPE_MASK,FREE,\nLOCAL,GLOBAL_IMPLICIT,GLOBAL_EXPLICIT,CELL)\n\nimport weakref\nfrom enum import StrEnum\n\n__all__=[\"symtable\",\"SymbolTableType\",\"SymbolTable\",\"Class\",\"Function\",\"Symbol\"]\n\ndef symtable(code,filename,compile_type):\n ''\n\n\n\n \n top=_symtable.symtable(code,filename,compile_type)\n return _newSymbolTable(top,filename)\n \nclass SymbolTableFactory:\n def __init__(self):\n self.__memo=weakref.WeakValueDictionary()\n \n def new(self,table,filename):\n if table.type ==_symtable.TYPE_FUNCTION:\n return Function(table,filename)\n if table.type ==_symtable.TYPE_CLASS:\n return Class(table,filename)\n return SymbolTable(table,filename)\n \n def __call__(self,table,filename):\n key=table,filename\n obj=self.__memo.get(key,None)\n if obj is None:\n obj=self.__memo[key]=self.new(table,filename)\n return obj\n \n_newSymbolTable=SymbolTableFactory()\n\n\nclass SymbolTableType(StrEnum):\n MODULE=\"module\"\n FUNCTION=\"function\"\n CLASS=\"class\"\n ANNOTATION=\"annotation\"\n TYPE_ALIAS=\"type alias\"\n TYPE_PARAMETERS=\"type parameters\"\n TYPE_VARIABLE=\"type variable\"\n \n \nclass SymbolTable:\n\n def __init__(self,raw_table,filename):\n self._table=raw_table\n self._filename=filename\n self._symbols={}\n \n def __repr__(self):\n if self.__class__ ==SymbolTable:\n kind=\"\"\n else:\n kind=\"%s \"%self.__class__.__name__\n \n if self._table.name ==\"top\":\n return \"<{0}SymbolTable for module {1}>\".format(kind,self._filename)\n else:\n return \"<{0}SymbolTable for {1} in {2}>\".format(kind,\n self._table.name,\n self._filename)\n \n def get_type(self):\n ''\n\n\n\n \n if self._table.type ==_symtable.TYPE_MODULE:\n return SymbolTableType.MODULE\n if self._table.type ==_symtable.TYPE_FUNCTION:\n return SymbolTableType.FUNCTION\n if self._table.type ==_symtable.TYPE_CLASS:\n return SymbolTableType.CLASS\n if self._table.type ==_symtable.TYPE_ANNOTATION:\n return SymbolTableType.ANNOTATION\n if self._table.type ==_symtable.TYPE_TYPE_ALIAS:\n return SymbolTableType.TYPE_ALIAS\n if self._table.type ==_symtable.TYPE_TYPE_PARAMETERS:\n return SymbolTableType.TYPE_PARAMETERS\n if self._table.type ==_symtable.TYPE_TYPE_VARIABLE:\n return SymbolTableType.TYPE_VARIABLE\n assert False,f\"unexpected type: {self._table.type}\"\n \n def get_id(self):\n ''\n \n return self._table.id\n \n def get_name(self):\n ''\n\n\n\n\n \n return self._table.name\n \n def get_lineno(self):\n ''\n\n \n return self._table.lineno\n \n def is_optimized(self):\n ''\n\n \n return bool(self._table.type ==_symtable.TYPE_FUNCTION)\n \n def is_nested(self):\n ''\n \n return bool(self._table.nested)\n \n def has_children(self):\n ''\n \n return bool(self._table.children)\n \n def get_identifiers(self):\n ''\n \n return self._table.symbols.keys()\n \n def lookup(self,name):\n ''\n\n\n \n sym=self._symbols.get(name)\n if sym is None:\n flags=self._table.symbols[name]\n namespaces=self.__check_children(name)\n module_scope=(self._table.name ==\"top\")\n sym=self._symbols[name]=Symbol(name,flags,namespaces,\n module_scope=module_scope)\n return sym\n \n def get_symbols(self):\n ''\n\n \n return[self.lookup(ident)for ident in self.get_identifiers()]\n \n def __check_children(self,name):\n return[_newSymbolTable(st,self._filename)\n for st in self._table.children\n if st.name ==name]\n \n def get_children(self):\n ''\n \n return[_newSymbolTable(st,self._filename)\n for st in self._table.children]\n \n \nclass Function(SymbolTable):\n\n\n __params=None\n __locals=None\n __frees=None\n __globals=None\n __nonlocals=None\n \n def __idents_matching(self,test_func):\n return tuple(ident for ident in self.get_identifiers()\n if test_func(self._table.symbols[ident]))\n \n def get_parameters(self):\n ''\n \n if self.__params is None:\n self.__params=self.__idents_matching(lambda x:x&DEF_PARAM)\n return self.__params\n \n def get_locals(self):\n ''\n \n if self.__locals is None:\n locs=(LOCAL,CELL)\n test=lambda x:((x >>SCOPE_OFF)&SCOPE_MASK)in locs\n self.__locals=self.__idents_matching(test)\n return self.__locals\n \n def get_globals(self):\n ''\n \n if self.__globals is None:\n glob=(GLOBAL_IMPLICIT,GLOBAL_EXPLICIT)\n test=lambda x:((x >>SCOPE_OFF)&SCOPE_MASK)in glob\n self.__globals=self.__idents_matching(test)\n return self.__globals\n \n def get_nonlocals(self):\n ''\n \n if self.__nonlocals is None:\n self.__nonlocals=self.__idents_matching(lambda x:x&DEF_NONLOCAL)\n return self.__nonlocals\n \n def get_frees(self):\n ''\n \n if self.__frees is None:\n is_free=lambda x:((x >>SCOPE_OFF)&SCOPE_MASK)==FREE\n self.__frees=self.__idents_matching(is_free)\n return self.__frees\n \n \nclass Class(SymbolTable):\n\n __methods=None\n \n def get_methods(self):\n ''\n \n if self.__methods is None:\n d={}\n \n def is_local_symbol(ident):\n flags=self._table.symbols.get(ident,0)\n return((flags >>SCOPE_OFF)&SCOPE_MASK)==LOCAL\n \n for st in self._table.children:\n \n if is_local_symbol(st.name):\n match st.type:\n case _symtable.TYPE_FUNCTION:\n \n \n \n if st.name =='genexpr'and '.0'in st.varnames:\n continue\n d[st.name]=1\n case _symtable.TYPE_TYPE_PARAMETERS:\n \n \n scope_name=st.name\n for c in st.children:\n if c.name ==scope_name and c.type ==_symtable.TYPE_FUNCTION:\n \n \n \n \n \n \n assert scope_name !='genexpr'or '.0'not in c.varnames\n d[scope_name]=1\n break\n self.__methods=tuple(d)\n return self.__methods\n \n \nclass Symbol:\n\n def __init__(self,name,flags,namespaces=None,*,module_scope=False):\n self.__name=name\n self.__flags=flags\n self.__scope=(flags >>SCOPE_OFF)&SCOPE_MASK\n self.__namespaces=namespaces or()\n self.__module_scope=module_scope\n \n def __repr__(self):\n flags_str='|'.join(self._flags_str())\n return f''\n \n def _scope_str(self):\n return _scopes_value_to_name.get(self.__scope)or str(self.__scope)\n \n def _flags_str(self):\n for flagname,flagvalue in _flags:\n if self.__flags&flagvalue ==flagvalue:\n yield flagname\n \n def get_name(self):\n ''\n \n return self.__name\n \n def is_referenced(self):\n ''\n\n \n return bool(self.__flags&_symtable.USE)\n \n def is_parameter(self):\n ''\n \n return bool(self.__flags&DEF_PARAM)\n \n def is_global(self):\n ''\n \n return bool(self.__scope in(GLOBAL_IMPLICIT,GLOBAL_EXPLICIT)\n or(self.__module_scope and self.__flags&DEF_BOUND))\n \n def is_nonlocal(self):\n ''\n return bool(self.__flags&DEF_NONLOCAL)\n \n def is_declared_global(self):\n ''\n \n return bool(self.__scope ==GLOBAL_EXPLICIT)\n \n def is_local(self):\n ''\n \n return bool(self.__scope in(LOCAL,CELL)\n or(self.__module_scope and self.__flags&DEF_BOUND))\n \n def is_annotated(self):\n ''\n \n return bool(self.__flags&DEF_ANNOT)\n \n def is_free(self):\n ''\n\n \n return bool(self.__scope ==FREE)\n \n def is_imported(self):\n ''\n\n \n return bool(self.__flags&DEF_IMPORT)\n \n def is_assigned(self):\n ''\n return bool(self.__flags&DEF_LOCAL)\n \n def is_namespace(self):\n ''\n\n\n\n\n\n\n\n\n \n return bool(self.__namespaces)\n \n def get_namespaces(self):\n ''\n return self.__namespaces\n \n def get_namespace(self):\n ''\n\n\n\n \n if len(self.__namespaces)==0:\n raise ValueError(\"name is not bound to any namespaces\")\n elif len(self.__namespaces)>1:\n raise ValueError(\"name is bound to multiple namespaces\")\n else:\n return self.__namespaces[0]\n \n \n_flags=[('USE',USE)]\n_flags.extend(kv for kv in globals().items()if kv[0].startswith('DEF_'))\n_scopes_names=('FREE','LOCAL','GLOBAL_IMPLICIT','GLOBAL_EXPLICIT','CELL')\n_scopes_value_to_name={globals()[n]:n for n in _scopes_names}\n\n\ndef main(args):\n import sys\n def print_symbols(table,level=0):\n indent=' '*level\n nested=\"nested \"if table.is_nested()else \"\"\n if table.get_type()=='module':\n what=f'from file {table._filename !r}'\n else:\n what=f'{table.get_name()!r}'\n print(f'{indent}symbol table for {nested}{table.get_type()} {what}:')\n for ident in table.get_identifiers():\n symbol=table.lookup(ident)\n flags=', '.join(symbol._flags_str()).lower()\n print(f' {indent}{symbol._scope_str().lower()} symbol {symbol.get_name()!r}: {flags}')\n print()\n \n for table2 in table.get_children():\n print_symbols(table2,level+1)\n \n for filename in args or['-']:\n if filename =='-':\n src=sys.stdin.read()\n filename=''\n else:\n with open(filename,'rb')as f:\n src=f.read()\n mod=symtable(src,filename,'exec')\n print_symbols(mod)\n \n \nif __name__ ==\"__main__\":\n import sys\n main(sys.argv[1:])\n", ["_symtable", "enum", "sys", "weakref"]], "sys": [".py", "\nfrom _sys import *\nimport _sys\n\n_getframe=_sys._getframe\n\nclass _dataclass(tuple):\n\n def __init__(self,**kwargs):\n self.keys=list(kwargs)\n self.__dict__.update(kwargs)\n \n def __getitem__(self,key):\n if isinstance(key,int)and 0 <=key <=len(self.keys):\n return self.__dict__[self.keys[key]]\n elif isinstance(key,slice):\n return[self.__dict__[k]for k in self.keys[key]]\n raise KeyError(key)\n \n def __iter__(self):\n return(self.__dict__[key]for key in self.keys)\n \n def __len__(self):\n return len(self.keys)\n \n def __repr__(self):\n s=', '.join(f'{k}={self.__dict__[k]!r}'for k in self.keys)\n return f'sys.{self.__class__.__name__}({s})'\n \n \ndef make_dataclass(name,bases=None):\n bases=[_dataclass]if bases is None else[*bases,_dataclass]\n cls=type(name,bases,{})\n return cls\n \n \n__breakpointhook__=breakpointhook\n\nabiflags=0\n\ndef audit(event,*args):\n ''\n pass\n \nbrython_debug_mode=__BRYTHON__.get_option('debug')\n\nbase_exec_prefix=__BRYTHON__.brython_path\n\nbase_prefix=__BRYTHON__.brython_path\n\nbuiltin_module_names=__BRYTHON__.builtin_module_names\n\nbyteorder='little'\n\ncopyright=\"\"\"Copyright (c) 2001-2023 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.\"\"\"\n\ndont_write_bytecode=True\n\nexec_prefix=__BRYTHON__.brython_path\n\nargv=orig_argv=[__BRYTHON__.script_path]+list(__BRYTHON__.get_option('args'))\n\ndef displayhook(value):\n if value is not None:\n stdout.write(repr(value))\n \n__displayhook__=displayhook\n\ndef exit(i=None):\n raise SystemExit('')\n \nflags=make_dataclass('flags')(\ndebug=0,\ninspect=0,\ninteractive=0,\noptimize=0,\ndont_write_bytecode=0,\nno_user_site=0,\nno_site=0,\nignore_environment=0,\nverbose=0,\nbytes_warning=0,\nquiet=0,\nhash_randomization=1,\nisolated=0,\ndev_mode=False,\nutf8_mode=0,\nwarn_default_encoding=0\n)\n\ndef getfilesystemencoding(*args,**kw):\n ''\n\n \n return 'utf-8'\n \ndef getfilesystemencodeerrors():\n return \"utf-8\"\n \ndef intern(string):\n return string\n \nint_info=make_dataclass('int_info')(\nbits_per_digit=30,\nsizeof_digit=4,\ndefault_max_str_digits=__BRYTHON__.int_max_str_digits,\nstr_digits_check_threshold=__BRYTHON__.str_digits_check_threshold)\n\ndef get_int_max_str_digits():\n return __BRYTHON__.int_max_str_digits\n \ndef set_int_max_str_digits(value):\n try:\n value=int(value)\n except:\n raise ValueError(f\"'{value.__class__.__name__}' object \"\n \"cannot be interpreted as an integer\")\n if value !=0 and value =other\n \n return NotImplemented\n \n def __gt__(self,other):\n if isinstance(other,tuple):\n return(self.major,self.minor,self.micro)>other\n \n return NotImplemented\n \n def __le__(self,other):\n if isinstance(other,tuple):\n return(self.major,self.minor,self.micro)<=other\n \n return NotImplemented\n \n def __lt__(self,other):\n if isinstance(other,tuple):\n return(self.major,self.minor,self.micro)0:\n for name in tuple(variables):\n value=notdone[name]\n m1=re.search(_findvar1_rx,value)\n m2=re.search(_findvar2_rx,value)\n if m1 and m2:\n m=m1 if m1.start()=\"5\":\n osname=\"solaris\"\n release=f\"{int(release[0])-3}.{release[2:]}\"\n \n \n \n bitness={2147483647:\"32bit\",9223372036854775807:\"64bit\"}\n machine +=f\".{bitness[sys.maxsize]}\"\n \n elif osname[:3]==\"aix\":\n from _aix_support import aix_platform\n return aix_platform()\n elif osname[:6]==\"cygwin\":\n osname=\"cygwin\"\n import re\n rel_re=re.compile(r'[\\d.]+')\n m=rel_re.match(release)\n if m:\n release=m.group()\n elif osname[:6]==\"darwin\":\n import _osx_support\n osname,release,machine=_osx_support.get_platform_osx(\n get_config_vars(),\n osname,release,machine)\n \n return f\"{osname}-{release}-{machine}\"\n \n \ndef get_python_version():\n return _PY_VERSION_SHORT\n \n \ndef expand_makefile_vars(s,vars):\n ''\n\n\n\n\n\n \n import re\n \n \n \n \n \n \n \n while True:\n m=re.search(_findvar1_rx,s)or re.search(_findvar2_rx,s)\n if m:\n (beg,end)=m.span()\n s=s[0:beg]+vars.get(m.group(1))+s[end:]\n else:\n break\n return s\n \n \ndef _print_dict(title,data):\n for index,(key,value)in enumerate(sorted(data.items())):\n if index ==0:\n print(f'{title}: ')\n print(f'\\t{key} = \"{value}\"')\n \n \ndef _main():\n ''\n if '--generate-posix-vars'in sys.argv:\n _generate_posix_vars()\n return\n print(f'Platform: \"{get_platform()}\"')\n print(f'Python version: \"{get_python_version()}\"')\n print(f'Current installation scheme: \"{get_default_scheme()}\"')\n print()\n _print_dict('Paths',get_paths())\n print()\n _print_dict('Variables',get_config_vars())\n \n \nif __name__ =='__main__':\n _main()\n", ["_aix_support", "_imp", "_osx_support", "os", "os.path", "pprint", "re", "sys", "threading", "types", "warnings"]], "tabnanny": [".py", "#! /usr/bin/env python3\n\n\"\"\"The Tab Nanny despises ambiguous indentation. She knows no mercy.\n\ntabnanny -- Detection of ambiguous indentation\n\nFor the time being this module is intended to be called as a script.\nHowever it is possible to import it into an IDE and use the function\ncheck() described below.\n\nWarning: The API provided by this module is likely to change in future\nreleases; such changes may not be backward compatible.\n\"\"\"\n\n\n\n\n\n\n\n__version__=\"6\"\n\nimport os\nimport sys\nimport tokenize\n\n__all__=[\"check\",\"NannyNag\",\"process_tokens\"]\n\nverbose=0\nfilename_only=0\n\ndef errprint(*args):\n sep=\"\"\n for arg in args:\n sys.stderr.write(sep+str(arg))\n sep=\" \"\n sys.stderr.write(\"\\n\")\n sys.exit(1)\n \ndef main():\n import getopt\n \n global verbose,filename_only\n try:\n opts,args=getopt.getopt(sys.argv[1:],\"qv\")\n except getopt.error as msg:\n errprint(msg)\n for o,a in opts:\n if o =='-q':\n filename_only=filename_only+1\n if o =='-v':\n verbose=verbose+1\n if not args:\n errprint(\"Usage:\",sys.argv[0],\"[-v] file_or_directory ...\")\n for arg in args:\n check(arg)\n \nclass NannyNag(Exception):\n ''\n\n\n \n def __init__(self,lineno,msg,line):\n self.lineno,self.msg,self.line=lineno,msg,line\n def get_lineno(self):\n return self.lineno\n def get_msg(self):\n return self.msg\n def get_line(self):\n return self.line\n \ndef check(file):\n ''\n\n\n\n\n\n\n \n \n if os.path.isdir(file)and not os.path.islink(file):\n if verbose:\n print(\"%r: listing directory\"%(file,))\n names=os.listdir(file)\n for name in names:\n fullname=os.path.join(file,name)\n if(os.path.isdir(fullname)and\n not os.path.islink(fullname)or\n os.path.normcase(name[-3:])==\".py\"):\n check(fullname)\n return\n \n try:\n f=tokenize.open(file)\n except OSError as msg:\n errprint(\"%r: I/O Error: %s\"%(file,msg))\n return\n \n if verbose >1:\n print(\"checking %r ...\"%file)\n \n try:\n process_tokens(tokenize.generate_tokens(f.readline))\n \n except tokenize.TokenError as msg:\n errprint(\"%r: Token Error: %s\"%(file,msg))\n return\n \n except SyntaxError as msg:\n errprint(\"%r: Token Error: %s\"%(file,msg))\n return\n \n except IndentationError as msg:\n errprint(\"%r: Indentation Error: %s\"%(file,msg))\n return\n \n except NannyNag as nag:\n badline=nag.get_lineno()\n line=nag.get_line()\n if verbose:\n print(\"%r: *** Line %d: trouble in tab city! ***\"%(file,badline))\n print(\"offending line: %r\"%(line,))\n print(nag.get_msg())\n else:\n if ' 'in file:file='\"'+file+'\"'\n if filename_only:print(file)\n else:print(file,badline,repr(line))\n return\n \n finally:\n f.close()\n \n if verbose:\n print(\"%r: Clean bill of health.\"%(file,))\n \nclass Whitespace:\n\n S,T=' \\t'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def __init__(self,ws):\n self.raw=ws\n S,T=Whitespace.S,Whitespace.T\n count=[]\n b=n=nt=0\n for ch in self.raw:\n if ch ==S:\n n=n+1\n b=b+1\n elif ch ==T:\n n=n+1\n nt=nt+1\n if b >=len(count):\n count=count+[0]*(b -len(count)+1)\n count[b]=count[b]+1\n b=0\n else:\n break\n self.n=n\n self.nt=nt\n self.norm=tuple(count),b\n self.is_simple=len(count)<=1\n \n \n \n def longest_run_of_spaces(self):\n count,trailing=self.norm\n return max(len(count)-1,trailing)\n \n def indent_level(self,tabsize):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n count,trailing=self.norm\n il=0\n for i in range(tabsize,len(count)):\n il=il+i //tabsize *count[i]\n return trailing+tabsize *(il+self.nt)\n \n \n \n def equal(self,other):\n return self.norm ==other.norm\n \n \n \n \n \n def not_equal_witness(self,other):\n n=max(self.longest_run_of_spaces(),\n other.longest_run_of_spaces())+1\n a=[]\n for ts in range(1,n+1):\n if self.indent_level(ts)!=other.indent_level(ts):\n a.append((ts,\n self.indent_level(ts),\n other.indent_level(ts)))\n return a\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def less(self,other):\n if self.n >=other.n:\n return False\n if self.is_simple and other.is_simple:\n return self.nt <=other.nt\n n=max(self.longest_run_of_spaces(),\n other.longest_run_of_spaces())+1\n \n for ts in range(2,n+1):\n if self.indent_level(ts)>=other.indent_level(ts):\n return False\n return True\n \n \n \n \n \n def not_less_witness(self,other):\n n=max(self.longest_run_of_spaces(),\n other.longest_run_of_spaces())+1\n a=[]\n for ts in range(1,n+1):\n if self.indent_level(ts)>=other.indent_level(ts):\n a.append((ts,\n self.indent_level(ts),\n other.indent_level(ts)))\n return a\n \ndef format_witnesses(w):\n firsts=(str(tup[0])for tup in w)\n prefix=\"at tab size\"\n if len(w)>1:\n prefix=prefix+\"s\"\n return prefix+\" \"+', '.join(firsts)\n \ndef process_tokens(tokens):\n try:\n _process_tokens(tokens)\n except TabError as e:\n raise NannyNag(e.lineno,e.msg,e.text)\n \ndef _process_tokens(tokens):\n INDENT=tokenize.INDENT\n DEDENT=tokenize.DEDENT\n NEWLINE=tokenize.NEWLINE\n JUNK=tokenize.COMMENT,tokenize.NL\n indents=[Whitespace(\"\")]\n check_equal=0\n \n for(type,token,start,end,line)in tokens:\n if type ==NEWLINE:\n \n \n \n \n \n check_equal=1\n \n elif type ==INDENT:\n check_equal=0\n thisguy=Whitespace(token)\n if not indents[-1].less(thisguy):\n witness=indents[-1].not_less_witness(thisguy)\n msg=\"indent not greater e.g. \"+format_witnesses(witness)\n raise NannyNag(start[0],msg,line)\n indents.append(thisguy)\n \n elif type ==DEDENT:\n \n \n \n \n \n \n \n \n \n check_equal=1\n \n del indents[-1]\n \n elif check_equal and type not in JUNK:\n \n \n \n \n \n \n check_equal=0\n thisguy=Whitespace(line)\n if not indents[-1].equal(thisguy):\n witness=indents[-1].not_equal_witness(thisguy)\n msg=\"indent not equal e.g. \"+format_witnesses(witness)\n raise NannyNag(start[0],msg,line)\n \n \nif __name__ =='__main__':\n main()\n", ["getopt", "os", "sys", "tokenize"]], "tarfile": [".py", "#!/usr/bin/env python3\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n''\n\n\nversion=\"0.9.0\"\n__author__=\"Lars Gust\\u00e4bel (lars@gustaebel.de)\"\n__credits__=\"Gustavo Niemeyer, Niels Gust\\u00e4bel, Richard Townsend.\"\n\n\n\n\nfrom builtins import open as bltn_open\nimport sys\nimport os\nimport io\nimport shutil\nimport stat\nimport time\nimport struct\nimport copy\nimport re\n\ntry:\n import pwd\nexcept ImportError:\n pwd=None\ntry:\n import grp\nexcept ImportError:\n grp=None\n \n \n \n \nsymlink_exception=(AttributeError,NotImplementedError,OSError)\n\n\n__all__=[\"TarFile\",\"TarInfo\",\"is_tarfile\",\"TarError\",\"ReadError\",\n\"CompressionError\",\"StreamError\",\"ExtractError\",\"HeaderError\",\n\"ENCODING\",\"USTAR_FORMAT\",\"GNU_FORMAT\",\"PAX_FORMAT\",\n\"DEFAULT_FORMAT\",\"open\",\"fully_trusted_filter\",\"data_filter\",\n\"tar_filter\",\"FilterError\",\"AbsoluteLinkError\",\n\"OutsideDestinationError\",\"SpecialFileError\",\"AbsolutePathError\",\n\"LinkOutsideDestinationError\"]\n\n\n\n\n\nNUL=b\"\\0\"\nBLOCKSIZE=512\nRECORDSIZE=BLOCKSIZE *20\nGNU_MAGIC=b\"ustar \\0\"\nPOSIX_MAGIC=b\"ustar\\x0000\"\n\nLENGTH_NAME=100\nLENGTH_LINK=100\nLENGTH_PREFIX=155\n\nREGTYPE=b\"0\"\nAREGTYPE=b\"\\0\"\nLNKTYPE=b\"1\"\nSYMTYPE=b\"2\"\nCHRTYPE=b\"3\"\nBLKTYPE=b\"4\"\nDIRTYPE=b\"5\"\nFIFOTYPE=b\"6\"\nCONTTYPE=b\"7\"\n\nGNUTYPE_LONGNAME=b\"L\"\nGNUTYPE_LONGLINK=b\"K\"\nGNUTYPE_SPARSE=b\"S\"\n\nXHDTYPE=b\"x\"\nXGLTYPE=b\"g\"\nSOLARIS_XHDTYPE=b\"X\"\n\nUSTAR_FORMAT=0\nGNU_FORMAT=1\nPAX_FORMAT=2\nDEFAULT_FORMAT=PAX_FORMAT\n\n\n\n\n\nSUPPORTED_TYPES=(REGTYPE,AREGTYPE,LNKTYPE,\nSYMTYPE,DIRTYPE,FIFOTYPE,\nCONTTYPE,CHRTYPE,BLKTYPE,\nGNUTYPE_LONGNAME,GNUTYPE_LONGLINK,\nGNUTYPE_SPARSE)\n\n\nREGULAR_TYPES=(REGTYPE,AREGTYPE,\nCONTTYPE,GNUTYPE_SPARSE)\n\n\nGNU_TYPES=(GNUTYPE_LONGNAME,GNUTYPE_LONGLINK,\nGNUTYPE_SPARSE)\n\n\nPAX_FIELDS=(\"path\",\"linkpath\",\"size\",\"mtime\",\n\"uid\",\"gid\",\"uname\",\"gname\")\n\n\nPAX_NAME_FIELDS={\"path\",\"linkpath\",\"uname\",\"gname\"}\n\n\n\nPAX_NUMBER_FIELDS={\n\"atime\":float,\n\"ctime\":float,\n\"mtime\":float,\n\"uid\":int,\n\"gid\":int,\n\"size\":int\n}\n\n\n\n\nif os.name ==\"nt\":\n ENCODING=\"utf-8\"\nelse:\n ENCODING=sys.getfilesystemencoding()\n \n \n \n \n \ndef stn(s,length,encoding,errors):\n ''\n \n if s is None:\n raise ValueError(\"metadata cannot contain None\")\n s=s.encode(encoding,errors)\n return s[:length]+(length -len(s))*NUL\n \ndef nts(s,encoding,errors):\n ''\n \n p=s.find(b\"\\0\")\n if p !=-1:\n s=s[:p]\n return s.decode(encoding,errors)\n \ndef nti(s):\n ''\n \n \n \n if s[0]in(0o200,0o377):\n n=0\n for i in range(len(s)-1):\n n <<=8\n n +=s[i+1]\n if s[0]==0o377:\n n=-(256 **(len(s)-1)-n)\n else:\n try:\n s=nts(s,\"ascii\",\"strict\")\n n=int(s.strip()or \"0\",8)\n except ValueError:\n raise InvalidHeaderError(\"invalid header\")\n return n\n \ndef itn(n,digits=8,format=DEFAULT_FORMAT):\n ''\n \n \n \n \n \n \n \n \n \n original_n=n\n n=int(n)\n if 0 <=n <8 **(digits -1):\n s=bytes(\"%0*o\"%(digits -1,n),\"ascii\")+NUL\n elif format ==GNU_FORMAT and -256 **(digits -1)<=n <256 **(digits -1):\n if n >=0:\n s=bytearray([0o200])\n else:\n s=bytearray([0o377])\n n=256 **digits+n\n \n for i in range(digits -1):\n s.insert(1,n&0o377)\n n >>=8\n else:\n raise ValueError(\"overflow in number field\")\n \n return s\n \ndef calc_chksums(buf):\n ''\n\n\n\n\n\n\n \n unsigned_chksum=256+sum(struct.unpack_from(\"148B8x356B\",buf))\n signed_chksum=256+sum(struct.unpack_from(\"148b8x356b\",buf))\n return unsigned_chksum,signed_chksum\n \ndef copyfileobj(src,dst,length=None,exception=OSError,bufsize=None):\n ''\n\n \n bufsize=bufsize or 16 *1024\n if length ==0:\n return\n if length is None:\n shutil.copyfileobj(src,dst,bufsize)\n return\n \n blocks,remainder=divmod(length,bufsize)\n for b in range(blocks):\n buf=src.read(bufsize)\n if len(buf)self.bufsize:\n self.fileobj.write(self.buf[:self.bufsize])\n self.buf=self.buf[self.bufsize:]\n \n def close(self):\n ''\n\n \n if self.closed:\n return\n \n self.closed=True\n try:\n if self.mode ==\"w\"and self.comptype !=\"tar\":\n self.buf +=self.cmp.flush()\n \n if self.mode ==\"w\"and self.buf:\n self.fileobj.write(self.buf)\n self.buf=b\"\"\n if self.comptype ==\"gz\":\n self.fileobj.write(struct.pack(\"=0:\n blocks,remainder=divmod(pos -self.pos,self.bufsize)\n for i in range(blocks):\n self.read(self.bufsize)\n self.read(remainder)\n else:\n raise StreamError(\"seeking backwards is not allowed\")\n return self.pos\n \n def read(self,size):\n ''\n assert size is not None\n buf=self._read(size)\n self.pos +=len(buf)\n return buf\n \n def _read(self,size):\n ''\n \n if self.comptype ==\"tar\":\n return self.__read(size)\n \n c=len(self.dbuf)\n t=[self.dbuf]\n while c lastpos:\n self.map.append((False,lastpos,offset,None))\n self.map.append((True,offset,offset+size,realpos))\n realpos +=size\n lastpos=offset+size\n if lastpos 0:\n while True:\n data,start,stop,offset=self.map[self.map_index]\n if start <=self.position \"%(self.__class__.__name__,self.name,id(self))\n \n def replace(self,*,\n name=_KEEP,mtime=_KEEP,mode=_KEEP,linkname=_KEEP,\n uid=_KEEP,gid=_KEEP,uname=_KEEP,gname=_KEEP,\n deep=True,_KEEP=_KEEP):\n ''\n \n if deep:\n result=copy.deepcopy(self)\n else:\n result=copy.copy(self)\n if name is not _KEEP:\n result.name=name\n if mtime is not _KEEP:\n result.mtime=mtime\n if mode is not _KEEP:\n result.mode=mode\n if linkname is not _KEEP:\n result.linkname=linkname\n if uid is not _KEEP:\n result.uid=uid\n if gid is not _KEEP:\n result.gid=gid\n if uname is not _KEEP:\n result.uname=uname\n if gname is not _KEEP:\n result.gname=gname\n return result\n \n def get_info(self):\n ''\n \n if self.mode is None:\n mode=None\n else:\n mode=self.mode&0o7777\n info={\n \"name\":self.name,\n \"mode\":mode,\n \"uid\":self.uid,\n \"gid\":self.gid,\n \"size\":self.size,\n \"mtime\":self.mtime,\n \"chksum\":self.chksum,\n \"type\":self.type,\n \"linkname\":self.linkname,\n \"uname\":self.uname,\n \"gname\":self.gname,\n \"devmajor\":self.devmajor,\n \"devminor\":self.devminor\n }\n \n if info[\"type\"]==DIRTYPE and not info[\"name\"].endswith(\"/\"):\n info[\"name\"]+=\"/\"\n \n return info\n \n def tobuf(self,format=DEFAULT_FORMAT,encoding=ENCODING,errors=\"surrogateescape\"):\n ''\n \n info=self.get_info()\n for name,value in info.items():\n if value is None:\n raise ValueError(\"%s may not be None\"%name)\n \n if format ==USTAR_FORMAT:\n return self.create_ustar_header(info,encoding,errors)\n elif format ==GNU_FORMAT:\n return self.create_gnu_header(info,encoding,errors)\n elif format ==PAX_FORMAT:\n return self.create_pax_header(info,encoding)\n else:\n raise ValueError(\"invalid format\")\n \n def create_ustar_header(self,info,encoding,errors):\n ''\n \n info[\"magic\"]=POSIX_MAGIC\n \n if len(info[\"linkname\"].encode(encoding,errors))>LENGTH_LINK:\n raise ValueError(\"linkname is too long\")\n \n if len(info[\"name\"].encode(encoding,errors))>LENGTH_NAME:\n info[\"prefix\"],info[\"name\"]=self._posix_split_name(info[\"name\"],encoding,errors)\n \n return self._create_header(info,USTAR_FORMAT,encoding,errors)\n \n def create_gnu_header(self,info,encoding,errors):\n ''\n \n info[\"magic\"]=GNU_MAGIC\n \n buf=b\"\"\n if len(info[\"linkname\"].encode(encoding,errors))>LENGTH_LINK:\n buf +=self._create_gnu_long_header(info[\"linkname\"],GNUTYPE_LONGLINK,encoding,errors)\n \n if len(info[\"name\"].encode(encoding,errors))>LENGTH_NAME:\n buf +=self._create_gnu_long_header(info[\"name\"],GNUTYPE_LONGNAME,encoding,errors)\n \n return buf+self._create_header(info,GNU_FORMAT,encoding,errors)\n \n def create_pax_header(self,info,encoding):\n ''\n\n\n \n info[\"magic\"]=POSIX_MAGIC\n pax_headers=self.pax_headers.copy()\n \n \n \n for name,hname,length in(\n (\"name\",\"path\",LENGTH_NAME),(\"linkname\",\"linkpath\",LENGTH_LINK),\n (\"uname\",\"uname\",32),(\"gname\",\"gname\",32)):\n \n if hname in pax_headers:\n \n continue\n \n \n try:\n info[name].encode(\"ascii\",\"strict\")\n except UnicodeEncodeError:\n pax_headers[hname]=info[name]\n continue\n \n if len(info[name])>length:\n pax_headers[hname]=info[name]\n \n \n \n for name,digits in((\"uid\",8),(\"gid\",8),(\"size\",12),(\"mtime\",12)):\n needs_pax=False\n \n val=info[name]\n val_is_float=isinstance(val,float)\n val_int=round(val)if val_is_float else val\n if not 0 <=val_int <8 **(digits -1):\n \n info[name]=0\n needs_pax=True\n elif val_is_float:\n \n \n info[name]=val_int\n needs_pax=True\n \n \n if needs_pax and name not in pax_headers:\n pax_headers[name]=str(val)\n \n \n if pax_headers:\n buf=self._create_pax_generic_header(pax_headers,XHDTYPE,encoding)\n else:\n buf=b\"\"\n \n return buf+self._create_header(info,USTAR_FORMAT,\"ascii\",\"replace\")\n \n @classmethod\n def create_pax_global_header(cls,pax_headers):\n ''\n \n return cls._create_pax_generic_header(pax_headers,XGLTYPE,\"utf-8\")\n \n def _posix_split_name(self,name,encoding,errors):\n ''\n\n \n components=name.split(\"/\")\n for i in range(1,len(components)):\n prefix=\"/\".join(components[:i])\n name=\"/\".join(components[i:])\n if len(prefix.encode(encoding,errors))<=LENGTH_PREFIX and\\\n len(name.encode(encoding,errors))<=LENGTH_NAME:\n break\n else:\n raise ValueError(\"name is too long\")\n \n return prefix,name\n \n @staticmethod\n def _create_header(info,format,encoding,errors):\n ''\n\n \n has_device_fields=info.get(\"type\")in(CHRTYPE,BLKTYPE)\n if has_device_fields:\n devmajor=itn(info.get(\"devmajor\",0),8,format)\n devminor=itn(info.get(\"devminor\",0),8,format)\n else:\n devmajor=stn(\"\",8,encoding,errors)\n devminor=stn(\"\",8,encoding,errors)\n \n \n \n filetype=info.get(\"type\",REGTYPE)\n if filetype is None:\n raise ValueError(\"TarInfo.type must not be None\")\n \n parts=[\n stn(info.get(\"name\",\"\"),100,encoding,errors),\n itn(info.get(\"mode\",0)&0o7777,8,format),\n itn(info.get(\"uid\",0),8,format),\n itn(info.get(\"gid\",0),8,format),\n itn(info.get(\"size\",0),12,format),\n itn(info.get(\"mtime\",0),12,format),\n b\" \",\n filetype,\n stn(info.get(\"linkname\",\"\"),100,encoding,errors),\n info.get(\"magic\",POSIX_MAGIC),\n stn(info.get(\"uname\",\"\"),32,encoding,errors),\n stn(info.get(\"gname\",\"\"),32,encoding,errors),\n devmajor,\n devminor,\n stn(info.get(\"prefix\",\"\"),155,encoding,errors)\n ]\n \n buf=struct.pack(\"%ds\"%BLOCKSIZE,b\"\".join(parts))\n chksum=calc_chksums(buf[-BLOCKSIZE:])[0]\n buf=buf[:-364]+bytes(\"%06o\\0\"%chksum,\"ascii\")+buf[-357:]\n return buf\n \n @staticmethod\n def _create_payload(payload):\n ''\n\n \n blocks,remainder=divmod(len(payload),BLOCKSIZE)\n if remainder >0:\n payload +=(BLOCKSIZE -remainder)*NUL\n return payload\n \n @classmethod\n def _create_gnu_long_header(cls,name,type,encoding,errors):\n ''\n\n \n name=name.encode(encoding,errors)+NUL\n \n info={}\n info[\"name\"]=\"././@LongLink\"\n info[\"type\"]=type\n info[\"size\"]=len(name)\n info[\"magic\"]=GNU_MAGIC\n \n \n return cls._create_header(info,USTAR_FORMAT,encoding,errors)+\\\n cls._create_payload(name)\n \n @classmethod\n def _create_pax_generic_header(cls,pax_headers,type,encoding):\n ''\n\n\n \n \n \n binary=False\n for keyword,value in pax_headers.items():\n try:\n value.encode(\"utf-8\",\"strict\")\n except UnicodeEncodeError:\n binary=True\n break\n \n records=b\"\"\n if binary:\n \n records +=b\"21 hdrcharset=BINARY\\n\"\n \n for keyword,value in pax_headers.items():\n keyword=keyword.encode(\"utf-8\")\n if binary:\n \n \n value=value.encode(encoding,\"surrogateescape\")\n else:\n value=value.encode(\"utf-8\")\n \n l=len(keyword)+len(value)+3\n n=p=0\n while True:\n n=l+len(str(p))\n if n ==p:\n break\n p=n\n records +=bytes(str(p),\"ascii\")+b\" \"+keyword+b\"=\"+value+b\"\\n\"\n \n \n \n info={}\n info[\"name\"]=\"././@PaxHeader\"\n info[\"type\"]=type\n info[\"size\"]=len(records)\n info[\"magic\"]=POSIX_MAGIC\n \n \n return cls._create_header(info,USTAR_FORMAT,\"ascii\",\"replace\")+\\\n cls._create_payload(records)\n \n @classmethod\n def frombuf(cls,buf,encoding,errors):\n ''\n \n if len(buf)==0:\n raise EmptyHeaderError(\"empty header\")\n if len(buf)!=BLOCKSIZE:\n raise TruncatedHeaderError(\"truncated header\")\n if buf.count(NUL)==BLOCKSIZE:\n raise EOFHeaderError(\"end of file header\")\n \n chksum=nti(buf[148:156])\n if chksum not in calc_chksums(buf):\n raise InvalidHeaderError(\"bad checksum\")\n \n obj=cls()\n obj.name=nts(buf[0:100],encoding,errors)\n obj.mode=nti(buf[100:108])\n obj.uid=nti(buf[108:116])\n obj.gid=nti(buf[116:124])\n obj.size=nti(buf[124:136])\n obj.mtime=nti(buf[136:148])\n obj.chksum=chksum\n obj.type=buf[156:157]\n obj.linkname=nts(buf[157:257],encoding,errors)\n obj.uname=nts(buf[265:297],encoding,errors)\n obj.gname=nts(buf[297:329],encoding,errors)\n obj.devmajor=nti(buf[329:337])\n obj.devminor=nti(buf[337:345])\n prefix=nts(buf[345:500],encoding,errors)\n \n \n \n if obj.type ==AREGTYPE and obj.name.endswith(\"/\"):\n obj.type=DIRTYPE\n \n \n \n \n if obj.type ==GNUTYPE_SPARSE:\n pos=386\n structs=[]\n for i in range(4):\n try:\n offset=nti(buf[pos:pos+12])\n numbytes=nti(buf[pos+12:pos+24])\n except ValueError:\n break\n structs.append((offset,numbytes))\n pos +=24\n isextended=bool(buf[482])\n origsize=nti(buf[483:495])\n obj._sparse_structs=(structs,isextended,origsize)\n \n \n if obj.isdir():\n obj.name=obj.name.rstrip(\"/\")\n \n \n if prefix and obj.type not in GNU_TYPES:\n obj.name=prefix+\"/\"+obj.name\n return obj\n \n @classmethod\n def fromtarfile(cls,tarfile):\n ''\n\n \n buf=tarfile.fileobj.read(BLOCKSIZE)\n obj=cls.frombuf(buf,tarfile.encoding,tarfile.errors)\n obj.offset=tarfile.fileobj.tell()-BLOCKSIZE\n return obj._proc_member(tarfile)\n \n \n \n \n \n \n \n \n \n \n \n \n def _proc_member(self,tarfile):\n ''\n\n \n if self.type in(GNUTYPE_LONGNAME,GNUTYPE_LONGLINK):\n return self._proc_gnulong(tarfile)\n elif self.type ==GNUTYPE_SPARSE:\n return self._proc_sparse(tarfile)\n elif self.type in(XHDTYPE,XGLTYPE,SOLARIS_XHDTYPE):\n return self._proc_pax(tarfile)\n else:\n return self._proc_builtin(tarfile)\n \n def _proc_builtin(self,tarfile):\n ''\n\n \n self.offset_data=tarfile.fileobj.tell()\n offset=self.offset_data\n if self.isreg()or self.type not in SUPPORTED_TYPES:\n \n offset +=self._block(self.size)\n tarfile.offset=offset\n \n \n \n self._apply_pax_info(tarfile.pax_headers,tarfile.encoding,tarfile.errors)\n \n \n \n if self.isdir():\n self.name=self.name.rstrip(\"/\")\n \n return self\n \n def _proc_gnulong(self,tarfile):\n ''\n\n \n buf=tarfile.fileobj.read(self._block(self.size))\n \n \n try:\n next=self.fromtarfile(tarfile)\n except HeaderError as e:\n raise SubsequentHeaderError(str(e))from None\n \n \n \n next.offset=self.offset\n if self.type ==GNUTYPE_LONGNAME:\n next.name=nts(buf,tarfile.encoding,tarfile.errors)\n elif self.type ==GNUTYPE_LONGLINK:\n next.linkname=nts(buf,tarfile.encoding,tarfile.errors)\n \n \n \n if next.isdir():\n next.name=next.name.removesuffix(\"/\")\n \n return next\n \n def _proc_sparse(self,tarfile):\n ''\n \n \n structs,isextended,origsize=self._sparse_structs\n del self._sparse_structs\n \n \n while isextended:\n buf=tarfile.fileobj.read(BLOCKSIZE)\n pos=0\n for i in range(21):\n try:\n offset=nti(buf[pos:pos+12])\n numbytes=nti(buf[pos+12:pos+24])\n except ValueError:\n break\n if offset and numbytes:\n structs.append((offset,numbytes))\n pos +=24\n isextended=bool(buf[504])\n self.sparse=structs\n \n self.offset_data=tarfile.fileobj.tell()\n tarfile.offset=self.offset_data+self._block(self.size)\n self.size=origsize\n return self\n \n def _proc_pax(self,tarfile):\n ''\n\n \n \n buf=tarfile.fileobj.read(self._block(self.size))\n \n \n \n \n if self.type ==XGLTYPE:\n pax_headers=tarfile.pax_headers\n else:\n pax_headers=tarfile.pax_headers.copy()\n \n \n \n \n \n \n match=re.search(br\"\\d+ hdrcharset=([^\\n]+)\\n\",buf)\n if match is not None:\n pax_headers[\"hdrcharset\"]=match.group(1).decode(\"utf-8\")\n \n \n \n \n hdrcharset=pax_headers.get(\"hdrcharset\")\n if hdrcharset ==\"BINARY\":\n encoding=tarfile.encoding\n else:\n encoding=\"utf-8\"\n \n \n \n \n \n regex=re.compile(br\"(\\d+) ([^=]+)=\")\n pos=0\n while match :=regex.match(buf,pos):\n length,keyword=match.groups()\n length=int(length)\n if length ==0:\n raise InvalidHeaderError(\"invalid header\")\n value=buf[match.end(2)+1:match.start(1)+length -1]\n \n \n \n \n \n \n \n \n keyword=self._decode_pax_field(keyword,\"utf-8\",\"utf-8\",\n tarfile.errors)\n if keyword in PAX_NAME_FIELDS:\n value=self._decode_pax_field(value,encoding,tarfile.encoding,\n tarfile.errors)\n else:\n value=self._decode_pax_field(value,\"utf-8\",\"utf-8\",\n tarfile.errors)\n \n pax_headers[keyword]=value\n pos +=length\n \n \n try:\n next=self.fromtarfile(tarfile)\n except HeaderError as e:\n raise SubsequentHeaderError(str(e))from None\n \n \n if \"GNU.sparse.map\"in pax_headers:\n \n self._proc_gnusparse_01(next,pax_headers)\n \n elif \"GNU.sparse.size\"in pax_headers:\n \n self._proc_gnusparse_00(next,pax_headers,buf)\n \n elif pax_headers.get(\"GNU.sparse.major\")==\"1\"and pax_headers.get(\"GNU.sparse.minor\")==\"0\":\n \n self._proc_gnusparse_10(next,pax_headers,tarfile)\n \n if self.type in(XHDTYPE,SOLARIS_XHDTYPE):\n \n next._apply_pax_info(pax_headers,tarfile.encoding,tarfile.errors)\n next.offset=self.offset\n \n if \"size\"in pax_headers:\n \n \n \n offset=next.offset_data\n if next.isreg()or next.type not in SUPPORTED_TYPES:\n offset +=next._block(next.size)\n tarfile.offset=offset\n \n return next\n \n def _proc_gnusparse_00(self,next,pax_headers,buf):\n ''\n \n offsets=[]\n for match in re.finditer(br\"\\d+ GNU.sparse.offset=(\\d+)\\n\",buf):\n offsets.append(int(match.group(1)))\n numbytes=[]\n for match in re.finditer(br\"\\d+ GNU.sparse.numbytes=(\\d+)\\n\",buf):\n numbytes.append(int(match.group(1)))\n next.sparse=list(zip(offsets,numbytes))\n \n def _proc_gnusparse_01(self,next,pax_headers):\n ''\n \n sparse=[int(x)for x in pax_headers[\"GNU.sparse.map\"].split(\",\")]\n next.sparse=list(zip(sparse[::2],sparse[1::2]))\n \n def _proc_gnusparse_10(self,next,pax_headers,tarfile):\n ''\n \n fields=None\n sparse=[]\n buf=tarfile.fileobj.read(BLOCKSIZE)\n fields,buf=buf.split(b\"\\n\",1)\n fields=int(fields)\n while len(sparse)0:\n self.fileobj.write(NUL *(RECORDSIZE -remainder))\n finally:\n if not self._extfileobj:\n self.fileobj.close()\n \n def getmember(self,name):\n ''\n\n\n\n \n tarinfo=self._getmember(name.rstrip('/'))\n if tarinfo is None:\n raise KeyError(\"filename %r not found\"%name)\n return tarinfo\n \n def getmembers(self):\n ''\n\n \n self._check()\n if not self._loaded:\n self._load()\n \n return self.members\n \n def getnames(self):\n ''\n\n \n return[tarinfo.name for tarinfo in self.getmembers()]\n \n def gettarinfo(self,name=None,arcname=None,fileobj=None):\n ''\n\n\n\n\n\n\n \n self._check(\"awx\")\n \n \n \n if fileobj is not None:\n name=fileobj.name\n \n \n \n \n if arcname is None:\n arcname=name\n drv,arcname=os.path.splitdrive(arcname)\n arcname=arcname.replace(os.sep,\"/\")\n arcname=arcname.lstrip(\"/\")\n \n \n \n tarinfo=self.tarinfo()\n tarinfo._tarfile=self\n \n \n if fileobj is None:\n if not self.dereference:\n statres=os.lstat(name)\n else:\n statres=os.stat(name)\n else:\n statres=os.fstat(fileobj.fileno())\n linkname=\"\"\n \n stmd=statres.st_mode\n if stat.S_ISREG(stmd):\n inode=(statres.st_ino,statres.st_dev)\n if not self.dereference and statres.st_nlink >1 and\\\n inode in self.inodes and arcname !=self.inodes[inode]:\n \n \n type=LNKTYPE\n linkname=self.inodes[inode]\n else:\n \n \n type=REGTYPE\n if inode[0]:\n self.inodes[inode]=arcname\n elif stat.S_ISDIR(stmd):\n type=DIRTYPE\n elif stat.S_ISFIFO(stmd):\n type=FIFOTYPE\n elif stat.S_ISLNK(stmd):\n type=SYMTYPE\n linkname=os.readlink(name)\n elif stat.S_ISCHR(stmd):\n type=CHRTYPE\n elif stat.S_ISBLK(stmd):\n type=BLKTYPE\n else:\n return None\n \n \n \n tarinfo.name=arcname\n tarinfo.mode=stmd\n tarinfo.uid=statres.st_uid\n tarinfo.gid=statres.st_gid\n if type ==REGTYPE:\n tarinfo.size=statres.st_size\n else:\n tarinfo.size=0\n tarinfo.mtime=statres.st_mtime\n tarinfo.type=type\n tarinfo.linkname=linkname\n if pwd:\n try:\n tarinfo.uname=pwd.getpwuid(tarinfo.uid)[0]\n except KeyError:\n pass\n if grp:\n try:\n tarinfo.gname=grp.getgrgid(tarinfo.gid)[0]\n except KeyError:\n pass\n \n if type in(CHRTYPE,BLKTYPE):\n if hasattr(os,\"major\")and hasattr(os,\"minor\"):\n tarinfo.devmajor=os.major(statres.st_rdev)\n tarinfo.devminor=os.minor(statres.st_rdev)\n return tarinfo\n \n def list(self,verbose=True,*,members=None):\n ''\n\n\n\n \n \n type2mode={REGTYPE:stat.S_IFREG,SYMTYPE:stat.S_IFLNK,\n FIFOTYPE:stat.S_IFIFO,CHRTYPE:stat.S_IFCHR,\n DIRTYPE:stat.S_IFDIR,BLKTYPE:stat.S_IFBLK}\n self._check()\n \n if members is None:\n members=self\n for tarinfo in members:\n if verbose:\n if tarinfo.mode is None:\n _safe_print(\"??????????\")\n else:\n modetype=type2mode.get(tarinfo.type,0)\n _safe_print(stat.filemode(modetype |tarinfo.mode))\n _safe_print(\"%s/%s\"%(tarinfo.uname or tarinfo.uid,\n tarinfo.gname or tarinfo.gid))\n if tarinfo.ischr()or tarinfo.isblk():\n _safe_print(\"%10s\"%\n (\"%d,%d\"%(tarinfo.devmajor,tarinfo.devminor)))\n else:\n _safe_print(\"%10d\"%tarinfo.size)\n if tarinfo.mtime is None:\n _safe_print(\"????-??-?? ??:??:??\")\n else:\n _safe_print(\"%d-%02d-%02d %02d:%02d:%02d\"\\\n %time.localtime(tarinfo.mtime)[:6])\n \n _safe_print(tarinfo.name+(\"/\"if tarinfo.isdir()else \"\"))\n \n if verbose:\n if tarinfo.issym():\n _safe_print(\"-> \"+tarinfo.linkname)\n if tarinfo.islnk():\n _safe_print(\"link to \"+tarinfo.linkname)\n print()\n \n def add(self,name,arcname=None,recursive=True,*,filter=None):\n ''\n\n\n\n\n\n\n\n \n self._check(\"awx\")\n \n if arcname is None:\n arcname=name\n \n \n if self.name is not None and os.path.abspath(name)==self.name:\n self._dbg(2,\"tarfile: Skipped %r\"%name)\n return\n \n self._dbg(1,name)\n \n \n tarinfo=self.gettarinfo(name,arcname)\n \n if tarinfo is None:\n self._dbg(1,\"tarfile: Unsupported type %r\"%name)\n return\n \n \n if filter is not None:\n tarinfo=filter(tarinfo)\n if tarinfo is None:\n self._dbg(2,\"tarfile: Excluded %r\"%name)\n return\n \n \n if tarinfo.isreg():\n with bltn_open(name,\"rb\")as f:\n self.addfile(tarinfo,f)\n \n elif tarinfo.isdir():\n self.addfile(tarinfo)\n if recursive:\n for f in sorted(os.listdir(name)):\n self.add(os.path.join(name,f),os.path.join(arcname,f),\n recursive,filter=filter)\n \n else:\n self.addfile(tarinfo)\n \n def addfile(self,tarinfo,fileobj=None):\n ''\n\n\n\n \n self._check(\"awx\")\n \n if fileobj is None and tarinfo.isreg()and tarinfo.size !=0:\n raise ValueError(\"fileobj not provided for non zero-size regular file\")\n \n tarinfo=copy.copy(tarinfo)\n \n buf=tarinfo.tobuf(self.format,self.encoding,self.errors)\n self.fileobj.write(buf)\n self.offset +=len(buf)\n bufsize=self.copybufsize\n \n if fileobj is not None:\n copyfileobj(fileobj,self.fileobj,tarinfo.size,bufsize=bufsize)\n blocks,remainder=divmod(tarinfo.size,BLOCKSIZE)\n if remainder >0:\n self.fileobj.write(NUL *(BLOCKSIZE -remainder))\n blocks +=1\n self.offset +=blocks *BLOCKSIZE\n \n self.members.append(tarinfo)\n \n def _get_filter_function(self,filter):\n if filter is None:\n filter=self.extraction_filter\n if filter is None:\n import warnings\n warnings.warn(\n 'Python 3.14 will, by default, filter extracted tar '\n +'archives and reject files or modify their metadata. '\n +'Use the filter argument to control this behavior.',\n DeprecationWarning,stacklevel=3)\n return fully_trusted_filter\n if isinstance(filter,str):\n raise TypeError(\n 'String names are not supported for '\n +'TarFile.extraction_filter. Use a function such as '\n +'tarfile.data_filter directly.')\n return filter\n if callable(filter):\n return filter\n try:\n return _NAMED_FILTERS[filter]\n except KeyError:\n raise ValueError(f\"filter {filter !r} not found\")from None\n \n def extractall(self,path=\".\",members=None,*,numeric_owner=False,\n filter=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n directories=[]\n \n filter_function=self._get_filter_function(filter)\n if members is None:\n members=self\n \n for member in members:\n tarinfo=self._get_extract_tarinfo(member,filter_function,path)\n if tarinfo is None:\n continue\n if tarinfo.isdir():\n \n \n \n directories.append(tarinfo)\n self._extract_one(tarinfo,path,set_attrs=not tarinfo.isdir(),\n numeric_owner=numeric_owner)\n \n \n directories.sort(key=lambda a:a.name,reverse=True)\n \n \n for tarinfo in directories:\n dirpath=os.path.join(path,tarinfo.name)\n try:\n self.chown(tarinfo,dirpath,numeric_owner=numeric_owner)\n self.utime(tarinfo,dirpath)\n self.chmod(tarinfo,dirpath)\n except ExtractError as e:\n self._handle_nonfatal_error(e)\n \n def extract(self,member,path=\"\",set_attrs=True,*,numeric_owner=False,\n filter=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n filter_function=self._get_filter_function(filter)\n tarinfo=self._get_extract_tarinfo(member,filter_function,path)\n if tarinfo is not None:\n self._extract_one(tarinfo,path,set_attrs,numeric_owner)\n \n def _get_extract_tarinfo(self,member,filter_function,path):\n ''\n if isinstance(member,str):\n tarinfo=self.getmember(member)\n else:\n tarinfo=member\n \n unfiltered=tarinfo\n try:\n tarinfo=filter_function(tarinfo,path)\n except(OSError,FilterError)as e:\n self._handle_fatal_error(e)\n except ExtractError as e:\n self._handle_nonfatal_error(e)\n if tarinfo is None:\n self._dbg(2,\"tarfile: Excluded %r\"%unfiltered.name)\n return None\n \n if tarinfo.islnk():\n tarinfo=copy.copy(tarinfo)\n tarinfo._link_target=os.path.join(path,tarinfo.linkname)\n return tarinfo\n \n def _extract_one(self,tarinfo,path,set_attrs,numeric_owner):\n ''\n self._check(\"r\")\n \n try:\n self._extract_member(tarinfo,os.path.join(path,tarinfo.name),\n set_attrs=set_attrs,\n numeric_owner=numeric_owner)\n except OSError as e:\n self._handle_fatal_error(e)\n except ExtractError as e:\n self._handle_nonfatal_error(e)\n \n def _handle_nonfatal_error(self,e):\n ''\n if self.errorlevel >1:\n raise\n else:\n self._dbg(1,\"tarfile: %s\"%e)\n \n def _handle_fatal_error(self,e):\n ''\n if self.errorlevel >0:\n raise\n elif isinstance(e,OSError):\n if e.filename is None:\n self._dbg(1,\"tarfile: %s\"%e.strerror)\n else:\n self._dbg(1,\"tarfile: %s %r\"%(e.strerror,e.filename))\n else:\n self._dbg(1,\"tarfile: %s %s\"%(type(e).__name__,e))\n \n def extractfile(self,member):\n ''\n\n\n\n\n \n self._check(\"r\")\n \n if isinstance(member,str):\n tarinfo=self.getmember(member)\n else:\n tarinfo=member\n \n if tarinfo.isreg()or tarinfo.type not in SUPPORTED_TYPES:\n \n return self.fileobject(self,tarinfo)\n \n elif tarinfo.islnk()or tarinfo.issym():\n if isinstance(self.fileobj,_Stream):\n \n \n \n raise StreamError(\"cannot extract (sym)link as file object\")\n else:\n \n return self.extractfile(self._find_link_target(tarinfo))\n else:\n \n \n return None\n \n def _extract_member(self,tarinfo,targetpath,set_attrs=True,\n numeric_owner=False):\n ''\n\n \n \n \n \n targetpath=targetpath.rstrip(\"/\")\n targetpath=targetpath.replace(\"/\",os.sep)\n \n \n upperdirs=os.path.dirname(targetpath)\n if upperdirs and not os.path.exists(upperdirs):\n \n \n os.makedirs(upperdirs,exist_ok=True)\n \n if tarinfo.islnk()or tarinfo.issym():\n self._dbg(1,\"%s -> %s\"%(tarinfo.name,tarinfo.linkname))\n else:\n self._dbg(1,tarinfo.name)\n \n if tarinfo.isreg():\n self.makefile(tarinfo,targetpath)\n elif tarinfo.isdir():\n self.makedir(tarinfo,targetpath)\n elif tarinfo.isfifo():\n self.makefifo(tarinfo,targetpath)\n elif tarinfo.ischr()or tarinfo.isblk():\n self.makedev(tarinfo,targetpath)\n elif tarinfo.islnk()or tarinfo.issym():\n self.makelink(tarinfo,targetpath)\n elif tarinfo.type not in SUPPORTED_TYPES:\n self.makeunknown(tarinfo,targetpath)\n else:\n self.makefile(tarinfo,targetpath)\n \n if set_attrs:\n self.chown(tarinfo,targetpath,numeric_owner)\n if not tarinfo.issym():\n self.chmod(tarinfo,targetpath)\n self.utime(tarinfo,targetpath)\n \n \n \n \n \n \n def makedir(self,tarinfo,targetpath):\n ''\n \n try:\n if tarinfo.mode is None:\n \n os.mkdir(targetpath)\n else:\n \n \n os.mkdir(targetpath,0o700)\n except FileExistsError:\n if not os.path.isdir(targetpath):\n raise\n \n def makefile(self,tarinfo,targetpath):\n ''\n \n source=self.fileobj\n source.seek(tarinfo.offset_data)\n bufsize=self.copybufsize\n with bltn_open(targetpath,\"wb\")as target:\n if tarinfo.sparse is not None:\n for offset,size in tarinfo.sparse:\n target.seek(offset)\n copyfileobj(source,target,size,ReadError,bufsize)\n target.seek(tarinfo.size)\n target.truncate()\n else:\n copyfileobj(source,target,tarinfo.size,ReadError,bufsize)\n \n def makeunknown(self,tarinfo,targetpath):\n ''\n\n \n self.makefile(tarinfo,targetpath)\n self._dbg(1,\"tarfile: Unknown file type %r, \"\\\n \"extracted as regular file.\"%tarinfo.type)\n \n def makefifo(self,tarinfo,targetpath):\n ''\n \n if hasattr(os,\"mkfifo\"):\n os.mkfifo(targetpath)\n else:\n raise ExtractError(\"fifo not supported by system\")\n \n def makedev(self,tarinfo,targetpath):\n ''\n \n if not hasattr(os,\"mknod\")or not hasattr(os,\"makedev\"):\n raise ExtractError(\"special devices not supported by system\")\n \n mode=tarinfo.mode\n if mode is None:\n \n mode=0o600\n if tarinfo.isblk():\n mode |=stat.S_IFBLK\n else:\n mode |=stat.S_IFCHR\n \n os.mknod(targetpath,mode,\n os.makedev(tarinfo.devmajor,tarinfo.devminor))\n \n def makelink(self,tarinfo,targetpath):\n ''\n\n\n \n try:\n \n if tarinfo.issym():\n if os.path.lexists(targetpath):\n \n os.unlink(targetpath)\n os.symlink(tarinfo.linkname,targetpath)\n else:\n if os.path.exists(tarinfo._link_target):\n os.link(tarinfo._link_target,targetpath)\n else:\n self._extract_member(self._find_link_target(tarinfo),\n targetpath)\n except symlink_exception:\n try:\n self._extract_member(self._find_link_target(tarinfo),\n targetpath)\n except KeyError:\n raise ExtractError(\"unable to resolve link inside archive\")from None\n \n def chown(self,tarinfo,targetpath,numeric_owner):\n ''\n\n\n\n \n if hasattr(os,\"geteuid\")and os.geteuid()==0:\n \n g=tarinfo.gid\n u=tarinfo.uid\n if not numeric_owner:\n try:\n if grp and tarinfo.gname:\n g=grp.getgrnam(tarinfo.gname)[2]\n except KeyError:\n pass\n try:\n if pwd and tarinfo.uname:\n u=pwd.getpwnam(tarinfo.uname)[2]\n except KeyError:\n pass\n if g is None:\n g=-1\n if u is None:\n u=-1\n try:\n if tarinfo.issym()and hasattr(os,\"lchown\"):\n os.lchown(targetpath,u,g)\n else:\n os.chown(targetpath,u,g)\n except(OSError,OverflowError)as e:\n \n raise ExtractError(\"could not change owner\")from e\n \n def chmod(self,tarinfo,targetpath):\n ''\n \n if tarinfo.mode is None:\n return\n try:\n os.chmod(targetpath,tarinfo.mode)\n except OSError as e:\n raise ExtractError(\"could not change mode\")from e\n \n def utime(self,tarinfo,targetpath):\n ''\n \n mtime=tarinfo.mtime\n if mtime is None:\n return\n if not hasattr(os,'utime'):\n return\n try:\n os.utime(targetpath,(mtime,mtime))\n except OSError as e:\n raise ExtractError(\"could not change modification time\")from e\n \n \n def next(self):\n ''\n\n\n \n self._check(\"ra\")\n if self.firstmember is not None:\n m=self.firstmember\n self.firstmember=None\n return m\n \n \n if self.offset !=self.fileobj.tell():\n if self.offset ==0:\n return None\n self.fileobj.seek(self.offset -1)\n if not self.fileobj.read(1):\n raise ReadError(\"unexpected end of data\")\n \n \n tarinfo=None\n while True:\n try:\n tarinfo=self.tarinfo.fromtarfile(self)\n except EOFHeaderError as e:\n if self.ignore_zeros:\n self._dbg(2,\"0x%X: %s\"%(self.offset,e))\n self.offset +=BLOCKSIZE\n continue\n except InvalidHeaderError as e:\n if self.ignore_zeros:\n self._dbg(2,\"0x%X: %s\"%(self.offset,e))\n self.offset +=BLOCKSIZE\n continue\n elif self.offset ==0:\n raise ReadError(str(e))from None\n except EmptyHeaderError:\n if self.offset ==0:\n raise ReadError(\"empty file\")from None\n except TruncatedHeaderError as e:\n if self.offset ==0:\n raise ReadError(str(e))from None\n except SubsequentHeaderError as e:\n raise ReadError(str(e))from None\n except Exception as e:\n try:\n import zlib\n if isinstance(e,zlib.error):\n raise ReadError(f'zlib error: {e}')from None\n else:\n raise e\n except ImportError:\n raise e\n break\n \n if tarinfo is not None:\n \n if not self.stream:\n self.members.append(tarinfo)\n else:\n self._loaded=True\n \n return tarinfo\n \n \n \n \n def _getmember(self,name,tarinfo=None,normalize=False):\n ''\n\n \n \n members=self.getmembers()\n \n \n skipping=False\n if tarinfo is not None:\n try:\n index=members.index(tarinfo)\n except ValueError:\n \n \n skipping=True\n else:\n \n members=members[:index]\n \n if normalize:\n name=os.path.normpath(name)\n \n for member in reversed(members):\n if skipping:\n if tarinfo.offset ==member.offset:\n skipping=False\n continue\n if normalize:\n member_name=os.path.normpath(member.name)\n else:\n member_name=member.name\n \n if name ==member_name:\n return member\n \n if skipping:\n \n raise ValueError(tarinfo)\n \n def _load(self):\n ''\n\n \n if not self.stream:\n while self.next()is not None:\n pass\n self._loaded=True\n \n def _check(self,mode=None):\n ''\n\n \n if self.closed:\n raise OSError(\"%s is closed\"%self.__class__.__name__)\n if mode is not None and self.mode not in mode:\n raise OSError(\"bad operation for mode %r\"%self.mode)\n \n def _find_link_target(self,tarinfo):\n ''\n\n \n if tarinfo.issym():\n \n linkname=\"/\".join(filter(None,(os.path.dirname(tarinfo.name),tarinfo.linkname)))\n limit=None\n else:\n \n \n linkname=tarinfo.linkname\n limit=tarinfo\n \n member=self._getmember(linkname,tarinfo=limit,normalize=True)\n if member is None:\n raise KeyError(\"linkname %r not found\"%linkname)\n return member\n \n def __iter__(self):\n ''\n \n if self._loaded:\n yield from self.members\n return\n \n \n \n index=0\n \n \n \n if self.firstmember is not None:\n tarinfo=self.next()\n index +=1\n yield tarinfo\n \n while True:\n if index ',''),\n help='Extract tarfile into target dir')\n group.add_argument('-c','--create',nargs='+',\n metavar=('',''),\n help='Create tarfile from sources')\n group.add_argument('-t','--test',metavar='',\n help='Test if a tarfile is valid')\n \n args=parser.parse_args()\n \n if args.filter and args.extract is None:\n parser.exit(1,'--filter is only valid for extraction\\n')\n \n if args.test is not None:\n src=args.test\n if is_tarfile(src):\n with open(src,'r')as tar:\n tar.getmembers()\n print(tar.getmembers(),file=sys.stderr)\n if args.verbose:\n print('{!r} is a tar archive.'.format(src))\n else:\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.list is not None:\n src=args.list\n if is_tarfile(src):\n with TarFile.open(src,'r:*')as tf:\n tf.list(verbose=args.verbose)\n else:\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.extract is not None:\n if len(args.extract)==1:\n src=args.extract[0]\n curdir=os.curdir\n elif len(args.extract)==2:\n src,curdir=args.extract\n else:\n parser.exit(1,parser.format_help())\n \n if is_tarfile(src):\n with TarFile.open(src,'r:*')as tf:\n tf.extractall(path=curdir,filter=args.filter)\n if args.verbose:\n if curdir =='.':\n msg='{!r} file is extracted.'.format(src)\n else:\n msg=('{!r} file is extracted '\n 'into {!r} directory.').format(src,curdir)\n print(msg)\n else:\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.create is not None:\n tar_name=args.create.pop(0)\n _,ext=os.path.splitext(tar_name)\n compressions={\n \n '.gz':'gz',\n '.tgz':'gz',\n \n '.xz':'xz',\n '.txz':'xz',\n \n '.bz2':'bz2',\n '.tbz':'bz2',\n '.tbz2':'bz2',\n '.tb2':'bz2',\n }\n tar_mode='w:'+compressions[ext]if ext in compressions else 'w'\n tar_files=args.create\n \n with TarFile.open(tar_name,tar_mode)as tf:\n for file_name in tar_files:\n tf.add(file_name)\n \n if args.verbose:\n print('{!r} file created.'.format(tar_name))\n \nif __name__ =='__main__':\n main()\n", ["argparse", "builtins", "bz2", "copy", "grp", "gzip", "io", "lzma", "os", "pwd", "re", "shutil", "stat", "struct", "sys", "time", "warnings", "zlib"]], "tb": [".py", "import sys\nfrom browser import console\n\nclass Trace:\n\n def __init__(self):\n self.lines=[]\n \n def write(self,*data):\n self.lines.append(\" \".join([str(x)for x in data]))\n \n def format(self):\n return '\\n'.join(self.lines)+'\\n'\n \ndef format_exc():\n trace=Trace()\n exc_class,exc,tb=sys.exc_info()\n exc_msg=str(exc)\n \n def handle_repeats(filename,lineno,count_repeats):\n if count_repeats >0:\n trace_lines=trace.lines[:]\n for _ in range(2):\n if not filename.startswith('<'):\n trace.write(trace_lines[-2])\n trace.write(trace_lines[-1])\n else:\n trace.write(trace_lines[-1])\n count_repeats -=1\n if count_repeats ==0:\n break\n if count_repeats >1:\n trace.write(f'[Previous line repeated {count_repeats} '+\n f'more time{\"s\"if count_repeats >1 else \"\"}]')\n \n def show_line():\n trace.write(f' File \"{filename}\", line {lineno}, in {name}')\n if not filename.startswith(\"<\"):\n src=open(filename,encoding='utf-8').read()\n lines=src.split('\\n')\n line=lines[tb.tb_lineno -1]\n trace.write(f\" {line.strip()}\")\n \n show=True\n started=False\n save_filename=None\n save_lineno=None\n save_scope=None\n same_line=False\n count_repeats=0\n \n while tb is not None:\n if show:\n trace.write(\"Traceback (most recent call last):\")\n show=False\n frame=tb.tb_frame\n code=frame.f_code\n lineno=frame.f_lineno\n name=code.co_name\n filename=code.co_filename\n if filename ==save_filename and lineno ==save_lineno\\\n and name ==save_name:\n count_repeats +=1\n tb=tb.tb_next\n continue\n handle_repeats(save_filename,save_lineno,count_repeats)\n save_filename=filename\n save_lineno=lineno\n save_name=name\n count_repeats=0\n show_line()\n tb=tb.tb_next\n \n handle_repeats(filename,lineno,count_repeats)\n \n if isinstance(exc,SyntaxError):\n trace.write(syntax_error(exc.args))\n else:\n message=exc_msg\n if isinstance(exc,AttributeError):\n suggestion=__BRYTHON__.offer_suggestions_for_attribute_error(exc)\n if suggestion is not None:\n message +=f\". Did you mean: '{suggestion}'?\"\n elif isinstance(exc,NameError):\n suggestion=__BRYTHON__.offer_suggestions_for_name_error(exc)\n if suggestion is not None:\n message +=f\". Did you mean: '{suggestion}'?\"\n elif exc.name in __BRYTHON__.stdlib_module_names:\n message +=f\". Did you forget to import '{exc.name}'?\"\n trace.write(f\"{exc_class.__name__}: {message}\")\n \n return trace.format()\n \ndef print_exc(file=None):\n if file is None:\n file=sys.stderr\n file.write(format_exc())\n \ndef syntax_error(args):\n trace=Trace()\n info,[filename,lineno,offset,line,*extra]=args\n trace.write(f' File \"{filename}\", line {lineno}')\n indent=len(line)-len(line.lstrip())\n trace.write(\" \"+line.strip())\n nb_marks=1\n if extra:\n end_lineno,end_offset=extra\n if end_lineno >lineno:\n nb_marks=len(line)-offset\n else:\n nb_marks=end_offset -offset\n nb_marks=max(nb_marks,1)\n trace.write(\" \"+(offset -1)*\" \"+\"^\"*nb_marks)\n trace.write(\"SyntaxError:\",info)\n return trace.format()\n", ["browser", "sys"]], "tempfile": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\n\"NamedTemporaryFile\",\"TemporaryFile\",\n\"SpooledTemporaryFile\",\"TemporaryDirectory\",\n\"mkstemp\",\"mkdtemp\",\n\"mktemp\",\n\"TMP_MAX\",\"gettempprefix\",\n\"tempdir\",\"gettempdir\",\n\"gettempprefixb\",\"gettempdirb\",\n]\n\n\n\n\nimport functools as _functools\nimport warnings as _warnings\nimport io as _io\nimport os as _os\nimport shutil as _shutil\nimport errno as _errno\nfrom random import Random as _Random\nimport sys as _sys\nimport types as _types\nimport weakref as _weakref\nimport _thread\n_allocate_lock=_thread.allocate_lock\n\n_text_openflags=_os.O_RDWR |_os.O_CREAT |_os.O_EXCL\nif hasattr(_os,'O_NOFOLLOW'):\n _text_openflags |=_os.O_NOFOLLOW\n \n_bin_openflags=_text_openflags\nif hasattr(_os,'O_BINARY'):\n _bin_openflags |=_os.O_BINARY\n \nif hasattr(_os,'TMP_MAX'):\n TMP_MAX=_os.TMP_MAX\nelse:\n TMP_MAX=10000\n \n \n \n \n \ntemplate=\"tmp\"\n\n\n\n_once_lock=_allocate_lock()\n\n\ndef _exists(fn):\n try:\n _os.lstat(fn)\n except OSError:\n return False\n else:\n return True\n \n \ndef _infer_return_type(*args):\n ''\n return_type=None\n for arg in args:\n if arg is None:\n continue\n \n if isinstance(arg,_os.PathLike):\n arg=_os.fspath(arg)\n \n if isinstance(arg,bytes):\n if return_type is str:\n raise TypeError(\"Can't mix bytes and non-bytes in \"\n \"path components.\")\n return_type=bytes\n else:\n if return_type is bytes:\n raise TypeError(\"Can't mix bytes and non-bytes in \"\n \"path components.\")\n return_type=str\n if return_type is None:\n if tempdir is None or isinstance(tempdir,str):\n return str\n else:\n \n return bytes\n return return_type\n \n \ndef _sanitize_params(prefix,suffix,dir):\n ''\n output_type=_infer_return_type(prefix,suffix,dir)\n if suffix is None:\n suffix=output_type()\n if prefix is None:\n if output_type is str:\n prefix=template\n else:\n prefix=_os.fsencode(template)\n if dir is None:\n if output_type is str:\n dir=gettempdir()\n else:\n dir=gettempdirb()\n return prefix,suffix,dir,output_type\n \n \nclass _RandomNameSequence:\n ''\n\n\n\n\n \n \n characters=\"abcdefghijklmnopqrstuvwxyz0123456789_\"\n \n @property\n def rng(self):\n cur_pid=_os.getpid()\n if cur_pid !=getattr(self,'_rng_pid',None):\n self._rng=_Random()\n self._rng_pid=cur_pid\n return self._rng\n \n def __iter__(self):\n return self\n \n def __next__(self):\n return ''.join(self.rng.choices(self.characters,k=8))\n \ndef _candidate_tempdir_list():\n ''\n \n \n dirlist=[]\n \n \n for envname in 'TMPDIR','TEMP','TMP':\n dirname=_os.getenv(envname)\n if dirname:dirlist.append(dirname)\n \n \n if _os.name =='nt':\n dirlist.extend([_os.path.expanduser(r'~\\AppData\\Local\\Temp'),\n _os.path.expandvars(r'%SYSTEMROOT%\\Temp'),\n r'c:\\temp',r'c:\\tmp',r'\\temp',r'\\tmp'])\n else:\n dirlist.extend(['/tmp','/var/tmp','/usr/tmp'])\n \n \n try:\n dirlist.append(_os.getcwd())\n except(AttributeError,OSError):\n dirlist.append(_os.curdir)\n \n return dirlist\n \ndef _get_default_tempdir():\n ''\n\n\n\n\n\n \n \n namer=_RandomNameSequence()\n dirlist=_candidate_tempdir_list()\n \n for dir in dirlist:\n if dir !=_os.curdir:\n dir=_os.path.abspath(dir)\n \n for seq in range(100):\n name=next(namer)\n filename=_os.path.join(dir,name)\n try:\n fd=_os.open(filename,_bin_openflags,0o600)\n try:\n try:\n _os.write(fd,b'blat')\n finally:\n _os.close(fd)\n finally:\n _os.unlink(filename)\n return dir\n except FileExistsError:\n pass\n except PermissionError:\n \n \n if(_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n break\n except OSError:\n break\n raise FileNotFoundError(_errno.ENOENT,\n \"No usable temporary directory found in %s\"%\n dirlist)\n \n_name_sequence=None\n\ndef _get_candidate_names():\n ''\n \n global _name_sequence\n if _name_sequence is None:\n _once_lock.acquire()\n try:\n if _name_sequence is None:\n _name_sequence=_RandomNameSequence()\n finally:\n _once_lock.release()\n return _name_sequence\n \n \ndef _mkstemp_inner(dir,pre,suf,flags,output_type):\n ''\n \n dir=_os.path.abspath(dir)\n names=_get_candidate_names()\n if output_type is bytes:\n names=map(_os.fsencode,names)\n \n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,pre+name+suf)\n _sys.audit(\"tempfile.mkstemp\",file)\n try:\n fd=_os.open(file,flags,0o600)\n except FileExistsError:\n continue\n except PermissionError:\n \n \n if(_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n else:\n raise\n return fd,file\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary file name found\")\n \ndef _dont_follow_symlinks(func,path,*args):\n\n if func in _os.supports_follow_symlinks:\n func(path,*args,follow_symlinks=False)\n elif not _os.path.islink(path):\n func(path,*args)\n \ndef _resetperms(path):\n try:\n chflags=_os.chflags\n except AttributeError:\n pass\n else:\n _dont_follow_symlinks(chflags,path,0)\n _dont_follow_symlinks(_os.chmod,path,0o700)\n \n \n \n \ndef gettempprefix():\n ''\n return _os.fsdecode(template)\n \ndef gettempprefixb():\n ''\n return _os.fsencode(template)\n \ntempdir=None\n\ndef _gettempdir():\n ''\n global tempdir\n if tempdir is None:\n _once_lock.acquire()\n try:\n if tempdir is None:\n tempdir=_get_default_tempdir()\n finally:\n _once_lock.release()\n return tempdir\n \ndef gettempdir():\n ''\n return _os.fsdecode(_gettempdir())\n \ndef gettempdirb():\n ''\n return _os.fsencode(_gettempdir())\n \ndef mkstemp(suffix=None,prefix=None,dir=None,text=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n if text:\n flags=_text_openflags\n else:\n flags=_bin_openflags\n \n return _mkstemp_inner(dir,prefix,suffix,flags,output_type)\n \n \ndef mkdtemp(suffix=None,prefix=None,dir=None):\n ''\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n names=_get_candidate_names()\n if output_type is bytes:\n names=map(_os.fsencode,names)\n \n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,prefix+name+suffix)\n _sys.audit(\"tempfile.mkdtemp\",file)\n try:\n _os.mkdir(file,0o700)\n except FileExistsError:\n continue\n except PermissionError:\n \n \n if(_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n else:\n raise\n return _os.path.abspath(file)\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary directory name found\")\n \ndef mktemp(suffix=\"\",prefix=template,dir=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n if dir is None:\n dir=gettempdir()\n \n names=_get_candidate_names()\n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,prefix+name+suffix)\n if not _exists(file):\n return file\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary filename found\")\n \n \nclass _TemporaryFileCloser:\n ''\n\n \n \n cleanup_called=False\n close_called=False\n \n def __init__(self,file,name,delete=True,delete_on_close=True):\n self.file=file\n self.name=name\n self.delete=delete\n self.delete_on_close=delete_on_close\n \n def cleanup(self,windows=(_os.name =='nt'),unlink=_os.unlink):\n if not self.cleanup_called:\n self.cleanup_called=True\n try:\n if not self.close_called:\n self.close_called=True\n self.file.close()\n finally:\n \n \n if self.delete and not(windows and self.delete_on_close):\n try:\n unlink(self.name)\n except FileNotFoundError:\n pass\n \n def close(self):\n if not self.close_called:\n self.close_called=True\n try:\n self.file.close()\n finally:\n if self.delete and self.delete_on_close:\n self.cleanup()\n \n def __del__(self):\n self.cleanup()\n \n \nclass _TemporaryFileWrapper:\n ''\n\n\n\n\n \n \n def __init__(self,file,name,delete=True,delete_on_close=True):\n self.file=file\n self.name=name\n self._closer=_TemporaryFileCloser(file,name,delete,\n delete_on_close)\n \n def __getattr__(self,name):\n \n \n \n file=self.__dict__['file']\n a=getattr(file,name)\n if hasattr(a,'__call__'):\n func=a\n @_functools.wraps(func)\n def func_wrapper(*args,**kwargs):\n return func(*args,**kwargs)\n \n \n func_wrapper._closer=self._closer\n a=func_wrapper\n if not isinstance(a,int):\n setattr(self,name,a)\n return a\n \n \n \n def __enter__(self):\n self.file.__enter__()\n return self\n \n \n \n def __exit__(self,exc,value,tb):\n result=self.file.__exit__(exc,value,tb)\n self._closer.cleanup()\n return result\n \n def close(self):\n ''\n\n \n self._closer.close()\n \n \n def __iter__(self):\n \n \n \n \n \n for line in self.file:\n yield line\n \ndef NamedTemporaryFile(mode='w+b',buffering=-1,encoding=None,\nnewline=None,suffix=None,prefix=None,\ndir=None,delete=True,*,errors=None,\ndelete_on_close=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n flags=_bin_openflags\n \n \n \n if _os.name =='nt'and delete and delete_on_close:\n flags |=_os.O_TEMPORARY\n \n if \"b\"not in mode:\n encoding=_io.text_encoding(encoding)\n \n name=None\n def opener(*args):\n nonlocal name\n fd,name=_mkstemp_inner(dir,prefix,suffix,flags,output_type)\n return fd\n try:\n file=_io.open(dir,mode,buffering=buffering,\n newline=newline,encoding=encoding,errors=errors,\n opener=opener)\n try:\n raw=getattr(file,'buffer',file)\n raw=getattr(raw,'raw',raw)\n raw.name=name\n return _TemporaryFileWrapper(file,name,delete,delete_on_close)\n except:\n file.close()\n raise\n except:\n if name is not None and not(\n _os.name =='nt'and delete and delete_on_close):\n _os.unlink(name)\n raise\n \nif _os.name !='posix'or _sys.platform =='cygwin':\n\n\n TemporaryFile=NamedTemporaryFile\n \nelse:\n\n\n\n _O_TMPFILE_WORKS=hasattr(_os,'O_TMPFILE')\n \n def TemporaryFile(mode='w+b',buffering=-1,encoding=None,\n newline=None,suffix=None,prefix=None,\n dir=None,*,errors=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n global _O_TMPFILE_WORKS\n \n if \"b\"not in mode:\n encoding=_io.text_encoding(encoding)\n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n flags=_bin_openflags\n if _O_TMPFILE_WORKS:\n fd=None\n def opener(*args):\n nonlocal fd\n flags2=(flags |_os.O_TMPFILE)&~_os.O_CREAT\n fd=_os.open(dir,flags2,0o600)\n return fd\n try:\n file=_io.open(dir,mode,buffering=buffering,\n newline=newline,encoding=encoding,\n errors=errors,opener=opener)\n raw=getattr(file,'buffer',file)\n raw=getattr(raw,'raw',raw)\n raw.name=fd\n return file\n except IsADirectoryError:\n \n \n \n \n \n _O_TMPFILE_WORKS=False\n except OSError:\n \n \n \n \n \n \n \n pass\n \n \n fd=None\n def opener(*args):\n nonlocal fd\n fd,name=_mkstemp_inner(dir,prefix,suffix,flags,output_type)\n try:\n _os.unlink(name)\n except BaseException as e:\n _os.close(fd)\n raise\n return fd\n file=_io.open(dir,mode,buffering=buffering,\n newline=newline,encoding=encoding,errors=errors,\n opener=opener)\n raw=getattr(file,'buffer',file)\n raw=getattr(raw,'raw',raw)\n raw.name=fd\n return file\n \nclass SpooledTemporaryFile(_io.IOBase):\n ''\n\n\n \n _rolled=False\n \n def __init__(self,max_size=0,mode='w+b',buffering=-1,\n encoding=None,newline=None,\n suffix=None,prefix=None,dir=None,*,errors=None):\n if 'b'in mode:\n self._file=_io.BytesIO()\n else:\n encoding=_io.text_encoding(encoding)\n self._file=_io.TextIOWrapper(_io.BytesIO(),\n encoding=encoding,errors=errors,\n newline=newline)\n self._max_size=max_size\n self._rolled=False\n self._TemporaryFileArgs={'mode':mode,'buffering':buffering,\n 'suffix':suffix,'prefix':prefix,\n 'encoding':encoding,'newline':newline,\n 'dir':dir,'errors':errors}\n \n __class_getitem__=classmethod(_types.GenericAlias)\n \n def _check(self,file):\n if self._rolled:return\n max_size=self._max_size\n if max_size and file.tell()>max_size:\n self.rollover()\n \n def rollover(self):\n if self._rolled:return\n file=self._file\n newfile=self._file=TemporaryFile(**self._TemporaryFileArgs)\n del self._TemporaryFileArgs\n \n pos=file.tell()\n if hasattr(newfile,'buffer'):\n newfile.buffer.write(file.detach().getvalue())\n else:\n newfile.write(file.getvalue())\n newfile.seek(pos,0)\n \n self._rolled=True\n \n \n \n \n \n \n \n def __enter__(self):\n if self._file.closed:\n raise ValueError(\"Cannot enter context with closed file\")\n return self\n \n def __exit__(self,exc,value,tb):\n self._file.close()\n \n \n def __iter__(self):\n return self._file.__iter__()\n \n def __del__(self):\n if not self.closed:\n _warnings.warn(\n \"Unclosed file {!r}\".format(self),\n ResourceWarning,\n stacklevel=2,\n source=self\n )\n self.close()\n \n def close(self):\n self._file.close()\n \n @property\n def closed(self):\n return self._file.closed\n \n @property\n def encoding(self):\n return self._file.encoding\n \n @property\n def errors(self):\n return self._file.errors\n \n def fileno(self):\n self.rollover()\n return self._file.fileno()\n \n def flush(self):\n self._file.flush()\n \n def isatty(self):\n return self._file.isatty()\n \n @property\n def mode(self):\n try:\n return self._file.mode\n except AttributeError:\n return self._TemporaryFileArgs['mode']\n \n @property\n def name(self):\n try:\n return self._file.name\n except AttributeError:\n return None\n \n @property\n def newlines(self):\n return self._file.newlines\n \n def readable(self):\n return self._file.readable()\n \n def read(self,*args):\n return self._file.read(*args)\n \n def read1(self,*args):\n return self._file.read1(*args)\n \n def readinto(self,b):\n return self._file.readinto(b)\n \n def readinto1(self,b):\n return self._file.readinto1(b)\n \n def readline(self,*args):\n return self._file.readline(*args)\n \n def readlines(self,*args):\n return self._file.readlines(*args)\n \n def seekable(self):\n return self._file.seekable()\n \n def seek(self,*args):\n return self._file.seek(*args)\n \n def tell(self):\n return self._file.tell()\n \n def truncate(self,size=None):\n if size is None:\n return self._file.truncate()\n else:\n if size >self._max_size:\n self.rollover()\n return self._file.truncate(size)\n \n def writable(self):\n return self._file.writable()\n \n def write(self,s):\n file=self._file\n rv=file.write(s)\n self._check(file)\n return rv\n \n def writelines(self,iterable):\n file=self._file\n rv=file.writelines(iterable)\n self._check(file)\n return rv\n \n def detach(self):\n return self._file.detach()\n \n \nclass TemporaryDirectory:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,suffix=None,prefix=None,dir=None,\n ignore_cleanup_errors=False,*,delete=True):\n self.name=mkdtemp(suffix,prefix,dir)\n self._ignore_cleanup_errors=ignore_cleanup_errors\n self._delete=delete\n self._finalizer=_weakref.finalize(\n self,self._cleanup,self.name,\n warn_message=\"Implicitly cleaning up {!r}\".format(self),\n ignore_errors=self._ignore_cleanup_errors,delete=self._delete)\n \n @classmethod\n def _rmtree(cls,name,ignore_errors=False,repeated=False):\n def onexc(func,path,exc):\n if isinstance(exc,PermissionError):\n if repeated and path ==name:\n if ignore_errors:\n return\n raise\n \n try:\n if path !=name:\n _resetperms(_os.path.dirname(path))\n _resetperms(path)\n \n try:\n _os.unlink(path)\n except IsADirectoryError:\n cls._rmtree(path,ignore_errors=ignore_errors)\n except PermissionError:\n \n \n \n \n \n \n \n if not _os.path.isdir(path)or _os.path.isjunction(path):\n if ignore_errors:\n return\n raise\n cls._rmtree(path,ignore_errors=ignore_errors,\n repeated=(path ==name))\n except FileNotFoundError:\n pass\n elif isinstance(exc,FileNotFoundError):\n pass\n else:\n if not ignore_errors:\n raise\n \n _shutil.rmtree(name,onexc=onexc)\n \n @classmethod\n def _cleanup(cls,name,warn_message,ignore_errors=False,delete=True):\n if delete:\n cls._rmtree(name,ignore_errors=ignore_errors)\n _warnings.warn(warn_message,ResourceWarning)\n \n def __repr__(self):\n return \"<{} {!r}>\".format(self.__class__.__name__,self.name)\n \n def __enter__(self):\n return self.name\n \n def __exit__(self,exc,value,tb):\n if self._delete:\n self.cleanup()\n \n def cleanup(self):\n if self._finalizer.detach()or _os.path.exists(self.name):\n self._rmtree(self.name,ignore_errors=self._ignore_cleanup_errors)\n \n __class_getitem__=classmethod(_types.GenericAlias)\n", ["_thread", "errno", "functools", "io", "os", "random", "shutil", "sys", "types", "warnings", "weakref"]], "textwrap": [".py", "''\n\n\n\n\n\n\nimport re\n\n__all__=['TextWrapper','wrap','fill','dedent','indent','shorten']\n\n\n\n\n_whitespace='\\t\\n\\x0b\\x0c\\r '\n\nclass TextWrapper:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n unicode_whitespace_trans=dict.fromkeys(map(ord,_whitespace),ord(' '))\n \n \n \n \n \n \n \n word_punct=r'[\\w!\"\\'&.,?]'\n letter=r'[^\\d\\W]'\n whitespace=r'[%s]'%re.escape(_whitespace)\n nowhitespace='[^'+whitespace[1:]\n wordsep_re=re.compile(r'''\n ( # any whitespace\n %(ws)s+\n | # em-dash between words\n (?<=%(wp)s) -{2,} (?=\\w)\n | # word, possibly hyphenated\n %(nws)s+? (?:\n # hyphenated word\n -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))\n (?= %(lt)s -? %(lt)s)\n | # end of word\n (?=%(ws)s|\\Z)\n | # em-dash\n (?<=%(wp)s) (?=-{2,}\\w)\n )\n )'''%{'wp':word_punct,'lt':letter,\n 'ws':whitespace,'nws':nowhitespace},\n re.VERBOSE)\n del word_punct,letter,nowhitespace\n \n \n \n \n \n wordsep_simple_re=re.compile(r'(%s+)'%whitespace)\n del whitespace\n \n \n \n sentence_end_re=re.compile(r'[a-z]'\n r'[\\.\\!\\?]'\n r'[\\\"\\']?'\n r'\\Z')\n \n def __init__(self,\n width=70,\n initial_indent=\"\",\n subsequent_indent=\"\",\n expand_tabs=True,\n replace_whitespace=True,\n fix_sentence_endings=False,\n break_long_words=True,\n drop_whitespace=True,\n break_on_hyphens=True,\n tabsize=8,\n *,\n max_lines=None,\n placeholder=' [...]'):\n self.width=width\n self.initial_indent=initial_indent\n self.subsequent_indent=subsequent_indent\n self.expand_tabs=expand_tabs\n self.replace_whitespace=replace_whitespace\n self.fix_sentence_endings=fix_sentence_endings\n self.break_long_words=break_long_words\n self.drop_whitespace=drop_whitespace\n self.break_on_hyphens=break_on_hyphens\n self.tabsize=tabsize\n self.max_lines=max_lines\n self.placeholder=placeholder\n \n \n \n \n \n def _munge_whitespace(self,text):\n ''\n\n\n\n\n \n if self.expand_tabs:\n text=text.expandtabs(self.tabsize)\n if self.replace_whitespace:\n text=text.translate(self.unicode_whitespace_trans)\n return text\n \n \n def _split(self,text):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self.break_on_hyphens is True:\n chunks=self.wordsep_re.split(text)\n else:\n chunks=self.wordsep_simple_re.split(text)\n chunks=[c for c in chunks if c]\n return chunks\n \n def _fix_sentence_endings(self,chunks):\n ''\n\n\n\n\n\n\n \n i=0\n patsearch=self.sentence_end_re.search\n while i space_left:\n \n \n hyphen=chunk.rfind('-',0,space_left)\n if hyphen >0 and any(c !='-'for c in chunk[:hyphen]):\n end=hyphen+1\n cur_line.append(chunk[:end])\n reversed_chunks[-1]=chunk[end:]\n \n \n \n \n elif not cur_line:\n cur_line.append(reversed_chunks.pop())\n \n \n \n \n \n \n \n def _wrap_chunks(self,chunks):\n ''\n\n\n\n\n\n\n\n\n\n\n \n lines=[]\n if self.width <=0:\n raise ValueError(\"invalid width %r (must be > 0)\"%self.width)\n if self.max_lines is not None:\n if self.max_lines >1:\n indent=self.subsequent_indent\n else:\n indent=self.initial_indent\n if len(indent)+len(self.placeholder.lstrip())>self.width:\n raise ValueError(\"placeholder too large for max width\")\n \n \n \n chunks.reverse()\n \n while chunks:\n \n \n \n cur_line=[]\n cur_len=0\n \n \n if lines:\n indent=self.subsequent_indent\n else:\n indent=self.initial_indent\n \n \n width=self.width -len(indent)\n \n \n \n if self.drop_whitespace and chunks[-1].strip()==''and lines:\n del chunks[-1]\n \n while chunks:\n l=len(chunks[-1])\n \n \n if cur_len+l <=width:\n cur_line.append(chunks.pop())\n cur_len +=l\n \n \n else:\n break\n \n \n \n if chunks and len(chunks[-1])>width:\n self._handle_long_word(chunks,cur_line,cur_len,width)\n cur_len=sum(map(len,cur_line))\n \n \n if self.drop_whitespace and cur_line and cur_line[-1].strip()=='':\n cur_len -=len(cur_line[-1])\n del cur_line[-1]\n \n if cur_line:\n if(self.max_lines is None or\n len(lines)+1 \"%(\n \"locked\"if self._block.locked()else \"unlocked\",\n self.__class__.__module__,\n self.__class__.__qualname__,\n owner,\n self._count,\n hex(id(self))\n )\n \n def _at_fork_reinit(self):\n self._block._at_fork_reinit()\n self._owner=None\n self._count=0\n \n def acquire(self,blocking=True,timeout=-1):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n me=get_ident()\n if self._owner ==me:\n self._count +=1\n return 1\n rc=self._block.acquire(blocking,timeout)\n if rc:\n self._owner=me\n self._count=1\n return rc\n \n __enter__=acquire\n \n def release(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self._owner !=get_ident():\n raise RuntimeError(\"cannot release un-acquired lock\")\n self._count=count=self._count -1\n if not count:\n self._owner=None\n self._block.release()\n \n def __exit__(self,t,v,tb):\n self.release()\n \n \n \n def _acquire_restore(self,state):\n self._block.acquire()\n self._count,self._owner=state\n \n def _release_save(self):\n if self._count ==0:\n raise RuntimeError(\"cannot release un-acquired lock\")\n count=self._count\n self._count=0\n owner=self._owner\n self._owner=None\n self._block.release()\n return(count,owner)\n \n def _is_owned(self):\n return self._owner ==get_ident()\n \n \n \n def _recursion_count(self):\n if self._owner !=get_ident():\n return 0\n return self._count\n \n_PyRLock=_RLock\n\n\nclass Condition:\n ''\n\n\n\n\n\n\n\n\n \n \n def __init__(self,lock=None):\n if lock is None:\n lock=RLock()\n self._lock=lock\n \n self.acquire=lock.acquire\n self.release=lock.release\n \n \n \n if hasattr(lock,'_release_save'):\n self._release_save=lock._release_save\n if hasattr(lock,'_acquire_restore'):\n self._acquire_restore=lock._acquire_restore\n if hasattr(lock,'_is_owned'):\n self._is_owned=lock._is_owned\n self._waiters=_deque()\n \n def _at_fork_reinit(self):\n self._lock._at_fork_reinit()\n self._waiters.clear()\n \n def __enter__(self):\n return self._lock.__enter__()\n \n def __exit__(self,*args):\n return self._lock.__exit__(*args)\n \n def __repr__(self):\n return \"\"%(self._lock,len(self._waiters))\n \n def _release_save(self):\n self._lock.release()\n \n def _acquire_restore(self,x):\n self._lock.acquire()\n \n def _is_owned(self):\n \n \n if self._lock.acquire(False):\n self._lock.release()\n return False\n else:\n return True\n \n def wait(self,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not self._is_owned():\n raise RuntimeError(\"cannot wait on un-acquired lock\")\n waiter=_allocate_lock()\n waiter.acquire()\n self._waiters.append(waiter)\n saved_state=self._release_save()\n gotit=False\n try:\n if timeout is None:\n waiter.acquire()\n gotit=True\n else:\n if timeout >0:\n gotit=waiter.acquire(True,timeout)\n else:\n gotit=waiter.acquire(False)\n return gotit\n finally:\n self._acquire_restore(saved_state)\n if not gotit:\n try:\n self._waiters.remove(waiter)\n except ValueError:\n pass\n \n def wait_for(self,predicate,timeout=None):\n ''\n\n\n\n\n\n \n endtime=None\n waittime=timeout\n result=predicate()\n while not result:\n if waittime is not None:\n if endtime is None:\n endtime=_time()+waittime\n else:\n waittime=endtime -_time()\n if waittime <=0:\n break\n self.wait(waittime)\n result=predicate()\n return result\n \n def notify(self,n=1):\n ''\n\n\n\n\n\n\n\n \n if not self._is_owned():\n raise RuntimeError(\"cannot notify on un-acquired lock\")\n waiters=self._waiters\n while waiters and n >0:\n waiter=waiters[0]\n try:\n waiter.release()\n except RuntimeError:\n \n \n \n \n pass\n else:\n n -=1\n try:\n waiters.remove(waiter)\n except ValueError:\n pass\n \n def notify_all(self):\n ''\n\n\n\n\n \n self.notify(len(self._waiters))\n \n def notifyAll(self):\n ''\n\n\n\n \n import warnings\n warnings.warn('notifyAll() is deprecated, use notify_all() instead',\n DeprecationWarning,stacklevel=2)\n self.notify_all()\n \n \nclass Semaphore:\n ''\n\n\n\n\n\n\n \n \n \n \n def __init__(self,value=1):\n if value <0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n self._cond=Condition(Lock())\n self._value=value\n \n def __repr__(self):\n cls=self.__class__\n return(f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}:\"\n f\" value={self._value}>\")\n \n def acquire(self,blocking=True,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not blocking and timeout is not None:\n raise ValueError(\"can't specify timeout for non-blocking acquire\")\n rc=False\n endtime=None\n with self._cond:\n while self._value ==0:\n if not blocking:\n break\n if timeout is not None:\n if endtime is None:\n endtime=_time()+timeout\n else:\n timeout=endtime -_time()\n if timeout <=0:\n break\n self._cond.wait(timeout)\n else:\n self._value -=1\n rc=True\n return rc\n \n __enter__=acquire\n \n def release(self,n=1):\n ''\n\n\n\n\n \n if n <1:\n raise ValueError('n must be one or more')\n with self._cond:\n self._value +=n\n self._cond.notify(n)\n \n def __exit__(self,t,v,tb):\n self.release()\n \n \nclass BoundedSemaphore(Semaphore):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,value=1):\n super().__init__(value)\n self._initial_value=value\n \n def __repr__(self):\n cls=self.__class__\n return(f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}:\"\n f\" value={self._value}/{self._initial_value}>\")\n \n def release(self,n=1):\n ''\n\n\n\n\n\n\n\n \n if n <1:\n raise ValueError('n must be one or more')\n with self._cond:\n if self._value+n >self._initial_value:\n raise ValueError(\"Semaphore released too many times\")\n self._value +=n\n self._cond.notify(n)\n \n \nclass Event:\n ''\n\n\n\n\n\n \n \n \n \n def __init__(self):\n self._cond=Condition(Lock())\n self._flag=False\n \n def __repr__(self):\n cls=self.__class__\n status='set'if self._flag else 'unset'\n return f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}: {status}>\"\n \n def _at_fork_reinit(self):\n \n self._cond._at_fork_reinit()\n \n def is_set(self):\n ''\n return self._flag\n \n def isSet(self):\n ''\n\n\n\n \n import warnings\n warnings.warn('isSet() is deprecated, use is_set() instead',\n DeprecationWarning,stacklevel=2)\n return self.is_set()\n \n def set(self):\n ''\n\n\n\n\n \n with self._cond:\n self._flag=True\n self._cond.notify_all()\n \n def clear(self):\n ''\n\n\n\n\n \n with self._cond:\n self._flag=False\n \n def wait(self,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n with self._cond:\n signaled=self._flag\n if not signaled:\n signaled=self._cond.wait(timeout)\n return signaled\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass Barrier:\n ''\n\n\n\n\n\n \n \n def __init__(self,parties,action=None,timeout=None):\n ''\n\n\n\n\n\n\n \n self._cond=Condition(Lock())\n self._action=action\n self._timeout=timeout\n self._parties=parties\n self._state=0\n self._count=0\n \n def __repr__(self):\n cls=self.__class__\n if self.broken:\n return f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}: broken>\"\n return(f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}:\"\n f\" waiters={self.n_waiting}/{self.parties}>\")\n \n def wait(self,timeout=None):\n ''\n\n\n\n\n\n\n \n if timeout is None:\n timeout=self._timeout\n with self._cond:\n self._enter()\n index=self._count\n self._count +=1\n try:\n if index+1 ==self._parties:\n \n self._release()\n else:\n \n self._wait(timeout)\n return index\n finally:\n self._count -=1\n \n self._exit()\n \n \n \n def _enter(self):\n while self._state in(-1,1):\n \n self._cond.wait()\n \n if self._state <0:\n raise BrokenBarrierError\n assert self._state ==0\n \n \n \n def _release(self):\n try:\n if self._action:\n self._action()\n \n self._state=1\n self._cond.notify_all()\n except:\n \n self._break()\n raise\n \n \n \n def _wait(self,timeout):\n if not self._cond.wait_for(lambda:self._state !=0,timeout):\n \n self._break()\n raise BrokenBarrierError\n if self._state <0:\n raise BrokenBarrierError\n assert self._state ==1\n \n \n \n def _exit(self):\n if self._count ==0:\n if self._state in(-1,1):\n \n self._state=0\n self._cond.notify_all()\n \n def reset(self):\n ''\n\n\n\n\n \n with self._cond:\n if self._count >0:\n if self._state ==0:\n \n self._state=-1\n elif self._state ==-2:\n \n \n self._state=-1\n else:\n self._state=0\n self._cond.notify_all()\n \n def abort(self):\n ''\n\n\n\n\n \n with self._cond:\n self._break()\n \n def _break(self):\n \n \n self._state=-2\n self._cond.notify_all()\n \n @property\n def parties(self):\n ''\n return self._parties\n \n @property\n def n_waiting(self):\n ''\n \n \n if self._state ==0:\n return self._count\n return 0\n \n @property\n def broken(self):\n ''\n return self._state ==-2\n \n \nclass BrokenBarrierError(RuntimeError):\n pass\n \n \n \n_counter=_count(1).__next__\ndef _newname(name_template):\n return name_template %_counter()\n \n \n \n \n \n_active_limbo_lock=RLock()\n_active={}\n_limbo={}\n_dangling=WeakSet()\n\n\n\n\nclass Thread:\n ''\n\n\n\n\n\n \n \n _initialized=False\n \n def __init__(self,group=None,target=None,name=None,\n args=(),kwargs=None,*,daemon=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n assert group is None,\"group argument must be None for now\"\n if kwargs is None:\n kwargs={}\n if name:\n name=str(name)\n else:\n name=_newname(\"Thread-%d\")\n if target is not None:\n try:\n target_name=target.__name__\n name +=f\" ({target_name})\"\n except AttributeError:\n pass\n \n self._target=target\n self._name=name\n self._args=args\n self._kwargs=kwargs\n if daemon is not None:\n if daemon and not _daemon_threads_allowed():\n raise RuntimeError('daemon threads are disabled in this (sub)interpreter')\n self._daemonic=daemon\n else:\n self._daemonic=current_thread().daemon\n self._ident=None\n if _HAVE_THREAD_NATIVE_ID:\n self._native_id=None\n self._handle=_ThreadHandle()\n self._started=Event()\n self._initialized=True\n \n self._stderr=_sys.stderr\n self._invoke_excepthook=_make_invoke_excepthook()\n \n _dangling.add(self)\n \n def _after_fork(self,new_ident=None):\n \n self._started._at_fork_reinit()\n if new_ident is not None:\n \n self._ident=new_ident\n assert self._handle.ident ==new_ident\n else:\n \n \n pass\n \n def __repr__(self):\n assert self._initialized,\"Thread.__init__() was not called\"\n status=\"initial\"\n if self._started.is_set():\n status=\"started\"\n if self._handle.is_done():\n status=\"stopped\"\n if self._daemonic:\n status +=\" daemon\"\n if self._ident is not None:\n status +=\" %s\"%self._ident\n return \"<%s(%s, %s)>\"%(self.__class__.__name__,self._name,status)\n \n def start(self):\n ''\n\n\n\n\n\n\n\n \n if not self._initialized:\n raise RuntimeError(\"thread.__init__() not called\")\n \n if self._started.is_set():\n raise RuntimeError(\"threads can only be started once\")\n \n with _active_limbo_lock:\n _limbo[self]=self\n try:\n \n _start_joinable_thread(self._bootstrap,handle=self._handle,\n daemon=self.daemon)\n except Exception:\n with _active_limbo_lock:\n del _limbo[self]\n raise\n self._started.wait()\n \n def run(self):\n ''\n\n\n\n\n\n\n \n try:\n if self._target is not None:\n self._target(*self._args,**self._kwargs)\n finally:\n \n \n del self._target,self._args,self._kwargs\n \n def _bootstrap(self):\n \n \n \n \n \n \n \n \n \n \n \n \n try:\n self._bootstrap_inner()\n except:\n if self._daemonic and _sys is None:\n return\n raise\n \n def _set_ident(self):\n self._ident=get_ident()\n \n if _HAVE_THREAD_NATIVE_ID:\n def _set_native_id(self):\n self._native_id=get_native_id()\n \n def _bootstrap_inner(self):\n try:\n self._set_ident()\n if _HAVE_THREAD_NATIVE_ID:\n self._set_native_id()\n self._started.set()\n with _active_limbo_lock:\n _active[self._ident]=self\n del _limbo[self]\n \n if _trace_hook:\n _sys.settrace(_trace_hook)\n if _profile_hook:\n _sys.setprofile(_profile_hook)\n \n try:\n self.run()\n except:\n self._invoke_excepthook(self)\n finally:\n self._delete()\n \n def _delete(self):\n ''\n with _active_limbo_lock:\n del _active[get_ident()]\n \n \n \n \n \n def join(self,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not self._initialized:\n raise RuntimeError(\"Thread.__init__() not called\")\n if not self._started.is_set():\n raise RuntimeError(\"cannot join thread before it is started\")\n if self is current_thread():\n raise RuntimeError(\"cannot join current thread\")\n \n \n \n if timeout is not None:\n timeout=max(timeout,0)\n \n self._handle.join(timeout)\n \n @property\n def name(self):\n ''\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._name\n \n @name.setter\n def name(self,name):\n assert self._initialized,\"Thread.__init__() not called\"\n self._name=str(name)\n \n @property\n def ident(self):\n ''\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._ident\n \n if _HAVE_THREAD_NATIVE_ID:\n @property\n def native_id(self):\n ''\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._native_id\n \n def is_alive(self):\n ''\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._started.is_set()and not self._handle.is_done()\n \n @property\n def daemon(self):\n ''\n\n\n\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._daemonic\n \n @daemon.setter\n def daemon(self,daemonic):\n if not self._initialized:\n raise RuntimeError(\"Thread.__init__() not called\")\n if daemonic and not _daemon_threads_allowed():\n raise RuntimeError('daemon threads are disabled in this interpreter')\n if self._started.is_set():\n raise RuntimeError(\"cannot set daemon status of active thread\")\n self._daemonic=daemonic\n \n def isDaemon(self):\n ''\n\n\n\n \n import warnings\n warnings.warn('isDaemon() is deprecated, get the daemon attribute instead',\n DeprecationWarning,stacklevel=2)\n return self.daemon\n \n def setDaemon(self,daemonic):\n ''\n\n\n\n \n import warnings\n warnings.warn('setDaemon() is deprecated, set the daemon attribute instead',\n DeprecationWarning,stacklevel=2)\n self.daemon=daemonic\n \n def getName(self):\n ''\n\n\n\n \n import warnings\n warnings.warn('getName() is deprecated, get the name attribute instead',\n DeprecationWarning,stacklevel=2)\n return self.name\n \n def setName(self,name):\n ''\n\n\n\n \n import warnings\n warnings.warn('setName() is deprecated, set the name attribute instead',\n DeprecationWarning,stacklevel=2)\n self.name=name\n \n \ntry:\n from _thread import(_excepthook as excepthook,\n _ExceptHookArgs as ExceptHookArgs)\nexcept ImportError:\n\n from traceback import print_exception as _print_exception\n from collections import namedtuple\n \n _ExceptHookArgs=namedtuple(\n 'ExceptHookArgs',\n 'exc_type exc_value exc_traceback thread')\n \n def ExceptHookArgs(args):\n return _ExceptHookArgs(*args)\n \n def excepthook(args,/):\n ''\n\n \n if args.exc_type ==SystemExit:\n \n return\n \n if _sys is not None and _sys.stderr is not None:\n stderr=_sys.stderr\n elif args.thread is not None:\n stderr=args.thread._stderr\n if stderr is None:\n \n \n return\n else:\n \n return\n \n if args.thread is not None:\n name=args.thread.name\n else:\n name=get_ident()\n print(f\"Exception in thread {name}:\",\n file=stderr,flush=True)\n _print_exception(args.exc_type,args.exc_value,args.exc_traceback,\n file=stderr)\n stderr.flush()\n \n \n \n__excepthook__=excepthook\n\n\ndef _make_invoke_excepthook():\n\n\n\n\n old_excepthook=excepthook\n old_sys_excepthook=_sys.excepthook\n if old_excepthook is None:\n raise RuntimeError(\"threading.excepthook is None\")\n if old_sys_excepthook is None:\n raise RuntimeError(\"sys.excepthook is None\")\n \n sys_exc_info=_sys.exc_info\n local_print=print\n local_sys=_sys\n \n def invoke_excepthook(thread):\n global excepthook\n try:\n hook=excepthook\n if hook is None:\n hook=old_excepthook\n \n args=ExceptHookArgs([*sys_exc_info(),thread])\n \n hook(args)\n except Exception as exc:\n exc.__suppress_context__=True\n del exc\n \n if local_sys is not None and local_sys.stderr is not None:\n stderr=local_sys.stderr\n else:\n stderr=thread._stderr\n \n local_print(\"Exception in threading.excepthook:\",\n file=stderr,flush=True)\n \n if local_sys is not None and local_sys.excepthook is not None:\n sys_excepthook=local_sys.excepthook\n else:\n sys_excepthook=old_sys_excepthook\n \n sys_excepthook(*sys_exc_info())\n finally:\n \n args=None\n \n return invoke_excepthook\n \n \n \n \nclass Timer(Thread):\n ''\n\n\n\n\n\n \n \n def __init__(self,interval,function,args=None,kwargs=None):\n Thread.__init__(self)\n self.interval=interval\n self.function=function\n self.args=args if args is not None else[]\n self.kwargs=kwargs if kwargs is not None else{}\n self.finished=Event()\n \n def cancel(self):\n ''\n self.finished.set()\n \n def run(self):\n self.finished.wait(self.interval)\n if not self.finished.is_set():\n self.function(*self.args,**self.kwargs)\n self.finished.set()\n \n \n \n \nclass _MainThread(Thread):\n\n def __init__(self):\n Thread.__init__(self,name=\"MainThread\",daemon=False)\n self._started.set()\n self._ident=_get_main_thread_ident()\n self._handle=_make_thread_handle(self._ident)\n if _HAVE_THREAD_NATIVE_ID:\n self._set_native_id()\n with _active_limbo_lock:\n _active[self._ident]=self\n \n \n \n \n_thread_local_info=local()\n\n\nclass _DeleteDummyThreadOnDel:\n ''\n\n \n \n def __init__(self,dummy_thread):\n self._dummy_thread=dummy_thread\n self._tident=dummy_thread.ident\n \n \n \n \n \n \n _thread_local_info._track_dummy_thread_ref=self\n \n def __del__(self):\n with _active_limbo_lock:\n if _active.get(self._tident)is self._dummy_thread:\n _active.pop(self._tident,None)\n \n \n \n \n \n \n \n \n \nclass _DummyThread(Thread):\n\n def __init__(self):\n Thread.__init__(self,name=_newname(\"Dummy-%d\"),\n daemon=_daemon_threads_allowed())\n self._started.set()\n self._set_ident()\n self._handle=_make_thread_handle(self._ident)\n if _HAVE_THREAD_NATIVE_ID:\n self._set_native_id()\n with _active_limbo_lock:\n _active[self._ident]=self\n _DeleteDummyThreadOnDel(self)\n \n def is_alive(self):\n if not self._handle.is_done()and self._started.is_set():\n return True\n raise RuntimeError(\"thread is not alive\")\n \n def join(self,timeout=None):\n raise RuntimeError(\"cannot join a dummy thread\")\n \n def _after_fork(self,new_ident=None):\n if new_ident is not None:\n self.__class__=_MainThread\n self._name='MainThread'\n self._daemonic=False\n Thread._after_fork(self,new_ident=new_ident)\n \n \n \n \ndef current_thread():\n ''\n\n\n\n\n \n try:\n return _active[get_ident()]\n except KeyError:\n return _DummyThread()\n \ndef currentThread():\n ''\n\n\n\n \n import warnings\n warnings.warn('currentThread() is deprecated, use current_thread() instead',\n DeprecationWarning,stacklevel=2)\n return current_thread()\n \ndef active_count():\n ''\n\n\n\n\n \n \n \n with _active_limbo_lock:\n return len(_active)+len(_limbo)\n \ndef activeCount():\n ''\n\n\n\n \n import warnings\n warnings.warn('activeCount() is deprecated, use active_count() instead',\n DeprecationWarning,stacklevel=2)\n return active_count()\n \ndef _enumerate():\n\n return list(_active.values())+list(_limbo.values())\n \ndef enumerate():\n ''\n\n\n\n\n\n \n with _active_limbo_lock:\n return list(_active.values())+list(_limbo.values())\n \n \n_threading_atexits=[]\n_SHUTTING_DOWN=False\n\ndef _register_atexit(func,*arg,**kwargs):\n ''\n\n\n\n\n\n\n\n \n if _SHUTTING_DOWN:\n raise RuntimeError(\"can't register atexit after shutdown\")\n \n _threading_atexits.append(lambda:func(*arg,**kwargs))\n \n \nfrom _thread import stack_size\n\n\n\n\n\n_main_thread=_MainThread()\n\ndef _shutdown():\n ''\n\n \n \n \n \n \n if _main_thread._handle.is_done()and _is_main_interpreter():\n \n return\n \n global _SHUTTING_DOWN\n _SHUTTING_DOWN=True\n \n \n \n for atexit_call in reversed(_threading_atexits):\n atexit_call()\n \n if _is_main_interpreter():\n _main_thread._handle._set_done()\n \n \n _thread_shutdown()\n \n \ndef main_thread():\n ''\n\n\n\n \n \n return _main_thread\n \n \ndef _after_fork():\n ''\n\n \n \n \n global _active_limbo_lock,_main_thread\n _active_limbo_lock=RLock()\n \n \n new_active={}\n \n try:\n current=_active[get_ident()]\n except KeyError:\n \n \n \n current=_MainThread()\n \n _main_thread=current\n \n with _active_limbo_lock:\n \n \n threads=set(_enumerate())\n threads.update(_dangling)\n for thread in threads:\n \n \n if thread is current:\n \n ident=get_ident()\n thread._after_fork(new_ident=ident)\n new_active[ident]=thread\n else:\n \n thread._after_fork()\n \n _limbo.clear()\n _active.clear()\n _active.update(new_active)\n assert len(_active)==1\n \n \nif hasattr(_os,\"register_at_fork\"):\n _os.register_at_fork(after_in_child=_after_fork)\n", ["_collections", "_thread", "_threading_local", "_weakrefset", "collections", "itertools", "os", "sys", "time", "traceback", "warnings"]], "time": [".py", "from browser import self as window\nimport _locale\nimport javascript\n\n\ndate=javascript.Date.new\nnow=javascript.Date.now\n\n\n\n\n\n\n\n_STRUCT_TM_ITEMS=9\n\n\n\n\n\ndef _get_day_of_year(arg):\n ''\n\n\n\n\n\n\n\n\n\n \n ml=[31,28,31,30,31,30,31,31,30,31,30,31]\n if arg[0]%4 ==0:\n ml[1]+=1\n i=1\n yday=0\n while i mm >13:\n raise ValueError(\"month out of range\")\n \n dd=t[2]\n if dd ==0:dd=1\n if -1 >dd >32:\n raise ValueError(\"day of month out of range\")\n \n hh=t[3]\n if -1 >hh >24:\n raise ValueError(\"hour out of range\")\n \n minu=t[4]\n if -1 >minu >60:\n raise ValueError(\"minute out of range\")\n \n ss=t[5]\n if -1 >ss >62:\n raise ValueError(\"seconds out of range\")\n \n wd=t[6]%7\n if wd <-2:\n raise ValueError(\"day of week out of range\")\n \n dy=t[7]\n if dy ==0:dy=1\n if -1 >dy >367:\n raise ValueError(\"day of year out of range\")\n \n return t[0],mm,dd,hh,minu,ss,wd,dy,t[-1]\n \n \ndef _is_dst(secs=None):\n ''\n d=date()\n if secs is not None:\n d=date(secs *1000)\n \n \n \n jan=date(d.getFullYear(),0,1)\n jul=date(d.getFullYear(),6,1)\n dst=int(d.getTimezoneOffset()=0 else 6\n tmp=struct_time([d.getUTCFullYear(),\n d.getUTCMonth()+1,d.getUTCDate(),\n d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),\n wday,0,0])\n tmp.args[7]=_get_day_of_year(tmp.args)\n return tmp\n \ndef localtime(secs=None):\n d=date()\n if secs is not None:\n d=date(secs *1000)\n dst=_is_dst(secs)\n wday=d.getDay()-1 if d.getDay()-1 >=0 else 6\n tmp=struct_time([d.getFullYear(),\n d.getMonth()+1,d.getDate(),\n d.getHours(),d.getMinutes(),d.getSeconds(),\n wday,0,dst])\n tmp.args[7]=_get_day_of_year(tmp.args)\n return tmp\n \ndef mktime(t):\n if isinstance(t,struct_time):\n d1=date(t.tm_year,t.tm_mon -1,t.tm_mday,\n t.tm_hour,t.tm_min,t.tm_sec,0).getTime()\n elif isinstance(t,tuple):\n d1=date(t[0],t[1]-1,t[2],t[3],t[4],t[5],0).getTime()\n else:\n raise ValueError(\"Tuple or struct_time argument required\")\n d2=date(0).getTime()\n return(d1 -d2)/1000.\n \ndef monotonic():\n return now()/1000.\n \ndef perf_counter():\n return window.performance.now()/1000.\n \ndef process_time():\n return now()/1000.\n \ndef time():\n return float(date().getTime()/1000)\n \ndef sleep(secs):\n ''\n\n \n \n float(secs)\n raise NotImplementedError(\"Blocking functions like time.sleep() are not \"\n \"supported in the browser. Use functions in module browser.timer \"\n \"instead.\")\n \ndef strftime(_format,t=None):\n def ns(t,nb):\n \n res=str(t)\n while len(res) float\n repeat(string, string) -> list\n default_timer() -> float\n\n\"\"\"\n\nimport gc\nimport itertools\nimport sys\nimport time\n\n__all__=[\"Timer\",\"timeit\",\"repeat\",\"default_timer\"]\n\ndummy_src_name=\"\"\ndefault_number=1000000\ndefault_repeat=5\ndefault_timer=time.perf_counter\n\n_globals=globals\n\n\n\n\ntemplate=\"\"\"\ndef inner(_it, _timer{init}):\n {setup}\n _t0 = _timer()\n for _i in _it:\n {stmt}\n pass\n _t1 = _timer()\n return _t1 - _t0\n\"\"\"\n\n\ndef reindent(src,indent):\n ''\n return src.replace(\"\\n\",\"\\n\"+\" \"*indent)\n \n \nclass Timer:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,stmt=\"pass\",setup=\"pass\",timer=default_timer,\n globals=None):\n ''\n self.timer=timer\n local_ns={}\n global_ns=_globals()if globals is None else globals\n init=''\n if isinstance(setup,str):\n \n compile(setup,dummy_src_name,\"exec\")\n stmtprefix=setup+'\\n'\n setup=reindent(setup,4)\n elif callable(setup):\n local_ns['_setup']=setup\n init +=', _setup=_setup'\n stmtprefix=''\n setup='_setup()'\n else:\n raise ValueError(\"setup is neither a string nor callable\")\n if isinstance(stmt,str):\n \n compile(stmtprefix+stmt,dummy_src_name,\"exec\")\n stmt=reindent(stmt,8)\n elif callable(stmt):\n local_ns['_stmt']=stmt\n init +=', _stmt=_stmt'\n stmt='_stmt()'\n else:\n raise ValueError(\"stmt is neither a string nor callable\")\n src=template.format(stmt=stmt,setup=setup,init=init)\n self.src=src\n code=compile(src,dummy_src_name,\"exec\")\n exec(code,global_ns,local_ns)\n self.inner=local_ns[\"inner\"]\n \n def print_exc(self,file=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n import linecache,traceback\n if self.src is not None:\n linecache.cache[dummy_src_name]=(len(self.src),\n None,\n self.src.split(\"\\n\"),\n dummy_src_name)\n \n \n traceback.print_exc(file=file)\n \n def timeit(self,number=default_number):\n ''\n\n\n\n\n\n\n\n \n it=itertools.repeat(None,number)\n gcold=gc.isenabled()\n gc.disable()\n try:\n timing=self.inner(it,self.timer)\n finally:\n if gcold:\n gc.enable()\n return timing\n \n def repeat(self,repeat=default_repeat,number=default_number):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n r=[]\n for i in range(repeat):\n t=self.timeit(number)\n r.append(t)\n return r\n \n def autorange(self,callback=None):\n ''\n\n\n\n\n\n\n\n \n i=1\n while True:\n for j in 1,2,5:\n number=i *j\n time_taken=self.timeit(number)\n if callback:\n callback(number,time_taken)\n if time_taken >=0.2:\n return(number,time_taken)\n i *=10\n \n \ndef timeit(stmt=\"pass\",setup=\"pass\",timer=default_timer,\nnumber=default_number,globals=None):\n ''\n return Timer(stmt,setup,timer,globals).timeit(number)\n \n \ndef repeat(stmt=\"pass\",setup=\"pass\",timer=default_timer,\nrepeat=default_repeat,number=default_number,globals=None):\n ''\n return Timer(stmt,setup,timer,globals).repeat(repeat,number)\n \n \ndef main(args=None,*,_wrap_timer=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if args is None:\n args=sys.argv[1:]\n import getopt\n try:\n opts,args=getopt.getopt(args,\"n:u:s:r:pvh\",\n [\"number=\",\"setup=\",\"repeat=\",\n \"process\",\"verbose\",\"unit=\",\"help\"])\n except getopt.error as err:\n print(err)\n print(\"use -h/--help for command line help\")\n return 2\n \n timer=default_timer\n stmt=\"\\n\".join(args)or \"pass\"\n number=0\n setup=[]\n repeat=default_repeat\n verbose=0\n time_unit=None\n units={\"nsec\":1e-9,\"usec\":1e-6,\"msec\":1e-3,\"sec\":1.0}\n precision=3\n for o,a in opts:\n if o in(\"-n\",\"--number\"):\n number=int(a)\n if o in(\"-s\",\"--setup\"):\n setup.append(a)\n if o in(\"-u\",\"--unit\"):\n if a in units:\n time_unit=a\n else:\n print(\"Unrecognized unit. Please select nsec, usec, msec, or sec.\",\n file=sys.stderr)\n return 2\n if o in(\"-r\",\"--repeat\"):\n repeat=int(a)\n if repeat <=0:\n repeat=1\n if o in(\"-p\",\"--process\"):\n timer=time.process_time\n if o in(\"-v\",\"--verbose\"):\n if verbose:\n precision +=1\n verbose +=1\n if o in(\"-h\",\"--help\"):\n print(__doc__,end=' ')\n return 0\n setup=\"\\n\".join(setup)or \"pass\"\n \n \n \n \n import os\n sys.path.insert(0,os.curdir)\n if _wrap_timer is not None:\n timer=_wrap_timer(timer)\n \n t=Timer(stmt,setup,timer)\n if number ==0:\n \n callback=None\n if verbose:\n def callback(number,time_taken):\n msg=\"{num} loop{s} -> {secs:.{prec}g} secs\"\n plural=(number !=1)\n print(msg.format(num=number,s='s'if plural else '',\n secs=time_taken,prec=precision))\n try:\n number,_=t.autorange(callback)\n except:\n t.print_exc()\n return 1\n \n if verbose:\n print()\n \n try:\n raw_timings=t.repeat(repeat,number)\n except:\n t.print_exc()\n return 1\n \n def format_time(dt):\n unit=time_unit\n \n if unit is not None:\n scale=units[unit]\n else:\n scales=[(scale,unit)for unit,scale in units.items()]\n scales.sort(reverse=True)\n for scale,unit in scales:\n if dt >=scale:\n break\n \n return \"%.*g %s\"%(precision,dt /scale,unit)\n \n if verbose:\n print(\"raw times: %s\"%\", \".join(map(format_time,raw_timings)))\n print()\n timings=[dt /number for dt in raw_timings]\n \n best=min(timings)\n print(\"%d loop%s, best of %d: %s per loop\"\n %(number,'s'if number !=1 else '',\n repeat,format_time(best)))\n \n best=min(timings)\n worst=max(timings)\n if worst >=best *4:\n import warnings\n warnings.warn_explicit(\"The test results are likely unreliable. \"\n \"The worst time (%s) was more than four times \"\n \"slower than the best time (%s).\"\n %(format_time(worst),format_time(best)),\n UserWarning,'',0)\n return None\n \n \nif __name__ ==\"__main__\":\n sys.exit(main())\n", ["gc", "getopt", "itertools", "linecache", "os", "sys", "time", "traceback", "warnings"]], "token": [".py", "''\n\n\n__all__=['tok_name','ISTERMINAL','ISNONTERMINAL','ISEOF']\n\nENDMARKER=0\nNAME=1\nNUMBER=2\nSTRING=3\nNEWLINE=4\nINDENT=5\nDEDENT=6\nLPAR=7\nRPAR=8\nLSQB=9\nRSQB=10\nCOLON=11\nCOMMA=12\nSEMI=13\nPLUS=14\nMINUS=15\nSTAR=16\nSLASH=17\nVBAR=18\nAMPER=19\nLESS=20\nGREATER=21\nEQUAL=22\nDOT=23\nPERCENT=24\nLBRACE=25\nRBRACE=26\nEQEQUAL=27\nNOTEQUAL=28\nLESSEQUAL=29\nGREATEREQUAL=30\nTILDE=31\nCIRCUMFLEX=32\nLEFTSHIFT=33\nRIGHTSHIFT=34\nDOUBLESTAR=35\nPLUSEQUAL=36\nMINEQUAL=37\nSTAREQUAL=38\nSLASHEQUAL=39\nPERCENTEQUAL=40\nAMPEREQUAL=41\nVBAREQUAL=42\nCIRCUMFLEXEQUAL=43\nLEFTSHIFTEQUAL=44\nRIGHTSHIFTEQUAL=45\nDOUBLESTAREQUAL=46\nDOUBLESLASH=47\nDOUBLESLASHEQUAL=48\nAT=49\nATEQUAL=50\nRARROW=51\nELLIPSIS=52\nCOLONEQUAL=53\nEXCLAMATION=54\nOP=55\nTYPE_IGNORE=56\nTYPE_COMMENT=57\nSOFT_KEYWORD=58\nFSTRING_START=59\nFSTRING_MIDDLE=60\nFSTRING_END=61\nCOMMENT=62\nNL=63\n\nERRORTOKEN=64\nENCODING=65\nN_TOKENS=66\n\nNT_OFFSET=256\n\ntok_name={value:name\nfor name,value in globals().items()\nif isinstance(value,int)and not name.startswith('_')}\n__all__.extend(tok_name.values())\n\nEXACT_TOKEN_TYPES={\n'!':EXCLAMATION,\n'!=':NOTEQUAL,\n'%':PERCENT,\n'%=':PERCENTEQUAL,\n'&':AMPER,\n'&=':AMPEREQUAL,\n'(':LPAR,\n')':RPAR,\n'*':STAR,\n'**':DOUBLESTAR,\n'**=':DOUBLESTAREQUAL,\n'*=':STAREQUAL,\n'+':PLUS,\n'+=':PLUSEQUAL,\n',':COMMA,\n'-':MINUS,\n'-=':MINEQUAL,\n'->':RARROW,\n'.':DOT,\n'...':ELLIPSIS,\n'/':SLASH,\n'//':DOUBLESLASH,\n'//=':DOUBLESLASHEQUAL,\n'/=':SLASHEQUAL,\n':':COLON,\n':=':COLONEQUAL,\n';':SEMI,\n'<':LESS,\n'<<':LEFTSHIFT,\n'<<=':LEFTSHIFTEQUAL,\n'<=':LESSEQUAL,\n'=':EQUAL,\n'==':EQEQUAL,\n'>':GREATER,\n'>=':GREATEREQUAL,\n'>>':RIGHTSHIFT,\n'>>=':RIGHTSHIFTEQUAL,\n'@':AT,\n'@=':ATEQUAL,\n'[':LSQB,\n']':RSQB,\n'^':CIRCUMFLEX,\n'^=':CIRCUMFLEXEQUAL,\n'{':LBRACE,\n'|':VBAR,\n'|=':VBAREQUAL,\n'}':RBRACE,\n'~':TILDE,\n}\n\ndef ISTERMINAL(x):\n return x =NT_OFFSET\n \ndef ISEOF(x):\n return x ==ENDMARKER\n", []], "tokenize": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__='Ka-Ping Yee '\n__credits__=('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '\n'Skip Montanaro, Raymond Hettinger, Trent Nelson, '\n'Michael Foord')\nfrom builtins import open as _builtin_open\nfrom codecs import lookup,BOM_UTF8\nimport collections\nimport functools\nfrom io import TextIOWrapper\nimport itertools as _itertools\nimport re\nimport sys\nfrom token import *\nfrom token import EXACT_TOKEN_TYPES\nimport _tokenize\n\ncookie_re=re.compile(r'^[ \\t\\f]*#.*?coding[:=][ \\t]*([-\\w.]+)',re.ASCII)\nblank_re=re.compile(br'^[ \\t\\f]*(?:[#\\r\\n]|$)',re.ASCII)\n\nimport token\n__all__=token.__all__+[\"tokenize\",\"generate_tokens\",\"detect_encoding\",\n\"untokenize\",\"TokenInfo\",\"open\",\"TokenError\"]\ndel token\n\nclass TokenInfo(collections.namedtuple('TokenInfo','type string start end line')):\n def __repr__(self):\n annotated_type='%d (%s)'%(self.type,tok_name[self.type])\n return('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)'%\n self._replace(type=annotated_type))\n \n @property\n def exact_type(self):\n if self.type ==OP and self.string in EXACT_TOKEN_TYPES:\n return EXACT_TOKEN_TYPES[self.string]\n else:\n return self.type\n \ndef group(*choices):return '('+'|'.join(choices)+')'\ndef any(*choices):return group(*choices)+'*'\ndef maybe(*choices):return group(*choices)+'?'\n\n\n\nWhitespace=r'[ \\f\\t]*'\nComment=r'#[^\\r\\n]*'\nIgnore=Whitespace+any(r'\\\\\\r?\\n'+Whitespace)+maybe(Comment)\nName=r'\\w+'\n\nHexnumber=r'0[xX](?:_?[0-9a-fA-F])+'\nBinnumber=r'0[bB](?:_?[01])+'\nOctnumber=r'0[oO](?:_?[0-7])+'\nDecnumber=r'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)'\nIntnumber=group(Hexnumber,Binnumber,Octnumber,Decnumber)\nExponent=r'[eE][-+]?[0-9](?:_?[0-9])*'\nPointfloat=group(r'[0-9](?:_?[0-9])*\\.(?:[0-9](?:_?[0-9])*)?',\nr'\\.[0-9](?:_?[0-9])*')+maybe(Exponent)\nExpfloat=r'[0-9](?:_?[0-9])*'+Exponent\nFloatnumber=group(Pointfloat,Expfloat)\nImagnumber=group(r'[0-9](?:_?[0-9])*[jJ]',Floatnumber+r'[jJ]')\nNumber=group(Imagnumber,Floatnumber,Intnumber)\n\n\ndef _all_string_prefixes():\n\n\n\n _valid_string_prefixes=['b','r','u','f','br','fr']\n \n result={''}\n for prefix in _valid_string_prefixes:\n for t in _itertools.permutations(prefix):\n \n \n for u in _itertools.product(*[(c,c.upper())for c in t]):\n result.add(''.join(u))\n return result\n \n@functools.lru_cache\ndef _compile(expr):\n return re.compile(expr,re.UNICODE)\n \n \n \nStringPrefix=group(*_all_string_prefixes())\n\n\nSingle=r\"[^'\\\\]*(?:\\\\.[^'\\\\]*)*'\"\n\nDouble=r'[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"'\n\nSingle3=r\"[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''\"\n\nDouble3=r'[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\"'\nTriple=group(StringPrefix+\"'''\",StringPrefix+'\"\"\"')\n\nString=group(StringPrefix+r\"'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'\",\nStringPrefix+r'\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*\"')\n\n\n\n\nSpecial=group(*map(re.escape,sorted(EXACT_TOKEN_TYPES,reverse=True)))\nFunny=group(r'\\r?\\n',Special)\n\nPlainToken=group(Number,Funny,String,Name)\nToken=Ignore+PlainToken\n\n\nContStr=group(StringPrefix+r\"'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*\"+\ngroup(\"'\",r'\\\\\\r?\\n'),\nStringPrefix+r'\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*'+\ngroup('\"',r'\\\\\\r?\\n'))\nPseudoExtras=group(r'\\\\\\r?\\n|\\Z',Comment,Triple)\nPseudoToken=Whitespace+group(PseudoExtras,Number,Funny,ContStr,Name)\n\n\n\n\nendpats={}\nfor _prefix in _all_string_prefixes():\n endpats[_prefix+\"'\"]=Single\n endpats[_prefix+'\"']=Double\n endpats[_prefix+\"'''\"]=Single3\n endpats[_prefix+'\"\"\"']=Double3\ndel _prefix\n\n\n\nsingle_quoted=set()\ntriple_quoted=set()\nfor t in _all_string_prefixes():\n for u in(t+'\"',t+\"'\"):\n single_quoted.add(u)\n for u in(t+'\"\"\"',t+\"'''\"):\n triple_quoted.add(u)\ndel t,u\n\ntabsize=8\n\nclass TokenError(Exception):pass\n\n\nclass Untokenizer:\n\n def __init__(self):\n self.tokens=[]\n self.prev_row=1\n self.prev_col=0\n self.prev_type=None\n self.encoding=None\n \n def add_whitespace(self,start):\n row,col=start\n if row =len(indent):\n self.tokens.append(indent)\n self.prev_col=len(indent)\n startline=False\n elif tok_type ==FSTRING_MIDDLE:\n if '{'in token or '}'in token:\n token=self.escape_brackets(token)\n last_line=token.splitlines()[-1]\n end_line,end_col=end\n extra_chars=last_line.count(\"{{\")+last_line.count(\"}}\")\n end=(end_line,end_col+extra_chars)\n elif tok_type in(STRING,FSTRING_START)and self.prev_type in(STRING,FSTRING_END):\n self.tokens.append(\" \")\n \n self.add_whitespace(start)\n self.tokens.append(token)\n self.prev_row,self.prev_col=end\n if tok_type in(NEWLINE,NL):\n self.prev_row +=1\n self.prev_col=0\n self.prev_type=tok_type\n return \"\".join(self.tokens)\n \n def compat(self,token,iterable):\n indents=[]\n toks_append=self.tokens.append\n startline=token[0]in(NEWLINE,NL)\n prevstring=False\n in_fstring=0\n \n for tok in _itertools.chain([token],iterable):\n toknum,tokval=tok[:2]\n if toknum ==ENCODING:\n self.encoding=tokval\n continue\n \n if toknum in(NAME,NUMBER):\n tokval +=' '\n \n \n if toknum ==STRING:\n if prevstring:\n tokval=' '+tokval\n prevstring=True\n else:\n prevstring=False\n \n if toknum ==FSTRING_START:\n in_fstring +=1\n elif toknum ==FSTRING_END:\n in_fstring -=1\n if toknum ==INDENT:\n indents.append(tokval)\n continue\n elif toknum ==DEDENT:\n indents.pop()\n continue\n elif toknum in(NEWLINE,NL):\n startline=True\n elif startline and indents:\n toks_append(indents[-1])\n startline=False\n elif toknum ==FSTRING_MIDDLE:\n tokval=self.escape_brackets(tokval)\n \n \n if tokval in{\"{\",\"}\"}and self.tokens and self.tokens[-1]==tokval and in_fstring:\n tokval=' '+tokval\n \n \n if toknum in(STRING,FSTRING_START)and self.prev_type in(STRING,FSTRING_END):\n self.tokens.append(\" \")\n \n toks_append(tokval)\n self.prev_type=toknum\n \n \ndef untokenize(iterable):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n ut=Untokenizer()\n out=ut.untokenize(iterable)\n if ut.encoding is not None:\n out=out.encode(ut.encoding)\n return out\n \n \ndef _get_normal_name(orig_enc):\n ''\n \n enc=orig_enc[:12].lower().replace(\"_\",\"-\")\n if enc ==\"utf-8\"or enc.startswith(\"utf-8-\"):\n return \"utf-8\"\n if enc in(\"latin-1\",\"iso-8859-1\",\"iso-latin-1\")or\\\n enc.startswith((\"latin-1-\",\"iso-8859-1-\",\"iso-latin-1-\")):\n return \"iso-8859-1\"\n return orig_enc\n \ndef detect_encoding(readline):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n filename=readline.__self__.name\n except AttributeError:\n filename=None\n bom_found=False\n encoding=None\n default='utf-8'\n def read_or_stop():\n try:\n return readline()\n except StopIteration:\n return b''\n \n def find_cookie(line):\n try:\n \n \n \n line_string=line.decode('utf-8')\n except UnicodeDecodeError:\n msg=\"invalid or missing encoding declaration\"\n if filename is not None:\n msg='{} for {!r}'.format(msg,filename)\n raise SyntaxError(msg)\n \n match=cookie_re.match(line_string)\n if not match:\n return None\n encoding=_get_normal_name(match.group(1))\n try:\n codec=lookup(encoding)\n except LookupError:\n \n if filename is None:\n msg=\"unknown encoding: \"+encoding\n else:\n msg=\"unknown encoding for {!r}: {}\".format(filename,\n encoding)\n raise SyntaxError(msg)\n \n if bom_found:\n if encoding !='utf-8':\n \n if filename is None:\n msg='encoding problem: utf-8'\n else:\n msg='encoding problem for {!r}: utf-8'.format(filename)\n raise SyntaxError(msg)\n encoding +='-sig'\n return encoding\n \n first=read_or_stop()\n if first.startswith(BOM_UTF8):\n bom_found=True\n first=first[3:]\n default='utf-8-sig'\n if not first:\n return default,[]\n \n encoding=find_cookie(first)\n if encoding:\n return encoding,[first]\n if not blank_re.match(first):\n return default,[first]\n \n second=read_or_stop()\n if not second:\n return default,[first]\n \n encoding=find_cookie(second)\n if encoding:\n return encoding,[first,second]\n \n return default,[first,second]\n \n \ndef open(filename):\n ''\n\n \n buffer=_builtin_open(filename,'rb')\n try:\n encoding,lines=detect_encoding(buffer.readline)\n buffer.seek(0)\n text=TextIOWrapper(buffer,encoding,line_buffering=True)\n text.mode='r'\n return text\n except:\n buffer.close()\n raise\n \ndef tokenize(readline):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n encoding,consumed=detect_encoding(readline)\n rl_gen=_itertools.chain(consumed,iter(readline,b\"\"))\n if encoding is not None:\n if encoding ==\"utf-8-sig\":\n \n encoding=\"utf-8\"\n yield TokenInfo(ENCODING,encoding,(0,0),(0,0),'')\n yield from _generate_tokens_from_c_tokenizer(rl_gen.__next__,encoding,extra_tokens=True)\n \ndef generate_tokens(readline):\n ''\n\n\n\n \n return _generate_tokens_from_c_tokenizer(readline,extra_tokens=True)\n \ndef main():\n import argparse\n \n \n def perror(message):\n sys.stderr.write(message)\n sys.stderr.write('\\n')\n \n def error(message,filename=None,location=None):\n if location:\n args=(filename,)+location+(message,)\n perror(\"%s:%d:%d: error: %s\"%args)\n elif filename:\n perror(\"%s: error: %s\"%(filename,message))\n else:\n perror(\"error: %s\"%message)\n sys.exit(1)\n \n \n parser=argparse.ArgumentParser(prog='python -m tokenize')\n parser.add_argument(dest='filename',nargs='?',\n metavar='filename.py',\n help='the file to tokenize; defaults to stdin')\n parser.add_argument('-e','--exact',dest='exact',action='store_true',\n help='display token names using the exact type')\n args=parser.parse_args()\n \n try:\n \n if args.filename:\n filename=args.filename\n with _builtin_open(filename,'rb')as f:\n tokens=list(tokenize(f.readline))\n else:\n filename=\"\"\n tokens=_generate_tokens_from_c_tokenizer(\n sys.stdin.readline,extra_tokens=True)\n \n \n \n for token in tokens:\n token_type=token.type\n if args.exact:\n token_type=token.exact_type\n token_range=\"%d,%d-%d,%d:\"%(token.start+token.end)\n print(\"%-20s%-15s%-15r\"%\n (token_range,tok_name[token_type],token.string))\n except IndentationError as err:\n line,column=err.args[1][1:3]\n error(err.args[0],filename,(line,column))\n except TokenError as err:\n line,column=err.args[1]\n error(err.args[0],filename,(line,column))\n except SyntaxError as err:\n error(err,filename)\n except OSError as err:\n error(err)\n except KeyboardInterrupt:\n print(\"interrupted\\n\")\n except Exception as err:\n perror(\"unexpected error: %s\"%err)\n raise\n \ndef _transform_msg(msg):\n ''\n\n\n\n \n if \"unterminated triple-quoted string literal\"in msg:\n return \"EOF in multi-line string\"\n return msg\n \ndef _generate_tokens_from_c_tokenizer(source,encoding=None,extra_tokens=False):\n ''\n if encoding is None:\n it=_tokenize.TokenizerIter(source,extra_tokens=extra_tokens)\n else:\n it=_tokenize.TokenizerIter(source,encoding=encoding,extra_tokens=extra_tokens)\n try:\n for info in it:\n yield TokenInfo._make(info)\n except SyntaxError as e:\n if type(e)!=SyntaxError:\n raise e from None\n msg=_transform_msg(e.msg)\n raise TokenError(msg,(e.lineno,e.offset))from None\n \n \nif __name__ ==\"__main__\":\n main()\n", ["_tokenize", "argparse", "builtins", "codecs", "collections", "functools", "io", "itertools", "re", "sys", "token"]], "traceback": [".py", "''\n\nimport collections.abc\nimport itertools\nimport linecache\nimport sys\nimport textwrap\nimport warnings\nfrom contextlib import suppress\nimport _colorize\nfrom _colorize import ANSIColors\n\n__all__=['extract_stack','extract_tb','format_exception',\n'format_exception_only','format_list','format_stack',\n'format_tb','print_exc','format_exc','print_exception',\n'print_last','print_stack','print_tb','clear_frames',\n'FrameSummary','StackSummary','TracebackException',\n'walk_stack','walk_tb']\n\n\n\n\n\n\ndef print_list(extracted_list,file=None):\n ''\n \n if file is None:\n file=sys.stderr\n for item in StackSummary.from_list(extracted_list).format():\n print(item,file=file,end=\"\")\n \ndef format_list(extracted_list):\n ''\n\n\n\n\n\n\n\n\n\n \n return StackSummary.from_list(extracted_list).format()\n \n \n \n \n \ndef print_tb(tb,limit=None,file=None):\n ''\n\n\n\n\n\n \n print_list(extract_tb(tb,limit=limit),file=file)\n \ndef format_tb(tb,limit=None):\n ''\n return extract_tb(tb,limit=limit).format()\n \ndef extract_tb(tb,limit=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n return StackSummary._extract_from_extended_frame_gen(\n _walk_tb_with_full_positions(tb),limit=limit)\n \n \n \n \n \n_cause_message=(\n\"\\nThe above exception was the direct cause \"\n\"of the following exception:\\n\\n\")\n\n_context_message=(\n\"\\nDuring handling of the above exception, \"\n\"another exception occurred:\\n\\n\")\n\n\nclass _Sentinel:\n def __repr__(self):\n return \"\"\n \n_sentinel=_Sentinel()\n\ndef _parse_value_tb(exc,value,tb):\n if(value is _sentinel)!=(tb is _sentinel):\n raise ValueError(\"Both or neither of value and tb must be given\")\n if value is tb is _sentinel:\n if exc is not None:\n if isinstance(exc,BaseException):\n return exc,exc.__traceback__\n \n raise TypeError(f'Exception expected for value, '\n f'{type(exc).__name__} found')\n else:\n return None,None\n return value,tb\n \n \ndef print_exception(exc,/,value=_sentinel,tb=_sentinel,limit=None,\\\nfile=None,chain=True,**kwargs):\n ''\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n value,tb=_parse_value_tb(exc,value,tb)\n te=TracebackException(type(value),value,tb,limit=limit,compact=True)\n te.print(file=file,chain=chain,colorize=colorize)\n \n \nBUILTIN_EXCEPTION_LIMIT=object()\n\n\ndef _print_exception_bltin(exc,/):\n file=sys.stderr if sys.stderr is not None else sys.__stderr__\n colorize=_colorize.can_colorize()\n return print_exception(exc,limit=BUILTIN_EXCEPTION_LIMIT,file=file,colorize=colorize)\n \n \ndef format_exception(exc,/,value=_sentinel,tb=_sentinel,limit=None,\\\nchain=True,**kwargs):\n ''\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n value,tb=_parse_value_tb(exc,value,tb)\n te=TracebackException(type(value),value,tb,limit=limit,compact=True)\n return list(te.format(chain=chain,colorize=colorize))\n \n \ndef format_exception_only(exc,/,value=_sentinel,*,show_group=False,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n if value is _sentinel:\n value=exc\n te=TracebackException(type(value),value,None,compact=True)\n return list(te.format_exception_only(show_group=show_group,colorize=colorize))\n \n \n \n \ndef _format_final_exc_line(etype,value,*,insert_final_newline=True,colorize=False):\n valuestr=_safe_string(value,'exception')\n end_char=\"\\n\"if insert_final_newline else \"\"\n if colorize:\n if value is None or not valuestr:\n line=f\"{ANSIColors.BOLD_MAGENTA}{etype}{ANSIColors.RESET}{end_char}\"\n else:\n line=f\"{ANSIColors.BOLD_MAGENTA}{etype}{ANSIColors.RESET}: {ANSIColors.MAGENTA}{valuestr}{ANSIColors.RESET}{end_char}\"\n else:\n if value is None or not valuestr:\n line=f\"{etype}{end_char}\"\n else:\n line=f\"{etype}: {valuestr}{end_char}\"\n return line\n \n \ndef _safe_string(value,what,func=str):\n try:\n return func(value)\n except:\n return f'<{what} {func.__name__}() failed>'\n \n \n \ndef print_exc(limit=None,file=None,chain=True):\n ''\n print_exception(sys.exception(),limit=limit,file=file,chain=chain)\n \ndef format_exc(limit=None,chain=True):\n ''\n return \"\".join(format_exception(sys.exception(),limit=limit,chain=chain))\n \ndef print_last(limit=None,file=None,chain=True):\n ''\n if not hasattr(sys,\"last_exc\")and not hasattr(sys,\"last_type\"):\n raise ValueError(\"no last exception\")\n \n if hasattr(sys,\"last_exc\"):\n print_exception(sys.last_exc,limit,file,chain)\n else:\n print_exception(sys.last_type,sys.last_value,sys.last_traceback,\n limit,file,chain)\n \n \n \n \n \n \ndef print_stack(f=None,limit=None,file=None):\n ''\n\n\n\n\n \n if f is None:\n f=sys._getframe().f_back\n print_list(extract_stack(f,limit=limit),file=file)\n \n \ndef format_stack(f=None,limit=None):\n ''\n if f is None:\n f=sys._getframe().f_back\n return format_list(extract_stack(f,limit=limit))\n \n \ndef extract_stack(f=None,limit=None):\n ''\n\n\n\n\n\n\n \n if f is None:\n f=sys._getframe().f_back\n stack=StackSummary.extract(walk_stack(f),limit=limit)\n stack.reverse()\n return stack\n \n \ndef clear_frames(tb):\n ''\n while tb is not None:\n try:\n tb.tb_frame.clear()\n except RuntimeError:\n \n pass\n tb=tb.tb_next\n \n \nclass FrameSummary:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('filename','lineno','end_lineno','colno','end_colno',\n 'name','_lines','_lines_dedented','locals')\n \n def __init__(self,filename,lineno,name,*,lookup_line=True,\n locals=None,line=None,\n end_lineno=None,colno=None,end_colno=None):\n ''\n\n\n\n\n\n\n\n \n self.filename=filename\n self.lineno=lineno\n self.end_lineno=lineno if end_lineno is None else end_lineno\n self.colno=colno\n self.end_colno=end_colno\n self.name=name\n self._lines=line\n self._lines_dedented=None\n if lookup_line:\n self.line\n self.locals={k:_safe_string(v,'local',func=repr)\n for k,v in locals.items()}if locals else None\n \n def __eq__(self,other):\n if isinstance(other,FrameSummary):\n return(self.filename ==other.filename and\n self.lineno ==other.lineno and\n self.name ==other.name and\n self.locals ==other.locals)\n if isinstance(other,tuple):\n return(self.filename,self.lineno,self.name,self.line)==other\n return NotImplemented\n \n def __getitem__(self,pos):\n return(self.filename,self.lineno,self.name,self.line)[pos]\n \n def __iter__(self):\n return iter([self.filename,self.lineno,self.name,self.line])\n \n def __repr__(self):\n return \"\".format(\n filename=self.filename,lineno=self.lineno,name=self.name)\n \n def __len__(self):\n return 4\n \n def _set_lines(self):\n if(\n self._lines is None\n and self.lineno is not None\n and self.end_lineno is not None\n ):\n lines=[]\n for lineno in range(self.lineno,self.end_lineno+1):\n \n lines.append(linecache.getline(self.filename,lineno).rstrip())\n self._lines=\"\\n\".join(lines)+\"\\n\"\n \n @property\n def _original_lines(self):\n \n self._set_lines()\n return self._lines\n \n @property\n def _dedented_lines(self):\n \n self._set_lines()\n if self._lines_dedented is None and self._lines is not None:\n self._lines_dedented=textwrap.dedent(self._lines)\n return self._lines_dedented\n \n @property\n def line(self):\n self._set_lines()\n if self._lines is None:\n return None\n \n return self._lines.partition(\"\\n\")[0].strip()\n \n \ndef walk_stack(f):\n ''\n\n\n\n \n if f is None:\n f=sys._getframe().f_back.f_back.f_back.f_back\n while f is not None:\n yield f,f.f_lineno\n f=f.f_back\n \n \ndef walk_tb(tb):\n ''\n\n\n\n \n while tb is not None:\n yield tb.tb_frame,tb.tb_lineno\n tb=tb.tb_next\n \n \ndef _walk_tb_with_full_positions(tb):\n\n\n while tb is not None:\n positions=_get_code_position(tb.tb_frame.f_code,tb.tb_lasti)\n \n \n if positions[0]is None:\n yield tb.tb_frame,(tb.tb_lineno,)+positions[1:]\n else:\n yield tb.tb_frame,positions\n tb=tb.tb_next\n \n \ndef _get_code_position(code,instruction_index):\n if instruction_index <0:\n return(None,None,None,None)\n positions_gen=code.co_positions()\n return next(itertools.islice(positions_gen,instruction_index //2,None))\n \n \n_RECURSIVE_CUTOFF=3\n\n\nclass StackSummary(list):\n ''\n \n @classmethod\n def extract(klass,frame_gen,*,limit=None,lookup_lines=True,\n capture_locals=False):\n ''\n\n\n\n\n\n\n\n\n\n \n def extended_frame_gen():\n for f,lineno in frame_gen:\n yield f,(lineno,None,None,None)\n \n return klass._extract_from_extended_frame_gen(\n extended_frame_gen(),limit=limit,lookup_lines=lookup_lines,\n capture_locals=capture_locals)\n \n @classmethod\n def _extract_from_extended_frame_gen(klass,frame_gen,*,limit=None,\n lookup_lines=True,capture_locals=False):\n \n \n \n \n builtin_limit=limit is BUILTIN_EXCEPTION_LIMIT\n if limit is None or builtin_limit:\n limit=getattr(sys,'tracebacklimit',None)\n if limit is not None and limit <0:\n limit=0\n if limit is not None:\n if builtin_limit:\n frame_gen=tuple(frame_gen)\n frame_gen=frame_gen[len(frame_gen)-limit:]\n elif limit >=0:\n frame_gen=itertools.islice(frame_gen,limit)\n else:\n frame_gen=collections.deque(frame_gen,maxlen=-limit)\n \n result=klass()\n fnames=set()\n for f,(lineno,end_lineno,colno,end_colno)in frame_gen:\n co=f.f_code\n filename=co.co_filename\n name=co.co_name\n fnames.add(filename)\n linecache.lazycache(filename,f.f_globals)\n \n if capture_locals:\n f_locals=f.f_locals\n else:\n f_locals=None\n result.append(FrameSummary(\n filename,lineno,name,lookup_line=False,locals=f_locals,\n end_lineno=end_lineno,colno=colno,end_colno=end_colno))\n for filename in fnames:\n linecache.checkcache(filename)\n \n \n if lookup_lines:\n for f in result:\n f.line\n return result\n \n @classmethod\n def from_list(klass,a_list):\n ''\n\n\n \n \n \n \n \n result=StackSummary()\n for frame in a_list:\n if isinstance(frame,FrameSummary):\n result.append(frame)\n else:\n filename,lineno,name,line=frame\n result.append(FrameSummary(filename,lineno,name,line=line))\n return result\n \n def format_frame_summary(self,frame_summary,**kwargs):\n ''\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n row=[]\n filename=frame_summary.filename\n if frame_summary.filename.startswith(\"-\"):\n filename=\"\"\n if colorize:\n row.append(' File {}\"{}\"{}, line {}{}{}, in {}{}{}\\n'.format(\n ANSIColors.MAGENTA,\n filename,\n ANSIColors.RESET,\n ANSIColors.MAGENTA,\n frame_summary.lineno,\n ANSIColors.RESET,\n ANSIColors.MAGENTA,\n frame_summary.name,\n ANSIColors.RESET,\n )\n )\n else:\n row.append(' File \"{}\", line {}, in {}\\n'.format(\n filename,frame_summary.lineno,frame_summary.name))\n if frame_summary._dedented_lines and frame_summary._dedented_lines.strip():\n if(\n frame_summary.colno is None or\n frame_summary.end_colno is None\n ):\n \n row.append(textwrap.indent(frame_summary.line,' ')+\"\\n\")\n else:\n \n all_lines_original=frame_summary._original_lines.splitlines()\n first_line=all_lines_original[0]\n \n last_line=all_lines_original[frame_summary.end_lineno -frame_summary.lineno]\n \n \n start_offset=_byte_offset_to_character_offset(first_line,frame_summary.colno)\n end_offset=_byte_offset_to_character_offset(last_line,frame_summary.end_colno)\n \n all_lines=frame_summary._dedented_lines.splitlines()[\n :frame_summary.end_lineno -frame_summary.lineno+1\n ]\n \n \n dedent_characters=len(first_line)-len(all_lines[0])\n start_offset=max(0,start_offset -dedent_characters)\n end_offset=max(0,end_offset -dedent_characters)\n \n \n \n \n dp_start_offset=_display_width(all_lines[0],offset=start_offset)\n dp_end_offset=_display_width(all_lines[-1],offset=end_offset)\n \n \n segment=\"\\n\".join(all_lines)\n segment=segment[start_offset:len(segment)-(len(all_lines[-1])-end_offset)]\n \n \n anchors=None\n show_carets=False\n with suppress(Exception):\n anchors=_extract_caret_anchors_from_line_segment(segment)\n show_carets=self._should_show_carets(start_offset,end_offset,all_lines,anchors)\n \n result=[]\n \n \n significant_lines={0,len(all_lines)-1}\n \n anchors_left_end_offset=0\n anchors_right_start_offset=0\n primary_char=\"^\"\n secondary_char=\"^\"\n if anchors:\n anchors_left_end_offset=anchors.left_end_offset\n anchors_right_start_offset=anchors.right_start_offset\n \n \n if anchors.left_end_lineno ==0:\n anchors_left_end_offset +=start_offset\n if anchors.right_start_lineno ==0:\n anchors_right_start_offset +=start_offset\n \n \n anchors_left_end_offset=_display_width(\n all_lines[anchors.left_end_lineno],offset=anchors_left_end_offset\n )\n anchors_right_start_offset=_display_width(\n all_lines[anchors.right_start_lineno],offset=anchors_right_start_offset\n )\n \n primary_char=anchors.primary_char\n secondary_char=anchors.secondary_char\n significant_lines.update(\n range(anchors.left_end_lineno -1,anchors.left_end_lineno+2)\n )\n significant_lines.update(\n range(anchors.right_start_lineno -1,anchors.right_start_lineno+2)\n )\n \n \n significant_lines.discard(-1)\n significant_lines.discard(len(all_lines))\n \n def output_line(lineno):\n ''\n result.append(all_lines[lineno]+\"\\n\")\n if not show_carets:\n return\n num_spaces=len(all_lines[lineno])-len(all_lines[lineno].lstrip())\n carets=[]\n num_carets=dp_end_offset if lineno ==len(all_lines)-1 else _display_width(all_lines[lineno])\n \n for col in range(num_carets):\n if col anchors.left_end_lineno or\n (lineno ==anchors.left_end_lineno and col >=anchors_left_end_offset)\n )and(\n lineno 2:\n \n result.append(f\"...<{linediff -1} lines>...\\n\")\n output_line(lineno)\n \n row.append(\n textwrap.indent(textwrap.dedent(\"\".join(result)),' ',lambda line:True)\n )\n if frame_summary.locals:\n for name,value in sorted(frame_summary.locals.items()):\n row.append(' {name} = {value}\\n'.format(name=name,value=value))\n \n return ''.join(row)\n \n def _should_show_carets(self,start_offset,end_offset,all_lines,anchors):\n with suppress(SyntaxError,ImportError):\n import ast\n tree=ast.parse('\\n'.join(all_lines))\n statement=tree.body[0]\n value=None\n def _spawns_full_line(value):\n return(\n value.lineno ==1\n and value.end_lineno ==len(all_lines)\n and value.col_offset ==start_offset\n and value.end_col_offset ==end_offset\n )\n match statement:\n case ast.Return(value=ast.Call()):\n if isinstance(statement.value.func,ast.Name):\n value=statement.value\n case ast.Assign(value=ast.Call()):\n if(\n len(statement.targets)==1 and\n isinstance(statement.targets[0],ast.Name)\n ):\n value=statement.value\n if value is not None and _spawns_full_line(value):\n return False\n if anchors:\n return True\n if all_lines[0][:start_offset].lstrip()or all_lines[-1][end_offset:].rstrip():\n return True\n return False\n \n def format(self,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n result=[]\n last_file=None\n last_line=None\n last_name=None\n count=0\n for frame_summary in self:\n formatted_frame=self.format_frame_summary(frame_summary,colorize=colorize)\n if formatted_frame is None:\n continue\n if(last_file is None or last_file !=frame_summary.filename or\n last_line is None or last_line !=frame_summary.lineno or\n last_name is None or last_name !=frame_summary.name):\n if count >_RECURSIVE_CUTOFF:\n count -=_RECURSIVE_CUTOFF\n result.append(\n f' [Previous line repeated {count} more '\n f'time{\"s\"if count >1 else \"\"}]\\n'\n )\n last_file=frame_summary.filename\n last_line=frame_summary.lineno\n last_name=frame_summary.name\n count=0\n count +=1\n if count >_RECURSIVE_CUTOFF:\n continue\n result.append(formatted_frame)\n \n if count >_RECURSIVE_CUTOFF:\n count -=_RECURSIVE_CUTOFF\n result.append(\n f' [Previous line repeated {count} more '\n f'time{\"s\"if count >1 else \"\"}]\\n'\n )\n return result\n \n \ndef _byte_offset_to_character_offset(str,offset):\n as_utf8=str.encode('utf-8')\n return len(as_utf8[:offset].decode(\"utf-8\",errors=\"replace\"))\n \n \n_Anchors=collections.namedtuple(\n\"_Anchors\",\n[\n\"left_end_lineno\",\n\"left_end_offset\",\n\"right_start_lineno\",\n\"right_start_offset\",\n\"primary_char\",\n\"secondary_char\",\n],\ndefaults=[\"~\",\"^\"]\n)\n\ndef _extract_caret_anchors_from_line_segment(segment):\n ''\n\n\n\n\n \n import ast\n \n try:\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n tree=ast.parse(f\"(\\n{segment}\\n)\")\n except SyntaxError:\n return None\n \n if len(tree.body)!=1:\n return None\n \n lines=segment.splitlines()\n \n def normalize(lineno,offset):\n ''\n return _byte_offset_to_character_offset(lines[lineno],offset)\n \n def next_valid_char(lineno,col):\n ''\n\n \n while lineno =len(lines[lineno]):\n col=0\n lineno +=1\n assert lineno lineno or\n right_col \"\n stype=smod+'.'+stype\n return stype\n \n def _load_lines(self):\n ''\n for frame in self.stack:\n frame.line\n \n def __eq__(self,other):\n if isinstance(other,TracebackException):\n return self.__dict__ ==other.__dict__\n return NotImplemented\n \n def __str__(self):\n return self._str\n \n def format_exception_only(self,*,show_group=False,_depth=0,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n \n indent=3 *_depth *' '\n if not self._have_exc_type:\n yield indent+_format_final_exc_line(None,self._str,colorize=colorize)\n return\n \n stype=self.exc_type_str\n if not self._is_syntax_error:\n if _depth >0:\n \n formatted=_format_final_exc_line(\n stype,self._str,insert_final_newline=False,colorize=colorize\n ).split('\\n')\n yield from[\n indent+l+'\\n'\n for l in formatted\n ]\n else:\n yield _format_final_exc_line(stype,self._str,colorize=colorize)\n else:\n yield from[indent+l for l in self._format_syntax_error(stype,colorize=colorize)]\n \n if(\n isinstance(self.__notes__,collections.abc.Sequence)\n and not isinstance(self.__notes__,(str,bytes))\n ):\n for note in self.__notes__:\n note=_safe_string(note,'note')\n yield from[indent+l+'\\n'for l in note.split('\\n')]\n elif self.__notes__ is not None:\n yield indent+\"{}\\n\".format(_safe_string(self.__notes__,'__notes__',func=repr))\n \n if self.exceptions and show_group:\n for ex in self.exceptions:\n yield from ex.format_exception_only(show_group=show_group,_depth=_depth+1,colorize=colorize)\n \n def _format_syntax_error(self,stype,**kwargs):\n ''\n \n colorize=kwargs.get(\"colorize\",False)\n filename_suffix=''\n if self.lineno is not None:\n if colorize:\n yield ' File {}\"{}\"{}, line {}{}{}\\n'.format(\n ANSIColors.MAGENTA,\n self.filename or \"\",\n ANSIColors.RESET,\n ANSIColors.MAGENTA,\n self.lineno,\n ANSIColors.RESET,\n )\n else:\n yield ' File \"{}\", line {}\\n'.format(\n self.filename or \"\",self.lineno)\n elif self.filename is not None:\n filename_suffix=' ({})'.format(self.filename)\n \n text=self.text\n if text is not None:\n \n \n \n rtext=text.rstrip('\\n')\n ltext=rtext.lstrip(' \\n\\f')\n spaces=len(rtext)-len(ltext)\n if self.offset is None:\n yield ' {}\\n'.format(ltext)\n else:\n offset=self.offset\n end_offset=self.end_offset if self.end_offset not in{None,0}else offset\n if self.text and offset >len(self.text):\n offset=len(self.text)+1\n if self.text and end_offset >len(self.text):\n end_offset=len(self.text)+1\n if offset >=end_offset or end_offset <0:\n end_offset=offset+1\n \n \n colno=offset -1 -spaces\n end_colno=end_offset -1 -spaces\n caretspace=' '\n if colno >=0:\n \n caretspace=((c if c.isspace()else ' ')for c in ltext[:colno])\n start_color=end_color=\"\"\n if colorize:\n \n ltext=(\n ltext[:colno]+\n ANSIColors.BOLD_RED+ltext[colno:end_colno]+ANSIColors.RESET+\n ltext[end_colno:]\n )\n start_color=ANSIColors.BOLD_RED\n end_color=ANSIColors.RESET\n yield ' {}\\n'.format(ltext)\n yield ' {}{}{}{}\\n'.format(\n \"\".join(caretspace),\n start_color,\n ('^'*(end_colno -colno)),\n end_color,\n )\n else:\n yield ' {}\\n'.format(ltext)\n msg=self.msg or \"\"\n if colorize:\n yield \"{}{}{}: {}{}{}{}\\n\".format(\n ANSIColors.BOLD_MAGENTA,\n stype,\n ANSIColors.RESET,\n ANSIColors.MAGENTA,\n msg,\n ANSIColors.RESET,\n filename_suffix)\n else:\n yield \"{}: {}{}\\n\".format(stype,msg,filename_suffix)\n \n def format(self,*,chain=True,_ctx=None,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n if _ctx is None:\n _ctx=_ExceptionPrintContext()\n \n output=[]\n exc=self\n if chain:\n while exc:\n if exc.__cause__ is not None:\n chained_msg=_cause_message\n chained_exc=exc.__cause__\n elif(exc.__context__ is not None and\n not exc.__suppress_context__):\n chained_msg=_context_message\n chained_exc=exc.__context__\n else:\n chained_msg=None\n chained_exc=None\n \n output.append((chained_msg,exc))\n exc=chained_exc\n else:\n output.append((None,exc))\n \n for msg,exc in reversed(output):\n if msg is not None:\n yield from _ctx.emit(msg)\n if exc.exceptions is None:\n if exc.stack:\n yield from _ctx.emit('Traceback (most recent call last):\\n')\n yield from _ctx.emit(exc.stack.format(colorize=colorize))\n yield from _ctx.emit(exc.format_exception_only(colorize=colorize))\n elif _ctx.exception_group_depth >self.max_group_depth:\n \n yield from _ctx.emit(\n f\"... (max_group_depth is {self.max_group_depth})\\n\")\n else:\n \n is_toplevel=(_ctx.exception_group_depth ==0)\n if is_toplevel:\n _ctx.exception_group_depth +=1\n \n if exc.stack:\n yield from _ctx.emit(\n 'Exception Group Traceback (most recent call last):\\n',\n margin_char='+'if is_toplevel else None)\n yield from _ctx.emit(exc.stack.format(colorize=colorize))\n \n yield from _ctx.emit(exc.format_exception_only(colorize=colorize))\n num_excs=len(exc.exceptions)\n if num_excs <=self.max_group_width:\n n=num_excs\n else:\n n=self.max_group_width+1\n _ctx.need_close=False\n for i in range(n):\n last_exc=(i ==n -1)\n if last_exc:\n \n _ctx.need_close=True\n \n if self.max_group_width is not None:\n truncated=(i >=self.max_group_width)\n else:\n truncated=False\n title=f'{i+1}'if not truncated else '...'\n yield(_ctx.indent()+\n ('+-'if i ==0 else ' ')+\n f'+---------------- {title} ----------------\\n')\n _ctx.exception_group_depth +=1\n if not truncated:\n yield from exc.exceptions[i].format(chain=chain,_ctx=_ctx)\n else:\n remaining=num_excs -self.max_group_width\n plural='s'if remaining >1 else ''\n yield from _ctx.emit(\n f\"and {remaining} more exception{plural}\\n\")\n \n if last_exc and _ctx.need_close:\n yield(_ctx.indent()+\n \"+------------------------------------\\n\")\n _ctx.need_close=False\n _ctx.exception_group_depth -=1\n \n if is_toplevel:\n assert _ctx.exception_group_depth ==1\n _ctx.exception_group_depth=0\n \n \n def print(self,*,file=None,chain=True,**kwargs):\n ''\n colorize=kwargs.get(\"colorize\",False)\n if file is None:\n file=sys.stderr\n for line in self.format(chain=chain,colorize=colorize):\n print(line,file=file,end=\"\")\n \n \n_MAX_CANDIDATE_ITEMS=750\n_MAX_STRING_SIZE=40\n_MOVE_COST=2\n_CASE_COST=1\n\n\ndef _substitution_cost(ch_a,ch_b):\n if ch_a ==ch_b:\n return 0\n if ch_a.lower()==ch_b.lower():\n return _CASE_COST\n return _MOVE_COST\n \n \ndef _compute_suggestion_error(exc_value,tb,wrong_name):\n if wrong_name is None or not isinstance(wrong_name,str):\n return None\n if isinstance(exc_value,AttributeError):\n obj=exc_value.obj\n try:\n d=dir(obj)\n hide_underscored=(wrong_name[:1]!='_')\n if hide_underscored and tb is not None:\n while tb.tb_next is not None:\n tb=tb.tb_next\n frame=tb.tb_frame\n if 'self'in frame.f_locals and frame.f_locals['self']is obj:\n hide_underscored=False\n if hide_underscored:\n d=[x for x in d if x[:1]!='_']\n except Exception:\n return None\n elif isinstance(exc_value,ImportError):\n try:\n mod=__import__(exc_value.name)\n d=dir(mod)\n if wrong_name[:1]!='_':\n d=[x for x in d if x[:1]!='_']\n except Exception:\n return None\n else:\n assert isinstance(exc_value,NameError)\n \n if tb is None:\n return None\n while tb.tb_next is not None:\n tb=tb.tb_next\n frame=tb.tb_frame\n d=(\n list(frame.f_locals)\n +list(frame.f_globals)\n +list(frame.f_builtins)\n )\n \n \n \n if 'self'in frame.f_locals:\n self=frame.f_locals['self']\n if hasattr(self,wrong_name):\n return f\"self.{wrong_name}\"\n \n try:\n import _suggestions\n except ImportError:\n pass\n else:\n return _suggestions._generate_suggestions(d,wrong_name)\n \n \n \n if len(d)>_MAX_CANDIDATE_ITEMS:\n return None\n wrong_name_len=len(wrong_name)\n if wrong_name_len >_MAX_STRING_SIZE:\n return None\n best_distance=wrong_name_len\n suggestion=None\n for possible_name in d:\n if possible_name ==wrong_name:\n \n continue\n \n max_distance=(len(possible_name)+wrong_name_len+3)*_MOVE_COST //6\n \n max_distance=min(max_distance,best_distance -1)\n current_distance=_levenshtein_distance(wrong_name,possible_name,max_distance)\n if current_distance >max_distance:\n continue\n if not suggestion or current_distance _MAX_STRING_SIZE or len(b)>_MAX_STRING_SIZE:\n return max_cost+1\n \n \n if len(b)max_cost:\n return max_cost+1\n \n \n \n \n row=list(range(_MOVE_COST,_MOVE_COST *(len(a)+1),_MOVE_COST))\n \n result=0\n for bindex in range(len(b)):\n bchar=b[bindex]\n distance=result=bindex *_MOVE_COST\n minimum=sys.maxsize\n for index in range(len(a)):\n \n substitute=distance+_substitution_cost(bchar,a[index])\n \n distance=row[index]\n \n \n insert_delete=min(result,distance)+_MOVE_COST\n result=min(insert_delete,substitute)\n \n \n row[index]=result\n if result max_cost:\n \n return max_cost+1\n return result\n", ["_colorize", "_suggestions", "ast", "collections.abc", "contextlib", "itertools", "linecache", "sys", "textwrap", "unicodedata", "warnings"]], "turtle": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport math\nimport sys\n\nfrom math import cos,sin\n\nfrom browser import console,document,html,timer\nimport _svg as svg\n\n\n\n\n\n\n_CFG={\n\n\n\"canvwidth\":500,\n\"canvheight\":500,\n\n\n\"mode\":\"standard\",\n\n\n\n\"shape\":\"classic\",\n\"pencolor\":\"black\",\n\"fillcolor\":\"black\",\n\n\"visible\":True,\n\n\n\n\n\n\n\n\"turtle_canvas_wrapper\":None,\n\"turtle_canvas_id\":\"turtle-canvas\",\n\"min_duration\":\"1ms\"\n}\n\n_cfg_copy=_CFG.copy()\n\n\ndef set_defaults(**params):\n ''\n _CFG.update(**params)\n Screen().reset()\n \n \nclass FormattedTuple(tuple):\n ''\n def __new__(cls,x,y):\n return tuple.__new__(cls,(x,y))\n def __repr__(self):\n return \"(%.2f, %.2f)\"%self\n \ndef create_circle(r):\n ''\n circle=svg.circle(x=0,y=0,r=r,stroke=\"black\",fill=\"black\")\n circle.setAttribute(\"stroke-width\",1)\n return circle\n \n \ndef create_polygon(points):\n ''\n points=[\"%s,%s \"%(x,y)for x,y in points]\n polygon=svg.polygon(points=points,stroke=\"black\",fill=\"black\")\n polygon.setAttribute(\"stroke-width\",1)\n return polygon\n \n \ndef create_rectangle(width=2,height=2,rx=None,ry=None):\n ''\n \n rectangle=svg.rect(x=-width /2,y=-height /2,width=width,\n height=height,stroke=\"black\",fill=\"black\")\n rectangle.setAttribute(\"stroke-width\",1)\n if rx is not None:\n rectangle.setAttribute(\"rx\",rx)\n if ry is not None:\n rectangle.setAttribute(\"ry\",ry)\n return rectangle\n \n \ndef create_square(size=2,r=None):\n ''\n \n return create_rectangle(width=size,height=size,rx=r,ry=r)\n \n \nclass TurtleGraphicsError(Exception):\n ''\n \n pass\n \n \nclass Singleton(type):\n _instances={}\n def __call__(cls,*args,**kwargs):\n if cls not in cls._instances:\n cls._instances[cls]=super(Singleton,cls).__call__(*args,**kwargs)\n return cls._instances[cls]\n \n \nclass Screen(metaclass=Singleton):\n\n def __init__(self):\n self.shapes={\n 'arrow':(create_polygon,((-10,0),(10,0),(0,10))),\n 'turtle':(create_polygon,((0,16),(-2,14),(-1,10),(-4,7),\n (-7,9),(-9,8),(-6,5),(-7,1),(-5,-3),(-8,-6),\n (-6,-8),(-4,-5),(0,-7),(4,-5),(6,-8),(8,-6),\n (5,-3),(7,1),(6,5),(9,8),(7,9),(4,7),(1,10),\n (2,14))),\n 'classic':(create_polygon,((0,0),(-5,-9),(0,-7),(5,-9))),\n 'triangle':(create_polygon,((10,-5.77),(0,11.55),(-10,-5.77))),\n 'square':(create_square,20),\n 'circle':(create_circle,10)\n }\n self.reset()\n self._set_geometry()\n \n def bgcolor(self,color=None):\n ''\n\n \n if color is None:\n return self.background_color\n self.background_color=color\n width=_CFG['canvwidth']\n height=_CFG['canvheight']\n if self.mode()in['logo','standard']:\n x=-width //2\n y=-height //2\n else:\n x=0\n y=-height\n \n self.frame_index +=1\n rect=svg.rect(x=x,y=y,width=width,height=height,fill=color,\n style={'display':'none'})\n an=svg.animate(Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"display\",attributeType=\"CSS\",\n From=\"block\",to=\"block\",\n dur=_CFG[\"min_duration\"],fill='freeze')\n an.setAttribute('begin',\"animation_frame%s.end\"%(self.frame_index -1))\n rect <=an\n \n self.background_canvas <=rect\n \n def _convert_coordinates(self,x,y):\n ''\n\n\n\n\n\n \n return x *self.yscale,self.y_points_down *y *self.yscale\n \n \n def create_svg_turtle(self,_turtle,name):\n if name in self.shapes:\n fn=self.shapes[name][0]\n arg=self.shapes[name][1]\n else:\n print(\"Unknown turtle '%s'; the default turtle will be used\")\n fn=self.shapes[_CVG[\"shape\"]][0]\n arg=self.shapes[_CVG[\"shape\"]][1]\n shape=fn(arg)\n if self._mode =='standard'or self._mode =='world':\n rotation=-90\n else:\n rotation=0\n return shape,rotation\n \n def _dot(self,pos,size,color):\n ''\n if color is None:\n color='black'\n if size is None or size <1:\n size=1\n self.frame_index +=1\n \n \n radius=size /2\n \n x,y=self._convert_coordinates(pos[0],pos[1])\n \n circle=svg.circle(cx=x,cy=y,r=radius,fill=color,\n style={'display':'none'})\n an=svg.animate(Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"display\",attributeType=\"CSS\",\n From=\"block\",to=\"block\",\n dur=_CFG[\"min_duration\"],fill='freeze')\n an.setAttribute('begin',\"animation_frame%s.end\"%(self.frame_index -1))\n circle <=an\n self.canvas <=circle\n \n def _drawline(self,_turtle,coordlist=None,\n color=None,width=1,speed=None):\n ''\n\n\n\n\n \n \n outline=color[0]\n fill=color[1]\n \n x0,y0=coordlist[0]\n x1,y1=coordlist[1]\n \n x0,y0=self._convert_coordinates(x0,y0)\n x1,y1=self._convert_coordinates(x1,y1)\n \n \n if speed ==0:\n duration=_CFG[\"min_duration\"]\n else:\n dist=_turtle._distance\n if speed is None or speed ==1:\n duration=0.02 *dist\n else:\n duration=0.02 *dist /speed **1.2\n if duration <0.001:\n duration=_CFG[\"min_duration\"]\n else:\n duration=\"%6.3fs\"%duration\n \n drawing=_turtle._drawing\n \n _line=svg.line(x1=x0,y1=y0,x2=x0,y2=y0,\n style={'stroke':outline,'stroke-width':width})\n if not drawing:\n _line.setAttribute('opacity',0)\n \n \n begin=\"animation_frame%s.end\"%self.frame_index\n self.frame_index +=1\n _an1=svg.animate(Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"x2\",attributeType=\"XML\",\n From=x0,to=x1,dur=duration,fill='freeze',\n begin=begin)\n _line <=_an1\n \n \n if drawing:\n _an2=svg.animate(attributeName=\"y2\",attributeType=\"XML\",\n begin=begin,\n From=y0,to=y1,dur=duration,fill='freeze')\n _line <=_an2\n \n if width >2:\n _line_cap=svg.set(attributeName=\"stroke-linecap\",\n begin=begin,\n attributeType=\"xml\",to=\"round\",dur=duration,fill='freeze')\n _line <=_line_cap\n \n self.canvas <=_line\n return begin,duration,(x0,y0),(x1,y1)\n \n def _drawpoly(self,coordlist,outline=None,fill=None,width=None):\n ''\n\n\n\n\n \n self.frame_index +=1\n shape=[\"%s,%s\"%self._convert_coordinates(x,y)for x,y in coordlist]\n \n style={'display':'none'}\n if fill is not None:\n style['fill']=fill\n if outline is not None:\n style['stroke']=outline\n if width is not None:\n style['stroke-width']=width\n else:\n style['stroke-width']=1\n \n polygon=svg.polygon(points=\" \".join(shape),style=style)\n \n an=svg.animate(Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"display\",attributeType=\"CSS\",\n From=\"block\",to=\"block\",\n dur=_CFG[\"min_duration\"],fill='freeze')\n \n an.setAttribute('begin',\"animation_frame%s.end\"%(self.frame_index -1))\n polygon <=an\n self.canvas <=polygon\n \n \n def _new_frame(self):\n ''\n \n previous_end=\"animation_frame%s.end\"%self.frame_index\n self.frame_index +=1\n new_frame_id=\"animation_frame%s\"%self.frame_index\n return previous_end,new_frame_id\n \n def mode(self,_mode=None):\n if _mode is None:\n return self._mode\n _CFG['mode']=_mode\n self.reset()\n \n \n def reset(self):\n self._turtles=[]\n self.frame_index=0\n self.background_color=\"white\"\n self._set_geometry()\n \n def _set_geometry(self):\n self.width=_CFG[\"canvwidth\"]\n self.height=_CFG[\"canvheight\"]\n self.x_offset=self.y_offset=0\n self.xscale=self.yscale=1\n \n self.y_points_down=-1\n self._mode=_CFG[\"mode\"].lower()\n if self._mode in['logo','standard']:\n self.translate_canvas=(self.width //2,self.height //2)\n elif self._mode =='world':\n self.translate_canvas=(0,self.height)\n self._setup_canvas()\n \n def _setup_canvas(self):\n self.svg_scene=svg.svg(Id=_CFG[\"turtle_canvas_id\"],width=self.width,\n height=self.height)\n translate=\"translate(%d %d)\"%self.translate_canvas\n \n \n self.svg_scene <=svg.animate(\n Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"width\",attributeType=\"CSS\",\n From=self.width,to=self.width,begin=\"0s\",\n dur=_CFG[\"min_duration\"],fill='freeze')\n \n \n \n \n self.background_canvas=svg.g(transform=translate)\n self.canvas=svg.g(transform=translate)\n self.writing_canvas=svg.g(transform=translate)\n self.turtle_canvas=svg.g(transform=translate)\n \n self.svg_scene <=self.background_canvas\n self.svg_scene <=self.canvas\n self.svg_scene <=self.writing_canvas\n self.svg_scene <=self.turtle_canvas\n \n \n def setworldcoordinates(self,llx,lly,urx,ury):\n ''\n\n\n\n\n\n\n\n\n\n\n \n self._mode=\"world\"\n \n if urx 2:\n self.screen._drawpoly(self._fillpath,outline=self._pencolor,\n fill=self._fillcolor,)\n else:\n print(\"No path to fill.\")\n self._fillpath=None\n \n def dot(self,size=None,color=None):\n ''\n \n if size is None:\n size=max(self._pensize+4,2 *self._pensize)\n if color is None:\n color=self._pencolor\n item=self.screen._dot((self._x,self._y),size,color=color)\n \n def _write(self,txt,align,font,color=None):\n ''\n \n if color is None:\n color=self._pencolor\n self.screen._write((self._x,self._y),txt,align,font,color)\n \n \n def write(self,arg,align=\"left\",font=(\"Arial\",8,\"normal\"),color=None):\n ''\n\n\n\n\n\n\n \n self._write(str(arg),align.lower(),font,color=color)\n \n def begin_poly(self):\n ''\n \n self._poly=[(self._x,self._y)]\n self._creatingPoly=True\n \n def end_poly(self):\n ''\n \n self._creatingPoly=False\n \n def get_poly(self):\n ''\n \n \n if self._poly is not None:\n return tuple(self._poly)\n \n def getscreen(self):\n ''\n \n return self.screen\n \n def getturtle(self):\n ''\n\n\n \n return self\n getpen=getturtle\n \n def _make_copy(self,name=None):\n ''\n\n \n \n if name is None:\n name=self.name\n \n \n \n \n \n _turtle,rotation=self.screen.create_svg_turtle(self,name=name)\n _turtle.setAttribute(\"opacity\",0)\n _turtle.setAttribute(\"fill\",self._fillcolor)\n _turtle.setAttribute(\"stroke\",self._pencolor)\n \n \n \n previous_end,new_frame_id=self.screen._new_frame()\n x,y=self.screen._convert_coordinates(self._x,self._y)\n _turtle <=svg.animateMotion(begin=previous_end,dur=_CFG[\"min_duration\"],\n fill=\"remove\")\n \n _turtle <=svg.animateMotion(Id=new_frame_id,\n From=\"%s,%s\"%(x,y),to=\"%s,%s\"%(x,y),\n dur=_CFG[\"min_duration\"],begin=previous_end,\n fill=\"freeze\")\n _turtle <=svg.animateTransform(attributeName=\"transform\",\n type=\"rotate\",\n From=\"%s,%s,%s\"%(self._old_heading,0,0),\n to=\"%s,%s,%s\"%(self._old_heading,0,0),\n begin=previous_end,\n dur=_CFG[\"min_duration\"],fill=\"freeze\")\n _turtle <=svg.animate(begin=previous_end,\n dur=_CFG[\"min_duration\"],fill=\"freeze\",\n attributeName=\"opacity\",attributeType=\"XML\",\n From=0,to=1)\n return _turtle\n \n def stamp(self):\n ''\n \n _turtle=self._make_copy(name=self.name)\n self.screen.canvas <=_turtle\n \n \n def clone(self):\n ''\n \n n=Turtle(self.name)\n \n attrs=vars(self)\n new_dict={}\n for attr in attrs:\n if isinstance(getattr(self,attr),(int,str,float)):\n new_dict[attr]=getattr(self,attr)\n n.__dict__.update(**new_dict)\n \n if not n._shown:\n n._shown=True\n n.hideturtle()\n n.left(0)\n n.fd(0)\n n.color(n.color())\n return n\n \n \nPen=Turtle\n\n\ndef done():\n Screen().show_scene()\nshow_scene=done\n\n\ndef replay_scene():\n ''\n if(_CFG[\"turtle_canvas_id\"]in document and\n document[_CFG[\"turtle_canvas_id\"]]is not None):\n element=document[_CFG[\"turtle_canvas_id\"]]\n element.parentNode.removeChild(element)\n show_scene()\n \n \ndef restart():\n ''\n _CFG.update(_cfg_copy)\n Screen().reset()\n Turtle._pen=None\n \n if(_CFG[\"turtle_canvas_id\"]in document and\n document[_CFG[\"turtle_canvas_id\"]]is not None):\n element=document[_CFG[\"turtle_canvas_id\"]]\n element.parentNode.removeChild(element)\n \n \n \n_tg_screen_functions=['addshape','bgcolor','bgpic','bye',\n'clearscreen','colormode','delay','exitonclick','getcanvas',\n'getshapes','listen','mainloop','mode','numinput',\n'onkey','onkeypress','onkeyrelease','onscreenclick','ontimer',\n'register_shape','resetscreen','screensize','setup',\n'setworldcoordinates','textinput','title','tracer','turtles','update',\n'window_height','window_width']\n\n_tg_turtle_functions=['back','backward','begin_fill','begin_poly','bk',\n'circle','clear','clearstamp','clearstamps','clone','color',\n'degrees','distance','dot','down','end_fill','end_poly','fd',\n'fillcolor','filling','forward','get_poly','getpen','getscreen','get_shapepoly',\n'getturtle','goto','heading','hideturtle','home','ht','isdown',\n'isvisible','left','lt','onclick','ondrag','onrelease','pd',\n'pen','pencolor','pendown','pensize','penup','pos','position',\n'pu','radians','right','reset','resizemode','rt',\n'seth','setheading','setpos','setposition','settiltangle',\n'setundobuffer','setx','sety','shape','shapesize','shapetransform','shearfactor','showturtle',\n'speed','st','stamp','tilt','tiltangle','towards',\n'turtlesize','undo','undobufferentries','up','width',\n'write','xcor','ycor']\n\n\n__all__=(_tg_screen_functions+_tg_turtle_functions+\n['done','restart','replay_scene','Turtle','Screen'])\n\n\n\n\n\n__func_body=\"\"\"\\\ndef {name}(*args, **kw):\n if {obj} is None:\n {obj} = {init}\n return {obj}.{name}(*args, **kw)\n\"\"\"\n\ndef _make_global_funcs(functions,cls,obj,init):\n for methodname in functions:\n try:\n method=getattr(cls,methodname)\n except AttributeError:\n print(\"methodname missing:\",methodname)\n continue\n defstr=__func_body.format(obj=obj,init=init,name=methodname)\n exec(defstr,globals())\n \n_make_global_funcs(_tg_turtle_functions,Turtle,'Turtle._pen','Turtle()')\n\n_make_global_funcs(_tg_screen_functions,Screen,'Turtle.screen','Screen()')\n", ["_svg", "browser", "browser.timer", "math", "sys"]], "types": [".py", "''\n\n\n\nimport sys\n\n\n\n\n\n\ndef _f():pass\nFunctionType=type(_f)\nLambdaType=type(lambda:None)\nCodeType=type(_f.__code__)\nMappingProxyType=type(type.__dict__)\nSimpleNamespace=type(sys.implementation)\n\ndef _cell_factory():\n a=1\n def f():\n nonlocal a\n return f.__closure__[0]\nCellType=type(_cell_factory())\n\ndef _g():\n yield 1\nGeneratorType=type(_g())\n\nasync def _c():pass\n_c=_c()\nCoroutineType=type(_c)\n_c.close()\n\nasync def _ag():\n yield\n_ag=_ag()\nAsyncGeneratorType=type(_ag)\n\nclass _C:\n def _m(self):pass\nMethodType=type(_C()._m)\n\nBuiltinFunctionType=type(len)\nBuiltinMethodType=type([].append)\n\nWrapperDescriptorType=type(object.__init__)\nMethodWrapperType=type(object().__str__)\nMethodDescriptorType=type(str.join)\nClassMethodDescriptorType=type(dict.__dict__['fromkeys'])\n\nModuleType=type(sys)\n\ntry:\n raise TypeError\nexcept TypeError as exc:\n TracebackType=type(exc.__traceback__)\n FrameType=type(exc.__traceback__.tb_frame)\n \nGetSetDescriptorType=type(FunctionType.__code__)\nMemberDescriptorType=type(FunctionType.__globals__)\n\ndel sys,_f,_g,_C,_c,_ag,_cell_factory\n\n\n\ndef new_class(name,bases=(),kwds=None,exec_body=None):\n ''\n resolved_bases=resolve_bases(bases)\n meta,ns,kwds=prepare_class(name,resolved_bases,kwds)\n if exec_body is not None:\n exec_body(ns)\n if resolved_bases is not bases:\n ns['__orig_bases__']=bases\n return meta(name,resolved_bases,ns,**kwds)\n \ndef resolve_bases(bases):\n ''\n new_bases=list(bases)\n updated=False\n shift=0\n for i,base in enumerate(bases):\n if isinstance(base,type):\n continue\n if not hasattr(base,\"__mro_entries__\"):\n continue\n new_base=base.__mro_entries__(bases)\n updated=True\n if not isinstance(new_base,tuple):\n raise TypeError(\"__mro_entries__ must return a tuple\")\n else:\n new_bases[i+shift:i+shift+1]=new_base\n shift +=len(new_base)-1\n if not updated:\n return bases\n return tuple(new_bases)\n \ndef prepare_class(name,bases=(),kwds=None):\n ''\n\n\n\n\n\n\n\n\n \n if kwds is None:\n kwds={}\n else:\n kwds=dict(kwds)\n if 'metaclass'in kwds:\n meta=kwds.pop('metaclass')\n else:\n if bases:\n meta=type(bases[0])\n else:\n meta=type\n if isinstance(meta,type):\n \n \n meta=_calculate_meta(meta,bases)\n if hasattr(meta,'__prepare__'):\n ns=meta.__prepare__(name,bases,**kwds)\n else:\n ns={}\n return meta,ns,kwds\n \ndef _calculate_meta(meta,bases):\n ''\n winner=meta\n for base in bases:\n base_meta=type(base)\n if issubclass(winner,base_meta):\n continue\n if issubclass(base_meta,winner):\n winner=base_meta\n continue\n \n raise TypeError(\"metaclass conflict: \"\n \"the metaclass of a derived class \"\n \"must be a (non-strict) subclass \"\n \"of the metaclasses of all its bases\")\n return winner\n \n \ndef get_original_bases(cls,/):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return cls.__dict__.get(\"__orig_bases__\",cls.__bases__)\n except AttributeError:\n raise TypeError(\n f\"Expected an instance of type, not {type(cls).__name__ !r}\"\n )from None\n \n \nclass DynamicClassAttribute:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,fget=None,fset=None,fdel=None,doc=None):\n self.fget=fget\n self.fset=fset\n self.fdel=fdel\n \n self.__doc__=doc or fget.__doc__\n self.overwrite_doc=doc is None\n \n self.__isabstractmethod__=bool(getattr(fget,'__isabstractmethod__',False))\n \n def __get__(self,instance,ownerclass=None):\n if instance is None:\n if self.__isabstractmethod__:\n return self\n raise AttributeError()\n elif self.fget is None:\n raise AttributeError(\"unreadable attribute\")\n return self.fget(instance)\n \n def __set__(self,instance,value):\n if self.fset is None:\n raise AttributeError(\"can't set attribute\")\n self.fset(instance,value)\n \n def __delete__(self,instance):\n if self.fdel is None:\n raise AttributeError(\"can't delete attribute\")\n self.fdel(instance)\n \n def getter(self,fget):\n fdoc=fget.__doc__ if self.overwrite_doc else None\n result=type(self)(fget,self.fset,self.fdel,fdoc or self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n def setter(self,fset):\n result=type(self)(self.fget,fset,self.fdel,self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n def deleter(self,fdel):\n result=type(self)(self.fget,self.fset,fdel,self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n \nclass _GeneratorWrapper:\n\n def __init__(self,gen):\n self.__wrapped=gen\n self.__isgen=gen.__class__ is GeneratorType\n self.__name__=getattr(gen,'__name__',None)\n self.__qualname__=getattr(gen,'__qualname__',None)\n def send(self,val):\n return self.__wrapped.send(val)\n def throw(self,tp,*rest):\n return self.__wrapped.throw(tp,*rest)\n def close(self):\n return self.__wrapped.close()\n @property\n def gi_code(self):\n return self.__wrapped.gi_code\n @property\n def gi_frame(self):\n return self.__wrapped.gi_frame\n @property\n def gi_running(self):\n return self.__wrapped.gi_running\n @property\n def gi_yieldfrom(self):\n return self.__wrapped.gi_yieldfrom\n cr_code=gi_code\n cr_frame=gi_frame\n cr_running=gi_running\n cr_await=gi_yieldfrom\n def __next__(self):\n return next(self.__wrapped)\n def __iter__(self):\n if self.__isgen:\n return self.__wrapped\n return self\n __await__=__iter__\n \ndef coroutine(func):\n ''\n \n if not callable(func):\n raise TypeError('types.coroutine() expects a callable')\n \n if(func.__class__ is FunctionType and\n getattr(func,'__code__',None).__class__ is CodeType):\n \n co_flags=func.__code__.co_flags\n \n \n \n if co_flags&0x180:\n return func\n \n \n \n if co_flags&0x20:\n \n co=func.__code__\n \n func.__code__=co.replace(co_flags=co.co_flags |0x100)\n return func\n \n \n \n \n \n \n import functools\n import _collections_abc\n @functools.wraps(func)\n def wrapped(*args,**kwargs):\n coro=func(*args,**kwargs)\n if(coro.__class__ is CoroutineType or\n coro.__class__ is GeneratorType and coro.gi_code.co_flags&0x100):\n \n return coro\n if(isinstance(coro,_collections_abc.Generator)and\n not isinstance(coro,_collections_abc.Coroutine)):\n \n \n \n return _GeneratorWrapper(coro)\n \n \n return coro\n \n return wrapped\n \nGenericAlias=type(list[int])\nUnionType=type(int |str)\n\nEllipsisType=type(Ellipsis)\nNoneType=type(None)\nNotImplementedType=type(NotImplemented)\n\ndef __getattr__(name):\n if name =='CapsuleType':\n import _socket\n return type(_socket.CAPI)\n raise AttributeError(f\"module {__name__ !r} has no attribute {name !r}\")\n \n__all__=[n for n in globals()if n[:1]!='_']\n__all__ +=['CapsuleType']\n", ["_collections_abc", "_socket", "functools", "sys"]], "typing": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom abc import abstractmethod,ABCMeta\nimport collections\nfrom collections import defaultdict\nimport collections.abc\nimport copyreg\nimport functools\nimport operator\nimport sys\nimport types\nfrom types import WrapperDescriptorType,MethodWrapperType,MethodDescriptorType,GenericAlias\n\nfrom _typing import(\n_idfunc,\nTypeVar,\nParamSpec,\nTypeVarTuple,\nParamSpecArgs,\nParamSpecKwargs,\nTypeAliasType,\nGeneric,\nNoDefault,\n)\n\n\n__all__=[\n\n'Annotated',\n'Any',\n'Callable',\n'ClassVar',\n'Concatenate',\n'Final',\n'ForwardRef',\n'Generic',\n'Literal',\n'Optional',\n'ParamSpec',\n'Protocol',\n'Tuple',\n'Type',\n'TypeVar',\n'TypeVarTuple',\n'Union',\n\n\n'AbstractSet',\n'ByteString',\n'Container',\n'ContextManager',\n'Hashable',\n'ItemsView',\n'Iterable',\n'Iterator',\n'KeysView',\n'Mapping',\n'MappingView',\n'MutableMapping',\n'MutableSequence',\n'MutableSet',\n'Sequence',\n'Sized',\n'ValuesView',\n'Awaitable',\n'AsyncIterator',\n'AsyncIterable',\n'Coroutine',\n'Collection',\n'AsyncGenerator',\n'AsyncContextManager',\n\n\n'Reversible',\n'SupportsAbs',\n'SupportsBytes',\n'SupportsComplex',\n'SupportsFloat',\n'SupportsIndex',\n'SupportsInt',\n'SupportsRound',\n\n\n'ChainMap',\n'Counter',\n'Deque',\n'Dict',\n'DefaultDict',\n'List',\n'OrderedDict',\n'Set',\n'FrozenSet',\n'NamedTuple',\n'TypedDict',\n'Generator',\n\n\n'BinaryIO',\n'IO',\n'Match',\n'Pattern',\n'TextIO',\n\n\n'AnyStr',\n'assert_type',\n'assert_never',\n'cast',\n'clear_overloads',\n'dataclass_transform',\n'final',\n'get_args',\n'get_origin',\n'get_overloads',\n'get_protocol_members',\n'get_type_hints',\n'is_protocol',\n'is_typeddict',\n'LiteralString',\n'Never',\n'NewType',\n'no_type_check',\n'no_type_check_decorator',\n'NoDefault',\n'NoReturn',\n'NotRequired',\n'overload',\n'override',\n'ParamSpecArgs',\n'ParamSpecKwargs',\n'ReadOnly',\n'Required',\n'reveal_type',\n'runtime_checkable',\n'Self',\n'Text',\n'TYPE_CHECKING',\n'TypeAlias',\n'TypeGuard',\n'TypeIs',\n'TypeAliasType',\n'Unpack',\n]\n\n\ndef _type_convert(arg,module=None,*,allow_special_forms=False):\n ''\n if arg is None:\n return type(None)\n if isinstance(arg,str):\n return ForwardRef(arg,module=module,is_class=allow_special_forms)\n return arg\n \n \ndef _type_check(arg,msg,is_argument=True,module=None,*,allow_special_forms=False):\n ''\n\n\n\n\n\n\n\n\n\n \n invalid_generic_forms=(Generic,Protocol)\n if not allow_special_forms:\n invalid_generic_forms +=(ClassVar,)\n if is_argument:\n invalid_generic_forms +=(Final,)\n \n arg=_type_convert(arg,module=module,allow_special_forms=allow_special_forms)\n if(isinstance(arg,_GenericAlias)and\n arg.__origin__ in invalid_generic_forms):\n raise TypeError(f\"{arg} is not valid as type argument\")\n if arg in(Any,LiteralString,NoReturn,Never,Self,TypeAlias):\n return arg\n if allow_special_forms and arg in(ClassVar,Final):\n return arg\n if isinstance(arg,_SpecialForm)or arg in(Generic,Protocol):\n raise TypeError(f\"Plain {arg} is not valid as type argument\")\n if type(arg)is tuple:\n raise TypeError(f\"{msg} Got {arg !r:.100}.\")\n return arg\n \n \ndef _is_param_expr(arg):\n return arg is ...or isinstance(arg,\n (tuple,list,ParamSpec,_ConcatenateGenericAlias))\n \n \ndef _should_unflatten_callable_args(typ,args):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return(\n typ.__origin__ is collections.abc.Callable\n and not(len(args)==2 and _is_param_expr(args[0]))\n )\n \n \ndef _type_repr(obj):\n ''\n\n\n\n\n\n \n \n \n \n if isinstance(obj,type):\n if obj.__module__ =='builtins':\n return obj.__qualname__\n return f'{obj.__module__}.{obj.__qualname__}'\n if obj is ...:\n return '...'\n if isinstance(obj,types.FunctionType):\n return obj.__name__\n if isinstance(obj,tuple):\n \n return '['+', '.join(_type_repr(t)for t in obj)+']'\n return repr(obj)\n \n \ndef _collect_type_parameters(args,*,enforce_default_ordering:bool=True):\n ''\n\n\n\n\n\n\n\n\n \n \n default_encountered=False\n \n type_var_tuple_encountered=False\n parameters=[]\n for t in args:\n if isinstance(t,type):\n \n pass\n elif isinstance(t,tuple):\n \n \n for x in t:\n for collected in _collect_type_parameters([x]):\n if collected not in parameters:\n parameters.append(collected)\n elif hasattr(t,'__typing_subst__'):\n if t not in parameters:\n if enforce_default_ordering:\n if type_var_tuple_encountered and t.has_default():\n raise TypeError('Type parameter with a default'\n ' follows TypeVarTuple')\n \n if t.has_default():\n default_encountered=True\n elif default_encountered:\n raise TypeError(f'Type parameter {t !r} without a default'\n ' follows type parameter with a default')\n \n parameters.append(t)\n else:\n if _is_unpacked_typevartuple(t):\n type_var_tuple_encountered=True\n for x in getattr(t,'__parameters__',()):\n if x not in parameters:\n parameters.append(x)\n return tuple(parameters)\n \n \ndef _check_generic_specialization(cls,arguments):\n ''\n\n\n \n expected_len=len(cls.__parameters__)\n if not expected_len:\n raise TypeError(f\"{cls} is not a generic class\")\n actual_len=len(arguments)\n if actual_len !=expected_len:\n \n if actual_len expected_len else 'few'} arguments\"\n f\" for {cls}; actual {actual_len}, expected {expect_val}\")\n \n \ndef _unpack_args(*args):\n newargs=[]\n for arg in args:\n subargs=getattr(arg,'__typing_unpacked_tuple_args__',None)\n if subargs is not None and not(subargs and subargs[-1]is ...):\n newargs.extend(subargs)\n else:\n newargs.append(arg)\n return newargs\n \ndef _deduplicate(params,*,unhashable_fallback=False):\n\n try:\n return dict.fromkeys(params)\n except TypeError:\n if not unhashable_fallback:\n raise\n \n return _deduplicate_unhashable(params)\n \ndef _deduplicate_unhashable(unhashable_params):\n new_unhashable=[]\n for t in unhashable_params:\n if t not in new_unhashable:\n new_unhashable.append(t)\n return new_unhashable\n \ndef _compare_args_orderless(first_args,second_args):\n first_unhashable=_deduplicate_unhashable(first_args)\n second_unhashable=_deduplicate_unhashable(second_args)\n t=list(second_unhashable)\n try:\n for elem in first_unhashable:\n t.remove(elem)\n except ValueError:\n return False\n return not t\n \ndef _remove_dups_flatten(parameters):\n ''\n\n\n \n \n params=[]\n for p in parameters:\n if isinstance(p,(_UnionGenericAlias,types.UnionType)):\n params.extend(p.__args__)\n else:\n params.append(p)\n \n return tuple(_deduplicate(params,unhashable_fallback=True))\n \n \ndef _flatten_literal_params(parameters):\n ''\n params=[]\n for p in parameters:\n if isinstance(p,_LiteralGenericAlias):\n params.extend(p.__args__)\n else:\n params.append(p)\n return tuple(params)\n \n \n_cleanups=[]\n_caches={}\n\n\ndef _tp_cache(func=None,/,*,typed=False):\n ''\n\n\n \n def decorator(func):\n \n \n \n \n \n cache=functools.lru_cache(typed=typed)(func)\n _caches[func]=cache\n _cleanups.append(cache.cache_clear)\n del cache\n \n @functools.wraps(func)\n def inner(*args,**kwds):\n try:\n return _caches[func](*args,**kwds)\n except TypeError:\n pass\n return func(*args,**kwds)\n return inner\n \n if func is not None:\n return decorator(func)\n \n return decorator\n \n \ndef _deprecation_warning_for_no_type_params_passed(funcname:str)->None:\n import warnings\n \n depr_message=(\n f\"Failing to pass a value to the 'type_params' parameter \"\n f\"of {funcname !r} is deprecated, as it leads to incorrect behaviour \"\n f\"when calling {funcname} on a stringified annotation \"\n f\"that references a PEP 695 type parameter. \"\n f\"It will be disallowed in Python 3.15.\"\n )\n warnings.warn(depr_message,category=DeprecationWarning,stacklevel=3)\n \n \nclass _Sentinel:\n __slots__=()\n def __repr__(self):\n return ''\n \n \n_sentinel=_Sentinel()\n\n\ndef _eval_type(t,globalns,localns,type_params=_sentinel,*,recursive_guard=frozenset()):\n ''\n\n\n\n\n \n if type_params is _sentinel:\n _deprecation_warning_for_no_type_params_passed(\"typing._eval_type\")\n type_params=()\n if isinstance(t,ForwardRef):\n return t._evaluate(globalns,localns,type_params,recursive_guard=recursive_guard)\n if isinstance(t,(_GenericAlias,GenericAlias,types.UnionType)):\n if isinstance(t,GenericAlias):\n args=tuple(\n ForwardRef(arg)if isinstance(arg,str)else arg\n for arg in t.__args__\n )\n is_unpacked=t.__unpacked__\n if _should_unflatten_callable_args(t,args):\n t=t.__origin__[(args[:-1],args[-1])]\n else:\n t=t.__origin__[args]\n if is_unpacked:\n t=Unpack[t]\n \n ev_args=tuple(\n _eval_type(\n a,globalns,localns,type_params,recursive_guard=recursive_guard\n )\n for a in t.__args__\n )\n if ev_args ==t.__args__:\n return t\n if isinstance(t,GenericAlias):\n return GenericAlias(t.__origin__,ev_args)\n if isinstance(t,types.UnionType):\n return functools.reduce(operator.or_,ev_args)\n else:\n return t.copy_with(ev_args)\n return t\n \n \nclass _Final:\n ''\n \n __slots__=('__weakref__',)\n \n def __init_subclass__(cls,/,*args,**kwds):\n if '_root'not in kwds:\n raise TypeError(\"Cannot subclass special typing classes\")\n \n \nclass _NotIterable:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n __iter__=None\n \n \n \n \nclass _SpecialForm(_Final,_NotIterable,_root=True):\n __slots__=('_name','__doc__','_getitem')\n \n def __init__(self,getitem):\n self._getitem=getitem\n self._name=getitem.__name__\n self.__doc__=getitem.__doc__\n \n def __getattr__(self,item):\n if item in{'__name__','__qualname__'}:\n return self._name\n \n raise AttributeError(item)\n \n def __mro_entries__(self,bases):\n raise TypeError(f\"Cannot subclass {self !r}\")\n \n def __repr__(self):\n return 'typing.'+self._name\n \n def __reduce__(self):\n return self._name\n \n def __call__(self,*args,**kwds):\n raise TypeError(f\"Cannot instantiate {self !r}\")\n \n def __or__(self,other):\n return Union[self,other]\n \n def __ror__(self,other):\n return Union[other,self]\n \n def __instancecheck__(self,obj):\n raise TypeError(f\"{self} cannot be used with isinstance()\")\n \n def __subclasscheck__(self,cls):\n raise TypeError(f\"{self} cannot be used with issubclass()\")\n \n @_tp_cache\n def __getitem__(self,parameters):\n return self._getitem(self,parameters)\n \n \nclass _TypedCacheSpecialForm(_SpecialForm,_root=True):\n def __getitem__(self,parameters):\n if not isinstance(parameters,tuple):\n parameters=(parameters,)\n return self._getitem(self,*parameters)\n \n \nclass _AnyMeta(type):\n def __instancecheck__(self,obj):\n if self is Any:\n raise TypeError(\"typing.Any cannot be used with isinstance()\")\n return super().__instancecheck__(obj)\n \n def __repr__(self):\n if self is Any:\n return \"typing.Any\"\n return super().__repr__()\n \n \nclass Any(metaclass=_AnyMeta):\n ''\n\n\n\n\n\n\n\n\n \n \n def __new__(cls,*args,**kwargs):\n if cls is Any:\n raise TypeError(\"Any cannot be instantiated\")\n return super().__new__(cls)\n \n \n@_SpecialForm\ndef NoReturn(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n \n \n@_SpecialForm\ndef Never(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n@_SpecialForm\ndef Self(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n@_SpecialForm\ndef LiteralString(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n@_SpecialForm\ndef ClassVar(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.',allow_special_forms=True)\n return _GenericAlias(self,(item,))\n \n@_SpecialForm\ndef Final(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.',allow_special_forms=True)\n return _GenericAlias(self,(item,))\n \n@_SpecialForm\ndef Union(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if parameters ==():\n raise TypeError(\"Cannot take a Union of no types.\")\n if not isinstance(parameters,tuple):\n parameters=(parameters,)\n msg=\"Union[arg, ...]: each arg must be a type.\"\n parameters=tuple(_type_check(p,msg)for p in parameters)\n parameters=_remove_dups_flatten(parameters)\n if len(parameters)==1:\n return parameters[0]\n if len(parameters)==2 and type(None)in parameters:\n return _UnionGenericAlias(self,parameters,name=\"Optional\")\n return _UnionGenericAlias(self,parameters)\n \ndef _make_union(left,right):\n ''\n\n\n\n\n \n return Union[left,right]\n \n@_SpecialForm\ndef Optional(self,parameters):\n ''\n arg=_type_check(parameters,f\"{self} requires a single type.\")\n return Union[arg,type(None)]\n \n@_TypedCacheSpecialForm\n@_tp_cache(typed=True)\ndef Literal(self,*parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n parameters=_flatten_literal_params(parameters)\n \n try:\n parameters=tuple(p for p,_ in _deduplicate(list(_value_and_type_iter(parameters))))\n except TypeError:\n pass\n \n return _LiteralGenericAlias(self,parameters)\n \n \n@_SpecialForm\ndef TypeAlias(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n@_SpecialForm\ndef Concatenate(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if parameters ==():\n raise TypeError(\"Cannot take a Concatenate of no types.\")\n if not isinstance(parameters,tuple):\n parameters=(parameters,)\n if not(parameters[-1]is ...or isinstance(parameters[-1],ParamSpec)):\n raise TypeError(\"The last parameter to Concatenate should be a \"\n \"ParamSpec variable or ellipsis.\")\n msg=\"Concatenate[arg, ...]: each arg must be a type.\"\n parameters=(*(_type_check(p,msg)for p in parameters[:-1]),parameters[-1])\n return _ConcatenateGenericAlias(self,parameters)\n \n \n@_SpecialForm\ndef TypeGuard(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.')\n return _GenericAlias(self,(item,))\n \n \n@_SpecialForm\ndef TypeIs(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.')\n return _GenericAlias(self,(item,))\n \n \nclass ForwardRef(_Final,_root=True):\n ''\n \n __slots__=('__forward_arg__','__forward_code__',\n '__forward_evaluated__','__forward_value__',\n '__forward_is_argument__','__forward_is_class__',\n '__forward_module__')\n \n def __init__(self,arg,is_argument=True,module=None,*,is_class=False):\n if not isinstance(arg,str):\n raise TypeError(f\"Forward reference must be a string -- got {arg !r}\")\n \n \n \n \n if arg.startswith('*'):\n arg_to_compile=f'({arg},)[0]'\n else:\n arg_to_compile=arg\n try:\n code=compile(arg_to_compile,'','eval')\n except SyntaxError:\n raise SyntaxError(f\"Forward reference must be an expression -- got {arg !r}\")\n \n self.__forward_arg__=arg\n self.__forward_code__=code\n self.__forward_evaluated__=False\n self.__forward_value__=None\n self.__forward_is_argument__=is_argument\n self.__forward_is_class__=is_class\n self.__forward_module__=module\n \n def _evaluate(self,globalns,localns,type_params=_sentinel,*,recursive_guard):\n if type_params is _sentinel:\n _deprecation_warning_for_no_type_params_passed(\"typing.ForwardRef._evaluate\")\n type_params=()\n if self.__forward_arg__ in recursive_guard:\n return self\n if not self.__forward_evaluated__ or localns is not globalns:\n if globalns is None and localns is None:\n globalns=localns={}\n elif globalns is None:\n globalns=localns\n elif localns is None:\n localns=globalns\n if self.__forward_module__ is not None:\n globalns=getattr(\n sys.modules.get(self.__forward_module__,None),'__dict__',globalns\n )\n \n \n \n \n \n \n \n \n if type_params:\n globalns,localns=dict(globalns),dict(localns)\n for param in type_params:\n param_name=param.__name__\n if not self.__forward_is_class__ or param_name not in globalns:\n globalns[param_name]=param\n localns.pop(param_name,None)\n \n type_=_type_check(\n eval(self.__forward_code__,globalns,localns),\n \"Forward references must evaluate to types.\",\n is_argument=self.__forward_is_argument__,\n allow_special_forms=self.__forward_is_class__,\n )\n self.__forward_value__=_eval_type(\n type_,\n globalns,\n localns,\n type_params,\n recursive_guard=(recursive_guard |{self.__forward_arg__}),\n )\n self.__forward_evaluated__=True\n return self.__forward_value__\n \n def __eq__(self,other):\n if not isinstance(other,ForwardRef):\n return NotImplemented\n if self.__forward_evaluated__ and other.__forward_evaluated__:\n return(self.__forward_arg__ ==other.__forward_arg__ and\n self.__forward_value__ ==other.__forward_value__)\n return(self.__forward_arg__ ==other.__forward_arg__ and\n self.__forward_module__ ==other.__forward_module__)\n \n def __hash__(self):\n return hash((self.__forward_arg__,self.__forward_module__))\n \n def __or__(self,other):\n return Union[self,other]\n \n def __ror__(self,other):\n return Union[other,self]\n \n def __repr__(self):\n if self.__forward_module__ is None:\n module_repr=''\n else:\n module_repr=f', module={self.__forward_module__ !r}'\n return f'ForwardRef({self.__forward_arg__ !r}{module_repr})'\n \n \ndef _is_unpacked_typevartuple(x:Any)->bool:\n return((not isinstance(x,type))and\n getattr(x,'__typing_is_unpacked_typevartuple__',False))\n \n \ndef _is_typevar_like(x:Any)->bool:\n return isinstance(x,(TypeVar,ParamSpec))or _is_unpacked_typevartuple(x)\n \n \ndef _typevar_subst(self,arg):\n msg=\"Parameters to generic types must be types.\"\n arg=_type_check(arg,msg,is_argument=True)\n if((isinstance(arg,_GenericAlias)and arg.__origin__ is Unpack)or\n (isinstance(arg,GenericAlias)and getattr(arg,'__unpacked__',False))):\n raise TypeError(f\"{arg} is not valid as type argument\")\n return arg\n \n \ndef _typevartuple_prepare_subst(self,alias,args):\n params=alias.__parameters__\n typevartuple_index=params.index(self)\n for param in params[typevartuple_index+1:]:\n if isinstance(param,TypeVarTuple):\n raise TypeError(f\"More than one TypeVarTuple parameter in {alias}\")\n \n alen=len(args)\n plen=len(params)\n left=typevartuple_index\n right=plen -typevartuple_index -1\n var_tuple_index=None\n fillarg=None\n for k,arg in enumerate(args):\n if not isinstance(arg,type):\n subargs=getattr(arg,'__typing_unpacked_tuple_args__',None)\n if subargs and len(subargs)==2 and subargs[-1]is ...:\n if var_tuple_index is not None:\n raise TypeError(\"More than one unpacked arbitrary-length tuple argument\")\n var_tuple_index=k\n fillarg=subargs[0]\n if var_tuple_index is not None:\n left=min(left,var_tuple_index)\n right=min(right,alen -var_tuple_index -1)\n elif left+right >alen:\n raise TypeError(f\"Too few arguments for {alias};\"\n f\" actual {alen}, expected at least {plen -1}\")\n if left ==alen -right and self.has_default():\n replacement=_unpack_args(self.__default__)\n else:\n replacement=args[left:alen -right]\n \n return(\n *args[:left],\n *([fillarg]*(typevartuple_index -left)),\n replacement,\n *([fillarg]*(plen -right -left -typevartuple_index -1)),\n *args[alen -right:],\n )\n \n \ndef _paramspec_subst(self,arg):\n if isinstance(arg,(list,tuple)):\n arg=tuple(_type_check(a,\"Expected a type.\")for a in arg)\n elif not _is_param_expr(arg):\n raise TypeError(f\"Expected a list of types, an ellipsis, \"\n f\"ParamSpec, or Concatenate. Got {arg}\")\n return arg\n \n \ndef _paramspec_prepare_subst(self,alias,args):\n params=alias.__parameters__\n i=params.index(self)\n if i ==len(args)and self.has_default():\n args=[*args,self.__default__]\n if i >=len(args):\n raise TypeError(f\"Too few arguments for {alias}\")\n \n if len(params)==1 and not _is_param_expr(args[0]):\n assert i ==0\n args=(args,)\n \n elif isinstance(args[i],list):\n args=(*args[:i],tuple(args[i]),*args[i+1:])\n return args\n \n \n@_tp_cache\ndef _generic_class_getitem(cls,args):\n ''\n\n\n\n\n\n\n\n \n if not isinstance(args,tuple):\n args=(args,)\n \n args=tuple(_type_convert(p)for p in args)\n is_generic_or_protocol=cls in(Generic,Protocol)\n \n if is_generic_or_protocol:\n \n if not args:\n raise TypeError(\n f\"Parameter list to {cls.__qualname__}[...] cannot be empty\"\n )\n if not all(_is_typevar_like(p)for p in args):\n raise TypeError(\n f\"Parameters to {cls.__name__}[...] must all be type variables \"\n f\"or parameter specification variables.\")\n if len(set(args))!=len(args):\n raise TypeError(\n f\"Parameters to {cls.__name__}[...] must all be unique\")\n else:\n \n for param in cls.__parameters__:\n prepare=getattr(param,'__typing_prepare_subst__',None)\n if prepare is not None:\n args=prepare(cls,args)\n _check_generic_specialization(cls,args)\n \n new_args=[]\n for param,new_arg in zip(cls.__parameters__,args):\n if isinstance(param,TypeVarTuple):\n new_args.extend(new_arg)\n else:\n new_args.append(new_arg)\n args=tuple(new_args)\n \n return _GenericAlias(cls,args)\n \n \ndef _generic_init_subclass(cls,*args,**kwargs):\n super(Generic,cls).__init_subclass__(*args,**kwargs)\n tvars=[]\n if '__orig_bases__'in cls.__dict__:\n error=Generic in cls.__orig_bases__\n else:\n error=(Generic in cls.__bases__ and\n cls.__name__ !='Protocol'and\n type(cls)!=_TypedDictMeta)\n if error:\n raise TypeError(\"Cannot inherit from plain Generic\")\n if '__orig_bases__'in cls.__dict__:\n tvars=_collect_type_parameters(cls.__orig_bases__)\n \n \n \n \n \n gvars=None\n for base in cls.__orig_bases__:\n if(isinstance(base,_GenericAlias)and\n base.__origin__ is Generic):\n if gvars is not None:\n raise TypeError(\n \"Cannot inherit from Generic[...] multiple times.\")\n gvars=base.__parameters__\n if gvars is not None:\n tvarset=set(tvars)\n gvarset=set(gvars)\n if not tvarset <=gvarset:\n s_vars=', '.join(str(t)for t in tvars if t not in gvarset)\n s_args=', '.join(str(g)for g in gvars)\n raise TypeError(f\"Some type variables ({s_vars}) are\"\n f\" not listed in Generic[{s_args}]\")\n tvars=gvars\n cls.__parameters__=tuple(tvars)\n \n \ndef _is_dunder(attr):\n return attr.startswith('__')and attr.endswith('__')\n \nclass _BaseGenericAlias(_Final,_root=True):\n ''\n\n\n\n\n\n\n \n \n def __init__(self,origin,*,inst=True,name=None):\n self._inst=inst\n self._name=name\n self.__origin__=origin\n self.__slots__=None\n \n def __call__(self,*args,**kwargs):\n if not self._inst:\n raise TypeError(f\"Type {self._name} cannot be instantiated; \"\n f\"use {self.__origin__.__name__}() instead\")\n result=self.__origin__(*args,**kwargs)\n try:\n result.__orig_class__=self\n \n \n except Exception:\n pass\n return result\n \n def __mro_entries__(self,bases):\n res=[]\n if self.__origin__ not in bases:\n res.append(self.__origin__)\n \n \n \n \n \n \n \n i=bases.index(self)\n for b in bases[i+1:]:\n if isinstance(b,_BaseGenericAlias):\n break\n if not isinstance(b,type):\n meth=getattr(b,\"__mro_entries__\",None)\n new_bases=meth(bases)if meth else None\n if(\n isinstance(new_bases,tuple)and\n any(\n isinstance(b2,type)and issubclass(b2,Generic)\n for b2 in new_bases\n )\n ):\n break\n elif issubclass(b,Generic):\n break\n else:\n res.append(Generic)\n return tuple(res)\n \n def __getattr__(self,attr):\n if attr in{'__name__','__qualname__'}:\n return self._name or self.__origin__.__name__\n \n \n \n if '__origin__'in self.__dict__ and not _is_dunder(attr):\n return getattr(self.__origin__,attr)\n raise AttributeError(attr)\n \n def __setattr__(self,attr,val):\n if _is_dunder(attr)or attr in{'_name','_inst','_nparams','_defaults'}:\n super().__setattr__(attr,val)\n else:\n setattr(self.__origin__,attr,val)\n \n def __instancecheck__(self,obj):\n return self.__subclasscheck__(type(obj))\n \n def __subclasscheck__(self,cls):\n raise TypeError(\"Subscripted generics cannot be used with\"\n \" class and instance checks\")\n \n def __dir__(self):\n return list(set(super().__dir__()\n +[attr for attr in dir(self.__origin__)if not _is_dunder(attr)]))\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass _GenericAlias(_BaseGenericAlias,_root=True):\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n def __init__(self,origin,args,*,inst=True,name=None):\n super().__init__(origin,inst=inst,name=name)\n if not isinstance(args,tuple):\n args=(args,)\n self.__args__=tuple(...if a is _TypingEllipsis else\n a for a in args)\n enforce_default_ordering=origin in(Generic,Protocol)\n self.__parameters__=_collect_type_parameters(\n args,\n enforce_default_ordering=enforce_default_ordering,\n )\n if not name:\n self.__module__=origin.__module__\n \n def __eq__(self,other):\n if not isinstance(other,_GenericAlias):\n return NotImplemented\n return(self.__origin__ ==other.__origin__\n and self.__args__ ==other.__args__)\n \n def __hash__(self):\n return hash((self.__origin__,self.__args__))\n \n def __or__(self,right):\n return Union[self,right]\n \n def __ror__(self,left):\n return Union[left,self]\n \n @_tp_cache\n def __getitem__(self,args):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if self.__origin__ in(Generic,Protocol):\n \n raise TypeError(f\"Cannot subscript already-subscripted {self}\")\n if not self.__parameters__:\n raise TypeError(f\"{self} is not a generic class\")\n \n \n if not isinstance(args,tuple):\n args=(args,)\n args=_unpack_args(*(_type_convert(p)for p in args))\n new_args=self._determine_new_args(args)\n r=self.copy_with(new_args)\n return r\n \n def _determine_new_args(self,args):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n params=self.__parameters__\n \n for param in params:\n prepare=getattr(param,'__typing_prepare_subst__',None)\n if prepare is not None:\n args=prepare(self,args)\n alen=len(args)\n plen=len(params)\n if alen !=plen:\n raise TypeError(f\"Too {'many'if alen >plen else 'few'} arguments for {self};\"\n f\" actual {alen}, expected {plen}\")\n new_arg_by_param=dict(zip(params,args))\n return tuple(self._make_substitution(self.__args__,new_arg_by_param))\n \n def _make_substitution(self,args,new_arg_by_param):\n ''\n new_args=[]\n for old_arg in args:\n if isinstance(old_arg,type):\n new_args.append(old_arg)\n continue\n \n substfunc=getattr(old_arg,'__typing_subst__',None)\n if substfunc:\n new_arg=substfunc(new_arg_by_param[old_arg])\n else:\n subparams=getattr(old_arg,'__parameters__',())\n if not subparams:\n new_arg=old_arg\n else:\n subargs=[]\n for x in subparams:\n if isinstance(x,TypeVarTuple):\n subargs.extend(new_arg_by_param[x])\n else:\n subargs.append(new_arg_by_param[x])\n new_arg=old_arg[tuple(subargs)]\n \n if self.__origin__ ==collections.abc.Callable and isinstance(new_arg,tuple):\n \n \n \n \n \n \n \n \n \n \n new_args.extend(new_arg)\n elif _is_unpacked_typevartuple(old_arg):\n \n \n \n \n \n \n \n \n \n new_args.extend(new_arg)\n elif isinstance(old_arg,tuple):\n \n \n \n \n \n \n \n new_args.append(\n tuple(self._make_substitution(old_arg,new_arg_by_param)),\n )\n else:\n new_args.append(new_arg)\n return new_args\n \n def copy_with(self,args):\n return self.__class__(self.__origin__,args,name=self._name,inst=self._inst)\n \n def __repr__(self):\n if self._name:\n name='typing.'+self._name\n else:\n name=_type_repr(self.__origin__)\n if self.__args__:\n args=\", \".join([_type_repr(a)for a in self.__args__])\n else:\n \n args=\"()\"\n return f'{name}[{args}]'\n \n def __reduce__(self):\n if self._name:\n origin=globals()[self._name]\n else:\n origin=self.__origin__\n args=tuple(self.__args__)\n if len(args)==1 and not isinstance(args[0],tuple):\n args,=args\n return operator.getitem,(origin,args)\n \n def __mro_entries__(self,bases):\n if isinstance(self.__origin__,_SpecialForm):\n raise TypeError(f\"Cannot subclass {self !r}\")\n \n if self._name:\n return super().__mro_entries__(bases)\n if self.__origin__ is Generic:\n if Protocol in bases:\n return()\n i=bases.index(self)\n for b in bases[i+1:]:\n if isinstance(b,_BaseGenericAlias)and b is not self:\n return()\n return(self.__origin__,)\n \n def __iter__(self):\n yield Unpack[self]\n \n \n \n \n \n \nclass _SpecialGenericAlias(_NotIterable,_BaseGenericAlias,_root=True):\n def __init__(self,origin,nparams,*,inst=True,name=None,defaults=()):\n if name is None:\n name=origin.__name__\n super().__init__(origin,inst=inst,name=name)\n self._nparams=nparams\n self._defaults=defaults\n if origin.__module__ =='builtins':\n self.__doc__=f'A generic version of {origin.__qualname__}.'\n else:\n self.__doc__=f'A generic version of {origin.__module__}.{origin.__qualname__}.'\n \n @_tp_cache\n def __getitem__(self,params):\n if not isinstance(params,tuple):\n params=(params,)\n msg=\"Parameters to generic types must be types.\"\n params=tuple(_type_check(p,msg)for p in params)\n if(self._defaults\n and len(params)=self._nparams\n ):\n params=(*params,*self._defaults[len(params)-self._nparams:])\n actual_len=len(params)\n \n if actual_len !=self._nparams:\n if self._defaults:\n expected=f\"at least {self._nparams -len(self._defaults)}\"\n else:\n expected=str(self._nparams)\n if not self._nparams:\n raise TypeError(f\"{self} is not a generic class\")\n raise TypeError(f\"Too {'many'if actual_len >self._nparams else 'few'} arguments for {self};\"\n f\" actual {actual_len}, expected {expected}\")\n return self.copy_with(params)\n \n def copy_with(self,params):\n return _GenericAlias(self.__origin__,params,\n name=self._name,inst=self._inst)\n \n def __repr__(self):\n return 'typing.'+self._name\n \n def __subclasscheck__(self,cls):\n if isinstance(cls,_SpecialGenericAlias):\n return issubclass(cls.__origin__,self.__origin__)\n if not isinstance(cls,_GenericAlias):\n return issubclass(cls,self.__origin__)\n return super().__subclasscheck__(cls)\n \n def __reduce__(self):\n return self._name\n \n def __or__(self,right):\n return Union[self,right]\n \n def __ror__(self,left):\n return Union[left,self]\n \n \nclass _DeprecatedGenericAlias(_SpecialGenericAlias,_root=True):\n def __init__(\n self,origin,nparams,*,removal_version,inst=True,name=None\n ):\n super().__init__(origin,nparams,inst=inst,name=name)\n self._removal_version=removal_version\n \n def __instancecheck__(self,inst):\n import warnings\n warnings._deprecated(\n f\"{self.__module__}.{self._name}\",remove=self._removal_version\n )\n return super().__instancecheck__(inst)\n \n \nclass _CallableGenericAlias(_NotIterable,_GenericAlias,_root=True):\n def __repr__(self):\n assert self._name =='Callable'\n args=self.__args__\n if len(args)==2 and _is_param_expr(args[0]):\n return super().__repr__()\n return(f'typing.Callable'\n f'[[{\", \".join([_type_repr(a)for a in args[:-1]])}], '\n f'{_type_repr(args[-1])}]')\n \n def __reduce__(self):\n args=self.__args__\n if not(len(args)==2 and _is_param_expr(args[0])):\n args=list(args[:-1]),args[-1]\n return operator.getitem,(Callable,args)\n \n \nclass _CallableType(_SpecialGenericAlias,_root=True):\n def copy_with(self,params):\n return _CallableGenericAlias(self.__origin__,params,\n name=self._name,inst=self._inst)\n \n def __getitem__(self,params):\n if not isinstance(params,tuple)or len(params)!=2:\n raise TypeError(\"Callable must be used as \"\n \"Callable[[arg, ...], result].\")\n args,result=params\n \n \n \n if isinstance(args,list):\n params=(tuple(args),result)\n else:\n params=(args,result)\n return self.__getitem_inner__(params)\n \n @_tp_cache\n def __getitem_inner__(self,params):\n args,result=params\n msg=\"Callable[args, result]: result must be a type.\"\n result=_type_check(result,msg)\n if args is Ellipsis:\n return self.copy_with((_TypingEllipsis,result))\n if not isinstance(args,tuple):\n args=(args,)\n args=tuple(_type_convert(arg)for arg in args)\n params=args+(result,)\n return self.copy_with(params)\n \n \nclass _TupleType(_SpecialGenericAlias,_root=True):\n @_tp_cache\n def __getitem__(self,params):\n if not isinstance(params,tuple):\n params=(params,)\n if len(params)>=2 and params[-1]is ...:\n msg=\"Tuple[t, ...]: t must be a type.\"\n params=tuple(_type_check(p,msg)for p in params[:-1])\n return self.copy_with((*params,_TypingEllipsis))\n msg=\"Tuple[t0, t1, ...]: each t must be a type.\"\n params=tuple(_type_check(p,msg)for p in params)\n return self.copy_with(params)\n \n \nclass _UnionGenericAlias(_NotIterable,_GenericAlias,_root=True):\n def copy_with(self,params):\n return Union[params]\n \n def __eq__(self,other):\n if not isinstance(other,(_UnionGenericAlias,types.UnionType)):\n return NotImplemented\n try:\n return set(self.__args__)==set(other.__args__)\n except TypeError:\n return _compare_args_orderless(self.__args__,other.__args__)\n \n def __hash__(self):\n return hash(frozenset(self.__args__))\n \n def __repr__(self):\n args=self.__args__\n if len(args)==2:\n if args[0]is type(None):\n return f'typing.Optional[{_type_repr(args[1])}]'\n elif args[1]is type(None):\n return f'typing.Optional[{_type_repr(args[0])}]'\n return super().__repr__()\n \n def __instancecheck__(self,obj):\n return self.__subclasscheck__(type(obj))\n \n def __subclasscheck__(self,cls):\n for arg in self.__args__:\n if issubclass(cls,arg):\n return True\n \n def __reduce__(self):\n func,(origin,args)=super().__reduce__()\n return func,(Union,args)\n \n \ndef _value_and_type_iter(parameters):\n return((p,type(p))for p in parameters)\n \n \nclass _LiteralGenericAlias(_GenericAlias,_root=True):\n def __eq__(self,other):\n if not isinstance(other,_LiteralGenericAlias):\n return NotImplemented\n \n return set(_value_and_type_iter(self.__args__))==set(_value_and_type_iter(other.__args__))\n \n def __hash__(self):\n return hash(frozenset(_value_and_type_iter(self.__args__)))\n \n \nclass _ConcatenateGenericAlias(_GenericAlias,_root=True):\n def copy_with(self,params):\n if isinstance(params[-1],(list,tuple)):\n return(*params[:-1],*params[-1])\n if isinstance(params[-1],_ConcatenateGenericAlias):\n params=(*params[:-1],*params[-1].__args__)\n return super().copy_with(params)\n \n \n@_SpecialForm\ndef Unpack(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.')\n return _UnpackGenericAlias(origin=self,args=(item,))\n \n \nclass _UnpackGenericAlias(_GenericAlias,_root=True):\n def __repr__(self):\n \n \n return f'typing.Unpack[{_type_repr(self.__args__[0])}]'\n \n def __getitem__(self,args):\n if self.__typing_is_unpacked_typevartuple__:\n return args\n return super().__getitem__(args)\n \n @property\n def __typing_unpacked_tuple_args__(self):\n assert self.__origin__ is Unpack\n assert len(self.__args__)==1\n arg,=self.__args__\n if isinstance(arg,(_GenericAlias,types.GenericAlias)):\n if arg.__origin__ is not tuple:\n raise TypeError(\"Unpack[...] must be used with a tuple type\")\n return arg.__args__\n return None\n \n @property\n def __typing_is_unpacked_typevartuple__(self):\n assert self.__origin__ is Unpack\n assert len(self.__args__)==1\n return isinstance(self.__args__[0],TypeVarTuple)\n \n \nclass _TypingEllipsis:\n ''\n \n \n_TYPING_INTERNALS=frozenset({\n'__parameters__','__orig_bases__','__orig_class__',\n'_is_protocol','_is_runtime_protocol','__protocol_attrs__',\n'__non_callable_proto_members__','__type_params__',\n})\n\n_SPECIAL_NAMES=frozenset({\n'__abstractmethods__','__annotations__','__dict__','__doc__',\n'__init__','__module__','__new__','__slots__',\n'__subclasshook__','__weakref__','__class_getitem__',\n'__match_args__','__static_attributes__','__firstlineno__',\n})\n\n\nEXCLUDED_ATTRIBUTES=_TYPING_INTERNALS |_SPECIAL_NAMES |{'_MutableMapping__marker'}\n\n\ndef _get_protocol_attrs(cls):\n ''\n\n\n\n \n attrs=set()\n for base in cls.__mro__[:-1]:\n if base.__name__ in{'Protocol','Generic'}:\n continue\n annotations=getattr(base,'__annotations__',{})\n for attr in(*base.__dict__,*annotations):\n if not attr.startswith('_abc_')and attr not in EXCLUDED_ATTRIBUTES:\n attrs.add(attr)\n return attrs\n \n \ndef _no_init_or_replace_init(self,*args,**kwargs):\n cls=type(self)\n \n if cls._is_protocol:\n raise TypeError('Protocols cannot be instantiated')\n \n \n \n if cls.__init__ is not _no_init_or_replace_init:\n return\n \n \n \n \n \n \n \n for base in cls.__mro__:\n init=base.__dict__.get('__init__',_no_init_or_replace_init)\n if init is not _no_init_or_replace_init:\n cls.__init__=init\n break\n else:\n \n cls.__init__=object.__init__\n \n cls.__init__(self,*args,**kwargs)\n \n \ndef _caller(depth=1,default='__main__'):\n try:\n return sys._getframemodulename(depth+1)or default\n except AttributeError:\n pass\n try:\n return sys._getframe(depth+1).f_globals.get('__name__',default)\n except(AttributeError,ValueError):\n pass\n return None\n \ndef _allow_reckless_class_checks(depth=2):\n ''\n\n\n\n \n return _caller(depth)in{'abc','functools',None}\n \n \n_PROTO_ALLOWLIST={\n'collections.abc':[\n'Callable','Awaitable','Iterable','Iterator','AsyncIterable',\n'Hashable','Sized','Container','Collection','Reversible','Buffer',\n],\n'contextlib':['AbstractContextManager','AbstractAsyncContextManager'],\n}\n\n\n@functools.cache\ndef _lazy_load_getattr_static():\n\n\n from inspect import getattr_static\n return getattr_static\n \n \n_cleanups.append(_lazy_load_getattr_static.cache_clear)\n\ndef _pickle_psargs(psargs):\n return ParamSpecArgs,(psargs.__origin__,)\n \ncopyreg.pickle(ParamSpecArgs,_pickle_psargs)\n\ndef _pickle_pskwargs(pskwargs):\n return ParamSpecKwargs,(pskwargs.__origin__,)\n \ncopyreg.pickle(ParamSpecKwargs,_pickle_pskwargs)\n\ndel _pickle_psargs,_pickle_pskwargs\n\n\n\n\n\n\n_abc_instancecheck=ABCMeta.__instancecheck__\n_abc_subclasscheck=ABCMeta.__subclasscheck__\n\n\ndef _type_check_issubclass_arg_1(arg):\n ''\n\n\n\n\n\n\n\n\n\n \n if not isinstance(arg,type):\n \n raise TypeError('issubclass() arg 1 must be a class')\n \n \nclass _ProtocolMeta(ABCMeta):\n\n\n def __new__(mcls,name,bases,namespace,/,**kwargs):\n if name ==\"Protocol\"and bases ==(Generic,):\n pass\n elif Protocol in bases:\n for base in bases:\n if not(\n base in{object,Generic}\n or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__,[])\n or(\n issubclass(base,Generic)\n and getattr(base,\"_is_protocol\",False)\n )\n ):\n raise TypeError(\n f\"Protocols can only inherit from other protocols, \"\n f\"got {base !r}\"\n )\n return super().__new__(mcls,name,bases,namespace,**kwargs)\n \n def __init__(cls,*args,**kwargs):\n super().__init__(*args,**kwargs)\n if getattr(cls,\"_is_protocol\",False):\n cls.__protocol_attrs__=_get_protocol_attrs(cls)\n \n def __subclasscheck__(cls,other):\n if cls is Protocol:\n return type.__subclasscheck__(cls,other)\n if(\n getattr(cls,'_is_protocol',False)\n and not _allow_reckless_class_checks()\n ):\n if not getattr(cls,'_is_runtime_protocol',False):\n _type_check_issubclass_arg_1(other)\n raise TypeError(\n \"Instance and class checks can only be used with \"\n \"@runtime_checkable protocols\"\n )\n if(\n \n cls.__non_callable_proto_members__\n and cls.__dict__.get(\"__subclasshook__\")is _proto_hook\n ):\n _type_check_issubclass_arg_1(other)\n non_method_attrs=sorted(cls.__non_callable_proto_members__)\n raise TypeError(\n \"Protocols with non-method members don't support issubclass().\"\n f\" Non-method members: {str(non_method_attrs)[1:-1]}.\"\n )\n return _abc_subclasscheck(cls,other)\n \n def __instancecheck__(cls,instance):\n \n \n if cls is Protocol:\n return type.__instancecheck__(cls,instance)\n if not getattr(cls,\"_is_protocol\",False):\n \n return _abc_instancecheck(cls,instance)\n \n if(\n not getattr(cls,'_is_runtime_protocol',False)and\n not _allow_reckless_class_checks()\n ):\n raise TypeError(\"Instance and class checks can only be used with\"\n \" @runtime_checkable protocols\")\n \n if _abc_instancecheck(cls,instance):\n return True\n \n getattr_static=_lazy_load_getattr_static()\n for attr in cls.__protocol_attrs__:\n try:\n val=getattr_static(instance,attr)\n except AttributeError:\n break\n \n if val is None and attr not in cls.__non_callable_proto_members__:\n break\n else:\n return True\n \n return False\n \n \n@classmethod\ndef _proto_hook(cls,other):\n if not cls.__dict__.get('_is_protocol',False):\n return NotImplemented\n \n for attr in cls.__protocol_attrs__:\n for base in other.__mro__:\n \n if attr in base.__dict__:\n if base.__dict__[attr]is None:\n return NotImplemented\n break\n \n \n annotations=getattr(base,'__annotations__',{})\n if(isinstance(annotations,collections.abc.Mapping)and\n attr in annotations and\n issubclass(other,Generic)and getattr(other,'_is_protocol',False)):\n break\n else:\n return NotImplemented\n return True\n \n \nclass Protocol(Generic,metaclass=_ProtocolMeta):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n _is_protocol=True\n _is_runtime_protocol=False\n \n def __init_subclass__(cls,*args,**kwargs):\n super().__init_subclass__(*args,**kwargs)\n \n \n if not cls.__dict__.get('_is_protocol',False):\n cls._is_protocol=any(b is Protocol for b in cls.__bases__)\n \n \n if '__subclasshook__'not in cls.__dict__:\n cls.__subclasshook__=_proto_hook\n \n \n if cls._is_protocol and cls.__init__ is Protocol.__init__:\n cls.__init__=_no_init_or_replace_init\n \n \nclass _AnnotatedAlias(_NotIterable,_GenericAlias,_root=True):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,origin,metadata):\n if isinstance(origin,_AnnotatedAlias):\n metadata=origin.__metadata__+metadata\n origin=origin.__origin__\n super().__init__(origin,origin,name='Annotated')\n self.__metadata__=metadata\n \n def copy_with(self,params):\n assert len(params)==1\n new_type=params[0]\n return _AnnotatedAlias(new_type,self.__metadata__)\n \n def __repr__(self):\n return \"typing.Annotated[{}, {}]\".format(\n _type_repr(self.__origin__),\n \", \".join(repr(a)for a in self.__metadata__)\n )\n \n def __reduce__(self):\n return operator.getitem,(\n Annotated,(self.__origin__,)+self.__metadata__\n )\n \n def __eq__(self,other):\n if not isinstance(other,_AnnotatedAlias):\n return NotImplemented\n return(self.__origin__ ==other.__origin__\n and self.__metadata__ ==other.__metadata__)\n \n def __hash__(self):\n return hash((self.__origin__,self.__metadata__))\n \n def __getattr__(self,attr):\n if attr in{'__name__','__qualname__'}:\n return 'Annotated'\n return super().__getattr__(attr)\n \n def __mro_entries__(self,bases):\n return(self.__origin__,)\n \n \n@_TypedCacheSpecialForm\n@_tp_cache(typed=True)\ndef Annotated(self,*params):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if len(params)<2:\n raise TypeError(\"Annotated[...] should be used \"\n \"with at least two arguments (a type and an \"\n \"annotation).\")\n if _is_unpacked_typevartuple(params[0]):\n raise TypeError(\"Annotated[...] should not be used with an \"\n \"unpacked TypeVarTuple\")\n msg=\"Annotated[t, ...]: t must be a type.\"\n origin=_type_check(params[0],msg,allow_special_forms=True)\n metadata=tuple(params[1:])\n return _AnnotatedAlias(origin,metadata)\n \n \ndef runtime_checkable(cls):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not issubclass(cls,Generic)or not getattr(cls,'_is_protocol',False):\n raise TypeError('@runtime_checkable can be only applied to protocol classes,'\n ' got %r'%cls)\n cls._is_runtime_protocol=True\n \n \n \n \n cls.__non_callable_proto_members__=set()\n for attr in cls.__protocol_attrs__:\n try:\n is_callable=callable(getattr(cls,attr,None))\n except Exception as e:\n raise TypeError(\n f\"Failed to determine whether protocol member {attr !r} \"\n \"is a method member\"\n )from e\n else:\n if not is_callable:\n cls.__non_callable_proto_members__.add(attr)\n return cls\n \n \ndef cast(typ,val):\n ''\n\n\n\n\n\n \n return val\n \n \ndef assert_type(val,typ,/):\n ''\n\n\n\n\n\n\n\n\n\n\n \n return val\n \n \n_allowed_types=(types.FunctionType,types.BuiltinFunctionType,\ntypes.MethodType,types.ModuleType,\nWrapperDescriptorType,MethodWrapperType,MethodDescriptorType)\n\n\ndef get_type_hints(obj,globalns=None,localns=None,include_extras=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if getattr(obj,'__no_type_check__',None):\n return{}\n \n if isinstance(obj,type):\n hints={}\n for base in reversed(obj.__mro__):\n if globalns is None:\n base_globals=getattr(sys.modules.get(base.__module__,None),'__dict__',{})\n else:\n base_globals=globalns\n ann=base.__dict__.get('__annotations__',{})\n if isinstance(ann,types.GetSetDescriptorType):\n ann={}\n base_locals=dict(vars(base))if localns is None else localns\n if localns is None and globalns is None:\n \n \n \n \n \n \n base_globals,base_locals=base_locals,base_globals\n for name,value in ann.items():\n if value is None:\n value=type(None)\n if isinstance(value,str):\n value=ForwardRef(value,is_argument=False,is_class=True)\n value=_eval_type(value,base_globals,base_locals,base.__type_params__)\n hints[name]=value\n return hints if include_extras else{k:_strip_annotations(t)for k,t in hints.items()}\n \n if globalns is None:\n if isinstance(obj,types.ModuleType):\n globalns=obj.__dict__\n else:\n nsobj=obj\n \n while hasattr(nsobj,'__wrapped__'):\n nsobj=nsobj.__wrapped__\n globalns=getattr(nsobj,'__globals__',{})\n if localns is None:\n localns=globalns\n elif localns is None:\n localns=globalns\n hints=getattr(obj,'__annotations__',None)\n if hints is None:\n \n if isinstance(obj,_allowed_types):\n return{}\n else:\n raise TypeError('{!r} is not a module, class, method, '\n 'or function.'.format(obj))\n hints=dict(hints)\n type_params=getattr(obj,\"__type_params__\",())\n for name,value in hints.items():\n if value is None:\n value=type(None)\n if isinstance(value,str):\n \n \n value=ForwardRef(\n value,\n is_argument=not isinstance(obj,types.ModuleType),\n is_class=False,\n )\n hints[name]=_eval_type(value,globalns,localns,type_params)\n return hints if include_extras else{k:_strip_annotations(t)for k,t in hints.items()}\n \n \ndef _strip_annotations(t):\n ''\n if isinstance(t,_AnnotatedAlias):\n return _strip_annotations(t.__origin__)\n if hasattr(t,\"__origin__\")and t.__origin__ in(Required,NotRequired,ReadOnly):\n return _strip_annotations(t.__args__[0])\n if isinstance(t,_GenericAlias):\n stripped_args=tuple(_strip_annotations(a)for a in t.__args__)\n if stripped_args ==t.__args__:\n return t\n return t.copy_with(stripped_args)\n if isinstance(t,GenericAlias):\n stripped_args=tuple(_strip_annotations(a)for a in t.__args__)\n if stripped_args ==t.__args__:\n return t\n return GenericAlias(t.__origin__,stripped_args)\n if isinstance(t,types.UnionType):\n stripped_args=tuple(_strip_annotations(a)for a in t.__args__)\n if stripped_args ==t.__args__:\n return t\n return functools.reduce(operator.or_,stripped_args)\n \n return t\n \n \ndef get_origin(tp):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(tp,_AnnotatedAlias):\n return Annotated\n if isinstance(tp,(_BaseGenericAlias,GenericAlias,\n ParamSpecArgs,ParamSpecKwargs)):\n return tp.__origin__\n if tp is Generic:\n return Generic\n if isinstance(tp,types.UnionType):\n return types.UnionType\n return None\n \n \ndef get_args(tp):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(tp,_AnnotatedAlias):\n return(tp.__origin__,)+tp.__metadata__\n if isinstance(tp,(_GenericAlias,GenericAlias)):\n res=tp.__args__\n if _should_unflatten_callable_args(tp,res):\n res=(list(res[:-1]),res[-1])\n return res\n if isinstance(tp,types.UnionType):\n return tp.__args__\n return()\n \n \ndef is_typeddict(tp):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n return isinstance(tp,_TypedDictMeta)\n \n \n_ASSERT_NEVER_REPR_MAX_LENGTH=100\n\n\ndef assert_never(arg:Never,/)->Never:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n value=repr(arg)\n if len(value)>_ASSERT_NEVER_REPR_MAX_LENGTH:\n value=value[:_ASSERT_NEVER_REPR_MAX_LENGTH]+'...'\n raise AssertionError(f\"Expected code to be unreachable, but got: {value}\")\n \n \ndef no_type_check(arg):\n ''\n\n\n\n\n\n\n \n if isinstance(arg,type):\n for key in dir(arg):\n obj=getattr(arg,key)\n if(\n not hasattr(obj,'__qualname__')\n or obj.__qualname__ !=f'{arg.__qualname__}.{obj.__name__}'\n or getattr(obj,'__module__',None)!=arg.__module__\n ):\n \n \n \n continue\n \n if isinstance(obj,types.FunctionType):\n obj.__no_type_check__=True\n if isinstance(obj,types.MethodType):\n obj.__func__.__no_type_check__=True\n \n if isinstance(obj,type):\n no_type_check(obj)\n try:\n arg.__no_type_check__=True\n except TypeError:\n pass\n return arg\n \n \ndef no_type_check_decorator(decorator):\n ''\n\n\n\n \n import warnings\n warnings._deprecated(\"typing.no_type_check_decorator\",remove=(3,15))\n @functools.wraps(decorator)\n def wrapped_decorator(*args,**kwds):\n func=decorator(*args,**kwds)\n func=no_type_check(func)\n return func\n \n return wrapped_decorator\n \n \ndef _overload_dummy(*args,**kwds):\n ''\n raise NotImplementedError(\n \"You should not call an overloaded function. \"\n \"A series of @overload-decorated functions \"\n \"outside a stub module should always be followed \"\n \"by an implementation that is not @overload-ed.\")\n \n \n \n_overload_registry=defaultdict(functools.partial(defaultdict,dict))\n\n\ndef overload(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n f=getattr(func,\"__func__\",func)\n try:\n _overload_registry[f.__module__][f.__qualname__][f.__code__.co_firstlineno]=func\n except AttributeError:\n \n pass\n return _overload_dummy\n \n \ndef get_overloads(func):\n ''\n \n f=getattr(func,\"__func__\",func)\n if f.__module__ not in _overload_registry:\n return[]\n mod_dict=_overload_registry[f.__module__]\n if f.__qualname__ not in mod_dict:\n return[]\n return list(mod_dict[f.__qualname__].values())\n \n \ndef clear_overloads():\n ''\n _overload_registry.clear()\n \n \ndef final(f):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n f.__final__=True\n except(AttributeError,TypeError):\n \n \n \n pass\n return f\n \n \n \n \n \nT=TypeVar('T')\nKT=TypeVar('KT')\nVT=TypeVar('VT')\nT_co=TypeVar('T_co',covariant=True)\nV_co=TypeVar('V_co',covariant=True)\nVT_co=TypeVar('VT_co',covariant=True)\nT_contra=TypeVar('T_contra',contravariant=True)\n\nCT_co=TypeVar('CT_co',covariant=True,bound=type)\n\n\n\n\nAnyStr=TypeVar('AnyStr',bytes,str)\n\n\n\n_alias=_SpecialGenericAlias\n\nHashable=_alias(collections.abc.Hashable,0)\nAwaitable=_alias(collections.abc.Awaitable,1)\nCoroutine=_alias(collections.abc.Coroutine,3)\nAsyncIterable=_alias(collections.abc.AsyncIterable,1)\nAsyncIterator=_alias(collections.abc.AsyncIterator,1)\nIterable=_alias(collections.abc.Iterable,1)\nIterator=_alias(collections.abc.Iterator,1)\nReversible=_alias(collections.abc.Reversible,1)\nSized=_alias(collections.abc.Sized,0)\nContainer=_alias(collections.abc.Container,1)\nCollection=_alias(collections.abc.Collection,1)\nCallable=_CallableType(collections.abc.Callable,2)\nCallable.__doc__=\\\n\"\"\"Deprecated alias to collections.abc.Callable.\n\n Callable[[int], str] signifies a function that takes a single\n parameter of type int and returns a str.\n\n The subscription syntax must always be used with exactly two\n values: the argument list and the return type.\n The argument list must be a list of types, a ParamSpec,\n Concatenate or ellipsis. The return type must be a single type.\n\n There is no syntax to indicate optional or keyword arguments;\n such function types are rarely used as callback types.\n \"\"\"\nAbstractSet=_alias(collections.abc.Set,1,name='AbstractSet')\nMutableSet=_alias(collections.abc.MutableSet,1)\n\nMapping=_alias(collections.abc.Mapping,2)\nMutableMapping=_alias(collections.abc.MutableMapping,2)\nSequence=_alias(collections.abc.Sequence,1)\nMutableSequence=_alias(collections.abc.MutableSequence,1)\nByteString=_DeprecatedGenericAlias(\ncollections.abc.ByteString,0,removal_version=(3,14)\n)\n\nTuple=_TupleType(tuple,-1,inst=False,name='Tuple')\nTuple.__doc__=\\\n\"\"\"Deprecated alias to builtins.tuple.\n\n Tuple[X, Y] is the cross-product type of X and Y.\n\n Example: Tuple[T1, T2] is a tuple of two elements corresponding\n to type variables T1 and T2. Tuple[int, float, str] is a tuple\n of an int, a float and a string.\n\n To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].\n \"\"\"\nList=_alias(list,1,inst=False,name='List')\nDeque=_alias(collections.deque,1,name='Deque')\nSet=_alias(set,1,inst=False,name='Set')\nFrozenSet=_alias(frozenset,1,inst=False,name='FrozenSet')\nMappingView=_alias(collections.abc.MappingView,1)\nKeysView=_alias(collections.abc.KeysView,1)\nItemsView=_alias(collections.abc.ItemsView,2)\nValuesView=_alias(collections.abc.ValuesView,1)\nDict=_alias(dict,2,inst=False,name='Dict')\nDefaultDict=_alias(collections.defaultdict,2,name='DefaultDict')\nOrderedDict=_alias(collections.OrderedDict,2)\nCounter=_alias(collections.Counter,1)\nChainMap=_alias(collections.ChainMap,2)\nGenerator=_alias(collections.abc.Generator,3,defaults=(types.NoneType,types.NoneType))\nAsyncGenerator=_alias(collections.abc.AsyncGenerator,2,defaults=(types.NoneType,))\nType=_alias(type,1,inst=False,name='Type')\nType.__doc__=\\\n\"\"\"Deprecated alias to builtins.type.\n\n builtins.type or typing.Type can be used to annotate class objects.\n For example, suppose we have the following classes::\n\n class User: ... # Abstract base for User classes\n class BasicUser(User): ...\n class ProUser(User): ...\n class TeamUser(User): ...\n\n And a function that takes a class argument that's a subclass of\n User and returns an instance of the corresponding class::\n\n def new_user[U](user_class: Type[U]) -> U:\n user = user_class()\n # (Here we could write the user object to a database)\n return user\n\n joe = new_user(BasicUser)\n\n At this point the type checker knows that joe has type BasicUser.\n \"\"\"\n\n\n@runtime_checkable\nclass SupportsInt(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __int__(self)->int:\n pass\n \n \n@runtime_checkable\nclass SupportsFloat(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __float__(self)->float:\n pass\n \n \n@runtime_checkable\nclass SupportsComplex(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __complex__(self)->complex:\n pass\n \n \n@runtime_checkable\nclass SupportsBytes(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __bytes__(self)->bytes:\n pass\n \n \n@runtime_checkable\nclass SupportsIndex(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __index__(self)->int:\n pass\n \n \n@runtime_checkable\nclass SupportsAbs[T](Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __abs__(self)->T:\n pass\n \n \n@runtime_checkable\nclass SupportsRound[T](Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __round__(self,ndigits:int=0)->T:\n pass\n \n \ndef _make_nmtuple(name,types,module,defaults=()):\n fields=[n for n,t in types]\n types={n:_type_check(t,f\"field {n} annotation must be a type\")\n for n,t in types}\n nm_tpl=collections.namedtuple(name,fields,\n defaults=defaults,module=module)\n nm_tpl.__annotations__=nm_tpl.__new__.__annotations__=types\n return nm_tpl\n \n \n \n_prohibited=frozenset({'__new__','__init__','__slots__','__getnewargs__',\n'_fields','_field_defaults',\n'_make','_replace','_asdict','_source'})\n\n_special=frozenset({'__module__','__name__','__annotations__'})\n\n\nclass NamedTupleMeta(type):\n def __new__(cls,typename,bases,ns):\n assert _NamedTuple in bases\n for base in bases:\n if base is not _NamedTuple and base is not Generic:\n raise TypeError(\n 'can only inherit from a NamedTuple type and Generic')\n bases=tuple(tuple if base is _NamedTuple else base for base in bases)\n types=ns.get('__annotations__',{})\n default_names=[]\n for field_name in types:\n if field_name in ns:\n default_names.append(field_name)\n elif default_names:\n raise TypeError(f\"Non-default namedtuple field {field_name} \"\n f\"cannot follow default field\"\n f\"{'s'if len(default_names)>1 else ''} \"\n f\"{', '.join(default_names)}\")\n nm_tpl=_make_nmtuple(typename,types.items(),\n defaults=[ns[n]for n in default_names],\n module=ns['__module__'])\n nm_tpl.__bases__=bases\n if Generic in bases:\n class_getitem=_generic_class_getitem\n nm_tpl.__class_getitem__=classmethod(class_getitem)\n \n for key,val in ns.items():\n if key in _prohibited:\n raise AttributeError(\"Cannot overwrite NamedTuple attribute \"+key)\n elif key not in _special:\n if key not in nm_tpl._fields:\n setattr(nm_tpl,key,val)\n try:\n set_name=type(val).__set_name__\n except AttributeError:\n pass\n else:\n try:\n set_name(val,nm_tpl,key)\n except BaseException as e:\n e.add_note(\n f\"Error calling __set_name__ on {type(val).__name__ !r} \"\n f\"instance {key !r} in {typename !r}\"\n )\n raise\n \n if Generic in bases:\n nm_tpl.__init_subclass__()\n return nm_tpl\n \n \ndef NamedTuple(typename,fields=_sentinel,/,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if fields is _sentinel:\n if kwargs:\n deprecated_thing=\"Creating NamedTuple classes using keyword arguments\"\n deprecation_msg=(\n \"{name} is deprecated and will be disallowed in Python {remove}. \"\n \"Use the class-based or functional syntax instead.\"\n )\n else:\n deprecated_thing=\"Failing to pass a value for the 'fields' parameter\"\n example=f\"`{typename} = NamedTuple({typename !r}, [])`\"\n deprecation_msg=(\n \"{name} is deprecated and will be disallowed in Python {remove}. \"\n \"To create a NamedTuple class with 0 fields \"\n \"using the functional syntax, \"\n \"pass an empty list, e.g. \"\n )+example+\".\"\n elif fields is None:\n if kwargs:\n raise TypeError(\n \"Cannot pass `None` as the 'fields' parameter \"\n \"and also specify fields using keyword arguments\"\n )\n else:\n deprecated_thing=\"Passing `None` as the 'fields' parameter\"\n example=f\"`{typename} = NamedTuple({typename !r}, [])`\"\n deprecation_msg=(\n \"{name} is deprecated and will be disallowed in Python {remove}. \"\n \"To create a NamedTuple class with 0 fields \"\n \"using the functional syntax, \"\n \"pass an empty list, e.g. \"\n )+example+\".\"\n elif kwargs:\n raise TypeError(\"Either list of fields or keywords\"\n \" can be provided to NamedTuple, not both\")\n if fields is _sentinel or fields is None:\n import warnings\n warnings._deprecated(deprecated_thing,message=deprecation_msg,remove=(3,15))\n fields=kwargs.items()\n nt=_make_nmtuple(typename,fields,module=_caller())\n nt.__orig_bases__=(NamedTuple,)\n return nt\n \n_NamedTuple=type.__new__(NamedTupleMeta,'NamedTuple',(),{})\n\ndef _namedtuple_mro_entries(bases):\n assert NamedTuple in bases\n return(_NamedTuple,)\n \nNamedTuple.__mro_entries__=_namedtuple_mro_entries\n\n\ndef _get_typeddict_qualifiers(annotation_type):\n while True:\n annotation_origin=get_origin(annotation_type)\n if annotation_origin is Annotated:\n annotation_args=get_args(annotation_type)\n if annotation_args:\n annotation_type=annotation_args[0]\n else:\n break\n elif annotation_origin is Required:\n yield Required\n (annotation_type,)=get_args(annotation_type)\n elif annotation_origin is NotRequired:\n yield NotRequired\n (annotation_type,)=get_args(annotation_type)\n elif annotation_origin is ReadOnly:\n yield ReadOnly\n (annotation_type,)=get_args(annotation_type)\n else:\n break\n \n \nclass _TypedDictMeta(type):\n def __new__(cls,name,bases,ns,total=True):\n ''\n\n\n\n\n\n \n for base in bases:\n if type(base)is not _TypedDictMeta and base is not Generic:\n raise TypeError('cannot inherit from both a TypedDict type '\n 'and a non-TypedDict base class')\n \n if any(issubclass(b,Generic)for b in bases):\n generic_base=(Generic,)\n else:\n generic_base=()\n \n tp_dict=type.__new__(_TypedDictMeta,name,(*generic_base,dict),ns)\n \n if not hasattr(tp_dict,'__orig_bases__'):\n tp_dict.__orig_bases__=bases\n \n annotations={}\n own_annotations=ns.get('__annotations__',{})\n msg=\"TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type\"\n own_annotations={\n n:_type_check(tp,msg,module=tp_dict.__module__)\n for n,tp in own_annotations.items()\n }\n required_keys=set()\n optional_keys=set()\n readonly_keys=set()\n mutable_keys=set()\n \n for base in bases:\n annotations.update(base.__dict__.get('__annotations__',{}))\n \n base_required=base.__dict__.get('__required_keys__',set())\n required_keys |=base_required\n optional_keys -=base_required\n \n base_optional=base.__dict__.get('__optional_keys__',set())\n required_keys -=base_optional\n optional_keys |=base_optional\n \n readonly_keys.update(base.__dict__.get('__readonly_keys__',()))\n mutable_keys.update(base.__dict__.get('__mutable_keys__',()))\n \n annotations.update(own_annotations)\n for annotation_key,annotation_type in own_annotations.items():\n qualifiers=set(_get_typeddict_qualifiers(annotation_type))\n if Required in qualifiers:\n is_required=True\n elif NotRequired in qualifiers:\n is_required=False\n else:\n is_required=total\n \n if is_required:\n required_keys.add(annotation_key)\n optional_keys.discard(annotation_key)\n else:\n optional_keys.add(annotation_key)\n required_keys.discard(annotation_key)\n \n if ReadOnly in qualifiers:\n if annotation_key in mutable_keys:\n raise TypeError(\n f\"Cannot override mutable key {annotation_key !r}\"\n \" with read-only key\"\n )\n readonly_keys.add(annotation_key)\n else:\n mutable_keys.add(annotation_key)\n readonly_keys.discard(annotation_key)\n \n assert required_keys.isdisjoint(optional_keys),(\n f\"Required keys overlap with optional keys in {name}:\"\n f\" {required_keys=}, {optional_keys=}\"\n )\n tp_dict.__annotations__=annotations\n tp_dict.__required_keys__=frozenset(required_keys)\n tp_dict.__optional_keys__=frozenset(optional_keys)\n tp_dict.__readonly_keys__=frozenset(readonly_keys)\n tp_dict.__mutable_keys__=frozenset(mutable_keys)\n tp_dict.__total__=total\n return tp_dict\n \n __call__=dict\n \n def __subclasscheck__(cls,other):\n \n raise TypeError('TypedDict does not support instance and class checks')\n \n __instancecheck__=__subclasscheck__\n \n \ndef TypedDict(typename,fields=_sentinel,/,*,total=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if fields is _sentinel or fields is None:\n import warnings\n \n if fields is _sentinel:\n deprecated_thing=\"Failing to pass a value for the 'fields' parameter\"\n else:\n deprecated_thing=\"Passing `None` as the 'fields' parameter\"\n \n example=f\"`{typename} = TypedDict({typename !r}, {{{{}}}})`\"\n deprecation_msg=(\n \"{name} is deprecated and will be disallowed in Python {remove}. \"\n \"To create a TypedDict class with 0 fields \"\n \"using the functional syntax, \"\n \"pass an empty dictionary, e.g. \"\n )+example+\".\"\n warnings._deprecated(deprecated_thing,message=deprecation_msg,remove=(3,15))\n fields={}\n \n ns={'__annotations__':dict(fields)}\n module=_caller()\n if module is not None:\n \n ns['__module__']=module\n \n td=_TypedDictMeta(typename,(),ns,total=total)\n td.__orig_bases__=(TypedDict,)\n return td\n \n_TypedDict=type.__new__(_TypedDictMeta,'TypedDict',(),{})\nTypedDict.__mro_entries__=lambda bases:(_TypedDict,)\n\n\n@_SpecialForm\ndef Required(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self._name} accepts only a single type.')\n return _GenericAlias(self,(item,))\n \n \n@_SpecialForm\ndef NotRequired(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self._name} accepts only a single type.')\n return _GenericAlias(self,(item,))\n \n \n@_SpecialForm\ndef ReadOnly(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self._name} accepts only a single type.')\n return _GenericAlias(self,(item,))\n \n \nclass NewType:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __call__=_idfunc\n \n def __init__(self,name,tp):\n self.__qualname__=name\n if '.'in name:\n name=name.rpartition('.')[-1]\n self.__name__=name\n self.__supertype__=tp\n def_mod=_caller()\n if def_mod !='typing':\n self.__module__=def_mod\n \n def __mro_entries__(self,bases):\n \n \n superclass_name=self.__name__\n \n class Dummy:\n def __init_subclass__(cls):\n subclass_name=cls.__name__\n raise TypeError(\n f\"Cannot subclass an instance of NewType. Perhaps you were looking for: \"\n f\"`{subclass_name} = NewType({subclass_name !r}, {superclass_name})`\"\n )\n \n return(Dummy,)\n \n def __repr__(self):\n return f'{self.__module__}.{self.__qualname__}'\n \n def __reduce__(self):\n return self.__qualname__\n \n def __or__(self,other):\n return Union[self,other]\n \n def __ror__(self,other):\n return Union[other,self]\n \n \n \nText=str\n\n\n\nTYPE_CHECKING=False\n\n\nclass IO(Generic[AnyStr]):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n @property\n @abstractmethod\n def mode(self)->str:\n pass\n \n @property\n @abstractmethod\n def name(self)->str:\n pass\n \n @abstractmethod\n def close(self)->None:\n pass\n \n @property\n @abstractmethod\n def closed(self)->bool:\n pass\n \n @abstractmethod\n def fileno(self)->int:\n pass\n \n @abstractmethod\n def flush(self)->None:\n pass\n \n @abstractmethod\n def isatty(self)->bool:\n pass\n \n @abstractmethod\n def read(self,n:int=-1)->AnyStr:\n pass\n \n @abstractmethod\n def readable(self)->bool:\n pass\n \n @abstractmethod\n def readline(self,limit:int=-1)->AnyStr:\n pass\n \n @abstractmethod\n def readlines(self,hint:int=-1)->List[AnyStr]:\n pass\n \n @abstractmethod\n def seek(self,offset:int,whence:int=0)->int:\n pass\n \n @abstractmethod\n def seekable(self)->bool:\n pass\n \n @abstractmethod\n def tell(self)->int:\n pass\n \n @abstractmethod\n def truncate(self,size:int=None)->int:\n pass\n \n @abstractmethod\n def writable(self)->bool:\n pass\n \n @abstractmethod\n def write(self,s:AnyStr)->int:\n pass\n \n @abstractmethod\n def writelines(self,lines:List[AnyStr])->None:\n pass\n \n @abstractmethod\n def __enter__(self)->'IO[AnyStr]':\n pass\n \n @abstractmethod\n def __exit__(self,type,value,traceback)->None:\n pass\n \n \nclass BinaryIO(IO[bytes]):\n ''\n \n __slots__=()\n \n @abstractmethod\n def write(self,s:Union[bytes,bytearray])->int:\n pass\n \n @abstractmethod\n def __enter__(self)->'BinaryIO':\n pass\n \n \nclass TextIO(IO[str]):\n ''\n \n __slots__=()\n \n @property\n @abstractmethod\n def buffer(self)->BinaryIO:\n pass\n \n @property\n @abstractmethod\n def encoding(self)->str:\n pass\n \n @property\n @abstractmethod\n def errors(self)->Optional[str]:\n pass\n \n @property\n @abstractmethod\n def line_buffering(self)->bool:\n pass\n \n @property\n @abstractmethod\n def newlines(self)->Any:\n pass\n \n @abstractmethod\n def __enter__(self)->'TextIO':\n pass\n \n \ndef reveal_type[T](obj:T,/)->T:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n print(f\"Runtime type is {type(obj).__name__ !r}\",file=sys.stderr)\n return obj\n \n \nclass _IdentityCallable(Protocol):\n def __call__[T](self,arg:T,/)->T:\n ...\n \n \ndef dataclass_transform(\n*,\neq_default:bool=True,\norder_default:bool=False,\nkw_only_default:bool=False,\nfrozen_default:bool=False,\nfield_specifiers:tuple[type[Any]|Callable[...,Any],...]=(),\n**kwargs:Any,\n)->_IdentityCallable:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def decorator(cls_or_fn):\n cls_or_fn.__dataclass_transform__={\n \"eq_default\":eq_default,\n \"order_default\":order_default,\n \"kw_only_default\":kw_only_default,\n \"frozen_default\":frozen_default,\n \"field_specifiers\":field_specifiers,\n \"kwargs\":kwargs,\n }\n return cls_or_fn\n return decorator\n \n \ntype _Func=Callable[...,Any]\n\n\ndef override[F:_Func](method:F,/)->F:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n method.__override__=True\n except(AttributeError,TypeError):\n \n \n \n pass\n return method\n \n \ndef is_protocol(tp:type,/)->bool:\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n return(\n isinstance(tp,type)\n and getattr(tp,'_is_protocol',False)\n and tp !=Protocol\n )\n \n \ndef get_protocol_members(tp:type,/)->frozenset[str]:\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if not is_protocol(tp):\n raise TypeError(f'{tp !r} is not a Protocol')\n return frozenset(tp.__protocol_attrs__)\n \n \ndef __getattr__(attr):\n ''\n\n\n\n \n if attr in{\"Pattern\",\"Match\"}:\n import re\n obj=_alias(getattr(re,attr),1)\n elif attr in{\"ContextManager\",\"AsyncContextManager\"}:\n import contextlib\n obj=_alias(getattr(contextlib,f\"Abstract{attr}\"),2,name=attr,defaults=(bool |None,))\n elif attr ==\"_collect_parameters\":\n import warnings\n \n depr_message=(\n \"The private _collect_parameters function is deprecated and will be\"\n \" removed in a future version of Python. Any use of private functions\"\n \" is discouraged and may break in the future.\"\n )\n warnings.warn(depr_message,category=DeprecationWarning,stacklevel=2)\n obj=_collect_type_parameters\n else:\n raise AttributeError(f\"module {__name__ !r} has no attribute {attr !r}\")\n globals()[attr]=obj\n return obj\n", ["_typing", "abc", "collections", "collections.abc", "contextlib", "copyreg", "functools", "inspect", "operator", "re", "sys", "types", "warnings"]], "uuid": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport os\nimport sys\n\nfrom enum import Enum,_simple_enum\n\n\n__author__='Ka-Ping Yee '\n\n\nif sys.platform in{'win32','darwin','emscripten','wasi'}:\n _AIX=_LINUX=False\nelif sys.platform =='linux':\n _LINUX=True\n _AIX=False\nelse:\n import platform\n _platform_system=platform.system()\n _AIX=_platform_system =='AIX'\n _LINUX=_platform_system in('Linux','Android')\n \n_MAC_DELIM=b':'\n_MAC_OMITS_LEADING_ZEROES=False\nif _AIX:\n _MAC_DELIM=b'.'\n _MAC_OMITS_LEADING_ZEROES=True\n \nRESERVED_NCS,RFC_4122,RESERVED_MICROSOFT,RESERVED_FUTURE=[\n'reserved for NCS compatibility','specified in RFC 4122',\n'reserved for Microsoft compatibility','reserved for future definition']\n\nint_=int\nbytes_=bytes\n\n\n@_simple_enum(Enum)\nclass SafeUUID:\n safe=0\n unsafe=-1\n unknown=None\n \n \nclass UUID:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('int','is_safe','__weakref__')\n \n def __init__(self,hex=None,bytes=None,bytes_le=None,fields=None,\n int=None,version=None,\n *,is_safe=SafeUUID.unknown):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if[hex,bytes,bytes_le,fields,int].count(None)!=4:\n raise TypeError('one of the hex, bytes, bytes_le, fields, '\n 'or int arguments must be given')\n if hex is not None:\n hex=hex.replace('urn:','').replace('uuid:','')\n hex=hex.strip('{}').replace('-','')\n if len(hex)!=32:\n raise ValueError('badly formed hexadecimal UUID string')\n int=int_(hex,16)\n if bytes_le is not None:\n if len(bytes_le)!=16:\n raise ValueError('bytes_le is not a 16-char string')\n bytes=(bytes_le[4 -1::-1]+bytes_le[6 -1:4 -1:-1]+\n bytes_le[8 -1:6 -1:-1]+bytes_le[8:])\n if bytes is not None:\n if len(bytes)!=16:\n raise ValueError('bytes is not a 16-char string')\n assert isinstance(bytes,bytes_),repr(bytes)\n int=int_.from_bytes(bytes)\n if fields is not None:\n if len(fields)!=6:\n raise ValueError('fields is not a 6-tuple')\n (time_low,time_mid,time_hi_version,\n clock_seq_hi_variant,clock_seq_low,node)=fields\n if not 0 <=time_low <1 <<32:\n raise ValueError('field 1 out of range (need a 32-bit value)')\n if not 0 <=time_mid <1 <<16:\n raise ValueError('field 2 out of range (need a 16-bit value)')\n if not 0 <=time_hi_version <1 <<16:\n raise ValueError('field 3 out of range (need a 16-bit value)')\n if not 0 <=clock_seq_hi_variant <1 <<8:\n raise ValueError('field 4 out of range (need an 8-bit value)')\n if not 0 <=clock_seq_low <1 <<8:\n raise ValueError('field 5 out of range (need an 8-bit value)')\n if not 0 <=node <1 <<48:\n raise ValueError('field 6 out of range (need a 48-bit value)')\n clock_seq=(clock_seq_hi_variant <<8)|clock_seq_low\n int=((time_low <<96)|(time_mid <<80)|\n (time_hi_version <<64)|(clock_seq <<48)|node)\n if int is not None:\n if not 0 <=int <1 <<128:\n raise ValueError('int is out of range (need a 128-bit value)')\n if version is not None:\n if not 1 <=version <=5:\n raise ValueError('illegal version number')\n \n int &=~(0xc000 <<48)\n int |=0x8000 <<48\n \n int &=~(0xf000 <<64)\n int |=version <<76\n object.__setattr__(self,'int',int)\n object.__setattr__(self,'is_safe',is_safe)\n \n def __getstate__(self):\n d={'int':self.int}\n if self.is_safe !=SafeUUID.unknown:\n \n \n d['is_safe']=self.is_safe.value\n return d\n \n def __setstate__(self,state):\n object.__setattr__(self,'int',state['int'])\n \n object.__setattr__(self,'is_safe',\n SafeUUID(state['is_safe'])\n if 'is_safe'in state else SafeUUID.unknown)\n \n def __eq__(self,other):\n if isinstance(other,UUID):\n return self.int ==other.int\n return NotImplemented\n \n \n \n \n def __lt__(self,other):\n if isinstance(other,UUID):\n return self.int other.int\n return NotImplemented\n \n def __le__(self,other):\n if isinstance(other,UUID):\n return self.int <=other.int\n return NotImplemented\n \n def __ge__(self,other):\n if isinstance(other,UUID):\n return self.int >=other.int\n return NotImplemented\n \n def __hash__(self):\n return hash(self.int)\n \n def __int__(self):\n return self.int\n \n def __repr__(self):\n return '%s(%r)'%(self.__class__.__name__,str(self))\n \n def __setattr__(self,name,value):\n raise TypeError('UUID objects are immutable')\n \n def __str__(self):\n hex='%032x'%self.int\n return '%s-%s-%s-%s-%s'%(\n hex[:8],hex[8:12],hex[12:16],hex[16:20],hex[20:])\n \n @property\n def bytes(self):\n return self.int.to_bytes(16)\n \n @property\n def bytes_le(self):\n bytes=self.bytes\n return(bytes[4 -1::-1]+bytes[6 -1:4 -1:-1]+bytes[8 -1:6 -1:-1]+\n bytes[8:])\n \n @property\n def fields(self):\n return(self.time_low,self.time_mid,self.time_hi_version,\n self.clock_seq_hi_variant,self.clock_seq_low,self.node)\n \n @property\n def time_low(self):\n return self.int >>96\n \n @property\n def time_mid(self):\n return(self.int >>80)&0xffff\n \n @property\n def time_hi_version(self):\n return(self.int >>64)&0xffff\n \n @property\n def clock_seq_hi_variant(self):\n return(self.int >>56)&0xff\n \n @property\n def clock_seq_low(self):\n return(self.int >>48)&0xff\n \n @property\n def time(self):\n return(((self.time_hi_version&0x0fff)<<48)|\n (self.time_mid <<32)|self.time_low)\n \n @property\n def clock_seq(self):\n return(((self.clock_seq_hi_variant&0x3f)<<8)|\n self.clock_seq_low)\n \n @property\n def node(self):\n return self.int&0xffffffffffff\n \n @property\n def hex(self):\n return '%032x'%self.int\n \n @property\n def urn(self):\n return 'urn:uuid:'+str(self)\n \n @property\n def variant(self):\n if not self.int&(0x8000 <<48):\n return RESERVED_NCS\n elif not self.int&(0x4000 <<48):\n return RFC_4122\n elif not self.int&(0x2000 <<48):\n return RESERVED_MICROSOFT\n else:\n return RESERVED_FUTURE\n \n @property\n def version(self):\n \n if self.variant ==RFC_4122:\n return int((self.int >>76)&0xf)\n \n \ndef _get_command_stdout(command,*args):\n import io,os,shutil,subprocess\n \n try:\n path_dirs=os.environ.get('PATH',os.defpath).split(os.pathsep)\n path_dirs.extend(['/sbin','/usr/sbin'])\n executable=shutil.which(command,path=os.pathsep.join(path_dirs))\n if executable is None:\n return None\n \n \n \n env=dict(os.environ)\n env['LC_ALL']='C'\n \n if args !=('',):\n command=(executable,*args)\n else:\n command=(executable,)\n proc=subprocess.Popen(command,\n stdout=subprocess.PIPE,\n stderr=subprocess.DEVNULL,\n env=env)\n if not proc:\n return None\n stdout,stderr=proc.communicate()\n return io.BytesIO(stdout)\n except(OSError,subprocess.SubprocessError):\n return None\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef _is_universal(mac):\n return not(mac&(1 <<41))\n \n \ndef _find_mac_near_keyword(command,args,keywords,get_word_index):\n ''\n\n\n\n\n\n\n \n stdout=_get_command_stdout(command,args)\n if stdout is None:\n return None\n \n first_local_mac=None\n for line in stdout:\n words=line.lower().rstrip().split()\n for i in range(len(words)):\n if words[i]in keywords:\n try:\n word=words[get_word_index(i)]\n mac=int(word.replace(_MAC_DELIM,b''),16)\n except(ValueError,IndexError):\n \n \n \n \n \n pass\n else:\n if _is_universal(mac):\n return mac\n first_local_mac=first_local_mac or mac\n return first_local_mac or None\n \n \ndef _parse_mac(word):\n\n\n\n\n\n\n parts=word.split(_MAC_DELIM)\n if len(parts)!=6:\n return\n if _MAC_OMITS_LEADING_ZEROES:\n \n \n \n \n if not all(1 <=len(part)<=2 for part in parts):\n return\n hexstr=b''.join(part.rjust(2,b'0')for part in parts)\n else:\n if not all(len(part)==2 for part in parts):\n return\n hexstr=b''.join(parts)\n try:\n return int(hexstr,16)\n except ValueError:\n return\n \n \ndef _find_mac_under_heading(command,args,heading):\n ''\n\n\n\n\n \n stdout=_get_command_stdout(command,args)\n if stdout is None:\n return None\n \n keywords=stdout.readline().rstrip().split()\n try:\n column_index=keywords.index(heading)\n except ValueError:\n return None\n \n first_local_mac=None\n for line in stdout:\n words=line.rstrip().split()\n try:\n word=words[column_index]\n except IndexError:\n continue\n \n mac=_parse_mac(word)\n if mac is None:\n continue\n if _is_universal(mac):\n return mac\n if first_local_mac is None:\n first_local_mac=mac\n \n return first_local_mac\n \n \n \n \ndef _ifconfig_getnode():\n ''\n \n keywords=(b'hwaddr',b'ether',b'address:',b'lladdr')\n for args in('','-a','-av'):\n mac=_find_mac_near_keyword('ifconfig',args,keywords,lambda i:i+1)\n if mac:\n return mac\n return None\n \ndef _ip_getnode():\n ''\n \n mac=_find_mac_near_keyword('ip','link',[b'link/ether'],lambda i:i+1)\n if mac:\n return mac\n return None\n \ndef _arp_getnode():\n ''\n import os,socket\n if not hasattr(socket,\"gethostbyname\"):\n return None\n try:\n ip_addr=socket.gethostbyname(socket.gethostname())\n except OSError:\n return None\n \n \n mac=_find_mac_near_keyword('arp','-an',[os.fsencode(ip_addr)],lambda i:-1)\n if mac:\n return mac\n \n \n mac=_find_mac_near_keyword('arp','-an',[os.fsencode(ip_addr)],lambda i:i+1)\n if mac:\n return mac\n \n \n mac=_find_mac_near_keyword('arp','-an',[os.fsencode('(%s)'%ip_addr)],\n lambda i:i+2)\n \n if mac:\n return mac\n return None\n \ndef _lanscan_getnode():\n ''\n \n return _find_mac_near_keyword('lanscan','-ai',[b'lan0'],lambda i:0)\n \ndef _netstat_getnode():\n ''\n \n return _find_mac_under_heading('netstat','-ian',b'Address')\n \n \n \ntry:\n import _uuid\n _generate_time_safe=getattr(_uuid,\"generate_time_safe\",None)\n _UuidCreate=getattr(_uuid,\"UuidCreate\",None)\nexcept ImportError:\n _uuid=None\n _generate_time_safe=None\n _UuidCreate=None\n \n \ndef _unix_getnode():\n ''\n if _generate_time_safe:\n uuid_time,_=_generate_time_safe()\n return UUID(bytes=uuid_time).node\n \ndef _windll_getnode():\n ''\n if _UuidCreate:\n uuid_bytes=_UuidCreate()\n return UUID(bytes_le=uuid_bytes).node\n \ndef _random_getnode():\n ''\n \n \n \n \n \n \n \n \n \n \n import random\n return random.getrandbits(48)|(1 <<40)\n \n \n \n \n \n \n \n \nif _LINUX:\n _OS_GETTERS=[_ip_getnode,_ifconfig_getnode]\nelif sys.platform =='darwin':\n _OS_GETTERS=[_ifconfig_getnode,_arp_getnode,_netstat_getnode]\nelif sys.platform =='win32':\n\n _OS_GETTERS=[]\nelif _AIX:\n _OS_GETTERS=[_netstat_getnode]\nelse:\n _OS_GETTERS=[_ifconfig_getnode,_ip_getnode,_arp_getnode,\n _netstat_getnode,_lanscan_getnode]\nif os.name =='posix':\n _GETTERS=[_unix_getnode]+_OS_GETTERS\nelif os.name =='nt':\n _GETTERS=[_windll_getnode]+_OS_GETTERS\nelse:\n _GETTERS=_OS_GETTERS\n \n_node=None\n\ndef getnode():\n ''\n\n\n\n\n\n \n global _node\n if _node is not None:\n return _node\n \n for getter in _GETTERS+[_random_getnode]:\n try:\n _node=getter()\n except:\n continue\n if(_node is not None)and(0 <=_node <(1 <<48)):\n return _node\n assert False,'_random_getnode() returned invalid value: {}'.format(_node)\n \n \n_last_timestamp=None\n\ndef uuid1(node=None,clock_seq=None):\n ''\n\n\n \n \n \n \n if _generate_time_safe is not None and node is clock_seq is None:\n uuid_time,safely_generated=_generate_time_safe()\n try:\n is_safe=SafeUUID(safely_generated)\n except ValueError:\n is_safe=SafeUUID.unknown\n return UUID(bytes=uuid_time,is_safe=is_safe)\n \n global _last_timestamp\n import time\n nanoseconds=time.time_ns()\n \n \n timestamp=nanoseconds //100+0x01b21dd213814000\n if _last_timestamp is not None and timestamp <=_last_timestamp:\n timestamp=_last_timestamp+1\n _last_timestamp=timestamp\n if clock_seq is None:\n import random\n clock_seq=random.getrandbits(14)\n time_low=timestamp&0xffffffff\n time_mid=(timestamp >>32)&0xffff\n time_hi_version=(timestamp >>48)&0x0fff\n clock_seq_low=clock_seq&0xff\n clock_seq_hi_variant=(clock_seq >>8)&0x3f\n if node is None:\n node=getnode()\n return UUID(fields=(time_low,time_mid,time_hi_version,\n clock_seq_hi_variant,clock_seq_low,node),version=1)\n \ndef uuid3(namespace,name):\n ''\n if isinstance(name,str):\n name=bytes(name,\"utf-8\")\n from hashlib import md5\n digest=md5(\n namespace.bytes+name,\n usedforsecurity=False\n ).digest()\n return UUID(bytes=digest[:16],version=3)\n \ndef uuid4():\n ''\n return UUID(bytes=os.urandom(16),version=4)\n \ndef uuid5(namespace,name):\n ''\n if isinstance(name,str):\n name=bytes(name,\"utf-8\")\n from hashlib import sha1\n hash=sha1(namespace.bytes+name).digest()\n return UUID(bytes=hash[:16],version=5)\n \n \ndef main():\n ''\n uuid_funcs={\n \"uuid1\":uuid1,\n \"uuid3\":uuid3,\n \"uuid4\":uuid4,\n \"uuid5\":uuid5\n }\n uuid_namespace_funcs=(\"uuid3\",\"uuid5\")\n namespaces={\n \"@dns\":NAMESPACE_DNS,\n \"@url\":NAMESPACE_URL,\n \"@oid\":NAMESPACE_OID,\n \"@x500\":NAMESPACE_X500\n }\n \n import argparse\n parser=argparse.ArgumentParser(\n description=\"Generates a uuid using the selected uuid function.\")\n parser.add_argument(\"-u\",\"--uuid\",choices=uuid_funcs.keys(),default=\"uuid4\",\n help=\"The function to use to generate the uuid. \"\n \"By default uuid4 function is used.\")\n parser.add_argument(\"-n\",\"--namespace\",\n help=\"The namespace is a UUID, or '@ns' where 'ns' is a \"\n \"well-known predefined UUID addressed by namespace name. \"\n \"Such as @dns, @url, @oid, and @x500. \"\n \"Only required for uuid3/uuid5 functions.\")\n parser.add_argument(\"-N\",\"--name\",\n help=\"The name used as part of generating the uuid. \"\n \"Only required for uuid3/uuid5 functions.\")\n \n args=parser.parse_args()\n uuid_func=uuid_funcs[args.uuid]\n namespace=args.namespace\n name=args.name\n \n if args.uuid in uuid_namespace_funcs:\n if not namespace or not name:\n parser.error(\n \"Incorrect number of arguments. \"\n f\"{args.uuid} requires a namespace and a name. \"\n \"Run 'python -m uuid -h' for more information.\"\n )\n namespace=namespaces[namespace]if namespace in namespaces else UUID(namespace)\n print(uuid_func(namespace,name))\n else:\n print(uuid_func())\n \n \n \n \nNAMESPACE_DNS=UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')\nNAMESPACE_URL=UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')\nNAMESPACE_OID=UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')\nNAMESPACE_X500=UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')\n\nif __name__ ==\"__main__\":\n main()\n", ["_uuid", "argparse", "enum", "hashlib", "io", "os", "platform", "random", "shutil", "socket", "subprocess", "sys", "time"]], "VFS_import": [".py", "import os\nimport sys\nfrom browser import doc\n\n\n\n\n\n\nVFS=dict(JSObject(__BRYTHON__.py_VFS))\nclass VFSModuleFinder:\n def __init__(self,path_entry):\n print(\"in VFSModuleFinder\")\n if path_entry.startswith('/libs')or path_entry.startswith('/Lib'):\n self.path_entry=path_entry\n else:\n raise ImportError()\n \n def __str__(self):\n return '<%s for \"%s\">'%(self.__class__.__name__,self.path_entry)\n \n def find_module(self,fullname,path=None):\n path=path or self.path_entry\n \n for _ext in['js','pyj','py']:\n _filepath=os.path.join(self.path_entry,'%s.%s'%(fullname,_ext))\n if _filepath in VFS:\n print(\"module found at %s:%s\"%(_filepath,fullname))\n return VFSModuleLoader(_filepath,fullname)\n \n print('module %s not found'%fullname)\n raise ImportError()\n return None\n \nclass VFSModuleLoader:\n ''\n \n def __init__(self,filepath,name):\n self._filepath=filepath\n self._name=name\n \n def get_source(self):\n if self._filepath in VFS:\n return JSObject(readFromVFS(self._filepath))\n \n raise ImportError('could not find source for %s'%fullname)\n \n def is_package(self):\n return '.'in self._name\n \n def load_module(self):\n if self._name in sys.modules:\n \n mod=sys.modules[self._name]\n return mod\n \n _src=self.get_source()\n if self._filepath.endswith('.js'):\n mod=JSObject(import_js_module(_src,self._filepath,self._name))\n elif self._filepath.endswith('.py'):\n mod=JSObject(import_py_module(_src,self._filepath,self._name))\n elif self._filepath.endswith('.pyj'):\n mod=JSObject(import_pyj_module(_src,self._filepath,self._name))\n else:\n raise ImportError('Invalid Module: %s'%self._filepath)\n \n \n mod.__file__=self._filepath\n mod.__name__=self._name\n mod.__path__=os.path.abspath(self._filepath)\n mod.__loader__=self\n mod.__package__='.'.join(self._name.split('.')[:-1])\n \n if self.is_package():\n print('adding path for package')\n \n \n mod.__path__=[self.path_entry]\n else:\n print('imported as regular module')\n \n print('creating a new module object for \"%s\"'%self._name)\n sys.modules.setdefault(self._name,mod)\n JSObject(__BRYTHON__.imported)[self._name]=mod\n \n return mod\n \nJSObject(__BRYTHON__.path_hooks.insert(0,VFSModuleFinder))\n", ["browser", "os", "sys"]], "warnings": [".py", "''\n\nimport sys\n\n\n__all__=[\"warn\",\"warn_explicit\",\"showwarning\",\n\"formatwarning\",\"filterwarnings\",\"simplefilter\",\n\"resetwarnings\",\"catch_warnings\",\"deprecated\"]\n\ndef showwarning(message,category,filename,lineno,file=None,line=None):\n ''\n msg=WarningMessage(message,category,filename,lineno,file,line)\n _showwarnmsg_impl(msg)\n \ndef formatwarning(message,category,filename,lineno,line=None):\n ''\n msg=WarningMessage(message,category,filename,lineno,None,line)\n return _formatwarnmsg_impl(msg)\n \ndef _showwarnmsg_impl(msg):\n file=msg.file\n if file is None:\n file=sys.stderr\n if file is None:\n \n \n return\n text=_formatwarnmsg(msg)\n try:\n file.write(text)\n except OSError:\n \n pass\n \ndef _formatwarnmsg_impl(msg):\n category=msg.category.__name__\n s=f\"{msg.filename}:{msg.lineno}: {category}: {msg.message}\\n\"\n \n if msg.line is None:\n try:\n import linecache\n line=linecache.getline(msg.filename,msg.lineno)\n except Exception:\n \n \n line=None\n linecache=None\n else:\n line=msg.line\n if line:\n line=line.strip()\n s +=\" %s\\n\"%line\n \n if msg.source is not None:\n try:\n import tracemalloc\n \n \n except Exception:\n \n suggest_tracemalloc=False\n tb=None\n else:\n try:\n suggest_tracemalloc=not tracemalloc.is_tracing()\n tb=tracemalloc.get_object_traceback(msg.source)\n except Exception:\n \n \n suggest_tracemalloc=False\n tb=None\n \n if tb is not None:\n s +='Object allocated at (most recent call last):\\n'\n for frame in tb:\n s +=(' File \"%s\", lineno %s\\n'\n %(frame.filename,frame.lineno))\n \n try:\n if linecache is not None:\n line=linecache.getline(frame.filename,frame.lineno)\n else:\n line=None\n except Exception:\n line=None\n if line:\n line=line.strip()\n s +=' %s\\n'%line\n elif suggest_tracemalloc:\n s +=(f'{category}: Enable tracemalloc to get the object '\n f'allocation traceback\\n')\n return s\n \n \n_showwarning_orig=showwarning\n\ndef _showwarnmsg(msg):\n ''\n try:\n sw=showwarning\n except NameError:\n pass\n else:\n if sw is not _showwarning_orig:\n \n if not callable(sw):\n raise TypeError(\"warnings.showwarning() must be set to a \"\n \"function or method\")\n \n sw(msg.message,msg.category,msg.filename,msg.lineno,\n msg.file,msg.line)\n return\n _showwarnmsg_impl(msg)\n \n \n_formatwarning_orig=formatwarning\n\ndef _formatwarnmsg(msg):\n ''\n try:\n fw=formatwarning\n except NameError:\n pass\n else:\n if fw is not _formatwarning_orig:\n \n return fw(msg.message,msg.category,\n msg.filename,msg.lineno,msg.line)\n return _formatwarnmsg_impl(msg)\n \ndef filterwarnings(action,message=\"\",category=Warning,module=\"\",lineno=0,\nappend=False):\n ''\n\n\n\n\n\n\n\n\n \n if action not in{\"error\",\"ignore\",\"always\",\"default\",\"module\",\"once\"}:\n raise ValueError(f\"invalid action: {action !r}\")\n if not isinstance(message,str):\n raise TypeError(\"message must be a string\")\n if not isinstance(category,type)or not issubclass(category,Warning):\n raise TypeError(\"category must be a Warning subclass\")\n if not isinstance(module,str):\n raise TypeError(\"module must be a string\")\n if not isinstance(lineno,int):\n raise TypeError(\"lineno must be an int\")\n if lineno <0:\n raise ValueError(\"lineno must be an int >= 0\")\n \n if message or module:\n import re\n \n if message:\n message=re.compile(message,re.I)\n else:\n message=None\n if module:\n module=re.compile(module)\n else:\n module=None\n \n _add_filter(action,message,category,module,lineno,append=append)\n \ndef simplefilter(action,category=Warning,lineno=0,append=False):\n ''\n\n\n\n\n\n\n\n \n if action not in{\"error\",\"ignore\",\"always\",\"default\",\"module\",\"once\"}:\n raise ValueError(f\"invalid action: {action !r}\")\n if not isinstance(lineno,int):\n raise TypeError(\"lineno must be an int\")\n if lineno <0:\n raise ValueError(\"lineno must be an int >= 0\")\n _add_filter(action,None,category,None,lineno,append=append)\n \ndef _add_filter(*item,append):\n\n\n if not append:\n try:\n filters.remove(item)\n except ValueError:\n pass\n filters.insert(0,item)\n else:\n if item not in filters:\n filters.append(item)\n _filters_mutated()\n \ndef resetwarnings():\n ''\n filters[:]=[]\n _filters_mutated()\n \nclass _OptionError(Exception):\n ''\n pass\n \n \ndef _processoptions(args):\n for arg in args:\n try:\n _setoption(arg)\n except _OptionError as msg:\n print(\"Invalid -W option ignored:\",msg,file=sys.stderr)\n \n \ndef _setoption(arg):\n parts=arg.split(':')\n if len(parts)>5:\n raise _OptionError(\"too many fields (max 5): %r\"%(arg,))\n while len(parts)<5:\n parts.append('')\n action,message,category,module,lineno=[s.strip()\n for s in parts]\n action=_getaction(action)\n category=_getcategory(category)\n if message or module:\n import re\n if message:\n message=re.escape(message)\n if module:\n module=re.escape(module)+r'\\Z'\n if lineno:\n try:\n lineno=int(lineno)\n if lineno <0:\n raise ValueError\n except(ValueError,OverflowError):\n raise _OptionError(\"invalid lineno %r\"%(lineno,))from None\n else:\n lineno=0\n filterwarnings(action,message,category,module,lineno)\n \n \ndef _getaction(action):\n if not action:\n return \"default\"\n if action ==\"all\":return \"always\"\n for a in('default','always','ignore','module','once','error'):\n if a.startswith(action):\n return a\n raise _OptionError(\"invalid action: %r\"%(action,))\n \n \ndef _getcategory(category):\n if not category:\n return Warning\n if '.'not in category:\n import builtins as m\n klass=category\n else:\n module,_,klass=category.rpartition('.')\n try:\n m=__import__(module,None,None,[klass])\n except ImportError:\n raise _OptionError(\"invalid module name: %r\"%(module,))from None\n try:\n cat=getattr(m,klass)\n except AttributeError:\n raise _OptionError(\"unknown warning category: %r\"%(category,))from None\n if not issubclass(cat,Warning):\n raise _OptionError(\"invalid warning category: %r\"%(category,))\n return cat\n \n \ndef _is_internal_filename(filename):\n return 'importlib'in filename and '_bootstrap'in filename\n \n \ndef _is_filename_to_skip(filename,skip_file_prefixes):\n return any(filename.startswith(prefix)for prefix in skip_file_prefixes)\n \n \ndef _is_internal_frame(frame):\n ''\n return _is_internal_filename(frame.f_code.co_filename)\n \n \ndef _next_external_frame(frame,skip_file_prefixes):\n ''\n frame=frame.f_back\n while frame is not None and(\n _is_internal_filename(filename :=frame.f_code.co_filename)or\n _is_filename_to_skip(filename,skip_file_prefixes)):\n frame=frame.f_back\n return frame\n \n \n \ndef warn(message,category=None,stacklevel=1,source=None,\n*,skip_file_prefixes=()):\n ''\n \n if isinstance(message,Warning):\n category=message.__class__\n \n if category is None:\n category=UserWarning\n if not(isinstance(category,type)and issubclass(category,Warning)):\n raise TypeError(\"category must be a Warning subclass, \"\n \"not '{:s}'\".format(type(category).__name__))\n if not isinstance(skip_file_prefixes,tuple):\n \n raise TypeError('skip_file_prefixes must be a tuple of strs.')\n if skip_file_prefixes:\n stacklevel=max(2,stacklevel)\n \n try:\n if stacklevel <=1 or _is_internal_frame(sys._getframe(1)):\n \n \n frame=sys._getframe(stacklevel)\n else:\n frame=sys._getframe(1)\n \n for x in range(stacklevel -1):\n frame=_next_external_frame(frame,skip_file_prefixes)\n if frame is None:\n raise ValueError\n except ValueError:\n globals=sys.__dict__\n filename=\"\"\n lineno=0\n else:\n globals=frame.f_globals\n filename=frame.f_code.co_filename\n lineno=frame.f_lineno\n if '__name__'in globals:\n module=globals['__name__']\n else:\n module=\"\"\n registry=globals.setdefault(\"__warningregistry__\",{})\n warn_explicit(message,category,filename,lineno,module,registry,\n globals,source)\n \ndef warn_explicit(message,category,filename,lineno,\nmodule=None,registry=None,module_globals=None,\nsource=None):\n lineno=int(lineno)\n if module is None:\n module=filename or \"\"\n if module[-3:].lower()==\".py\":\n module=module[:-3]\n if registry is None:\n registry={}\n if registry.get('version',0)!=_filters_version:\n registry.clear()\n registry['version']=_filters_version\n if isinstance(message,Warning):\n text=str(message)\n category=message.__class__\n else:\n text=message\n message=category(message)\n key=(text,category,lineno)\n \n if registry.get(key):\n return\n \n for item in filters:\n action,msg,cat,mod,ln=item\n if((msg is None or msg.match(text))and\n issubclass(category,cat)and\n (mod is None or mod.match(module))and\n (ln ==0 or lineno ==ln)):\n break\n else:\n action=defaultaction\n \n if action ==\"ignore\":\n return\n \n \n \n import linecache\n linecache.getlines(filename,module_globals)\n \n if action ==\"error\":\n raise message\n \n if action ==\"once\":\n registry[key]=1\n oncekey=(text,category)\n if onceregistry.get(oncekey):\n return\n onceregistry[oncekey]=1\n elif action ==\"always\":\n pass\n elif action ==\"module\":\n registry[key]=1\n altkey=(text,category,0)\n if registry.get(altkey):\n return\n registry[altkey]=1\n elif action ==\"default\":\n registry[key]=1\n else:\n \n raise RuntimeError(\n \"Unrecognized action (%r) in warnings.filters:\\n %s\"%\n (action,item))\n \n msg=WarningMessage(message,category,filename,lineno,source)\n _showwarnmsg(msg)\n \n \nclass WarningMessage(object):\n\n _WARNING_DETAILS=(\"message\",\"category\",\"filename\",\"lineno\",\"file\",\n \"line\",\"source\")\n \n def __init__(self,message,category,filename,lineno,file=None,\n line=None,source=None):\n self.message=message\n self.category=category\n self.filename=filename\n self.lineno=lineno\n self.file=file\n self.line=line\n self.source=source\n self._category_name=category.__name__ if category else None\n \n def __str__(self):\n return(\"{message : %r, category : %r, filename : %r, lineno : %s, \"\n \"line : %r}\"%(self.message,self._category_name,\n self.filename,self.lineno,self.line))\n \n \nclass catch_warnings(object):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,*,record=False,module=None,\n action=None,category=Warning,lineno=0,append=False):\n ''\n\n\n\n\n\n \n self._record=record\n self._module=sys.modules['warnings']if module is None else module\n self._entered=False\n if action is None:\n self._filter=None\n else:\n self._filter=(action,category,lineno,append)\n \n def __repr__(self):\n args=[]\n if self._record:\n args.append(\"record=True\")\n if self._module is not sys.modules['warnings']:\n args.append(\"module=%r\"%self._module)\n name=type(self).__name__\n return \"%s(%s)\"%(name,\", \".join(args))\n \n def __enter__(self):\n if self._entered:\n raise RuntimeError(\"Cannot enter %r twice\"%self)\n self._entered=True\n self._filters=self._module.filters\n self._module.filters=self._filters[:]\n self._module._filters_mutated()\n self._showwarning=self._module.showwarning\n self._showwarnmsg_impl=self._module._showwarnmsg_impl\n if self._filter is not None:\n simplefilter(*self._filter)\n if self._record:\n log=[]\n self._module._showwarnmsg_impl=log.append\n \n \n self._module.showwarning=self._module._showwarning_orig\n return log\n else:\n return None\n \n def __exit__(self,*exc_info):\n if not self._entered:\n raise RuntimeError(\"Cannot exit %r without entering first\"%self)\n self._module.filters=self._filters\n self._module._filters_mutated()\n self._module.showwarning=self._showwarning\n self._module._showwarnmsg_impl=self._showwarnmsg_impl\n \n \nclass deprecated:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(\n self,\n message:str,\n /,\n *,\n category:type[Warning]|None=DeprecationWarning,\n stacklevel:int=1,\n )->None:\n if not isinstance(message,str):\n raise TypeError(\n f\"Expected an object of type str for 'message', not {type(message).__name__ !r}\"\n )\n self.message=message\n self.category=category\n self.stacklevel=stacklevel\n \n def __call__(self,arg,/):\n \n \n msg=self.message\n category=self.category\n stacklevel=self.stacklevel\n if category is None:\n arg.__deprecated__=msg\n return arg\n elif isinstance(arg,type):\n import functools\n from types import MethodType\n \n original_new=arg.__new__\n \n @functools.wraps(original_new)\n def __new__(cls,*args,**kwargs):\n if cls is arg:\n warn(msg,category=category,stacklevel=stacklevel+1)\n if original_new is not object.__new__:\n return original_new(cls,*args,**kwargs)\n \n elif cls.__init__ is object.__init__ and(args or kwargs):\n raise TypeError(f\"{cls.__name__}() takes no arguments\")\n else:\n return original_new(cls)\n \n arg.__new__=staticmethod(__new__)\n \n original_init_subclass=arg.__init_subclass__\n \n \n if isinstance(original_init_subclass,MethodType):\n original_init_subclass=original_init_subclass.__func__\n \n @functools.wraps(original_init_subclass)\n def __init_subclass__(*args,**kwargs):\n warn(msg,category=category,stacklevel=stacklevel+1)\n return original_init_subclass(*args,**kwargs)\n \n arg.__init_subclass__=classmethod(__init_subclass__)\n \n \n else:\n @functools.wraps(original_init_subclass)\n def __init_subclass__(*args,**kwargs):\n warn(msg,category=category,stacklevel=stacklevel+1)\n return original_init_subclass(*args,**kwargs)\n \n arg.__init_subclass__=__init_subclass__\n \n arg.__deprecated__=__new__.__deprecated__=msg\n __init_subclass__.__deprecated__=msg\n return arg\n elif callable(arg):\n import functools\n \n @functools.wraps(arg)\n def wrapper(*args,**kwargs):\n warn(msg,category=category,stacklevel=stacklevel+1)\n return arg(*args,**kwargs)\n \n arg.__deprecated__=wrapper.__deprecated__=msg\n return wrapper\n else:\n raise TypeError(\n \"@deprecated decorator with non-None category must be applied to \"\n f\"a class or callable, not {arg !r}\"\n )\n \n \n_DEPRECATED_MSG=\"{name!r} is deprecated and slated for removal in Python {remove}\"\n\ndef _deprecated(name,message=_DEPRECATED_MSG,*,remove,_version=sys.version_info):\n ''\n\n\n\n\n\n\n\n \n remove_formatted=f\"{remove[0]}.{remove[1]}\"\n if(_version[:2]>remove)or(_version[:2]==remove and _version[3]!=\"alpha\"):\n msg=f\"{name !r} was slated for removal after Python {remove_formatted} alpha\"\n raise RuntimeError(msg)\n else:\n msg=message.format(name=name,remove=remove_formatted)\n warn(msg,DeprecationWarning,stacklevel=3)\n \n \n \ndef _warn_unawaited_coroutine(coro):\n msg_lines=[\n f\"coroutine '{coro.__qualname__}' was never awaited\\n\"\n ]\n if coro.cr_origin is not None:\n import linecache,traceback\n def extract():\n for filename,lineno,funcname in reversed(coro.cr_origin):\n line=linecache.getline(filename,lineno)\n yield(filename,lineno,funcname,line)\n msg_lines.append(\"Coroutine created at (most recent call last)\\n\")\n msg_lines +=traceback.format_list(list(extract()))\n msg=\"\".join(msg_lines).rstrip(\"\\n\")\n \n \n \n \n \n \n warn(msg,category=RuntimeWarning,stacklevel=2,source=coro)\n \n \n \n \n \n \n \n \n \n \ntry:\n from _warnings import(filters,_defaultaction,_onceregistry,\n warn,warn_explicit,_filters_mutated)\n defaultaction=_defaultaction\n onceregistry=_onceregistry\n _warnings_defaults=True\nexcept ImportError:\n filters=[]\n defaultaction=\"default\"\n onceregistry={}\n \n _filters_version=1\n \n def _filters_mutated():\n global _filters_version\n _filters_version +=1\n \n _warnings_defaults=False\n \n \n \n_processoptions(sys.warnoptions)\nif not _warnings_defaults:\n\n if not hasattr(sys,'gettotalrefcount'):\n filterwarnings(\"default\",category=DeprecationWarning,\n module=\"__main__\",append=1)\n simplefilter(\"ignore\",category=DeprecationWarning,append=1)\n simplefilter(\"ignore\",category=PendingDeprecationWarning,append=1)\n simplefilter(\"ignore\",category=ImportWarning,append=1)\n simplefilter(\"ignore\",category=ResourceWarning,append=1)\n \ndel _warnings_defaults\n", ["_warnings", "builtins", "functools", "linecache", "re", "sys", "traceback", "tracemalloc", "types"]], "weakref": [".py", "''\n\n\n\n\n\n\n\n\n\n\nfrom _weakref import(\ngetweakrefcount,\ngetweakrefs,\nref,\nproxy,\nCallableProxyType,\nProxyType,\nReferenceType,\n_remove_dead_weakref)\n\nfrom _weakrefset import WeakSet,_IterationGuard\n\nimport _collections_abc\nimport sys\nimport itertools\n\nProxyTypes=(ProxyType,CallableProxyType)\n\n__all__=[\"ref\",\"proxy\",\"getweakrefcount\",\"getweakrefs\",\n\"WeakKeyDictionary\",\"ReferenceType\",\"ProxyType\",\n\"CallableProxyType\",\"ProxyTypes\",\"WeakValueDictionary\",\n\"WeakSet\",\"WeakMethod\",\"finalize\"]\n\n\n_collections_abc.MutableSet.register(WeakSet)\n\nclass WeakMethod(ref):\n ''\n\n\n \n \n __slots__=\"_func_ref\",\"_meth_type\",\"_alive\",\"__weakref__\"\n \n def __new__(cls,meth,callback=None):\n try:\n obj=meth.__self__\n func=meth.__func__\n except AttributeError:\n raise TypeError(\"argument should be a bound method, not {}\"\n .format(type(meth)))from None\n def _cb(arg):\n \n \n self=self_wr()\n if self._alive:\n self._alive=False\n if callback is not None:\n callback(self)\n self=ref.__new__(cls,obj,_cb)\n self._func_ref=ref(func,_cb)\n self._meth_type=type(meth)\n self._alive=True\n self_wr=ref(self)\n return self\n \n def __call__(self):\n obj=super().__call__()\n func=self._func_ref()\n if obj is None or func is None:\n return None\n return self._meth_type(func,obj)\n \n def __eq__(self,other):\n if isinstance(other,WeakMethod):\n if not self._alive or not other._alive:\n return self is other\n return ref.__eq__(self,other)and self._func_ref ==other._func_ref\n return NotImplemented\n \n def __ne__(self,other):\n if isinstance(other,WeakMethod):\n if not self._alive or not other._alive:\n return self is not other\n return ref.__ne__(self,other)or self._func_ref !=other._func_ref\n return NotImplemented\n \n __hash__=ref.__hash__\n \n \nclass WeakValueDictionary(_collections_abc.MutableMapping):\n ''\n\n\n\n \n \n \n \n \n \n \n def __init__(self,other=(),/,**kw):\n def remove(wr,selfref=ref(self),_atomic_removal=_remove_dead_weakref):\n self=selfref()\n if self is not None:\n if self._iterating:\n self._pending_removals.append(wr.key)\n else:\n \n \n _atomic_removal(self.data,wr.key)\n self._remove=remove\n \n self._pending_removals=[]\n self._iterating=set()\n self.data={}\n self.update(other,**kw)\n \n def _commit_removals(self,_atomic_removal=_remove_dead_weakref):\n pop=self._pending_removals.pop\n d=self.data\n \n \n while True:\n try:\n key=pop()\n except IndexError:\n return\n _atomic_removal(d,key)\n \n def __getitem__(self,key):\n if self._pending_removals:\n self._commit_removals()\n o=self.data[key]()\n if o is None:\n raise KeyError(key)\n else:\n return o\n \n def __delitem__(self,key):\n if self._pending_removals:\n self._commit_removals()\n del self.data[key]\n \n def __len__(self):\n if self._pending_removals:\n self._commit_removals()\n return len(self.data)\n \n def __contains__(self,key):\n if self._pending_removals:\n self._commit_removals()\n try:\n o=self.data[key]()\n except KeyError:\n return False\n return o is not None\n \n def __repr__(self):\n return \"<%s at %#x>\"%(self.__class__.__name__,id(self))\n \n def __setitem__(self,key,value):\n if self._pending_removals:\n self._commit_removals()\n self.data[key]=KeyedRef(value,self._remove,key)\n \n def copy(self):\n if self._pending_removals:\n self._commit_removals()\n new=WeakValueDictionary()\n with _IterationGuard(self):\n for key,wr in self.data.items():\n o=wr()\n if o is not None:\n new[key]=o\n return new\n \n __copy__=copy\n \n def __deepcopy__(self,memo):\n from copy import deepcopy\n if self._pending_removals:\n self._commit_removals()\n new=self.__class__()\n with _IterationGuard(self):\n for key,wr in self.data.items():\n o=wr()\n if o is not None:\n new[deepcopy(key,memo)]=o\n return new\n \n def get(self,key,default=None):\n if self._pending_removals:\n self._commit_removals()\n try:\n wr=self.data[key]\n except KeyError:\n return default\n else:\n o=wr()\n if o is None:\n \n return default\n else:\n return o\n \n def items(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for k,wr in self.data.items():\n v=wr()\n if v is not None:\n yield k,v\n \n def keys(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for k,wr in self.data.items():\n if wr()is not None:\n yield k\n \n __iter__=keys\n \n def itervaluerefs(self):\n ''\n\n\n\n\n\n\n\n \n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n yield from self.data.values()\n \n def values(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for wr in self.data.values():\n obj=wr()\n if obj is not None:\n yield obj\n \n def popitem(self):\n if self._pending_removals:\n self._commit_removals()\n while True:\n key,wr=self.data.popitem()\n o=wr()\n if o is not None:\n return key,o\n \n def pop(self,key,*args):\n if self._pending_removals:\n self._commit_removals()\n try:\n o=self.data.pop(key)()\n except KeyError:\n o=None\n if o is None:\n if args:\n return args[0]\n else:\n raise KeyError(key)\n else:\n return o\n \n def setdefault(self,key,default=None):\n try:\n o=self.data[key]()\n except KeyError:\n o=None\n if o is None:\n if self._pending_removals:\n self._commit_removals()\n self.data[key]=KeyedRef(default,self._remove,key)\n return default\n else:\n return o\n \n def update(self,other=None,/,**kwargs):\n if self._pending_removals:\n self._commit_removals()\n d=self.data\n if other is not None:\n if not hasattr(other,\"items\"):\n other=dict(other)\n for key,o in other.items():\n d[key]=KeyedRef(o,self._remove,key)\n for key,o in kwargs.items():\n d[key]=KeyedRef(o,self._remove,key)\n \n def valuerefs(self):\n ''\n\n\n\n\n\n\n\n \n if self._pending_removals:\n self._commit_removals()\n return list(self.data.values())\n \n def __ior__(self,other):\n self.update(other)\n return self\n \n def __or__(self,other):\n if isinstance(other,_collections_abc.Mapping):\n c=self.copy()\n c.update(other)\n return c\n return NotImplemented\n \n def __ror__(self,other):\n if isinstance(other,_collections_abc.Mapping):\n c=self.__class__()\n c.update(other)\n c.update(self)\n return c\n return NotImplemented\n \n \nclass KeyedRef(ref):\n ''\n\n\n\n\n\n\n \n \n __slots__=\"key\",\n \n def __new__(type,ob,callback,key):\n self=ref.__new__(type,ob,callback)\n self.key=key\n return self\n \n def __init__(self,ob,callback,key):\n super().__init__(ob,callback)\n \n \nclass WeakKeyDictionary(_collections_abc.MutableMapping):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,dict=None):\n self.data={}\n def remove(k,selfref=ref(self)):\n self=selfref()\n if self is not None:\n if self._iterating:\n self._pending_removals.append(k)\n else:\n try:\n del self.data[k]\n except KeyError:\n pass\n self._remove=remove\n \n self._pending_removals=[]\n self._iterating=set()\n self._dirty_len=False\n if dict is not None:\n self.update(dict)\n \n def _commit_removals(self):\n \n \n \n \n pop=self._pending_removals.pop\n d=self.data\n while True:\n try:\n key=pop()\n except IndexError:\n return\n \n try:\n del d[key]\n except KeyError:\n pass\n \n def _scrub_removals(self):\n d=self.data\n self._pending_removals=[k for k in self._pending_removals if k in d]\n self._dirty_len=False\n \n def __delitem__(self,key):\n self._dirty_len=True\n del self.data[ref(key)]\n \n def __getitem__(self,key):\n return self.data[ref(key)]\n \n def __len__(self):\n if self._dirty_len and self._pending_removals:\n \n \n self._scrub_removals()\n return len(self.data)-len(self._pending_removals)\n \n def __repr__(self):\n return \"<%s at %#x>\"%(self.__class__.__name__,id(self))\n \n def __setitem__(self,key,value):\n self.data[ref(key,self._remove)]=value\n \n def copy(self):\n new=WeakKeyDictionary()\n with _IterationGuard(self):\n for key,value in self.data.items():\n o=key()\n if o is not None:\n new[o]=value\n return new\n \n __copy__=copy\n \n def __deepcopy__(self,memo):\n from copy import deepcopy\n new=self.__class__()\n with _IterationGuard(self):\n for key,value in self.data.items():\n o=key()\n if o is not None:\n new[o]=deepcopy(value,memo)\n return new\n \n def get(self,key,default=None):\n return self.data.get(ref(key),default)\n \n def __contains__(self,key):\n try:\n wr=ref(key)\n except TypeError:\n return False\n return wr in self.data\n \n def items(self):\n with _IterationGuard(self):\n for wr,value in self.data.items():\n key=wr()\n if key is not None:\n yield key,value\n \n def keys(self):\n with _IterationGuard(self):\n for wr in self.data:\n obj=wr()\n if obj is not None:\n yield obj\n \n __iter__=keys\n \n def values(self):\n with _IterationGuard(self):\n for wr,value in self.data.items():\n if wr()is not None:\n yield value\n \n def keyrefs(self):\n ''\n\n\n\n\n\n\n\n \n return list(self.data)\n \n def popitem(self):\n self._dirty_len=True\n while True:\n key,value=self.data.popitem()\n o=key()\n if o is not None:\n return o,value\n \n def pop(self,key,*args):\n self._dirty_len=True\n return self.data.pop(ref(key),*args)\n \n def setdefault(self,key,default=None):\n return self.data.setdefault(ref(key,self._remove),default)\n \n def update(self,dict=None,/,**kwargs):\n d=self.data\n if dict is not None:\n if not hasattr(dict,\"items\"):\n dict=type({})(dict)\n for key,value in dict.items():\n d[ref(key,self._remove)]=value\n if len(kwargs):\n self.update(kwargs)\n \n def __ior__(self,other):\n self.update(other)\n return self\n \n def __or__(self,other):\n if isinstance(other,_collections_abc.Mapping):\n c=self.copy()\n c.update(other)\n return c\n return NotImplemented\n \n def __ror__(self,other):\n if isinstance(other,_collections_abc.Mapping):\n c=self.__class__()\n c.update(other)\n c.update(self)\n return c\n return NotImplemented\n \n \nclass finalize:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n __slots__=()\n _registry={}\n _shutdown=False\n _index_iter=itertools.count()\n _dirty=False\n _registered_with_atexit=False\n \n class _Info:\n __slots__=(\"weakref\",\"func\",\"args\",\"kwargs\",\"atexit\",\"index\")\n \n def __init__(self,obj,func,/,*args,**kwargs):\n if not self._registered_with_atexit:\n \n \n import atexit\n atexit.register(self._exitfunc)\n finalize._registered_with_atexit=True\n info=self._Info()\n info.weakref=ref(obj,self)\n info.func=func\n info.args=args\n info.kwargs=kwargs or None\n info.atexit=True\n info.index=next(self._index_iter)\n self._registry[self]=info\n finalize._dirty=True\n \n def __call__(self,_=None):\n ''\n \n info=self._registry.pop(self,None)\n if info and not self._shutdown:\n return info.func(*info.args,**(info.kwargs or{}))\n \n def detach(self):\n ''\n \n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is not None and self._registry.pop(self,None):\n return(obj,info.func,info.args,info.kwargs or{})\n \n def peek(self):\n ''\n \n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is not None:\n return(obj,info.func,info.args,info.kwargs or{})\n \n @property\n def alive(self):\n ''\n return self in self._registry\n \n @property\n def atexit(self):\n ''\n info=self._registry.get(self)\n return bool(info)and info.atexit\n \n @atexit.setter\n def atexit(self,value):\n info=self._registry.get(self)\n if info:\n info.atexit=bool(value)\n \n def __repr__(self):\n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is None:\n return '<%s object at %#x; dead>'%(type(self).__name__,id(self))\n else:\n return '<%s object at %#x; for %r at %#x>'%\\\n (type(self).__name__,id(self),type(obj).__name__,id(obj))\n \n @classmethod\n def _select_for_exit(cls):\n \n L=[(f,i)for(f,i)in cls._registry.items()if i.atexit]\n L.sort(key=lambda item:item[1].index)\n return[f for(f,i)in L]\n \n @classmethod\n def _exitfunc(cls):\n \n \n \n reenable_gc=False\n try:\n if cls._registry:\n import gc\n if gc.isenabled():\n reenable_gc=True\n gc.disable()\n pending=None\n while True:\n if pending is None or finalize._dirty:\n pending=cls._select_for_exit()\n finalize._dirty=False\n if not pending:\n break\n f=pending.pop()\n try:\n \n \n \n \n f()\n except Exception:\n sys.excepthook(*sys.exc_info())\n assert f not in cls._registry\n finally:\n \n finalize._shutdown=True\n if reenable_gc:\n gc.enable()\n", ["_collections_abc", "_weakref", "_weakrefset", "atexit", "copy", "gc", "itertools", "sys"]], "webbrowser": [".py", "\n\nfrom browser import window\n\ndef open(url,new=0,autoraise=True):\n window.open(url)\n \ndef open_new(url):\n return window.open(url,\"_blank\")\n \ndef open_new_tab(url):\n return open(url)\n \n", ["browser"]], "zipfile": [".py", "''\n\n\n\n\nimport binascii\nimport importlib.util\nimport io\nimport itertools\nimport os\nimport posixpath\nimport shutil\nimport stat\nimport struct\nimport sys\nimport threading\nimport time\nimport contextlib\nimport pathlib\n\ntry:\n import zlib\n crc32=zlib.crc32\nexcept ImportError:\n zlib=None\n crc32=binascii.crc32\n \ntry:\n import bz2\nexcept ImportError:\n bz2=None\n \ntry:\n import lzma\nexcept ImportError:\n lzma=None\n \n__all__=[\"BadZipFile\",\"BadZipfile\",\"error\",\n\"ZIP_STORED\",\"ZIP_DEFLATED\",\"ZIP_BZIP2\",\"ZIP_LZMA\",\n\"is_zipfile\",\"ZipInfo\",\"ZipFile\",\"PyZipFile\",\"LargeZipFile\",\n\"Path\"]\n\nclass BadZipFile(Exception):\n pass\n \n \nclass LargeZipFile(Exception):\n ''\n\n\n \n \nerror=BadZipfile=BadZipFile\n\n\nZIP64_LIMIT=(1 <<31)-1\nZIP_FILECOUNT_LIMIT=(1 <<16)-1\nZIP_MAX_COMMENT=(1 <<16)-1\n\n\nZIP_STORED=0\nZIP_DEFLATED=8\nZIP_BZIP2=12\nZIP_LZMA=14\n\n\nDEFAULT_VERSION=20\nZIP64_VERSION=45\nBZIP2_VERSION=46\nLZMA_VERSION=63\n\nMAX_EXTRACT_VERSION=63\n\n\n\n\n\n\n\n\n\nstructEndArchive=b\"<4s4H2LH\"\nstringEndArchive=b\"PK\\005\\006\"\nsizeEndCentDir=struct.calcsize(structEndArchive)\n\n_ECD_SIGNATURE=0\n_ECD_DISK_NUMBER=1\n_ECD_DISK_START=2\n_ECD_ENTRIES_THIS_DISK=3\n_ECD_ENTRIES_TOTAL=4\n_ECD_SIZE=5\n_ECD_OFFSET=6\n_ECD_COMMENT_SIZE=7\n\n\n_ECD_COMMENT=8\n_ECD_LOCATION=9\n\n\n\nstructCentralDir=\"<4s4B4HL2L5H2L\"\nstringCentralDir=b\"PK\\001\\002\"\nsizeCentralDir=struct.calcsize(structCentralDir)\n\n\n_CD_SIGNATURE=0\n_CD_CREATE_VERSION=1\n_CD_CREATE_SYSTEM=2\n_CD_EXTRACT_VERSION=3\n_CD_EXTRACT_SYSTEM=4\n_CD_FLAG_BITS=5\n_CD_COMPRESS_TYPE=6\n_CD_TIME=7\n_CD_DATE=8\n_CD_CRC=9\n_CD_COMPRESSED_SIZE=10\n_CD_UNCOMPRESSED_SIZE=11\n_CD_FILENAME_LENGTH=12\n_CD_EXTRA_FIELD_LENGTH=13\n_CD_COMMENT_LENGTH=14\n_CD_DISK_NUMBER_START=15\n_CD_INTERNAL_FILE_ATTRIBUTES=16\n_CD_EXTERNAL_FILE_ATTRIBUTES=17\n_CD_LOCAL_HEADER_OFFSET=18\n\n\n\n_MASK_ENCRYPTED=1 <<0\n\n_MASK_COMPRESS_OPTION_1=1 <<1\n\n\n\n\n_MASK_USE_DATA_DESCRIPTOR=1 <<3\n\n\n_MASK_COMPRESSED_PATCH=1 <<5\n_MASK_STRONG_ENCRYPTION=1 <<6\n\n\n\n\n_MASK_UTF_FILENAME=1 <<11\n\n\n\n\n\n\n\n\n\nstructFileHeader=\"<4s2B4HL2L2H\"\nstringFileHeader=b\"PK\\003\\004\"\nsizeFileHeader=struct.calcsize(structFileHeader)\n\n_FH_SIGNATURE=0\n_FH_EXTRACT_VERSION=1\n_FH_EXTRACT_SYSTEM=2\n_FH_GENERAL_PURPOSE_FLAG_BITS=3\n_FH_COMPRESSION_METHOD=4\n_FH_LAST_MOD_TIME=5\n_FH_LAST_MOD_DATE=6\n_FH_CRC=7\n_FH_COMPRESSED_SIZE=8\n_FH_UNCOMPRESSED_SIZE=9\n_FH_FILENAME_LENGTH=10\n_FH_EXTRA_FIELD_LENGTH=11\n\n\nstructEndArchive64Locator=\"<4sLQL\"\nstringEndArchive64Locator=b\"PK\\x06\\x07\"\nsizeEndCentDir64Locator=struct.calcsize(structEndArchive64Locator)\n\n\n\nstructEndArchive64=\"<4sQ2H2L4Q\"\nstringEndArchive64=b\"PK\\x06\\x06\"\nsizeEndCentDir64=struct.calcsize(structEndArchive64)\n\n_CD64_SIGNATURE=0\n_CD64_DIRECTORY_RECSIZE=1\n_CD64_CREATE_VERSION=2\n_CD64_EXTRACT_VERSION=3\n_CD64_DISK_NUMBER=4\n_CD64_DISK_NUMBER_START=5\n_CD64_NUMBER_ENTRIES_THIS_DISK=6\n_CD64_NUMBER_ENTRIES_TOTAL=7\n_CD64_DIRECTORY_SIZE=8\n_CD64_OFFSET_START_CENTDIR=9\n\n_DD_SIGNATURE=0x08074b50\n\n_EXTRA_FIELD_STRUCT=struct.Struct('1:\n raise BadZipFile(\"zipfiles that span multiple disks are not supported\")\n \n \n fpin.seek(offset -sizeEndCentDir64Locator -sizeEndCentDir64,2)\n data=fpin.read(sizeEndCentDir64)\n if len(data)!=sizeEndCentDir64:\n return endrec\n sig,sz,create_version,read_version,disk_num,disk_dir,\\\n dircount,dircount2,dirsize,diroffset=\\\n struct.unpack(structEndArchive64,data)\n if sig !=stringEndArchive64:\n return endrec\n \n \n endrec[_ECD_SIGNATURE]=sig\n endrec[_ECD_DISK_NUMBER]=disk_num\n endrec[_ECD_DISK_START]=disk_dir\n endrec[_ECD_ENTRIES_THIS_DISK]=dircount\n endrec[_ECD_ENTRIES_TOTAL]=dircount2\n endrec[_ECD_SIZE]=dirsize\n endrec[_ECD_OFFSET]=diroffset\n return endrec\n \n \ndef _EndRecData(fpin):\n ''\n\n\n \n \n \n fpin.seek(0,2)\n filesize=fpin.tell()\n \n \n \n \n try:\n fpin.seek(-sizeEndCentDir,2)\n except OSError:\n return None\n data=fpin.read()\n if(len(data)==sizeEndCentDir and\n data[0:4]==stringEndArchive and\n data[-2:]==b\"\\000\\000\"):\n \n endrec=struct.unpack(structEndArchive,data)\n endrec=list(endrec)\n \n \n endrec.append(b\"\")\n endrec.append(filesize -sizeEndCentDir)\n \n \n return _EndRecData64(fpin,-sizeEndCentDir,endrec)\n \n \n \n \n \n \n maxCommentStart=max(filesize -(1 <<16)-sizeEndCentDir,0)\n fpin.seek(maxCommentStart,0)\n data=fpin.read()\n start=data.rfind(stringEndArchive)\n if start >=0:\n \n recData=data[start:start+sizeEndCentDir]\n if len(recData)!=sizeEndCentDir:\n \n return None\n endrec=list(struct.unpack(structEndArchive,recData))\n commentSize=endrec[_ECD_COMMENT_SIZE]\n comment=data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]\n endrec.append(comment)\n endrec.append(maxCommentStart+start)\n \n \n return _EndRecData64(fpin,maxCommentStart+start -filesize,\n endrec)\n \n \n return None\n \n \nclass ZipInfo(object):\n ''\n \n __slots__=(\n 'orig_filename',\n 'filename',\n 'date_time',\n 'compress_type',\n '_compresslevel',\n 'comment',\n 'extra',\n 'create_system',\n 'create_version',\n 'extract_version',\n 'reserved',\n 'flag_bits',\n 'volume',\n 'internal_attr',\n 'external_attr',\n 'header_offset',\n 'CRC',\n 'compress_size',\n 'file_size',\n '_raw_time',\n )\n \n def __init__(self,filename=\"NoName\",date_time=(1980,1,1,0,0,0)):\n self.orig_filename=filename\n \n \n \n null_byte=filename.find(chr(0))\n if null_byte >=0:\n filename=filename[0:null_byte]\n \n \n \n if os.sep !=\"/\"and os.sep in filename:\n filename=filename.replace(os.sep,\"/\")\n \n self.filename=filename\n self.date_time=date_time\n \n if date_time[0]<1980:\n raise ValueError('ZIP does not support timestamps before 1980')\n \n \n self.compress_type=ZIP_STORED\n self._compresslevel=None\n self.comment=b\"\"\n self.extra=b\"\"\n if sys.platform =='win32':\n self.create_system=0\n else:\n \n self.create_system=3\n self.create_version=DEFAULT_VERSION\n self.extract_version=DEFAULT_VERSION\n self.reserved=0\n self.flag_bits=0\n self.volume=0\n self.internal_attr=0\n self.external_attr=0\n self.compress_size=0\n self.file_size=0\n \n \n \n \n def __repr__(self):\n result=['<%s filename=%r'%(self.__class__.__name__,self.filename)]\n if self.compress_type !=ZIP_STORED:\n result.append(' compress_type=%s'%\n compressor_names.get(self.compress_type,\n self.compress_type))\n hi=self.external_attr >>16\n lo=self.external_attr&0xFFFF\n if hi:\n result.append(' filemode=%r'%stat.filemode(hi))\n if lo:\n result.append(' external_attr=%#x'%lo)\n isdir=self.is_dir()\n if not isdir or self.file_size:\n result.append(' file_size=%r'%self.file_size)\n if((not isdir or self.compress_size)and\n (self.compress_type !=ZIP_STORED or\n self.file_size !=self.compress_size)):\n result.append(' compress_size=%r'%self.compress_size)\n result.append('>')\n return ''.join(result)\n \n def FileHeader(self,zip64=None):\n ''\n dt=self.date_time\n dosdate=(dt[0]-1980)<<9 |dt[1]<<5 |dt[2]\n dostime=dt[3]<<11 |dt[4]<<5 |(dt[5]//2)\n if self.flag_bits&_MASK_USE_DATA_DESCRIPTOR:\n \n CRC=compress_size=file_size=0\n else:\n CRC=self.CRC\n compress_size=self.compress_size\n file_size=self.file_size\n \n extra=self.extra\n \n min_version=0\n if zip64 is None:\n zip64=file_size >ZIP64_LIMIT or compress_size >ZIP64_LIMIT\n if zip64:\n fmt='ZIP64_LIMIT or compress_size >ZIP64_LIMIT:\n if not zip64:\n raise LargeZipFile(\"Filesize would require ZIP64 extensions\")\n \n \n file_size=0xffffffff\n compress_size=0xffffffff\n min_version=ZIP64_VERSION\n \n if self.compress_type ==ZIP_BZIP2:\n min_version=max(BZIP2_VERSION,min_version)\n elif self.compress_type ==ZIP_LZMA:\n min_version=max(LZMA_VERSION,min_version)\n \n self.extract_version=max(min_version,self.extract_version)\n self.create_version=max(min_version,self.create_version)\n filename,flag_bits=self._encodeFilenameFlags()\n header=struct.pack(structFileHeader,stringFileHeader,\n self.extract_version,self.reserved,flag_bits,\n self.compress_type,dostime,dosdate,CRC,\n compress_size,file_size,\n len(filename),len(extra))\n return header+filename+extra\n \n def _encodeFilenameFlags(self):\n try:\n return self.filename.encode('ascii'),self.flag_bits\n except UnicodeEncodeError:\n return self.filename.encode('utf-8'),self.flag_bits |_MASK_UTF_FILENAME\n \n def _decodeExtra(self):\n \n extra=self.extra\n unpack=struct.unpack\n while len(extra)>=4:\n tp,ln=unpack('len(extra):\n raise BadZipFile(\"Corrupt extra field %04x (size=%d)\"%(tp,ln))\n if tp ==0x0001:\n data=extra[4:ln+4]\n \n try:\n if self.file_size in(0xFFFF_FFFF_FFFF_FFFF,0xFFFF_FFFF):\n field=\"File size\"\n self.file_size,=unpack('2107:\n date_time=(2107,12,31,23,59,59)\n \n if arcname is None:\n arcname=filename\n arcname=os.path.normpath(os.path.splitdrive(arcname)[1])\n while arcname[0]in(os.sep,os.altsep):\n arcname=arcname[1:]\n if isdir:\n arcname +='/'\n zinfo=cls(arcname,date_time)\n zinfo.external_attr=(st.st_mode&0xFFFF)<<16\n if isdir:\n zinfo.file_size=0\n zinfo.external_attr |=0x10\n else:\n zinfo.file_size=st.st_size\n \n return zinfo\n \n def is_dir(self):\n ''\n return self.filename[-1]=='/'\n \n \n \n \n \n \n_crctable=None\ndef _gen_crc(crc):\n for j in range(8):\n if crc&1:\n crc=(crc >>1)^0xEDB88320\n else:\n crc >>=1\n return crc\n \n \n \n \n \n \n \n \n \ndef _ZipDecrypter(pwd):\n key0=305419896\n key1=591751049\n key2=878082192\n \n global _crctable\n if _crctable is None:\n _crctable=list(map(_gen_crc,range(256)))\n crctable=_crctable\n \n def crc32(ch,crc):\n ''\n return(crc >>8)^crctable[(crc ^ch)&0xFF]\n \n def update_keys(c):\n nonlocal key0,key1,key2\n key0=crc32(c,key0)\n key1=(key1+(key0&0xFF))&0xFFFFFFFF\n key1=(key1 *134775813+1)&0xFFFFFFFF\n key2=crc32(key1 >>24,key2)\n \n for p in pwd:\n update_keys(p)\n \n def decrypter(data):\n ''\n result=bytearray()\n append=result.append\n for c in data:\n k=key2 |2\n c ^=((k *(k ^1))>>8)&0xFF\n update_keys(c)\n append(c)\n return bytes(result)\n \n return decrypter\n \n \nclass LZMACompressor:\n\n def __init__(self):\n self._comp=None\n \n def _init(self):\n props=lzma._encode_filter_properties({'id':lzma.FILTER_LZMA1})\n self._comp=lzma.LZMACompressor(lzma.FORMAT_RAW,filters=[\n lzma._decode_filter_properties(lzma.FILTER_LZMA1,props)\n ])\n return struct.pack('>8)&0xff\n else:\n \n check_byte=(zipinfo.CRC >>24)&0xff\n h=self._init_decrypter()\n if h !=check_byte:\n raise RuntimeError(\"Bad password for file %r\"%zipinfo.orig_filename)\n \n \n def _init_decrypter(self):\n self._decrypter=_ZipDecrypter(self._pwd)\n \n \n \n \n \n header=self._fileobj.read(12)\n self._compress_left -=12\n return self._decrypter(header)[11]\n \n def __repr__(self):\n result=['<%s.%s'%(self.__class__.__module__,\n self.__class__.__qualname__)]\n if not self.closed:\n result.append(' name=%r mode=%r'%(self.name,self.mode))\n if self._compress_type !=ZIP_STORED:\n result.append(' compress_type=%s'%\n compressor_names.get(self._compress_type,\n self._compress_type))\n else:\n result.append(' [closed]')\n result.append('>')\n return ''.join(result)\n \n def readline(self,limit=-1):\n ''\n\n\n \n \n if limit <0:\n \n i=self._readbuffer.find(b'\\n',self._offset)+1\n if i >0:\n line=self._readbuffer[self._offset:i]\n self._offset=i\n return line\n \n return io.BufferedIOBase.readline(self,limit)\n \n def peek(self,n=1):\n ''\n if n >len(self._readbuffer)-self._offset:\n chunk=self.read(n)\n if len(chunk)>self._offset:\n self._readbuffer=chunk+self._readbuffer[self._offset:]\n self._offset=0\n else:\n self._offset -=len(chunk)\n \n \n return self._readbuffer[self._offset:self._offset+512]\n \n def readable(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file.\")\n return True\n \n def read(self,n=-1):\n ''\n\n \n if self.closed:\n raise ValueError(\"read from closed file.\")\n if n is None or n <0:\n buf=self._readbuffer[self._offset:]\n self._readbuffer=b''\n self._offset=0\n while not self._eof:\n buf +=self._read1(self.MAX_N)\n return buf\n \n end=n+self._offset\n if end 0 and not self._eof:\n data=self._read1(n)\n if n 0:\n while not self._eof:\n data=self._read1(n)\n if n len(data):\n data +=self._read2(n -len(data))\n else:\n data=self._read2(n)\n \n if self._compress_type ==ZIP_STORED:\n self._eof=self._compress_left <=0\n elif self._compress_type ==ZIP_DEFLATED:\n n=max(n,self.MIN_READ_SIZE)\n data=self._decompressor.decompress(data,n)\n self._eof=(self._decompressor.eof or\n self._compress_left <=0 and\n not self._decompressor.unconsumed_tail)\n if self._eof:\n data +=self._decompressor.flush()\n else:\n data=self._decompressor.decompress(data)\n self._eof=self._decompressor.eof or self._compress_left <=0\n \n data=data[:self._left]\n self._left -=len(data)\n if self._left <=0:\n self._eof=True\n self._update_crc(data)\n return data\n \n def _read2(self,n):\n if self._compress_left <=0:\n return b''\n \n n=max(n,self.MIN_READ_SIZE)\n n=min(n,self._compress_left)\n \n data=self._fileobj.read(n)\n self._compress_left -=len(data)\n if not data:\n raise EOFError\n \n if self._decrypter is not None:\n data=self._decrypter(data)\n return data\n \n def close(self):\n try:\n if self._close_fileobj:\n self._fileobj.close()\n finally:\n super().close()\n \n def seekable(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file.\")\n return self._seekable\n \n def seek(self,offset,whence=0):\n if self.closed:\n raise ValueError(\"seek on closed file.\")\n if not self._seekable:\n raise io.UnsupportedOperation(\"underlying stream is not seekable\")\n curr_pos=self.tell()\n if whence ==0:\n new_pos=offset\n elif whence ==1:\n new_pos=curr_pos+offset\n elif whence ==2:\n new_pos=self._orig_file_size+offset\n else:\n raise ValueError(\"whence must be os.SEEK_SET (0), \"\n \"os.SEEK_CUR (1), or os.SEEK_END (2)\")\n \n if new_pos >self._orig_file_size:\n new_pos=self._orig_file_size\n \n if new_pos <0:\n new_pos=0\n \n read_offset=new_pos -curr_pos\n buff_offset=read_offset+self._offset\n \n if buff_offset >=0 and buff_offset 0:\n read_len=min(self.MAX_SEEK_READ,read_offset)\n self.read(read_len)\n read_offset -=read_len\n \n return self.tell()\n \n def tell(self):\n if self.closed:\n raise ValueError(\"tell on closed file.\")\n if not self._seekable:\n raise io.UnsupportedOperation(\"underlying stream is not seekable\")\n filepos=self._orig_file_size -self._left -len(self._readbuffer)+self._offset\n return filepos\n \n \nclass _ZipWriteFile(io.BufferedIOBase):\n def __init__(self,zf,zinfo,zip64):\n self._zinfo=zinfo\n self._zip64=zip64\n self._zipfile=zf\n self._compressor=_get_compressor(zinfo.compress_type,\n zinfo._compresslevel)\n self._file_size=0\n self._compress_size=0\n self._crc=0\n \n @property\n def _fileobj(self):\n return self._zipfile.fp\n \n def writable(self):\n return True\n \n def write(self,data):\n if self.closed:\n raise ValueError('I/O operation on closed file.')\n \n \n if isinstance(data,(bytes,bytearray)):\n nbytes=len(data)\n else:\n data=memoryview(data)\n nbytes=data.nbytes\n self._file_size +=nbytes\n \n self._crc=crc32(data,self._crc)\n if self._compressor:\n data=self._compressor.compress(data)\n self._compress_size +=len(data)\n self._fileobj.write(data)\n return nbytes\n \n def close(self):\n if self.closed:\n return\n try:\n super().close()\n \n if self._compressor:\n buf=self._compressor.flush()\n self._compress_size +=len(buf)\n self._fileobj.write(buf)\n self._zinfo.compress_size=self._compress_size\n else:\n self._zinfo.compress_size=self._file_size\n self._zinfo.CRC=self._crc\n self._zinfo.file_size=self._file_size\n \n \n if self._zinfo.flag_bits&_MASK_USE_DATA_DESCRIPTOR:\n \n fmt='ZIP64_LIMIT:\n raise RuntimeError(\n 'File size unexpectedly exceeded ZIP64 limit')\n if self._compress_size >ZIP64_LIMIT:\n raise RuntimeError(\n 'Compressed size unexpectedly exceeded ZIP64 limit')\n \n \n \n \n self._zipfile.start_dir=self._fileobj.tell()\n self._fileobj.seek(self._zinfo.header_offset)\n self._fileobj.write(self._zinfo.FileHeader(self._zip64))\n self._fileobj.seek(self._zipfile.start_dir)\n \n \n self._zipfile.filelist.append(self._zinfo)\n self._zipfile.NameToInfo[self._zinfo.filename]=self._zinfo\n finally:\n self._zipfile._writing=False\n \n \n \nclass ZipFile:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n fp=None\n _windows_illegal_name_trans_table=None\n \n def __init__(self,file,mode=\"r\",compression=ZIP_STORED,allowZip64=True,\n compresslevel=None,*,strict_timestamps=True,metadata_encoding=None):\n ''\n \n if mode not in('r','w','x','a'):\n raise ValueError(\"ZipFile requires mode 'r', 'w', 'x', or 'a'\")\n \n _check_compression(compression)\n \n self._allowZip64=allowZip64\n self._didModify=False\n self.debug=0\n self.NameToInfo={}\n self.filelist=[]\n self.compression=compression\n self.compresslevel=compresslevel\n self.mode=mode\n self.pwd=None\n self._comment=b''\n self._strict_timestamps=strict_timestamps\n self.metadata_encoding=metadata_encoding\n \n \n if self.metadata_encoding and mode !='r':\n raise ValueError(\n \"metadata_encoding is only supported for reading files\")\n \n \n if isinstance(file,os.PathLike):\n file=os.fspath(file)\n if isinstance(file,str):\n \n self._filePassed=0\n self.filename=file\n modeDict={'r':'rb','w':'w+b','x':'x+b','a':'r+b',\n 'r+b':'w+b','w+b':'wb','x+b':'xb'}\n filemode=modeDict[mode]\n while True:\n try:\n self.fp=io.open(file,filemode)\n except OSError:\n if filemode in modeDict:\n filemode=modeDict[filemode]\n continue\n raise\n break\n else:\n self._filePassed=1\n self.fp=file\n self.filename=getattr(file,'name',None)\n self._fileRefCnt=1\n self._lock=threading.RLock()\n self._seekable=True\n self._writing=False\n \n try:\n if mode =='r':\n self._RealGetContents()\n elif mode in('w','x'):\n \n \n self._didModify=True\n try:\n self.start_dir=self.fp.tell()\n except(AttributeError,OSError):\n self.fp=_Tellable(self.fp)\n self.start_dir=0\n self._seekable=False\n else:\n \n try:\n self.fp.seek(self.start_dir)\n except(AttributeError,OSError):\n self._seekable=False\n elif mode =='a':\n try:\n \n self._RealGetContents()\n \n self.fp.seek(self.start_dir)\n except BadZipFile:\n \n self.fp.seek(0,2)\n \n \n \n self._didModify=True\n self.start_dir=self.fp.tell()\n else:\n raise ValueError(\"Mode must be 'r', 'w', 'x', or 'a'\")\n except:\n fp=self.fp\n self.fp=None\n self._fpclose(fp)\n raise\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,traceback):\n self.close()\n \n def __repr__(self):\n result=['<%s.%s'%(self.__class__.__module__,\n self.__class__.__qualname__)]\n if self.fp is not None:\n if self._filePassed:\n result.append(' file=%r'%self.fp)\n elif self.filename is not None:\n result.append(' filename=%r'%self.filename)\n result.append(' mode=%r'%self.mode)\n else:\n result.append(' [closed]')\n result.append('>')\n return ''.join(result)\n \n def _RealGetContents(self):\n ''\n fp=self.fp\n try:\n endrec=_EndRecData(fp)\n except OSError:\n raise BadZipFile(\"File is not a zip file\")\n if not endrec:\n raise BadZipFile(\"File is not a zip file\")\n if self.debug >1:\n print(endrec)\n size_cd=endrec[_ECD_SIZE]\n offset_cd=endrec[_ECD_OFFSET]\n self._comment=endrec[_ECD_COMMENT]\n \n \n concat=endrec[_ECD_LOCATION]-size_cd -offset_cd\n if endrec[_ECD_SIGNATURE]==stringEndArchive64:\n \n concat -=(sizeEndCentDir64+sizeEndCentDir64Locator)\n \n if self.debug >2:\n inferred=concat+offset_cd\n print(\"given, inferred, offset\",offset_cd,inferred,concat)\n \n self.start_dir=offset_cd+concat\n if self.start_dir <0:\n raise BadZipFile(\"Bad offset for central directory\")\n fp.seek(self.start_dir,0)\n data=fp.read(size_cd)\n fp=io.BytesIO(data)\n total=0\n while total 2:\n print(centdir)\n filename=fp.read(centdir[_CD_FILENAME_LENGTH])\n flags=centdir[_CD_FLAG_BITS]\n if flags&_MASK_UTF_FILENAME:\n \n filename=filename.decode('utf-8')\n else:\n \n filename=filename.decode(self.metadata_encoding or 'cp437')\n \n x=ZipInfo(filename)\n x.extra=fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])\n x.comment=fp.read(centdir[_CD_COMMENT_LENGTH])\n x.header_offset=centdir[_CD_LOCAL_HEADER_OFFSET]\n (x.create_version,x.create_system,x.extract_version,x.reserved,\n x.flag_bits,x.compress_type,t,d,\n x.CRC,x.compress_size,x.file_size)=centdir[1:12]\n if x.extract_version >MAX_EXTRACT_VERSION:\n raise NotImplementedError(\"zip file version %.1f\"%\n (x.extract_version /10))\n x.volume,x.internal_attr,x.external_attr=centdir[15:18]\n \n x._raw_time=t\n x.date_time=((d >>9)+1980,(d >>5)&0xF,d&0x1F,\n t >>11,(t >>5)&0x3F,(t&0x1F)*2)\n \n x._decodeExtra()\n x.header_offset=x.header_offset+concat\n self.filelist.append(x)\n self.NameToInfo[x.filename]=x\n \n \n total=(total+sizeCentralDir+centdir[_CD_FILENAME_LENGTH]\n +centdir[_CD_EXTRA_FIELD_LENGTH]\n +centdir[_CD_COMMENT_LENGTH])\n \n if self.debug >2:\n print(\"total\",total)\n \n \n def namelist(self):\n ''\n return[data.filename for data in self.filelist]\n \n def infolist(self):\n ''\n \n return self.filelist\n \n def printdir(self,file=None):\n ''\n print(\"%-46s %19s %12s\"%(\"File Name\",\"Modified \",\"Size\"),\n file=file)\n for zinfo in self.filelist:\n date=\"%d-%02d-%02d %02d:%02d:%02d\"%zinfo.date_time[:6]\n print(\"%-46s %s %12d\"%(zinfo.filename,date,zinfo.file_size),\n file=file)\n \n def testzip(self):\n ''\n chunk_size=2 **20\n for zinfo in self.filelist:\n try:\n \n \n with self.open(zinfo.filename,\"r\")as f:\n while f.read(chunk_size):\n pass\n except BadZipFile:\n return zinfo.filename\n \n def getinfo(self,name):\n ''\n info=self.NameToInfo.get(name)\n if info is None:\n raise KeyError(\n 'There is no item named %r in the archive'%name)\n \n return info\n \n def setpassword(self,pwd):\n ''\n if pwd and not isinstance(pwd,bytes):\n raise TypeError(\"pwd: expected bytes, got %s\"%type(pwd).__name__)\n if pwd:\n self.pwd=pwd\n else:\n self.pwd=None\n \n @property\n def comment(self):\n ''\n return self._comment\n \n @comment.setter\n def comment(self,comment):\n if not isinstance(comment,bytes):\n raise TypeError(\"comment: expected bytes, got %s\"%type(comment).__name__)\n \n if len(comment)>ZIP_MAX_COMMENT:\n import warnings\n warnings.warn('Archive comment is too long; truncating to %d bytes'\n %ZIP_MAX_COMMENT,stacklevel=2)\n comment=comment[:ZIP_MAX_COMMENT]\n self._comment=comment\n self._didModify=True\n \n def read(self,name,pwd=None):\n ''\n with self.open(name,\"r\",pwd)as fp:\n return fp.read()\n \n def open(self,name,mode=\"r\",pwd=None,*,force_zip64=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if mode not in{\"r\",\"w\"}:\n raise ValueError('open() requires mode \"r\" or \"w\"')\n if pwd and(mode ==\"w\"):\n raise ValueError(\"pwd is only supported for reading files\")\n if not self.fp:\n raise ValueError(\n \"Attempt to use ZIP archive that was already closed\")\n \n \n if isinstance(name,ZipInfo):\n \n zinfo=name\n elif mode =='w':\n zinfo=ZipInfo(name)\n zinfo.compress_type=self.compression\n zinfo._compresslevel=self.compresslevel\n else:\n \n zinfo=self.getinfo(name)\n \n if mode =='w':\n return self._open_to_write(zinfo,force_zip64=force_zip64)\n \n if self._writing:\n raise ValueError(\"Can't read from the ZIP file while there \"\n \"is an open writing handle on it. \"\n \"Close the writing handle before trying to read.\")\n \n \n self._fileRefCnt +=1\n zef_file=_SharedFile(self.fp,zinfo.header_offset,\n self._fpclose,self._lock,lambda:self._writing)\n try:\n \n fheader=zef_file.read(sizeFileHeader)\n if len(fheader)!=sizeFileHeader:\n raise BadZipFile(\"Truncated file header\")\n fheader=struct.unpack(structFileHeader,fheader)\n if fheader[_FH_SIGNATURE]!=stringFileHeader:\n raise BadZipFile(\"Bad magic number for file header\")\n \n fname=zef_file.read(fheader[_FH_FILENAME_LENGTH])\n if fheader[_FH_EXTRA_FIELD_LENGTH]:\n zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])\n \n if zinfo.flag_bits&_MASK_COMPRESSED_PATCH:\n \n raise NotImplementedError(\"compressed patched data (flag bit 5)\")\n \n if zinfo.flag_bits&_MASK_STRONG_ENCRYPTION:\n \n raise NotImplementedError(\"strong encryption (flag bit 6)\")\n \n if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS]&_MASK_UTF_FILENAME:\n \n fname_str=fname.decode(\"utf-8\")\n else:\n fname_str=fname.decode(self.metadata_encoding or \"cp437\")\n \n if fname_str !=zinfo.orig_filename:\n raise BadZipFile(\n 'File name in directory %r and header %r differ.'\n %(zinfo.orig_filename,fname))\n \n \n is_encrypted=zinfo.flag_bits&_MASK_ENCRYPTED\n if is_encrypted:\n if not pwd:\n pwd=self.pwd\n if pwd and not isinstance(pwd,bytes):\n raise TypeError(\"pwd: expected bytes, got %s\"%type(pwd).__name__)\n if not pwd:\n raise RuntimeError(\"File %r is encrypted, password \"\n \"required for extraction\"%name)\n else:\n pwd=None\n \n return ZipExtFile(zef_file,mode,zinfo,pwd,True)\n except:\n zef_file.close()\n raise\n \n def _open_to_write(self,zinfo,force_zip64=False):\n if force_zip64 and not self._allowZip64:\n raise ValueError(\n \"force_zip64 is True, but allowZip64 was False when opening \"\n \"the ZIP file.\"\n )\n if self._writing:\n raise ValueError(\"Can't write to the ZIP file while there is \"\n \"another write handle open on it. \"\n \"Close the first handle before opening another.\")\n \n \n zinfo.compress_size=0\n zinfo.CRC=0\n \n zinfo.flag_bits=0x00\n if zinfo.compress_type ==ZIP_LZMA:\n \n zinfo.flag_bits |=_MASK_COMPRESS_OPTION_1\n if not self._seekable:\n zinfo.flag_bits |=_MASK_USE_DATA_DESCRIPTOR\n \n if not zinfo.external_attr:\n zinfo.external_attr=0o600 <<16\n \n \n zip64=self._allowZip64 and\\\n (force_zip64 or zinfo.file_size *1.05 >ZIP64_LIMIT)\n \n if self._seekable:\n self.fp.seek(self.start_dir)\n zinfo.header_offset=self.fp.tell()\n \n self._writecheck(zinfo)\n self._didModify=True\n \n self.fp.write(zinfo.FileHeader(zip64))\n \n self._writing=True\n return _ZipWriteFile(self,zinfo,zip64)\n \n def extract(self,member,path=None,pwd=None):\n ''\n\n\n\n \n if path is None:\n path=os.getcwd()\n else:\n path=os.fspath(path)\n \n return self._extract_member(member,path,pwd)\n \n def extractall(self,path=None,members=None,pwd=None):\n ''\n\n\n\n \n if members is None:\n members=self.namelist()\n \n if path is None:\n path=os.getcwd()\n else:\n path=os.fspath(path)\n \n for zipinfo in members:\n self._extract_member(zipinfo,path,pwd)\n \n @classmethod\n def _sanitize_windows_name(cls,arcname,pathsep):\n ''\n table=cls._windows_illegal_name_trans_table\n if not table:\n illegal=':<>|\"?*'\n table=str.maketrans(illegal,'_'*len(illegal))\n cls._windows_illegal_name_trans_table=table\n arcname=arcname.translate(table)\n \n arcname=(x.rstrip('.')for x in arcname.split(pathsep))\n \n arcname=pathsep.join(x for x in arcname if x)\n return arcname\n \n def _extract_member(self,member,targetpath,pwd):\n ''\n\n \n if not isinstance(member,ZipInfo):\n member=self.getinfo(member)\n \n \n \n arcname=member.filename.replace('/',os.path.sep)\n \n if os.path.altsep:\n arcname=arcname.replace(os.path.altsep,os.path.sep)\n \n \n arcname=os.path.splitdrive(arcname)[1]\n invalid_path_parts=('',os.path.curdir,os.path.pardir)\n arcname=os.path.sep.join(x for x in arcname.split(os.path.sep)\n if x not in invalid_path_parts)\n if os.path.sep =='\\\\':\n \n arcname=self._sanitize_windows_name(arcname,os.path.sep)\n \n targetpath=os.path.join(targetpath,arcname)\n targetpath=os.path.normpath(targetpath)\n \n \n upperdirs=os.path.dirname(targetpath)\n if upperdirs and not os.path.exists(upperdirs):\n os.makedirs(upperdirs)\n \n if member.is_dir():\n if not os.path.isdir(targetpath):\n os.mkdir(targetpath)\n return targetpath\n \n with self.open(member,pwd=pwd)as source,\\\n open(targetpath,\"wb\")as target:\n shutil.copyfileobj(source,target)\n \n return targetpath\n \n def _writecheck(self,zinfo):\n ''\n if zinfo.filename in self.NameToInfo:\n import warnings\n warnings.warn('Duplicate name: %r'%zinfo.filename,stacklevel=3)\n if self.mode not in('w','x','a'):\n raise ValueError(\"write() requires mode 'w', 'x', or 'a'\")\n if not self.fp:\n raise ValueError(\n \"Attempt to write ZIP archive that was already closed\")\n _check_compression(zinfo.compress_type)\n if not self._allowZip64:\n requires_zip64=None\n if len(self.filelist)>=ZIP_FILECOUNT_LIMIT:\n requires_zip64=\"Files count\"\n elif zinfo.file_size >ZIP64_LIMIT:\n requires_zip64=\"Filesize\"\n elif zinfo.header_offset >ZIP64_LIMIT:\n requires_zip64=\"Zipfile size\"\n if requires_zip64:\n raise LargeZipFile(requires_zip64+\n \" would require ZIP64 extensions\")\n \n def write(self,filename,arcname=None,\n compress_type=None,compresslevel=None):\n ''\n \n if not self.fp:\n raise ValueError(\n \"Attempt to write to ZIP archive that was already closed\")\n if self._writing:\n raise ValueError(\n \"Can't write to ZIP archive while an open writing handle exists\"\n )\n \n zinfo=ZipInfo.from_file(filename,arcname,\n strict_timestamps=self._strict_timestamps)\n \n if zinfo.is_dir():\n zinfo.compress_size=0\n zinfo.CRC=0\n self.mkdir(zinfo)\n else:\n if compress_type is not None:\n zinfo.compress_type=compress_type\n else:\n zinfo.compress_type=self.compression\n \n if compresslevel is not None:\n zinfo._compresslevel=compresslevel\n else:\n zinfo._compresslevel=self.compresslevel\n \n with open(filename,\"rb\")as src,self.open(zinfo,'w')as dest:\n shutil.copyfileobj(src,dest,1024 *8)\n \n def writestr(self,zinfo_or_arcname,data,\n compress_type=None,compresslevel=None):\n ''\n\n\n\n \n if isinstance(data,str):\n data=data.encode(\"utf-8\")\n if not isinstance(zinfo_or_arcname,ZipInfo):\n zinfo=ZipInfo(filename=zinfo_or_arcname,\n date_time=time.localtime(time.time())[:6])\n zinfo.compress_type=self.compression\n zinfo._compresslevel=self.compresslevel\n if zinfo.filename[-1]=='/':\n zinfo.external_attr=0o40775 <<16\n zinfo.external_attr |=0x10\n else:\n zinfo.external_attr=0o600 <<16\n else:\n zinfo=zinfo_or_arcname\n \n if not self.fp:\n raise ValueError(\n \"Attempt to write to ZIP archive that was already closed\")\n if self._writing:\n raise ValueError(\n \"Can't write to ZIP archive while an open writing handle exists.\"\n )\n \n if compress_type is not None:\n zinfo.compress_type=compress_type\n \n if compresslevel is not None:\n zinfo._compresslevel=compresslevel\n \n zinfo.file_size=len(data)\n with self._lock:\n with self.open(zinfo,mode='w')as dest:\n dest.write(data)\n \n def mkdir(self,zinfo_or_directory_name,mode=511):\n ''\n if isinstance(zinfo_or_directory_name,ZipInfo):\n zinfo=zinfo_or_directory_name\n if not zinfo.is_dir():\n raise ValueError(\"The given ZipInfo does not describe a directory\")\n elif isinstance(zinfo_or_directory_name,str):\n directory_name=zinfo_or_directory_name\n if not directory_name.endswith(\"/\"):\n directory_name +=\"/\"\n zinfo=ZipInfo(directory_name)\n zinfo.compress_size=0\n zinfo.CRC=0\n zinfo.external_attr=((0o40000 |mode)&0xFFFF)<<16\n zinfo.file_size=0\n zinfo.external_attr |=0x10\n else:\n raise TypeError(\"Expected type str or ZipInfo\")\n \n with self._lock:\n if self._seekable:\n self.fp.seek(self.start_dir)\n zinfo.header_offset=self.fp.tell()\n if zinfo.compress_type ==ZIP_LZMA:\n \n zinfo.flag_bits |=_MASK_COMPRESS_OPTION_1\n \n self._writecheck(zinfo)\n self._didModify=True\n \n self.filelist.append(zinfo)\n self.NameToInfo[zinfo.filename]=zinfo\n self.fp.write(zinfo.FileHeader(False))\n self.start_dir=self.fp.tell()\n \n def __del__(self):\n ''\n self.close()\n \n def close(self):\n ''\n \n if self.fp is None:\n return\n \n if self._writing:\n raise ValueError(\"Can't close the ZIP file while there is \"\n \"an open writing handle on it. \"\n \"Close the writing handle before closing the zip.\")\n \n try:\n if self.mode in('w','x','a')and self._didModify:\n with self._lock:\n if self._seekable:\n self.fp.seek(self.start_dir)\n self._write_end_record()\n finally:\n fp=self.fp\n self.fp=None\n self._fpclose(fp)\n \n def _write_end_record(self):\n for zinfo in self.filelist:\n dt=zinfo.date_time\n dosdate=(dt[0]-1980)<<9 |dt[1]<<5 |dt[2]\n dostime=dt[3]<<11 |dt[4]<<5 |(dt[5]//2)\n extra=[]\n if zinfo.file_size >ZIP64_LIMIT\\\n or zinfo.compress_size >ZIP64_LIMIT:\n extra.append(zinfo.file_size)\n extra.append(zinfo.compress_size)\n file_size=0xffffffff\n compress_size=0xffffffff\n else:\n file_size=zinfo.file_size\n compress_size=zinfo.compress_size\n \n if zinfo.header_offset >ZIP64_LIMIT:\n extra.append(zinfo.header_offset)\n header_offset=0xffffffff\n else:\n header_offset=zinfo.header_offset\n \n extra_data=zinfo.extra\n min_version=0\n if extra:\n \n extra_data=_strip_extra(extra_data,(1,))\n extra_data=struct.pack(\n 'ZIP_FILECOUNT_LIMIT:\n requires_zip64=\"Files count\"\n elif centDirOffset >ZIP64_LIMIT:\n requires_zip64=\"Central directory offset\"\n elif centDirSize >ZIP64_LIMIT:\n requires_zip64=\"Central directory size\"\n if requires_zip64:\n \n if not self._allowZip64:\n raise LargeZipFile(requires_zip64+\n \" would require ZIP64 extensions\")\n zip64endrec=struct.pack(\n structEndArchive64,stringEndArchive64,\n 44,45,45,0,0,centDirCount,centDirCount,\n centDirSize,centDirOffset)\n self.fp.write(zip64endrec)\n \n zip64locrec=struct.pack(\n structEndArchive64Locator,\n stringEndArchive64Locator,0,pos2,1)\n self.fp.write(zip64locrec)\n centDirCount=min(centDirCount,0xFFFF)\n centDirSize=min(centDirSize,0xFFFFFFFF)\n centDirOffset=min(centDirOffset,0xFFFFFFFF)\n \n endrec=struct.pack(structEndArchive,stringEndArchive,\n 0,0,centDirCount,centDirCount,\n centDirSize,centDirOffset,len(self._comment))\n self.fp.write(endrec)\n self.fp.write(self._comment)\n if self.mode ==\"a\":\n self.fp.truncate()\n self.fp.flush()\n \n def _fpclose(self,fp):\n assert self._fileRefCnt >0\n self._fileRefCnt -=1\n if not self._fileRefCnt and not self._filePassed:\n fp.close()\n \n \nclass PyZipFile(ZipFile):\n ''\n \n def __init__(self,file,mode=\"r\",compression=ZIP_STORED,\n allowZip64=True,optimize=-1):\n ZipFile.__init__(self,file,mode=mode,compression=compression,\n allowZip64=allowZip64)\n self._optimize=optimize\n \n def writepy(self,pathname,basename=\"\",filterfunc=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n pathname=os.fspath(pathname)\n if filterfunc and not filterfunc(pathname):\n if self.debug:\n label='path'if os.path.isdir(pathname)else 'file'\n print('%s %r skipped by filterfunc'%(label,pathname))\n return\n dir,name=os.path.split(pathname)\n if os.path.isdir(pathname):\n initname=os.path.join(pathname,\"__init__.py\")\n if os.path.isfile(initname):\n \n if basename:\n basename=\"%s/%s\"%(basename,name)\n else:\n basename=name\n if self.debug:\n print(\"Adding package in\",pathname,\"as\",basename)\n fname,arcname=self._get_codename(initname[0:-3],basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n dirlist=sorted(os.listdir(pathname))\n dirlist.remove(\"__init__.py\")\n \n for filename in dirlist:\n path=os.path.join(pathname,filename)\n root,ext=os.path.splitext(filename)\n if os.path.isdir(path):\n if os.path.isfile(os.path.join(path,\"__init__.py\")):\n \n self.writepy(path,basename,\n filterfunc=filterfunc)\n elif ext ==\".py\":\n if filterfunc and not filterfunc(path):\n if self.debug:\n print('file %r skipped by filterfunc'%path)\n continue\n fname,arcname=self._get_codename(path[0:-3],\n basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n else:\n \n if self.debug:\n print(\"Adding files from directory\",pathname)\n for filename in sorted(os.listdir(pathname)):\n path=os.path.join(pathname,filename)\n root,ext=os.path.splitext(filename)\n if ext ==\".py\":\n if filterfunc and not filterfunc(path):\n if self.debug:\n print('file %r skipped by filterfunc'%path)\n continue\n fname,arcname=self._get_codename(path[0:-3],\n basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n else:\n if pathname[-3:]!=\".py\":\n raise RuntimeError(\n 'Files added with writepy() must end with \".py\"')\n fname,arcname=self._get_codename(pathname[0:-3],basename)\n if self.debug:\n print(\"Adding file\",arcname)\n self.write(fname,arcname)\n \n def _get_codename(self,pathname,basename):\n ''\n\n\n\n\n \n def _compile(file,optimize=-1):\n import py_compile\n if self.debug:\n print(\"Compiling\",file)\n try:\n py_compile.compile(file,doraise=True,optimize=optimize)\n except py_compile.PyCompileError as err:\n print(err.msg)\n return False\n return True\n \n file_py=pathname+\".py\"\n file_pyc=pathname+\".pyc\"\n pycache_opt0=importlib.util.cache_from_source(file_py,optimization='')\n pycache_opt1=importlib.util.cache_from_source(file_py,optimization=1)\n pycache_opt2=importlib.util.cache_from_source(file_py,optimization=2)\n if self._optimize ==-1:\n \n if(os.path.isfile(file_pyc)and\n os.stat(file_pyc).st_mtime >=os.stat(file_py).st_mtime):\n \n arcname=fname=file_pyc\n elif(os.path.isfile(pycache_opt0)and\n os.stat(pycache_opt0).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt0\n arcname=file_pyc\n elif(os.path.isfile(pycache_opt1)and\n os.stat(pycache_opt1).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt1\n arcname=file_pyc\n elif(os.path.isfile(pycache_opt2)and\n os.stat(pycache_opt2).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt2\n arcname=file_pyc\n else:\n \n if _compile(file_py):\n if sys.flags.optimize ==0:\n fname=pycache_opt0\n elif sys.flags.optimize ==1:\n fname=pycache_opt1\n else:\n fname=pycache_opt2\n arcname=file_pyc\n else:\n fname=arcname=file_py\n else:\n \n if self._optimize ==0:\n fname=pycache_opt0\n arcname=file_pyc\n else:\n arcname=file_pyc\n if self._optimize ==1:\n fname=pycache_opt1\n elif self._optimize ==2:\n fname=pycache_opt2\n else:\n msg=\"invalid value for 'optimize': {!r}\".format(self._optimize)\n raise ValueError(msg)\n if not(os.path.isfile(fname)and\n os.stat(fname).st_mtime >=os.stat(file_py).st_mtime):\n if not _compile(file_py,optimize=self._optimize):\n fname=arcname=file_py\n archivename=os.path.split(arcname)[1]\n if basename:\n archivename=\"%s/%s\"%(basename,archivename)\n return(fname,archivename)\n \n \ndef _parents(path):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return itertools.islice(_ancestry(path),1,None)\n \n \ndef _ancestry(path):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n path=path.rstrip(posixpath.sep)\n while path and path !=posixpath.sep:\n yield path\n path,tail=posixpath.split(path)\n \n \n_dedupe=dict.fromkeys\n''\n\n\ndef _difference(minuend,subtrahend):\n ''\n\n\n \n return itertools.filterfalse(set(subtrahend).__contains__,minuend)\n \n \nclass CompleteDirs(ZipFile):\n ''\n\n\n \n \n @staticmethod\n def _implied_dirs(names):\n parents=itertools.chain.from_iterable(map(_parents,names))\n as_dirs=(p+posixpath.sep for p in parents)\n return _dedupe(_difference(as_dirs,names))\n \n def namelist(self):\n names=super(CompleteDirs,self).namelist()\n return names+list(self._implied_dirs(names))\n \n def _name_set(self):\n return set(self.namelist())\n \n def resolve_dir(self,name):\n ''\n\n\n \n names=self._name_set()\n dirname=name+'/'\n dir_match=name not in names and dirname in names\n return dirname if dir_match else name\n \n @classmethod\n def make(cls,source):\n ''\n\n\n \n if isinstance(source,CompleteDirs):\n return source\n \n if not isinstance(source,ZipFile):\n return cls(source)\n \n \n if 'r'not in source.mode:\n cls=CompleteDirs\n \n source.__class__=cls\n return source\n \n \nclass FastLookup(CompleteDirs):\n ''\n\n\n \n \n def namelist(self):\n with contextlib.suppress(AttributeError):\n return self.__names\n self.__names=super(FastLookup,self).namelist()\n return self.__names\n \n def _name_set(self):\n with contextlib.suppress(AttributeError):\n return self.__lookup\n self.__lookup=super(FastLookup,self)._name_set()\n return self.__lookup\n \n \nclass Path:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __repr=\"{self.__class__.__name__}({self.root.filename!r}, {self.at!r})\"\n \n def __init__(self,root,at=\"\"):\n ''\n\n\n\n\n\n\n\n \n self.root=FastLookup.make(root)\n self.at=at\n \n def open(self,mode='r',*args,pwd=None,**kwargs):\n ''\n\n\n\n \n if self.is_dir():\n raise IsADirectoryError(self)\n zip_mode=mode[0]\n if not self.exists()and zip_mode =='r':\n raise FileNotFoundError(self)\n stream=self.root.open(self.at,zip_mode,pwd=pwd)\n if 'b'in mode:\n if args or kwargs:\n raise ValueError(\"encoding args invalid for binary operation\")\n return stream\n else:\n kwargs[\"encoding\"]=io.text_encoding(kwargs.get(\"encoding\"))\n return io.TextIOWrapper(stream,*args,**kwargs)\n \n @property\n def name(self):\n return pathlib.Path(self.at).name or self.filename.name\n \n @property\n def suffix(self):\n return pathlib.Path(self.at).suffix or self.filename.suffix\n \n @property\n def suffixes(self):\n return pathlib.Path(self.at).suffixes or self.filename.suffixes\n \n @property\n def stem(self):\n return pathlib.Path(self.at).stem or self.filename.stem\n \n @property\n def filename(self):\n return pathlib.Path(self.root.filename).joinpath(self.at)\n \n def read_text(self,*args,**kwargs):\n kwargs[\"encoding\"]=io.text_encoding(kwargs.get(\"encoding\"))\n with self.open('r',*args,**kwargs)as strm:\n return strm.read()\n \n def read_bytes(self):\n with self.open('rb')as strm:\n return strm.read()\n \n def _is_child(self,path):\n return posixpath.dirname(path.at.rstrip(\"/\"))==self.at.rstrip(\"/\")\n \n def _next(self,at):\n return self.__class__(self.root,at)\n \n def is_dir(self):\n return not self.at or self.at.endswith(\"/\")\n \n def is_file(self):\n return self.exists()and not self.is_dir()\n \n def exists(self):\n return self.at in self.root._name_set()\n \n def iterdir(self):\n if not self.is_dir():\n raise ValueError(\"Can't listdir a file\")\n subs=map(self._next,self.root.namelist())\n return filter(self._is_child,subs)\n \n def __str__(self):\n return posixpath.join(self.root.filename,self.at)\n \n def __repr__(self):\n return self.__repr.format(self=self)\n \n def joinpath(self,*other):\n next=posixpath.join(self.at,*other)\n return self._next(self.root.resolve_dir(next))\n \n __truediv__=joinpath\n \n @property\n def parent(self):\n if not self.at:\n return self.filename.parent\n parent_at=posixpath.dirname(self.at.rstrip('/'))\n if parent_at:\n parent_at +='/'\n return self._next(parent_at)\n \n \ndef main(args=None):\n import argparse\n \n description='A simple command-line interface for zipfile module.'\n parser=argparse.ArgumentParser(description=description)\n group=parser.add_mutually_exclusive_group(required=True)\n group.add_argument('-l','--list',metavar='',\n help='Show listing of a zipfile')\n group.add_argument('-e','--extract',nargs=2,\n metavar=('',''),\n help='Extract zipfile into target dir')\n group.add_argument('-c','--create',nargs='+',\n metavar=('',''),\n help='Create zipfile from sources')\n group.add_argument('-t','--test',metavar='',\n help='Test if a zipfile is valid')\n parser.add_argument('--metadata-encoding',metavar='',\n help='Specify encoding of member names for -l, -e and -t')\n args=parser.parse_args(args)\n \n encoding=args.metadata_encoding\n \n if args.test is not None:\n src=args.test\n with ZipFile(src,'r',metadata_encoding=encoding)as zf:\n badfile=zf.testzip()\n if badfile:\n print(\"The following enclosed file is corrupted: {!r}\".format(badfile))\n print(\"Done testing\")\n \n elif args.list is not None:\n src=args.list\n with ZipFile(src,'r',metadata_encoding=encoding)as zf:\n zf.printdir()\n \n elif args.extract is not None:\n src,curdir=args.extract\n with ZipFile(src,'r',metadata_encoding=encoding)as zf:\n zf.extractall(curdir)\n \n elif args.create is not None:\n if encoding:\n print(\"Non-conforming encodings not supported with -c.\",\n file=sys.stderr)\n sys.exit(1)\n \n zip_name=args.create.pop(0)\n files=args.create\n \n def addToZip(zf,path,zippath):\n if os.path.isfile(path):\n zf.write(path,zippath,ZIP_DEFLATED)\n elif os.path.isdir(path):\n if zippath:\n zf.write(path,zippath)\n for nm in sorted(os.listdir(path)):\n addToZip(zf,\n os.path.join(path,nm),os.path.join(zippath,nm))\n \n \n with ZipFile(zip_name,'w')as zf:\n for path in files:\n zippath=os.path.basename(path)\n if not zippath:\n zippath=os.path.basename(os.path.dirname(path))\n if zippath in('',os.curdir,os.pardir):\n zippath=''\n addToZip(zf,path,zippath)\n \n \nif __name__ ==\"__main__\":\n main()\n", ["argparse", "binascii", "bz2", "contextlib", "importlib.util", "io", "itertools", "lzma", "os", "pathlib", "posixpath", "py_compile", "shutil", "stat", "struct", "sys", "threading", "time", "warnings", "zlib"]], "zipimport": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport _frozen_importlib_external as _bootstrap_external\nfrom _frozen_importlib_external import _unpack_uint16,_unpack_uint32,_unpack_uint64\nimport _frozen_importlib as _bootstrap\nimport _imp\nimport _io\nimport marshal\nimport sys\nimport time\nimport _warnings\n\n__all__=['ZipImportError','zipimporter']\n\n\npath_sep=_bootstrap_external.path_sep\nalt_path_sep=_bootstrap_external.path_separators[1:]\n\n\nclass ZipImportError(ImportError):\n pass\n \n \n_zip_directory_cache={}\n\n_module_type=type(sys)\n\nEND_CENTRAL_DIR_SIZE=22\nEND_CENTRAL_DIR_SIZE_64=56\nEND_CENTRAL_DIR_LOCATOR_SIZE_64=20\nSTRING_END_ARCHIVE=b'PK\\x05\\x06'\nSTRING_END_LOCATOR_64=b'PK\\x06\\x07'\nSTRING_END_ZIP_64=b'PK\\x06\\x06'\nMAX_COMMENT_LEN=(1 <<16)-1\nMAX_UINT32=0xffffffff\nZIP64_EXTRA_TAG=0x1\n\nclass zipimporter(_bootstrap_external._LoaderBasics):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n def __init__(self,path):\n if not isinstance(path,str):\n raise TypeError(f\"expected str, not {type(path)!r}\")\n if not path:\n raise ZipImportError('archive path is empty',path=path)\n if alt_path_sep:\n path=path.replace(alt_path_sep,path_sep)\n \n prefix=[]\n while True:\n try:\n st=_bootstrap_external._path_stat(path)\n except(OSError,ValueError):\n \n \n dirname,basename=_bootstrap_external._path_split(path)\n if dirname ==path:\n raise ZipImportError('not a Zip file',path=path)\n path=dirname\n prefix.append(basename)\n else:\n \n if(st.st_mode&0o170000)!=0o100000:\n \n raise ZipImportError('not a Zip file',path=path)\n break\n \n if path not in _zip_directory_cache:\n _zip_directory_cache[path]=_read_directory(path)\n self.archive=path\n \n self.prefix=_bootstrap_external._path_join(*prefix[::-1])\n if self.prefix:\n self.prefix +=path_sep\n \n \n def find_spec(self,fullname,target=None):\n ''\n\n\n \n module_info=_get_module_info(self,fullname)\n if module_info is not None:\n return _bootstrap.spec_from_loader(fullname,self,is_package=module_info)\n else:\n \n \n \n \n \n modpath=_get_module_path(self,fullname)\n if _is_dir(self,modpath):\n \n \n \n path=f'{self.archive}{path_sep}{modpath}'\n spec=_bootstrap.ModuleSpec(name=fullname,loader=None,\n is_package=True)\n spec.submodule_search_locations.append(path)\n return spec\n else:\n return None\n \n def get_code(self,fullname):\n ''\n\n\n\n \n code,ispackage,modpath=_get_module_code(self,fullname)\n return code\n \n \n def get_data(self,pathname):\n ''\n\n\n\n \n if alt_path_sep:\n pathname=pathname.replace(alt_path_sep,path_sep)\n \n key=pathname\n if pathname.startswith(self.archive+path_sep):\n key=pathname[len(self.archive+path_sep):]\n \n try:\n toc_entry=self._get_files()[key]\n except KeyError:\n raise OSError(0,'',key)\n return _get_data(self.archive,toc_entry)\n \n \n \n def get_filename(self,fullname):\n ''\n\n\n\n \n \n \n code,ispackage,modpath=_get_module_code(self,fullname)\n return modpath\n \n \n def get_source(self,fullname):\n ''\n\n\n\n\n \n mi=_get_module_info(self,fullname)\n if mi is None:\n raise ZipImportError(f\"can't find module {fullname !r}\",name=fullname)\n \n path=_get_module_path(self,fullname)\n if mi:\n fullpath=_bootstrap_external._path_join(path,'__init__.py')\n else:\n fullpath=f'{path}.py'\n \n try:\n toc_entry=self._get_files()[fullpath]\n except KeyError:\n \n return None\n return _get_data(self.archive,toc_entry).decode()\n \n \n \n def is_package(self,fullname):\n ''\n\n\n\n \n mi=_get_module_info(self,fullname)\n if mi is None:\n raise ZipImportError(f\"can't find module {fullname !r}\",name=fullname)\n return mi\n \n \n \n def load_module(self,fullname):\n ''\n\n\n\n\n\n\n \n msg=(\"zipimport.zipimporter.load_module() is deprecated and slated for \"\n \"removal in Python 3.12; use exec_module() instead\")\n _warnings.warn(msg,DeprecationWarning)\n code,ispackage,modpath=_get_module_code(self,fullname)\n mod=sys.modules.get(fullname)\n if mod is None or not isinstance(mod,_module_type):\n mod=_module_type(fullname)\n sys.modules[fullname]=mod\n mod.__loader__=self\n \n try:\n if ispackage:\n \n \n path=_get_module_path(self,fullname)\n fullpath=_bootstrap_external._path_join(self.archive,path)\n mod.__path__=[fullpath]\n \n if not hasattr(mod,'__builtins__'):\n mod.__builtins__=__builtins__\n _bootstrap_external._fix_up_module(mod.__dict__,fullname,modpath)\n exec(code,mod.__dict__)\n except:\n del sys.modules[fullname]\n raise\n \n try:\n mod=sys.modules[fullname]\n except KeyError:\n raise ImportError(f'Loaded module {fullname !r} not found in sys.modules')\n _bootstrap._verbose_message('import {} # loaded from Zip {}',fullname,modpath)\n return mod\n \n \n def get_resource_reader(self,fullname):\n ''\n\n\n\n \n try:\n if not self.is_package(fullname):\n return None\n except ZipImportError:\n return None\n from importlib.readers import ZipReader\n return ZipReader(self,fullname)\n \n \n def _get_files(self):\n ''\n try:\n files=_zip_directory_cache[self.archive]\n except KeyError:\n try:\n files=_zip_directory_cache[self.archive]=_read_directory(self.archive)\n except ZipImportError:\n files={}\n \n return files\n \n \n def invalidate_caches(self):\n ''\n _zip_directory_cache.pop(self.archive,None)\n \n \n def __repr__(self):\n return f''\n \n \n \n \n \n \n \n_zip_searchorder=(\n(path_sep+'__init__.pyc',True,True),\n(path_sep+'__init__.py',False,True),\n('.pyc',True,False),\n('.py',False,False),\n)\n\n\n\ndef _get_module_path(self,fullname):\n return self.prefix+fullname.rpartition('.')[2]\n \n \ndef _is_dir(self,path):\n\n\n\n dirpath=path+path_sep\n \n return dirpath in self._get_files()\n \n \ndef _get_module_info(self,fullname):\n path=_get_module_path(self,fullname)\n for suffix,isbytecode,ispackage in _zip_searchorder:\n fullpath=path+suffix\n if fullpath in self._get_files():\n return ispackage\n return None\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef _read_directory(archive):\n try:\n fp=_io.open_code(archive)\n except OSError:\n raise ZipImportError(f\"can't open Zip file: {archive !r}\",path=archive)\n \n with fp:\n \n \n \n start_offset=fp.tell()\n try:\n \n try:\n fp.seek(0,2)\n file_size=fp.tell()\n except OSError:\n raise ZipImportError(f\"can't read Zip file: {archive !r}\",\n path=archive)\n max_comment_plus_dirs_size=(\n MAX_COMMENT_LEN+END_CENTRAL_DIR_SIZE+\n END_CENTRAL_DIR_SIZE_64+END_CENTRAL_DIR_LOCATOR_SIZE_64)\n max_comment_start=max(file_size -max_comment_plus_dirs_size,0)\n try:\n fp.seek(max_comment_start)\n data=fp.read(max_comment_plus_dirs_size)\n except OSError:\n raise ZipImportError(f\"can't read Zip file: {archive !r}\",\n path=archive)\n pos=data.rfind(STRING_END_ARCHIVE)\n pos64=data.rfind(STRING_END_ZIP_64)\n \n if(pos64 >=0 and pos64+END_CENTRAL_DIR_SIZE_64+END_CENTRAL_DIR_LOCATOR_SIZE_64 ==pos):\n \n buffer=data[pos64:pos64+END_CENTRAL_DIR_SIZE_64]\n if len(buffer)!=END_CENTRAL_DIR_SIZE_64:\n raise ZipImportError(\n f\"corrupt Zip64 file: Expected {END_CENTRAL_DIR_SIZE_64} byte \"\n f\"zip64 central directory, but read {len(buffer)} bytes.\",\n path=archive)\n header_position=file_size -len(data)+pos64\n \n central_directory_size=_unpack_uint64(buffer[40:48])\n central_directory_position=_unpack_uint64(buffer[48:56])\n num_entries=_unpack_uint64(buffer[24:32])\n elif pos >=0:\n buffer=data[pos:pos+END_CENTRAL_DIR_SIZE]\n if len(buffer)!=END_CENTRAL_DIR_SIZE:\n raise ZipImportError(f\"corrupt Zip file: {archive !r}\",\n path=archive)\n \n header_position=file_size -len(data)+pos\n \n \n \n central_directory_size=_unpack_uint32(buffer[12:16])\n central_directory_position=_unpack_uint32(buffer[16:20])\n num_entries=_unpack_uint16(buffer[8:10])\n \n \n \n else:\n raise ZipImportError(f'not a Zip file: {archive !r}',\n path=archive)\n \n \n \n \n \n if header_position 3:\n raise ZipImportError(f\"can't read header extra: {archive !r}\",path=archive)\n import struct\n values=list(struct.unpack_from(f\"<{min(num_extra_values,3)}Q\",\n extra_data,offset=4))\n \n \n \n \n if file_size ==MAX_UINT32:\n file_size=values.pop(0)\n if data_size ==MAX_UINT32:\n data_size=values.pop(0)\n if file_offset ==MAX_UINT32:\n file_offset=values.pop(0)\n \n break\n \n \n \n extra_data=extra_data[4+size:]\n else:\n _bootstrap._verbose_message(\n \"zipimport: suspected zip64 but no zip64 extra for {!r}\",\n path,\n )\n \n \n \n \n \n if file_offset >central_directory_position:\n raise ZipImportError(f'bad local header offset: {archive !r}',path=archive)\n file_offset +=arc_offset\n \n t=(path,compress,data_size,file_size,file_offset,time,date,crc)\n files[name]=t\n count +=1\n finally:\n fp.seek(start_offset)\n _bootstrap._verbose_message('zipimport: found {} names in {!r}',count,archive)\n return files\n \n \n \n \n \n \n \ncp437_table=(\n\n'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f'\n'\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f'\n' !\"#$%&\\'()*+,-./'\n'0123456789:;<=>?'\n'@ABCDEFGHIJKLMNO'\n'PQRSTUVWXYZ[\\\\]^_'\n'`abcdefghijklmno'\n'pqrstuvwxyz{|}~\\x7f'\n\n'\\xc7\\xfc\\xe9\\xe2\\xe4\\xe0\\xe5\\xe7'\n'\\xea\\xeb\\xe8\\xef\\xee\\xec\\xc4\\xc5'\n'\\xc9\\xe6\\xc6\\xf4\\xf6\\xf2\\xfb\\xf9'\n'\\xff\\xd6\\xdc\\xa2\\xa3\\xa5\\u20a7\\u0192'\n'\\xe1\\xed\\xf3\\xfa\\xf1\\xd1\\xaa\\xba'\n'\\xbf\\u2310\\xac\\xbd\\xbc\\xa1\\xab\\xbb'\n'\\u2591\\u2592\\u2593\\u2502\\u2524\\u2561\\u2562\\u2556'\n'\\u2555\\u2563\\u2551\\u2557\\u255d\\u255c\\u255b\\u2510'\n'\\u2514\\u2534\\u252c\\u251c\\u2500\\u253c\\u255e\\u255f'\n'\\u255a\\u2554\\u2569\\u2566\\u2560\\u2550\\u256c\\u2567'\n'\\u2568\\u2564\\u2565\\u2559\\u2558\\u2552\\u2553\\u256b'\n'\\u256a\\u2518\\u250c\\u2588\\u2584\\u258c\\u2590\\u2580'\n'\\u03b1\\xdf\\u0393\\u03c0\\u03a3\\u03c3\\xb5\\u03c4'\n'\\u03a6\\u0398\\u03a9\\u03b4\\u221e\\u03c6\\u03b5\\u2229'\n'\\u2261\\xb1\\u2265\\u2264\\u2320\\u2321\\xf7\\u2248'\n'\\xb0\\u2219\\xb7\\u221a\\u207f\\xb2\\u25a0\\xa0'\n)\n\n_importing_zlib=False\n\n\n\n\ndef _get_decompress_func():\n global _importing_zlib\n if _importing_zlib:\n \n \n _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')\n raise ZipImportError(\"can't decompress data; zlib not available\")\n \n _importing_zlib=True\n try:\n from zlib import decompress\n except Exception:\n _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')\n raise ZipImportError(\"can't decompress data; zlib not available\")\n finally:\n _importing_zlib=False\n \n _bootstrap._verbose_message('zipimport: zlib available')\n return decompress\n \n \ndef _get_data(archive,toc_entry):\n datapath,compress,data_size,file_size,file_offset,time,date,crc=toc_entry\n if data_size <0:\n raise ZipImportError('negative data size')\n \n with _io.open_code(archive)as fp:\n \n try:\n fp.seek(file_offset)\n except OSError:\n raise ZipImportError(f\"can't read Zip file: {archive !r}\",path=archive)\n buffer=fp.read(30)\n if len(buffer)!=30:\n raise EOFError('EOF read where not expected')\n \n if buffer[:4]!=b'PK\\x03\\x04':\n \n raise ZipImportError(f'bad local file header: {archive !r}',path=archive)\n \n name_size=_unpack_uint16(buffer[26:28])\n extra_size=_unpack_uint16(buffer[28:30])\n header_size=30+name_size+extra_size\n file_offset +=header_size\n try:\n fp.seek(file_offset)\n except OSError:\n raise ZipImportError(f\"can't read Zip file: {archive !r}\",path=archive)\n raw_data=fp.read(data_size)\n if len(raw_data)!=data_size:\n raise OSError(\"zipimport: can't read data\")\n \n if compress ==0:\n \n return raw_data\n \n \n try:\n decompress=_get_decompress_func()\n except Exception:\n raise ZipImportError(\"can't decompress data; zlib not available\")\n return decompress(raw_data,-15)\n \n \n \n \n \ndef _eq_mtime(t1,t2):\n\n return abs(t1 -t2)<=1\n \n \n \n \n \ndef _unmarshal_code(self,pathname,fullpath,fullname,data):\n exc_details={\n 'name':fullname,\n 'path':fullpath,\n }\n \n flags=_bootstrap_external._classify_pyc(data,fullname,exc_details)\n \n hash_based=flags&0b1 !=0\n if hash_based:\n check_source=flags&0b10 !=0\n if(_imp.check_hash_based_pycs !='never'and\n (check_source or _imp.check_hash_based_pycs =='always')):\n source_bytes=_get_pyc_source(self,fullpath)\n if source_bytes is not None:\n source_hash=_imp.source_hash(\n _bootstrap_external._RAW_MAGIC_NUMBER,\n source_bytes,\n )\n \n _bootstrap_external._validate_hash_pyc(\n data,source_hash,fullname,exc_details)\n else:\n source_mtime,source_size=\\\n _get_mtime_and_size_of_source(self,fullpath)\n \n if source_mtime:\n \n \n if(not _eq_mtime(_unpack_uint32(data[8:12]),source_mtime)or\n _unpack_uint32(data[12:16])!=source_size):\n _bootstrap._verbose_message(\n f'bytecode is stale for {fullname !r}')\n return None\n \n code=marshal.loads(data[16:])\n if not isinstance(code,_code_type):\n raise TypeError(f'compiled module {pathname !r} is not a code object')\n return code\n \n_code_type=type(_unmarshal_code.__code__)\n\n\n\n\ndef _normalize_line_endings(source):\n source=source.replace(b'\\r\\n',b'\\n')\n source=source.replace(b'\\r',b'\\n')\n return source\n \n \n \ndef _compile_source(pathname,source):\n source=_normalize_line_endings(source)\n return compile(source,pathname,'exec',dont_inherit=True)\n \n \n \ndef _parse_dostime(d,t):\n return time.mktime((\n (d >>9)+1980,\n (d >>5)&0xF,\n d&0x1F,\n t >>11,\n (t >>5)&0x3F,\n (t&0x1F)*2,\n -1,-1,-1))\n \n \n \n \ndef _get_mtime_and_size_of_source(self,path):\n try:\n \n assert path[-1:]in('c','o')\n path=path[:-1]\n toc_entry=self._get_files()[path]\n \n \n time=toc_entry[5]\n date=toc_entry[6]\n uncompressed_size=toc_entry[3]\n return _parse_dostime(date,time),uncompressed_size\n except(KeyError,IndexError,TypeError):\n return 0,0\n \n \n \n \n \ndef _get_pyc_source(self,path):\n\n assert path[-1:]in('c','o')\n path=path[:-1]\n \n try:\n toc_entry=self._get_files()[path]\n except KeyError:\n return None\n else:\n return _get_data(self.archive,toc_entry)\n \n \n \n \ndef _get_module_code(self,fullname):\n path=_get_module_path(self,fullname)\n import_error=None\n for suffix,isbytecode,ispackage in _zip_searchorder:\n fullpath=path+suffix\n _bootstrap._verbose_message('trying {}{}{}',self.archive,path_sep,fullpath,verbosity=2)\n try:\n toc_entry=self._get_files()[fullpath]\n except KeyError:\n pass\n else:\n modpath=toc_entry[0]\n data=_get_data(self.archive,toc_entry)\n code=None\n if isbytecode:\n try:\n code=_unmarshal_code(self,modpath,fullpath,fullname,data)\n except ImportError as exc:\n import_error=exc\n else:\n code=_compile_source(modpath,data)\n if code is None:\n \n \n continue\n modpath=toc_entry[0]\n return code,ispackage,modpath\n else:\n if import_error:\n msg=f\"module load failed: {import_error}\"\n raise ZipImportError(msg,name=fullname)from import_error\n else:\n raise ZipImportError(f\"can't find module {fullname !r}\",name=fullname)\n", ["_frozen_importlib", "_frozen_importlib_external", "_imp", "_io", "_warnings", "importlib.readers", "marshal", "struct", "sys", "time", "zlib"]], "zlib": [".py", "''\n\n\n\nfrom _zlib_utils import lz_generator,crc32\n\nDEFLATED=8\nDEF_BUF_SIZE=16384\nDEF_MEM_LEVEL=8\nMAX_WBITS=15\nZLIB_RUNTIME_VERSION='1.2.11'\nZLIB_VERSION='1.2.11'\nZ_BEST_COMPRESSION=9\nZ_BEST_SPEED=1\nZ_BLOCK=5\nZ_DEFAULT_COMPRESSION=-1\nZ_DEFAULT_STRATEGY=0\nZ_FILTERED=1\nZ_FINISH=4\nZ_FIXED=4\nZ_FULL_FLUSH=3\nZ_HUFFMAN_ONLY=2\nZ_NO_COMPRESSION=0\nZ_NO_FLUSH=0\nZ_PARTIAL_FLUSH=1\nZ_RLE=3\nZ_SYNC_FLUSH=2\nZ_TREES=6\n\nclass BitIO:\n\n def __init__(self,bytestream=None):\n self.bytestream=bytearray(bytestream or[])\n self.bytenum=0\n self.bitnum=0\n self.revbits=0\n self.position=0\n self.bitcoef=1\n \n @property\n def pos(self):\n return self.bytenum *8+self.bitnum\n \n def read(self,nb,order=\"lsf\",trace=False):\n result=0\n coef=1 if order ==\"lsf\"else 2 **(nb -1)\n for _ in range(nb):\n if self.bitnum ==8:\n if self.bytenum ==len(self.bytestream)-1:\n return None\n self.bytenum +=1\n self.bitnum=0\n mask=2 **self.bitnum\n if trace:\n print(\"byte\",self.bytenum,\"bitnum\",self.bitnum,\n \"bit\",int(bool(mask&self.bytestream[self.bytenum])))\n result +=coef *bool(mask&self.bytestream[self.bytenum])\n self.bitnum +=1\n if order ==\"lsf\":\n coef *=2\n else:\n coef //=2\n return result\n \n def move(self,nb):\n if nb ==0:\n return\n elif nb >0:\n bitpos=self.bitnum+nb\n while bitpos >7:\n self.bytenum +=1\n if self.bytenum ==len(self.bytestream):\n raise Exception(\"can't move {} bits\".format(nb))\n bitpos -=8\n self.bitnum=bitpos\n else:\n bitpos=self.bitnum+nb\n while bitpos <0:\n self.bytenum -=1\n if self.bytenum ==-1:\n raise Exception(\"can't move {} bits\".format(nb))\n bitpos +=8\n self.bitnum=bitpos\n \n def show(self):\n res=\"\"\n for x in self.bytestream:\n s=str(bin(x))[2:]\n s=\"0\"*(8 -len(s))+s\n res +=s+\" \"\n return res\n \n def write(self,*bits):\n for bit in bits:\n self.write_bit(bit)\n \n def write_int(self,value,nb,order=\"lsf\"):\n ''\n v=value\n if value >=2 **nb:\n raise ValueError(\"can't write value on {} bits\".format(nb))\n bits=[]\n while value:\n bits.append(value&1)\n value >>=1\n \n bits=bits+[0]*(nb -len(bits))\n if order !=\"lsf\":\n bits.reverse()\n assert len(bits)==nb\n self.write(*bits)\n \n def write_bit(self,v):\n self.revbits +=self.bitcoef *v\n self.bitcoef *=2\n if self.bitcoef ==256:\n self.flush()\n \n def pad_last(self):\n if self.bitcoef !=1:\n self.flush()\n \n def flush(self):\n self.bytestream.append(self.revbits)\n self.bitcoef=1\n self.revbits=0\n \nclass Error(Exception):\n pass\n \n \nclass ResizeError(Exception):\n pass\n \n \nclass Node:\n\n def __init__(self,char=None,weight=0,level=0):\n self.char=char\n self.is_leaf=char is not None\n self.level=level\n self.weight=weight\n \n def add(self,children):\n self.children=children\n for child in self.children:\n child.parent=self\n child.level=self.level+1\n \n def __repr__(self):\n return f\"\"\n \nclass Tree:\n\n def __init__(self,root):\n self.root=root\n \n def length(self):\n self.root.level=0\n node=self.root\n nb_levels=0\n def set_level(node):\n nonlocal nb_levels\n for child in node.children:\n child.level=node.level+1\n nb_levels=max(nb_levels,child.level)\n if not child.is_leaf:\n set_level(child)\n set_level(self.root)\n return nb_levels\n \n def reduce_tree(self):\n ''\n\n\n \n currentlen=self.length()\n deepest=self.nodes_at(currentlen)\n deepest_leaves=[node for node in deepest if node.is_leaf]\n rightmost_leaf=deepest_leaves[-1]\n sibling=rightmost_leaf.parent.children[0]\n \n \n parent=rightmost_leaf.parent\n grand_parent=parent.parent\n rank=grand_parent.children.index(parent)\n children=grand_parent.children\n children[rank]=rightmost_leaf\n grand_parent.add(children)\n \n \n up_level=rightmost_leaf.level -2\n while up_level >0:\n nodes=self.nodes_at(up_level)\n leaf_nodes=[node for node in nodes if node.is_leaf]\n if leaf_nodes:\n leftmost_leaf=leaf_nodes[0]\n \n parent=leftmost_leaf.parent\n rank=parent.children.index(leftmost_leaf)\n new_node=Node()\n new_node.level=leftmost_leaf.level\n children=[sibling,leftmost_leaf]\n new_node.add(children)\n parent.children[rank]=new_node\n new_node.parent=parent\n break\n else:\n up_level -=1\n if up_level ==0:\n raise ResizeError\n \n def nodes_at(self,level,top=None):\n ''\n res=[]\n if top is None:\n top=self.root\n if top.level ==level:\n res=[top]\n elif not top.is_leaf:\n for child in top.children:\n res +=self.nodes_at(level,child)\n return res\n \n def reduce(self,maxlevels):\n ''\n while self.length()>maxlevels:\n self.reduce_tree()\n \n def codes(self,node=None,code=''):\n ''\n \n if node is None:\n self.dic={}\n node=self.root\n if node.is_leaf:\n self.dic[node.char]=code\n else:\n for i,child in enumerate(node.children):\n self.codes(child,code+str(i))\n return self.dic\n \n \ndef codelengths_from_frequencies(freqs):\n ''\n\n\n\n \n freqs=sorted(freqs.items(),\n key=lambda item:(item[1],-item[0]),reverse=True)\n nodes=[Node(char=key,weight=value)for(key,value)in freqs]\n while len(nodes)>1:\n right,left=nodes.pop(),nodes.pop()\n node=Node(weight=right.weight+left.weight)\n node.add([left,right])\n if not nodes:\n nodes.append(node)\n else:\n pos=0\n while pos node.weight:\n pos +=1\n nodes.insert(pos,node)\n \n top=nodes[0]\n tree=Tree(top)\n tree.reduce(15)\n \n codes=tree.codes()\n \n code_items=list(codes.items())\n code_items.sort(key=lambda item:(len(item[1]),item[0]))\n return[(car,len(value))for car,value in code_items]\n \ndef normalized(codelengths):\n car,codelength=codelengths[0]\n value=0\n codes={car:\"0\"*codelength}\n \n for(newcar,nbits)in codelengths[1:]:\n value +=1\n bvalue=str(bin(value))[2:]\n bvalue=\"0\"*(codelength -len(bvalue))+bvalue\n if nbits >codelength:\n codelength=nbits\n bvalue +=\"0\"*(codelength -len(bvalue))\n value=int(bvalue,2)\n assert len(bvalue)==nbits,(len(bvalue),'!=',nbits,'for',newcar,nbits)\n codes[newcar]=bvalue\n \n return codes\n \ndef make_tree(node,codes):\n if not hasattr(node,\"parent\"):\n node.code=''\n children=[]\n for bit in '01':\n next_code=node.code+bit\n if next_code in codes:\n child=Node(char=codes[next_code])\n else:\n child=Node()\n child.code=next_code\n children.append(child)\n node.add(children)\n for child in children:\n if not child.is_leaf:\n make_tree(child,codes)\n \ndef decompresser(codelengths):\n lengths=list(codelengths.items())\n \n lengths=[x for x in lengths if x[1]>0]\n lengths.sort(key=lambda item:(item[1],item[0]))\n codes=normalized(lengths)\n codes={value:key for key,value in codes.items()}\n root=Node()\n make_tree(root,codes)\n return{\"root\":root,\"codes\":codes}\n \ndef tree_from_codelengths(codelengths):\n return decompresser(codelengths)[\"root\"]\n \nclass error(Exception):\n pass\n \n \nfixed_codelengths={}\nfor car in range(144):\n fixed_codelengths[car]=8\nfor car in range(144,256):\n fixed_codelengths[car]=9\nfor car in range(256,280):\n fixed_codelengths[car]=7\nfor car in range(280,288):\n fixed_codelengths[car]=8\n \nfixed_decomp=decompresser(fixed_codelengths)\nfixed_lit_len_tree=fixed_decomp[\"root\"]\nfixed_lit_len_codes={value:key\nfor(key,value)in fixed_decomp[\"codes\"].items()}\n\ndef decomp_repeat(n):\n if n <=6:\n return[n]\n elif n <=9:\n return[n -3,3]\n elif n <=12:\n return[6,n -6]\n t=[]\n while n >12:\n t.append(6)\n n -=6\n t +=decomp(n)\n return t\n \ndef cl_encode(lengths):\n ''\n \n dic={char:len(code)for(char,code)in lengths.items()}\n items=[dic.get(i,0)for i in range(max(dic)+1)]\n pos=0\n while pos 256:\n \n if child.char <265:\n length=child.char -254\n elif child.char <269:\n length=11+2 *(child.char -265)+reader.read(1)\n elif child.char <273:\n length=19+4 *(child.char -269)+reader.read(2)\n elif child.char <277:\n length=35+8 *(child.char -273)+reader.read(3)\n elif child.char <281:\n length=67+16 *(child.char -277)+reader.read(4)\n elif child.char <285:\n length=131+32 *(child.char -281)+reader.read(5)\n elif child.char ==285:\n length=258\n return(\"length\",length)\n else:\n node=child\n \ndef adler32(source):\n a=1\n b=0\n for byte in source:\n a +=byte\n a %=65521\n b +=a\n b %=65521\n return a,b\n \n \ndef compress_dynamic(out,source,store,lit_len_count,distance_count):\n write_int=out.write_int\n \n \n lit_len_count[256]=1\n \n \n \n \n \n \n lengths=codelengths_from_frequencies(lit_len_count)\n lit_len_codes=normalized(lengths)\n \n HLIT=1+max(lit_len_codes)-257\n \n \n \n \n \n \n coded_lit_len=list(cl_encode(lit_len_codes))\n \n \n distance_codes=normalized(codelengths_from_frequencies(distance_count))\n HDIST=max(distance_codes)\n coded_distance=list(cl_encode(distance_codes))\n \n \n codelengths_count={}\n for coded in coded_lit_len,coded_distance:\n for item in coded:\n length=item[0]if isinstance(item,tuple)else item\n codelengths_count[length]=codelengths_count.get(length,0)+1\n \n \n codelengths_codes=normalized(\n codelengths_from_frequencies(codelengths_count))\n codelengths_dict={char:len(value)\n for(char,value)in codelengths_codes.items()}\n \n alphabet=(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,\n 15)\n \n \n codelengths_list=[codelengths_dict.get(car,0)for car in alphabet]\n \n while codelengths_list[-1]==0:\n codelengths_list.pop()\n HCLEN=len(codelengths_list)-4\n \n out.write(0,1)\n \n write_int(HLIT,5)\n write_int(HDIST,5)\n write_int(HCLEN,4)\n \n \n for length,car in zip(codelengths_list,alphabet):\n write_int(length,3)\n \n \n t=[]\n pr=lambda *args:t.append(args)\n for item in coded_lit_len+coded_distance:\n if isinstance(item,tuple):\n length,extra=item\n code=codelengths_codes[length]\n value,nbits=int(code,2),len(code)\n write_int(value,nbits,order=\"msf\")\n if length ==16:\n write_int(extra,2)\n elif length ==17:\n write_int(extra,3)\n elif length ==18:\n write_int(extra,7)\n else:\n code=codelengths_codes[item]\n value,nbits=int(code,2),len(code)\n write_int(value,nbits,order=\"msf\")\n \n \n for item in store:\n if isinstance(item,tuple):\n length,extra_length,distance,extra_distance=item\n \n code=lit_len_codes[length]\n value,nb=int(code,2),len(code)\n write_int(value,nb,order=\"msf\")\n \n value,nb=extra_length\n if nb:\n write_int(value,nb)\n \n code=distance_codes[distance]\n value,nb=int(code,2),len(code)\n write_int(value,nb,order=\"msf\")\n \n value,nb=extra_distance\n if nb:\n write_int(value,nb)\n else:\n literal=item\n code=lit_len_codes[item]\n value,nb=int(code,2),len(code)\n write_int(value,nb,order=\"msf\")\n \ndef compress_fixed(out,source,items):\n ''\n out.write(1,0)\n \n for item in items:\n if isinstance(item,tuple):\n length,extra_length,distance,extra_distance=item\n \n code=fixed_lit_len_codes[length]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \n value,nb=extra_length\n if nb:\n out.write_int(value,nb)\n \n out.write_int(distance,5,order=\"msf\")\n \n value,nb=extra_distance\n if nb:\n out.write_int(value,nb)\n else:\n literal=item\n code=fixed_lit_len_codes[item]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \ndef compress(data,/,level=-1,wbits=MAX_WBITS):\n\n window_size=32 *1024\n \n \n out=BitIO()\n \n \n out.write_int(8,4)\n size=window_size >>8\n nb=0\n while size >1:\n size >>=1\n nb +=1\n out.write_int(nb,4)\n out.write_int(0x9c,8)\n header=out.bytestream\n compressor=_Compressor(level)\n payload=compressor.compress(data)+compressor.flush()\n a,b=adler32(data)\n checksum=divmod(b,256)+divmod(a,256)\n return header+payload+bytes(checksum)\n \ndef convert32bits(n):\n result=[]\n for _ in range(4):\n n,rest=divmod(n,256)\n result.append(rest)\n return result\n \nclass _Compressor:\n\n def __init__(self,level=-1,method=DEFLATED,wbits=MAX_WBITS,\n memLevel=DEF_MEM_LEVEL,strategy=Z_DEFAULT_STRATEGY,\n zdict=None):\n self.level=level\n self.method=method\n self.wbits=wbits\n self.window_size=32 *1024\n self.memLevel=memLevel\n self.strategy=strategy\n self.zdict=zdict\n self._flushed=False\n \n def compress(self,source):\n \n \n lit_len_count={}\n \n \n distance_count={}\n \n store=[]\n replaced=0\n nb_tuples=0\n \n for item in lz_generator(source,self.window_size):\n if isinstance(item,tuple):\n nb_tuples +=1\n length,distance=item\n replaced +=length\n \n \n length_code,*extra_length=length_to_code(length)\n \n lit_len_count[length_code]=lit_len_count.get(length_code,0)+1\n \n \n \n distance_code,*extra_dist=distance_to_code(distance)\n \n distance_count[distance_code]=\\\n distance_count.get(distance_code,0)+1\n \n \n store.append((length_code,extra_length,distance_code,\n extra_dist))\n else:\n literal=item\n lit_len_count[literal]=lit_len_count.get(literal,0)+1\n store.append(literal)\n \n store.append(256)\n \n \n \n \n score=replaced -100 -(nb_tuples *20 //8)\n \n \n out=BitIO()\n \n out.write(1)\n \n if score <0:\n compress_fixed(out,source,store)\n else:\n compress_dynamic(out,source,store,lit_len_count,distance_count)\n \n \n out.pad_last()\n \n self._compressed=bytes(out.bytestream)\n \n return b''\n \n def flush(self,mode=Z_FINISH):\n if self._flushed:\n raise Error('inconsistent flush state')\n self._flushed=True\n return self._compressed\n \n \ndef compressobj(level=-1,method=DEFLATED,wbits=MAX_WBITS,\nmemLevel=DEF_MEM_LEVEL,strategy=Z_DEFAULT_STRATEGY,\nzdict=None):\n return _Compressor(level,method,wbits,memLevel,strategy,zdict)\n \n \ndef decompress(data,/,wbits=MAX_WBITS,bufsize=DEF_BUF_SIZE):\n if wbits >0:\n decompressor=_Decompressor(wbits,bufsize)\n source=BitIO(data)\n assert source.read(4)==8\n nb=source.read(4)\n window_size=2 **(nb+8)\n assert source.read(8)==0x9c\n checksum=data[-4:]\n a=256 *checksum[2]+checksum[3]\n b=256 *checksum[0]+checksum[1]\n assert a,b ==adler32(data)\n return decompressor.decompress(data[2:-4])\n else:\n decompressor=_Decompressor(-wbits,bufsize)\n return decompressor.decompress(data)\n \nclass _Decompressor:\n\n def __init__(self,wbits=MAX_WBITS,bufsize=DEF_BUF_SIZE,zdict=None):\n self.wbits=wbits\n self.bufsize=bufsize\n self.zdict=zdict\n self.eof=False\n self.unconsumed_tail=b''\n self.unused_data=b''\n \n def decompress(self,data,max_length=0):\n self.data=data\n if data ==b'':\n return data\n \n reader=self._reader=BitIO(data)\n \n result=bytearray()\n \n while True:\n BFINAL=reader.read(1)\n \n BTYPE=reader.read(2)\n \n if BTYPE ==0b01:\n \n \n root=fixed_lit_len_tree\n \n while True:\n \n _type,value=read_literal_or_length(reader,root)\n if _type =='eob':\n break\n elif _type =='literal':\n result.append(value)\n elif _type =='length':\n length=value\n \n dist_code=reader.read(5,\"msf\")\n if dist_code <3:\n distance=dist_code+1\n else:\n nb=(dist_code //2)-1\n extra=reader.read(nb)\n half,delta=divmod(dist_code,2)\n distance=(1+(2 **half)+\n delta *(2 **(half -1))+extra)\n for _ in range(length):\n result.append(result[-distance])\n \n node=root\n else:\n node=child\n elif BTYPE ==0b10:\n \n \n \n lit_len_tree,distance_tree=dynamic_trees(reader)\n \n t=[]\n while True:\n \n _type,value=read_literal_or_length(reader,lit_len_tree)\n if _type =='eob':\n break\n elif _type =='literal':\n result.append(value)\n t.append(value)\n elif _type =='length':\n \n length=value\n distance=read_distance(reader,distance_tree)\n t.append([length,distance])\n for _ in range(length):\n result.append(result[-distance])\n \n if BFINAL:\n rank=reader.bytenum\n self.unused_data=bytes(data[rank+1:])\n self.eof=True\n return bytes(result)\n \ndef decompressobj(wbits=MAX_WBITS,zdict=None):\n return _Decompressor(wbits,zdict)\n", ["_zlib_utils"]], "_aio": [".py", "from browser.aio import run,sleep,Future\n\n\ndef _task(coro,Id,block):\n async def _task():\n block[Id]=None\n try:\n block[Id]=await coro\n except Exception as e:\n block[Id]=e\n \n if not block[Id]:\n del block[Id]\n return _task()\n \n \nasync def gather(*coros,rate=0):\n dones={}\n counts=0\n for c in coros:\n run(_task(c,f'task{counts}',dones))\n counts +=1\n while not all(dones.values()):\n await sleep(rate)\n return dones\n \n \nclass QueueEmpty(Exception):\n pass\n \n \nclass QueueFull(Exception):\n pass\n \n \nclass Queue(object):\n\n def __init__(self,maxsize=0):\n from collections import deque\n self.maxsize=maxsize\n self.data=deque(maxlen=maxsize or None)\n self.readers=deque()\n self.writers=deque()\n self.joiners=deque()\n self.tasks=0\n \n def qsize(self):\n return len(self.data)\n \n def empty(self):\n return self.qsize()==0\n \n def full(self):\n return self.maxsize and self.qsize()==self.maxsize\n \n async def get(self):\n if self.empty():\n future=Future()\n def reader(val):\n future.set_result(val)\n self.readers.append(reader)\n return await future\n \n item=self.get_nowait()\n if self.writers:\n \n writer=self.writers.popleft()\n writer()\n return item\n \n def get_nowait(self):\n try:\n return self.data.popleft()\n except IndexError:\n raise QueueEmpty()\n \n async def put(self,item):\n if self.full():\n future=Future()\n def writer():\n self.put_nowait(item)\n future.set_result(True)\n self.writers.append(writer)\n await future\n return\n \n if self.readers:\n \n self.tasks +=1\n reader=self.readers.popleft()\n reader(item)\n else:\n \n self.put_nowait(item)\n \n def put_nowait(self,item):\n if self.full():\n raise QueueFull()\n self.data.append(item)\n self.tasks +=1\n \n async def join(self):\n if self.tasks >0:\n future=Future()\n def setres():\n future.set_result(True)\n await future\n \n def task_done(self):\n if self.tasks ==0:\n raise ValueError(\"no tasks\")\n self.tasks -=1\n if tasks ==0:\n for joiner in self.joiners:\n joiner()\n", ["browser.aio", "collections"]], "_codecs": [".py", "\ndef ascii_decode(*args,**kw):\n pass\n \ndef ascii_encode(*args,**kw):\n pass\n \ndef charbuffer_encode(*args,**kw):\n pass\n \ndef charmap_build(decoding_table):\n return{car:i for(i,car)in enumerate(decoding_table)}\n \ndef charmap_decode(input,errors,decoding_table):\n res=''\n for car in input:\n code=decoding_table[car]\n if code is None:\n raise UnicodeDecodeError(input)\n res +=code\n return res,len(input)\n \ndef charmap_encode(input,errors,encoding_table):\n t=[]\n for car in input:\n code=encoding_table.get(car)\n if code is None:\n raise UnicodeEncodeError(input)\n t.append(code)\n return bytes(t),len(input)\n \ndef decode(obj,encoding=\"utf-8\",errors=\"strict\"):\n ''\n\n\n\n\n\n \n return __BRYTHON__.decode(obj,encoding,errors)\n \ndef encode(obj,encoding=\"utf-8\",errors=\"strict\"):\n ''\n\n\n\n\n\n \n return __BRYTHON__.encode(obj,encoding,errors)\n \ndef escape_decode(*args,**kw):\n pass\n \ndef escape_encode(*args,**kw):\n pass\n \ndef latin_1_decode(*args,**kw):\n pass\n \ndef latin_1_encode(*args,**kw):\n pass\n \ndef lookup(encoding):\n ''\n\n \n if encoding in('utf-8','utf_8'):\n import encodings.utf_8\n return encodings.utf_8.getregentry()\n \n LookupError(encoding)\n \ndef lookup_error(*args,**kw):\n ''\n\n \n pass\n \ndef mbcs_decode(*args,**kw):\n pass\n \ndef mbcs_encode(*args,**kw):\n pass\n \ndef raw_unicode_escape_decode(*args,**kw):\n pass\n \ndef raw_unicode_escape_encode(*args,**kw):\n pass\n \ndef readbuffer_encode(*args,**kw):\n pass\n \ndef register(*args,**kw):\n ''\n\n\n\n \n pass\n \ndef register_error(*args,**kw):\n ''\n\n\n\n\n \n pass\n \ndef unicode_escape_decode(*args,**kw):\n pass\n \ndef unicode_escape_encode(*args,**kw):\n pass\n \ndef unicode_internal_decode(*args,**kw):\n pass\n \ndef unicode_internal_encode(*args,**kw):\n pass\n \ndef _reader(b,nb,endian):\n pos=0\n while pos 2 **16:\n \n code=cp -2 **16\n hi=0xD800 |(code >>10)\n lo=0xDC00 |(code&0x3FF)\n t +=divmod(hi,256)\n t +=divmod(lo,256)\n else:\n t.append(0)\n t.append(cp)\n \n return bytes(t),len(arg)\n \ndef utf_16_decode(b,errors,*args):\n if b[0]==0xfe and b[1]==0xff:\n return utf_16_le_decode(b[2:],errors,*args)\n return utf_16_le_decode(b,errors,*args)\n \ndef utf_16_encode(arg):\n b=utf_16_le_encode(arg)[0]\n return bytes([0xfe,0xff])+b,len(arg)\n \ndef utf_16_ex_decode(*args,**kw):\n pass\n \ndef utf_16_le_decode(b,errors,*args):\n t=[]\n reader=_reader(b,2,'little')\n for cp in reader:\n if cp <0xd800:\n t.append(chr(cp))\n else:\n hi=cp\n lo=next(reader)\n t.append(chr(_to_codepoint(lo,hi)))\n return ''.join(t),len(t)\n \ndef utf_16_le_encode(arg):\n t=[]\n for char in arg:\n cp=ord(char)\n if cp >2 **16:\n \n code=cp -2 **16\n hi=0xD800 |(code >>10)\n lo=0xDC00 |(code&0x3FF)\n t +=reversed(divmod(hi,256))\n t +=reversed(divmod(lo,256))\n else:\n t.append(cp)\n t.append(0)\n return bytes(t),len(arg)\n \ndef utf_32_be_decode(b,errors,*args):\n t=[]\n reader=_reader(b,4,'big')\n for cp in reader:\n t.append(chr(cp))\n return ''.join(t),len(t)\n \ndef utf_32_be_encode(s):\n res=[]\n for char in s:\n t=[]\n x=ord(char)\n for i in range(4):\n x,y=divmod(x,256)\n t.append(y)\n res +=reversed(t)\n return bytes(res),len(s)\n \ndef utf_32_decode(*args,**kw):\n pass\n \ndef utf_32_encode(*args,**kw):\n pass\n \ndef utf_32_ex_decode(*args,**kw):\n pass\n \ndef utf_32_le_decode(b,errors,*args):\n t=[]\n reader=_reader(b,4,'little')\n for cp in reader:\n t.append(chr(cp))\n return ''.join(t),len(t)\n \ndef utf_32_le_encode(s):\n res=[]\n for char in s:\n t=[]\n x=ord(char)\n for i in range(4):\n x,y=divmod(x,256)\n t.append(y)\n res +=t\n return bytes(res),len(s)\n \ndef utf_7_decode(*args,**kw):\n pass\n \ndef utf_7_encode(*args,**kw):\n pass\n \ndef utf_8_decode(decoder,bytes_obj,errors,*args):\n return(bytes_obj.decode(\"utf-8\"),len(bytes_obj))\n \ndef utf_8_encode(*args,**kw):\n input=args[0]\n if len(args)==2:\n errors=args[1]\n else:\n errors=kw.get('errors','strict')\n \n \n return(bytes(input,'utf-8'),len(input))\n", ["encodings.utf_8"]], "_codecs_jp": [".py", "from encoding_cp932 import encoding_table,decoding_table\n\n\n\nclass Codec:\n\n def encode(self,input,errors='strict'):\n b=[]\n for pos,car in enumerate(input):\n cp=ord(car)\n try:\n code=encoding_table[cp]\n high=((code >>8)&0xff)\n low=code&0xff\n if high:\n b.append(high)\n b.append(low)\n except IndexError:\n raise UnicodeEncodeError(pos)\n return[bytes(b),len(input)]\n \n def decode(self,input,errors='strict'):\n i=0\n string=''\n while i self.maxlen:\n self.popleft()\n \n def appendleft(self,x):\n self.state +=1\n self.leftndx -=1\n if self.leftndx ==-1:\n newblock=[None]*BLOCKSIZ\n self.left[LFTLNK]=newblock\n newblock[RGTLNK]=self.left\n self.left=newblock\n self.leftndx=n -1\n self.length +=1\n self.left[self.leftndx]=x\n if self.maxlen is not None and self.length >self.maxlen:\n self.pop()\n \n def extend(self,iterable):\n if iterable is self:\n iterable=list(iterable)\n for elem in iterable:\n self.append(elem)\n \n def extendleft(self,iterable):\n if iterable is self:\n iterable=list(iterable)\n for elem in iterable:\n self.appendleft(elem)\n \n def pop(self):\n if self.left is self.right and self.leftndx >self.rightndx:\n \n raise IndexError(\"pop from an empty deque\")\n x=self.right[self.rightndx]\n self.right[self.rightndx]=None\n self.length -=1\n self.rightndx -=1\n self.state +=1\n if self.rightndx ==-1:\n prevblock=self.right[LFTLNK]\n if prevblock is None:\n \n self.rightndx=n //2\n self.leftndx=n //2+1\n else:\n prevblock[RGTLNK]=None\n self.right[LFTLNK]=None\n self.right=prevblock\n self.rightndx=n -1\n return x\n \n def popleft(self):\n if self.left is self.right and self.leftndx >self.rightndx:\n \n raise IndexError(\"pop from an empty deque\")\n x=self.left[self.leftndx]\n self.left[self.leftndx]=None\n self.length -=1\n self.leftndx +=1\n self.state +=1\n if self.leftndx ==n:\n prevblock=self.left[RGTLNK]\n if prevblock is None:\n \n self.rightndx=n //2\n self.leftndx=n //2+1\n else:\n prevblock[LFTLNK]=None\n self.left[RGTLNK]=None\n self.left=prevblock\n self.leftndx=0\n return x\n \n def count(self,value):\n c=0\n for item in self:\n if item ==value:\n c +=1\n return c\n \n def remove(self,value):\n \n for i in range(len(self)):\n if self[i]==value:\n del self[i]\n return\n raise ValueError(\"deque.remove(x): x not in deque\")\n \n def rotate(self,n=1):\n length=len(self)\n if length ==0:\n return\n halflen=(length+1)>>1\n if n >halflen or n <-halflen:\n n %=length\n if n >halflen:\n n -=length\n elif n <-halflen:\n n +=length\n while n >0:\n self.appendleft(self.pop())\n n -=1\n while n <0:\n self.append(self.popleft())\n n +=1\n \n def reverse(self):\n ''\n leftblock=self.left\n rightblock=self.right\n leftindex=self.leftndx\n rightindex=self.rightndx\n for i in range(self.length //2):\n \n assert leftblock !=rightblock or leftindex =0:\n block=self.left\n while block:\n l,r=0,n\n if block is self.left:\n l=self.leftndx\n if block is self.right:\n r=self.rightndx+1\n span=r -l\n if index =negative_span:\n return block,r+index\n index -=negative_span\n block=block[LFTLNK]\n raise IndexError(\"deque index out of range\")\n \n def __getitem__(self,index):\n block,index=self.__getref(index)\n return block[index]\n \n def __setitem__(self,index,value):\n block,index=self.__getref(index)\n block[index]=value\n \n def __delitem__(self,index):\n length=len(self)\n if index >=0:\n if index >=length:\n raise IndexError(\"deque index out of range\")\n self.rotate(-index)\n self.popleft()\n self.rotate(index)\n else:\n \n index=index ^(2 **31)\n if index >=length:\n raise IndexError(\"deque index out of range\")\n self.rotate(index)\n self.pop()\n self.rotate(-index)\n \n def __reduce_ex__(self,proto):\n return type(self),(list(self),self.maxlen)\n \n def __hash__(self):\n \n raise TypeError(\"deque objects are unhashable\")\n \n def __copy__(self):\n return self.__class__(self,self.maxlen)\n \n \n def __eq__(self,other):\n if isinstance(other,deque):\n return list(self)==list(other)\n else:\n return NotImplemented\n \n def __ne__(self,other):\n if isinstance(other,deque):\n return list(self)!=list(other)\n else:\n return NotImplemented\n \n def __lt__(self,other):\n if isinstance(other,deque):\n return list(self)list(other)\n else:\n return NotImplemented\n \n def __ge__(self,other):\n if isinstance(other,deque):\n return list(self)>=list(other)\n else:\n return NotImplemented\n \n def __iadd__(self,other):\n self.extend(other)\n return self\n \n \nclass deque_iterator(object):\n\n def __init__(self,deq,itergen):\n self.counter=len(deq)\n def giveup():\n self.counter=0\n \n raise RuntimeError(\"deque mutated during iteration\")\n self._gen=itergen(deq.state,giveup)\n \n def __next__(self):\n res=self._gen.__next__()\n self.counter -=1\n return res\n \n def __iter__(self):\n return self\n \nclass defaultdict(dict):\n\n def __init__(self,*args,**kwds):\n if len(args)>0:\n default_factory=args[0]\n args=args[1:]\n if not callable(default_factory)and default_factory is not None:\n raise TypeError(\"first argument must be callable\")\n else:\n default_factory=None\n dict.__init__(self,*args,**kwds)\n self.default_factory=default_factory\n self.update(*args,**kwds)\n super(defaultdict,self).__init__(*args,**kwds)\n \n def __missing__(self,key):\n \n if self.default_factory is None:\n raise KeyError(key)\n self[key]=value=self.default_factory()\n return value\n \n def __repr__(self,recurse=set()):\n if id(self)in recurse:\n return \"defaultdict(...)\"\n try:\n recurse.add(id(self))\n return \"defaultdict(%s, %s)\"%(repr(self.default_factory),super(defaultdict,self).__repr__())\n finally:\n recurse.remove(id(self))\n \n def copy(self):\n return type(self)(self.default_factory,self)\n \n def __copy__(self):\n return self.copy()\n \n def __reduce__(self):\n \n \n \n \n \n \n \n \n \n \n \n return(type(self),(self.default_factory,),None,None,self.items())\n \nfrom operator import itemgetter as _itemgetter\nfrom keyword import iskeyword as _iskeyword\nimport sys as _sys\n\ndef namedtuple(typename,field_names,verbose=False,rename=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n if isinstance(field_names,str):\n field_names=field_names.replace(',',' ').split()\n field_names=tuple(map(str,field_names))\n if rename:\n names=list(field_names)\n seen=set()\n for i,name in enumerate(names):\n if(not min(c.isalnum()or c =='_'for c in name)or _iskeyword(name)\n or not name or name[0].isdigit()or name.startswith('_')\n or name in seen):\n names[i]='_%d'%i\n seen.add(name)\n field_names=tuple(names)\n for name in(typename,)+field_names:\n if not min(c.isalnum()or c =='_'for c in name):\n raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r'%name)\n if _iskeyword(name):\n raise ValueError('Type names and field names cannot be a keyword: %r'%name)\n if name[0].isdigit():\n raise ValueError('Type names and field names cannot start with a number: %r'%name)\n seen_names=set()\n for name in field_names:\n if name.startswith('_')and not rename:\n raise ValueError('Field names cannot start with an underscore: %r'%name)\n if name in seen_names:\n raise ValueError('Encountered duplicate field name: %r'%name)\n seen_names.add(name)\n \n \n numfields=len(field_names)\n argtxt=repr(field_names).replace(\"'\",\"\")[1:-1]\n reprtxt=', '.join('%s=%%r'%name for name in field_names)\n \n template='''class %(typename)s(tuple):\n '%(typename)s(%(argtxt)s)' \\n\n __slots__ = () \\n\n _fields = %(field_names)r \\n\n def __new__(_cls, %(argtxt)s):\n return tuple.__new__(_cls, (%(argtxt)s)) \\n\n @classmethod\n def _make(cls, iterable, new=tuple.__new__, len=len):\n 'Make a new %(typename)s object from a sequence or iterable'\n result = new(cls, iterable)\n if len(result) != %(numfields)d:\n raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))\n return result \\n\n def __repr__(self):\n return '%(typename)s(%(reprtxt)s)' %% self \\n\n def _asdict(self):\n 'Return a new dict which maps field names to their values'\n return dict(zip(self._fields, self)) \\n\n def _replace(_self, **kwds):\n 'Return a new %(typename)s object replacing specified fields with new values'\n result = _self._make(map(kwds.pop, %(field_names)r, _self))\n if kwds:\n raise ValueError('Got unexpected field names: %%r' %% kwds.keys())\n return result \\n\n def __getnewargs__(self):\n return tuple(self) \\n\\n'''%locals()\n for i,name in enumerate(field_names):\n template +=' %s = _property(_itemgetter(%d))\\n'%(name,i)\n \n if verbose:\n print(template)\n \n \n namespace=dict(_itemgetter=_itemgetter,__name__='namedtuple_%s'%typename,\n _property=property,_tuple=tuple)\n try:\n exec(template,namespace)\n except SyntaxError as e:\n raise SyntaxError(e.message+':\\n'+template)\n result=namespace[typename]\n \n \n \n \n \n try:\n result.__module__=_sys._getframe(1).f_globals.get('__name__','__main__')\n except(AttributeError,ValueError):\n pass\n \n return result\n \nif __name__ =='__main__':\n Point=namedtuple('Point',['x','y'])\n p=Point(11,y=22)\n print(p[0]+p[1])\n x,y=p\n print(x,y)\n print(p.x+p.y)\n print(p)\n", ["keyword", "operator", "sys"]], "_collections_abc": [".py", "\n\n\n\"\"\"Abstract Base Classes (ABCs) for collections, according to PEP 3119.\n\nUnit tests are in test_collections.\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom abc import ABCMeta,abstractmethod\nimport sys\n\nGenericAlias=type(list[int])\nEllipsisType=type(...)\ndef _f():pass\nFunctionType=type(_f)\ndel _f\n\n__all__=[\"Awaitable\",\"Coroutine\",\n\"AsyncIterable\",\"AsyncIterator\",\"AsyncGenerator\",\n\"Hashable\",\"Iterable\",\"Iterator\",\"Generator\",\"Reversible\",\n\"Sized\",\"Container\",\"Callable\",\"Collection\",\n\"Set\",\"MutableSet\",\n\"Mapping\",\"MutableMapping\",\n\"MappingView\",\"KeysView\",\"ItemsView\",\"ValuesView\",\n\"Sequence\",\"MutableSequence\",\n\"ByteString\",\"Buffer\",\n]\n\n\n\n\n\n__name__=\"collections.abc\"\n\n\n\n\n\n\n\n\nbytes_iterator=type(iter(b''))\nbytearray_iterator=type(iter(bytearray()))\n\ndict_keyiterator=type(iter({}.keys()))\ndict_valueiterator=type(iter({}.values()))\ndict_itemiterator=type(iter({}.items()))\nlist_iterator=type(iter([]))\nlist_reverseiterator=type(iter(reversed([])))\nrange_iterator=type(iter(range(0)))\nlongrange_iterator=type(iter(range(1 <<1000)))\nset_iterator=type(iter(set()))\nstr_iterator=type(iter(\"\"))\ntuple_iterator=type(iter(()))\nzip_iterator=type(iter(zip()))\n\ndict_keys=type({}.keys())\ndict_values=type({}.values())\ndict_items=type({}.items())\n\nmappingproxy=type(type.__dict__)\ngenerator=type((lambda:(yield))())\n\nasync def _coro():pass\n_coro=_coro()\ncoroutine=type(_coro)\n_coro.close()\ndel _coro\n\nasync def _ag():yield\n_ag=_ag()\nasync_generator=type(_ag)\ndel _ag\n\n\n\n\ndef _check_methods(C,*methods):\n mro=C.__mro__\n for method in methods:\n for B in mro:\n if method in B.__dict__:\n if B.__dict__[method]is None:\n return NotImplemented\n break\n else:\n return NotImplemented\n return True\n \nclass Hashable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __hash__(self):\n return 0\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Hashable:\n return _check_methods(C,\"__hash__\")\n return NotImplemented\n \n \nclass Awaitable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __await__(self):\n yield\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Awaitable:\n return _check_methods(C,\"__await__\")\n return NotImplemented\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass Coroutine(Awaitable):\n\n __slots__=()\n \n @abstractmethod\n def send(self,value):\n ''\n\n \n raise StopIteration\n \n @abstractmethod\n def throw(self,typ,val=None,tb=None):\n ''\n\n \n if val is None:\n if tb is None:\n raise typ\n val=typ()\n if tb is not None:\n val=val.with_traceback(tb)\n raise val\n \n def close(self):\n ''\n \n try:\n self.throw(GeneratorExit)\n except(GeneratorExit,StopIteration):\n pass\n else:\n raise RuntimeError(\"coroutine ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Coroutine:\n return _check_methods(C,'__await__','send','throw','close')\n return NotImplemented\n \n \nCoroutine.register(coroutine)\n\n\nclass AsyncIterable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __aiter__(self):\n return AsyncIterator()\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncIterable:\n return _check_methods(C,\"__aiter__\")\n return NotImplemented\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass AsyncIterator(AsyncIterable):\n\n __slots__=()\n \n @abstractmethod\n async def __anext__(self):\n ''\n raise StopAsyncIteration\n \n def __aiter__(self):\n return self\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncIterator:\n return _check_methods(C,\"__anext__\",\"__aiter__\")\n return NotImplemented\n \n \nclass AsyncGenerator(AsyncIterator):\n\n __slots__=()\n \n async def __anext__(self):\n ''\n\n \n return await self.asend(None)\n \n @abstractmethod\n async def asend(self,value):\n ''\n\n \n raise StopAsyncIteration\n \n @abstractmethod\n async def athrow(self,typ,val=None,tb=None):\n ''\n\n \n if val is None:\n if tb is None:\n raise typ\n val=typ()\n if tb is not None:\n val=val.with_traceback(tb)\n raise val\n \n async def aclose(self):\n ''\n \n try:\n await self.athrow(GeneratorExit)\n except(GeneratorExit,StopAsyncIteration):\n pass\n else:\n raise RuntimeError(\"asynchronous generator ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncGenerator:\n return _check_methods(C,'__aiter__','__anext__',\n 'asend','athrow','aclose')\n return NotImplemented\n \n \nAsyncGenerator.register(async_generator)\n\n\nclass Iterable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __iter__(self):\n while False:\n yield None\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Iterable:\n return _check_methods(C,\"__iter__\")\n return NotImplemented\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass Iterator(Iterable):\n\n __slots__=()\n \n @abstractmethod\n def __next__(self):\n ''\n raise StopIteration\n \n def __iter__(self):\n return self\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Iterator:\n return _check_methods(C,'__iter__','__next__')\n return NotImplemented\n \n \nIterator.register(bytes_iterator)\nIterator.register(bytearray_iterator)\n\nIterator.register(dict_keyiterator)\nIterator.register(dict_valueiterator)\nIterator.register(dict_itemiterator)\nIterator.register(list_iterator)\nIterator.register(list_reverseiterator)\nIterator.register(range_iterator)\nIterator.register(longrange_iterator)\nIterator.register(set_iterator)\nIterator.register(str_iterator)\nIterator.register(tuple_iterator)\nIterator.register(zip_iterator)\n\n\nclass Reversible(Iterable):\n\n __slots__=()\n \n @abstractmethod\n def __reversed__(self):\n while False:\n yield None\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Reversible:\n return _check_methods(C,\"__reversed__\",\"__iter__\")\n return NotImplemented\n \n \nclass Generator(Iterator):\n\n __slots__=()\n \n def __next__(self):\n ''\n\n \n return self.send(None)\n \n @abstractmethod\n def send(self,value):\n ''\n\n \n raise StopIteration\n \n @abstractmethod\n def throw(self,typ,val=None,tb=None):\n ''\n\n \n if val is None:\n if tb is None:\n raise typ\n val=typ()\n if tb is not None:\n val=val.with_traceback(tb)\n raise val\n \n def close(self):\n ''\n \n try:\n self.throw(GeneratorExit)\n except(GeneratorExit,StopIteration):\n pass\n else:\n raise RuntimeError(\"generator ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Generator:\n return _check_methods(C,'__iter__','__next__',\n 'send','throw','close')\n return NotImplemented\n \n \nGenerator.register(generator)\n\n\nclass Sized(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __len__(self):\n return 0\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Sized:\n return _check_methods(C,\"__len__\")\n return NotImplemented\n \n \nclass Container(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __contains__(self,x):\n return False\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Container:\n return _check_methods(C,\"__contains__\")\n return NotImplemented\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass Collection(Sized,Iterable,Container):\n\n __slots__=()\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Collection:\n return _check_methods(C,\"__len__\",\"__iter__\",\"__contains__\")\n return NotImplemented\n \n \nclass Buffer(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __buffer__(self,flags:int,/)->memoryview:\n raise NotImplementedError\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Buffer:\n return _check_methods(C,\"__buffer__\")\n return NotImplemented\n \n \nclass _CallableGenericAlias(GenericAlias):\n ''\n\n\n\n\n\n\n \n \n __slots__=()\n \n def __new__(cls,origin,args):\n if not(isinstance(args,tuple)and len(args)==2):\n raise TypeError(\n \"Callable must be used as Callable[[arg, ...], result].\")\n t_args,t_result=args\n if isinstance(t_args,(tuple,list)):\n args=(*t_args,t_result)\n elif not _is_param_expr(t_args):\n raise TypeError(f\"Expected a list of types, an ellipsis, \"\n f\"ParamSpec, or Concatenate. Got {t_args}\")\n return super().__new__(cls,origin,args)\n \n def __repr__(self):\n if len(self.__args__)==2 and _is_param_expr(self.__args__[0]):\n return super().__repr__()\n return(f'collections.abc.Callable'\n f'[[{\", \".join([_type_repr(a)for a in self.__args__[:-1]])}], '\n f'{_type_repr(self.__args__[-1])}]')\n \n def __reduce__(self):\n args=self.__args__\n if not(len(args)==2 and _is_param_expr(args[0])):\n args=list(args[:-1]),args[-1]\n return _CallableGenericAlias,(Callable,args)\n \n def __getitem__(self,item):\n \n \n \n \n if not isinstance(item,tuple):\n item=(item,)\n \n new_args=super().__getitem__(item).__args__\n \n \n if not isinstance(new_args[0],(tuple,list)):\n t_result=new_args[-1]\n t_args=new_args[:-1]\n new_args=(t_args,t_result)\n return _CallableGenericAlias(Callable,tuple(new_args))\n \ndef _is_param_expr(obj):\n ''\n\n \n if obj is Ellipsis:\n return True\n if isinstance(obj,list):\n return True\n obj=type(obj)\n names=('ParamSpec','_ConcatenateGenericAlias')\n return obj.__module__ =='typing'and any(obj.__name__ ==name for name in names)\n \ndef _type_repr(obj):\n ''\n\n\n\n\n \n if isinstance(obj,type):\n if obj.__module__ =='builtins':\n return obj.__qualname__\n return f'{obj.__module__}.{obj.__qualname__}'\n if obj is Ellipsis:\n return '...'\n if isinstance(obj,FunctionType):\n return obj.__name__\n return repr(obj)\n \n \nclass Callable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __call__(self,*args,**kwds):\n return False\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Callable:\n return _check_methods(C,\"__call__\")\n return NotImplemented\n \n __class_getitem__=classmethod(_CallableGenericAlias)\n \n \n \n \n \nclass Set(Collection):\n ''\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n def __le__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n if len(self)>len(other):\n return False\n for elem in self:\n if elem not in other:\n return False\n return True\n \n def __lt__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n return len(self)len(other)and self.__ge__(other)\n \n def __ge__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n if len(self)>11)^(h >>25)\n h=h *69069+907133923\n h &=MASK\n if h >MAX:\n h -=MASK+1\n if h ==-1:\n h=590923713\n return h\n \n \nSet.register(frozenset)\n\n\nclass MutableSet(Set):\n ''\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def add(self,value):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def discard(self,value):\n ''\n raise NotImplementedError\n \n def remove(self,value):\n ''\n if value not in self:\n raise KeyError(value)\n self.discard(value)\n \n def pop(self):\n ''\n it=iter(self)\n try:\n value=next(it)\n except StopIteration:\n raise KeyError from None\n self.discard(value)\n return value\n \n def clear(self):\n ''\n try:\n while True:\n self.pop()\n except KeyError:\n pass\n \n def __ior__(self,it):\n for value in it:\n self.add(value)\n return self\n \n def __iand__(self,it):\n for value in(self -it):\n self.discard(value)\n return self\n \n def __ixor__(self,it):\n if it is self:\n self.clear()\n else:\n if not isinstance(it,Set):\n it=self._from_iterable(it)\n for value in it:\n if value in self:\n self.discard(value)\n else:\n self.add(value)\n return self\n \n def __isub__(self,it):\n if it is self:\n self.clear()\n else:\n for value in it:\n self.discard(value)\n return self\n \n \nMutableSet.register(set)\n\n\n\n\nclass Mapping(Collection):\n ''\n\n\n\n\n \n \n __slots__=()\n \n \n __abc_tpflags__=1 <<6\n \n @abstractmethod\n def __getitem__(self,key):\n raise KeyError\n \n def get(self,key,default=None):\n ''\n try:\n return self[key]\n except KeyError:\n return default\n \n def __contains__(self,key):\n try:\n self[key]\n except KeyError:\n return False\n else:\n return True\n \n def keys(self):\n ''\n return KeysView(self)\n \n def items(self):\n ''\n return ItemsView(self)\n \n def values(self):\n ''\n return ValuesView(self)\n \n def __eq__(self,other):\n if not isinstance(other,Mapping):\n return NotImplemented\n return dict(self.items())==dict(other.items())\n \n __reversed__=None\n \nMapping.register(mappingproxy)\n\n\nclass MappingView(Sized):\n\n __slots__='_mapping',\n \n def __init__(self,mapping):\n self._mapping=mapping\n \n def __len__(self):\n return len(self._mapping)\n \n def __repr__(self):\n return '{0.__class__.__name__}({0._mapping!r})'.format(self)\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass KeysView(MappingView,Set):\n\n __slots__=()\n \n @classmethod\n def _from_iterable(cls,it):\n return set(it)\n \n def __contains__(self,key):\n return key in self._mapping\n \n def __iter__(self):\n yield from self._mapping\n \n \nKeysView.register(dict_keys)\n\n\nclass ItemsView(MappingView,Set):\n\n __slots__=()\n \n @classmethod\n def _from_iterable(cls,it):\n return set(it)\n \n def __contains__(self,item):\n key,value=item\n try:\n v=self._mapping[key]\n except KeyError:\n return False\n else:\n return v is value or v ==value\n \n def __iter__(self):\n for key in self._mapping:\n yield(key,self._mapping[key])\n \n \nItemsView.register(dict_items)\n\n\nclass ValuesView(MappingView,Collection):\n\n __slots__=()\n \n def __contains__(self,value):\n for key in self._mapping:\n v=self._mapping[key]\n if v is value or v ==value:\n return True\n return False\n \n def __iter__(self):\n for key in self._mapping:\n yield self._mapping[key]\n \n \nValuesView.register(dict_values)\n\n\nclass MutableMapping(Mapping):\n ''\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __setitem__(self,key,value):\n raise KeyError\n \n @abstractmethod\n def __delitem__(self,key):\n raise KeyError\n \n __marker=object()\n \n def pop(self,key,default=__marker):\n ''\n\n \n try:\n value=self[key]\n except KeyError:\n if default is self.__marker:\n raise\n return default\n else:\n del self[key]\n return value\n \n def popitem(self):\n ''\n\n \n try:\n key=next(iter(self))\n except StopIteration:\n raise KeyError from None\n value=self[key]\n del self[key]\n return key,value\n \n def clear(self):\n ''\n try:\n while True:\n self.popitem()\n except KeyError:\n pass\n \n def update(self,other=(),/,**kwds):\n ''\n\n\n\n \n if isinstance(other,Mapping):\n for key in other:\n self[key]=other[key]\n elif hasattr(other,\"keys\"):\n for key in other.keys():\n self[key]=other[key]\n else:\n for key,value in other:\n self[key]=value\n for key,value in kwds.items():\n self[key]=value\n \n def setdefault(self,key,default=None):\n ''\n try:\n return self[key]\n except KeyError:\n self[key]=default\n return default\n \n \nMutableMapping.register(dict)\n\n\n\n\nclass Sequence(Reversible,Collection):\n ''\n\n\n\n \n \n __slots__=()\n \n \n __abc_tpflags__=1 <<5\n \n @abstractmethod\n def __getitem__(self,index):\n raise IndexError\n \n def __iter__(self):\n i=0\n try:\n while True:\n v=self[i]\n yield v\n i +=1\n except IndexError:\n return\n \n def __contains__(self,value):\n for v in self:\n if v is value or v ==value:\n return True\n return False\n \n def __reversed__(self):\n for i in reversed(range(len(self))):\n yield self[i]\n \n def index(self,value,start=0,stop=None):\n ''\n\n\n\n\n \n if start is not None and start <0:\n start=max(len(self)+start,0)\n if stop is not None and stop <0:\n stop +=len(self)\n \n i=start\n while stop is None or i ANSIColors:\n if colorize or can_colorize():\n return ANSIColors()\n else:\n return NoColors\n \n \ndef can_colorize()->bool:\n if sys.platform ==\"win32\":\n try:\n import nt\n \n if not nt._supports_virtual_terminal():\n return False\n except(ImportError,AttributeError):\n return False\n if not sys.flags.ignore_environment:\n if os.environ.get(\"PYTHON_COLORS\")==\"0\":\n return False\n if os.environ.get(\"PYTHON_COLORS\")==\"1\":\n return True\n if \"NO_COLOR\"in os.environ:\n return False\n if not COLORIZE:\n return False\n if not sys.flags.ignore_environment:\n if \"FORCE_COLOR\"in os.environ:\n return True\n if os.environ.get(\"TERM\")==\"dumb\":\n return False\n \n if not hasattr(sys.stderr,\"fileno\"):\n return False\n \n try:\n return os.isatty(sys.stderr.fileno())\n except io.UnsupportedOperation:\n return sys.stderr.isatty()\n", ["io", "nt", "os", "sys"]], "_compat_pickle": [".py", "\n\n\n\n\n\n\nIMPORT_MAPPING={\n'__builtin__':'builtins',\n'copy_reg':'copyreg',\n'Queue':'queue',\n'SocketServer':'socketserver',\n'ConfigParser':'configparser',\n'repr':'reprlib',\n'tkFileDialog':'tkinter.filedialog',\n'tkSimpleDialog':'tkinter.simpledialog',\n'tkColorChooser':'tkinter.colorchooser',\n'tkCommonDialog':'tkinter.commondialog',\n'Dialog':'tkinter.dialog',\n'Tkdnd':'tkinter.dnd',\n'tkFont':'tkinter.font',\n'tkMessageBox':'tkinter.messagebox',\n'ScrolledText':'tkinter.scrolledtext',\n'Tkconstants':'tkinter.constants',\n'ttk':'tkinter.ttk',\n'Tkinter':'tkinter',\n'markupbase':'_markupbase',\n'_winreg':'winreg',\n'thread':'_thread',\n'dummy_thread':'_dummy_thread',\n'dbhash':'dbm.bsd',\n'dumbdbm':'dbm.dumb',\n'dbm':'dbm.ndbm',\n'gdbm':'dbm.gnu',\n'xmlrpclib':'xmlrpc.client',\n'SimpleXMLRPCServer':'xmlrpc.server',\n'httplib':'http.client',\n'htmlentitydefs':'html.entities',\n'HTMLParser':'html.parser',\n'Cookie':'http.cookies',\n'cookielib':'http.cookiejar',\n'BaseHTTPServer':'http.server',\n'test.test_support':'test.support',\n'commands':'subprocess',\n'urlparse':'urllib.parse',\n'robotparser':'urllib.robotparser',\n'urllib2':'urllib.request',\n'anydbm':'dbm',\n'_abcoll':'collections.abc',\n}\n\n\n\n\n\nNAME_MAPPING={\n('__builtin__','xrange'):('builtins','range'),\n('__builtin__','reduce'):('functools','reduce'),\n('__builtin__','intern'):('sys','intern'),\n('__builtin__','unichr'):('builtins','chr'),\n('__builtin__','unicode'):('builtins','str'),\n('__builtin__','long'):('builtins','int'),\n('itertools','izip'):('builtins','zip'),\n('itertools','imap'):('builtins','map'),\n('itertools','ifilter'):('builtins','filter'),\n('itertools','ifilterfalse'):('itertools','filterfalse'),\n('itertools','izip_longest'):('itertools','zip_longest'),\n('UserDict','IterableUserDict'):('collections','UserDict'),\n('UserList','UserList'):('collections','UserList'),\n('UserString','UserString'):('collections','UserString'),\n('whichdb','whichdb'):('dbm','whichdb'),\n('_socket','fromfd'):('socket','fromfd'),\n('_multiprocessing','Connection'):('multiprocessing.connection','Connection'),\n('multiprocessing.process','Process'):('multiprocessing.context','Process'),\n('multiprocessing.forking','Popen'):('multiprocessing.popen_fork','Popen'),\n('urllib','ContentTooShortError'):('urllib.error','ContentTooShortError'),\n('urllib','getproxies'):('urllib.request','getproxies'),\n('urllib','pathname2url'):('urllib.request','pathname2url'),\n('urllib','quote_plus'):('urllib.parse','quote_plus'),\n('urllib','quote'):('urllib.parse','quote'),\n('urllib','unquote_plus'):('urllib.parse','unquote_plus'),\n('urllib','unquote'):('urllib.parse','unquote'),\n('urllib','url2pathname'):('urllib.request','url2pathname'),\n('urllib','urlcleanup'):('urllib.request','urlcleanup'),\n('urllib','urlencode'):('urllib.parse','urlencode'),\n('urllib','urlopen'):('urllib.request','urlopen'),\n('urllib','urlretrieve'):('urllib.request','urlretrieve'),\n('urllib2','HTTPError'):('urllib.error','HTTPError'),\n('urllib2','URLError'):('urllib.error','URLError'),\n}\n\nPYTHON2_EXCEPTIONS=(\n\"ArithmeticError\",\n\"AssertionError\",\n\"AttributeError\",\n\"BaseException\",\n\"BufferError\",\n\"BytesWarning\",\n\"DeprecationWarning\",\n\"EOFError\",\n\"EnvironmentError\",\n\"Exception\",\n\"FloatingPointError\",\n\"FutureWarning\",\n\"GeneratorExit\",\n\"IOError\",\n\"ImportError\",\n\"ImportWarning\",\n\"IndentationError\",\n\"IndexError\",\n\"KeyError\",\n\"KeyboardInterrupt\",\n\"LookupError\",\n\"MemoryError\",\n\"NameError\",\n\"NotImplementedError\",\n\"OSError\",\n\"OverflowError\",\n\"PendingDeprecationWarning\",\n\"ReferenceError\",\n\"RuntimeError\",\n\"RuntimeWarning\",\n\n\"StopIteration\",\n\"SyntaxError\",\n\"SyntaxWarning\",\n\"SystemError\",\n\"SystemExit\",\n\"TabError\",\n\"TypeError\",\n\"UnboundLocalError\",\n\"UnicodeDecodeError\",\n\"UnicodeEncodeError\",\n\"UnicodeError\",\n\"UnicodeTranslateError\",\n\"UnicodeWarning\",\n\"UserWarning\",\n\"ValueError\",\n\"Warning\",\n\"ZeroDivisionError\",\n)\n\ntry:\n WindowsError\nexcept NameError:\n pass\nelse:\n PYTHON2_EXCEPTIONS +=(\"WindowsError\",)\n \nfor excname in PYTHON2_EXCEPTIONS:\n NAME_MAPPING[(\"exceptions\",excname)]=(\"builtins\",excname)\n \nMULTIPROCESSING_EXCEPTIONS=(\n'AuthenticationError',\n'BufferTooShort',\n'ProcessError',\n'TimeoutError',\n)\n\nfor excname in MULTIPROCESSING_EXCEPTIONS:\n NAME_MAPPING[(\"multiprocessing\",excname)]=(\"multiprocessing.context\",excname)\n \n \nREVERSE_IMPORT_MAPPING=dict((v,k)for(k,v)in IMPORT_MAPPING.items())\nassert len(REVERSE_IMPORT_MAPPING)==len(IMPORT_MAPPING)\nREVERSE_NAME_MAPPING=dict((v,k)for(k,v)in NAME_MAPPING.items())\nassert len(REVERSE_NAME_MAPPING)==len(NAME_MAPPING)\n\n\n\nIMPORT_MAPPING.update({\n'cPickle':'pickle',\n'_elementtree':'xml.etree.ElementTree',\n'FileDialog':'tkinter.filedialog',\n'SimpleDialog':'tkinter.simpledialog',\n'DocXMLRPCServer':'xmlrpc.server',\n'SimpleHTTPServer':'http.server',\n'CGIHTTPServer':'http.server',\n\n'UserDict':'collections',\n'UserList':'collections',\n'UserString':'collections',\n'whichdb':'dbm',\n'StringIO':'io',\n'cStringIO':'io',\n})\n\nREVERSE_IMPORT_MAPPING.update({\n'_bz2':'bz2',\n'_dbm':'dbm',\n'_functools':'functools',\n'_gdbm':'gdbm',\n'_pickle':'pickle',\n})\n\nNAME_MAPPING.update({\n('__builtin__','basestring'):('builtins','str'),\n('exceptions','StandardError'):('builtins','Exception'),\n('UserDict','UserDict'):('collections','UserDict'),\n('socket','_socketobject'):('socket','SocketType'),\n})\n\nREVERSE_NAME_MAPPING.update({\n('_functools','reduce'):('__builtin__','reduce'),\n('tkinter.filedialog','FileDialog'):('FileDialog','FileDialog'),\n('tkinter.filedialog','LoadFileDialog'):('FileDialog','LoadFileDialog'),\n('tkinter.filedialog','SaveFileDialog'):('FileDialog','SaveFileDialog'),\n('tkinter.simpledialog','SimpleDialog'):('SimpleDialog','SimpleDialog'),\n('xmlrpc.server','ServerHTMLDoc'):('DocXMLRPCServer','ServerHTMLDoc'),\n('xmlrpc.server','XMLRPCDocGenerator'):\n('DocXMLRPCServer','XMLRPCDocGenerator'),\n('xmlrpc.server','DocXMLRPCRequestHandler'):\n('DocXMLRPCServer','DocXMLRPCRequestHandler'),\n('xmlrpc.server','DocXMLRPCServer'):\n('DocXMLRPCServer','DocXMLRPCServer'),\n('xmlrpc.server','DocCGIXMLRPCRequestHandler'):\n('DocXMLRPCServer','DocCGIXMLRPCRequestHandler'),\n('http.server','SimpleHTTPRequestHandler'):\n('SimpleHTTPServer','SimpleHTTPRequestHandler'),\n('http.server','CGIHTTPRequestHandler'):\n('CGIHTTPServer','CGIHTTPRequestHandler'),\n('_socket','socket'):('socket','_socketobject'),\n})\n\nPYTHON3_OSERROR_EXCEPTIONS=(\n'BrokenPipeError',\n'ChildProcessError',\n'ConnectionAbortedError',\n'ConnectionError',\n'ConnectionRefusedError',\n'ConnectionResetError',\n'FileExistsError',\n'FileNotFoundError',\n'InterruptedError',\n'IsADirectoryError',\n'NotADirectoryError',\n'PermissionError',\n'ProcessLookupError',\n'TimeoutError',\n)\n\nfor excname in PYTHON3_OSERROR_EXCEPTIONS:\n REVERSE_NAME_MAPPING[('builtins',excname)]=('exceptions','OSError')\n \nPYTHON3_IMPORTERROR_EXCEPTIONS=(\n'ModuleNotFoundError',\n)\n\nfor excname in PYTHON3_IMPORTERROR_EXCEPTIONS:\n REVERSE_NAME_MAPPING[('builtins',excname)]=('exceptions','ImportError')\ndel excname\n", []], "_compression": [".py", "''\n\nimport io\nimport sys\n\nBUFFER_SIZE=io.DEFAULT_BUFFER_SIZE\n\n\nclass BaseStream(io.BufferedIOBase):\n ''\n \n def _check_not_closed(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file\")\n \n def _check_can_read(self):\n if not self.readable():\n raise io.UnsupportedOperation(\"File not open for reading\")\n \n def _check_can_write(self):\n if not self.writable():\n raise io.UnsupportedOperation(\"File not open for writing\")\n \n def _check_can_seek(self):\n if not self.readable():\n raise io.UnsupportedOperation(\"Seeking is only supported \"\n \"on files open for reading\")\n if not self.seekable():\n raise io.UnsupportedOperation(\"The underlying file object \"\n \"does not support seeking\")\n \n \nclass DecompressReader(io.RawIOBase):\n ''\n \n def readable(self):\n return True\n \n def __init__(self,fp,decomp_factory,trailing_error=(),**decomp_args):\n self._fp=fp\n self._eof=False\n self._pos=0\n \n \n self._size=-1\n \n \n \n \n \n self._decomp_factory=decomp_factory\n self._decomp_args=decomp_args\n self._decompressor=self._decomp_factory(**self._decomp_args)\n \n \n \n self._trailing_error=trailing_error\n \n def close(self):\n self._decompressor=None\n return super().close()\n \n def seekable(self):\n return self._fp.seekable()\n \n def readinto(self,b):\n with memoryview(b)as view,view.cast(\"B\")as byte_view:\n data=self.read(len(byte_view))\n byte_view[:len(data)]=data\n return len(data)\n \n def read(self,size=-1):\n if size <0:\n return self.readall()\n \n if not size or self._eof:\n return b\"\"\n data=None\n \n \n while True:\n if self._decompressor.eof:\n rawblock=(self._decompressor.unused_data or\n self._fp.read(BUFFER_SIZE))\n if not rawblock:\n break\n \n self._decompressor=self._decomp_factory(\n **self._decomp_args)\n try:\n data=self._decompressor.decompress(rawblock,size)\n except self._trailing_error:\n \n break\n else:\n if self._decompressor.needs_input:\n rawblock=self._fp.read(BUFFER_SIZE)\n if not rawblock:\n raise EOFError(\"Compressed file ended before the \"\n \"end-of-stream marker was reached\")\n else:\n rawblock=b\"\"\n data=self._decompressor.decompress(rawblock,size)\n if data:\n break\n if not data:\n self._eof=True\n self._size=self._pos\n return b\"\"\n self._pos +=len(data)\n return data\n \n def readall(self):\n chunks=[]\n \n \n \n while data :=self.read(sys.maxsize):\n chunks.append(data)\n \n return b\"\".join(chunks)\n \n \n def _rewind(self):\n self._fp.seek(0)\n self._eof=False\n self._pos=0\n self._decompressor=self._decomp_factory(**self._decomp_args)\n \n def seek(self,offset,whence=io.SEEK_SET):\n \n if whence ==io.SEEK_SET:\n pass\n elif whence ==io.SEEK_CUR:\n offset=self._pos+offset\n elif whence ==io.SEEK_END:\n \n if self._size <0:\n while self.read(io.DEFAULT_BUFFER_SIZE):\n pass\n offset=self._size+offset\n else:\n raise ValueError(\"Invalid value for whence: {}\".format(whence))\n \n \n if offset 0:\n data=self.read(min(io.DEFAULT_BUFFER_SIZE,offset))\n if not data:\n break\n offset -=len(data)\n \n return self._pos\n \n def tell(self):\n ''\n return self._pos\n", ["io", "sys"]], "_contextvars": [".py", "''\n\n\nclass Context(object):\n\n __contains__=\"\"\n \n copy=\"\"\n \n def get(self,*args):\n pass\n \n items=\"\"\n \n keys=\"\"\n \n run=\"\"\n \n values=\"\"\n \nclass ContextVar:\n\n def __init__(self,name,**kw):\n ''\n self.name=name\n if \"default\"in kw:\n self.default=kw[\"default\"]\n \n def get(self,*args):\n if hasattr(self,\"value\"):\n return self.value\n elif len(args)==1:\n return args[0]\n elif hasattr(self,\"default\"):\n return self.default\n raise LookupError(self.name)\n \n def reset(self,token):\n if token.old_value ==Token.MISSING:\n del self.value\n else:\n self.value=token.old_value\n \n def set(self,value):\n self.value=value\n return Token(self)\n \nclass Token(object):\n\n MISSING=\"\"\n \n def __init__(self,contextvar):\n self.var=contextvar\n try:\n self.old_value=contextvar.get()\n except LookupError:\n self.old_value=Token.MISSING\n \ndef copy_context(*args,**kw):\n pass\n", []], "_csv": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__=\"1.0\"\n\nQUOTE_MINIMAL,QUOTE_ALL,QUOTE_NONNUMERIC,QUOTE_NONE,QUOTE_STRINGS,QUOTE_NOTNULL=range(6)\n_dialects={}\n_field_limit=128 *1024\n\nclass Error(Exception):\n pass\n \nclass Dialect(object):\n ''\n\n \n \n __slots__=[\"_delimiter\",\"_doublequote\",\"_escapechar\",\n \"_lineterminator\",\"_quotechar\",\"_quoting\",\n \"_skipinitialspace\",\"_strict\"]\n \n def __new__(cls,dialect,**kwargs):\n \n for name in kwargs:\n if '_'+name not in Dialect.__slots__:\n raise TypeError(\"unexpected keyword argument '%s'\"%\n (name,))\n \n if dialect is not None:\n if isinstance(dialect,str):\n dialect=get_dialect(dialect)\n \n \n if(isinstance(dialect,Dialect)\n and all(value is None for value in kwargs.values())):\n return dialect\n \n self=object.__new__(cls)\n \n \n def set_char(x):\n if x is None:\n return None\n if isinstance(x,str)and len(x)<=1:\n return x\n raise TypeError(\"%r must be a 1-character string\"%(name,))\n def set_str(x):\n if isinstance(x,str):\n return x\n raise TypeError(\"%r must be a string\"%(name,))\n def set_quoting(x):\n if x in range(4):\n return x\n raise TypeError(\"bad 'quoting' value\")\n \n attributes={\"delimiter\":(',',set_char),\n \"doublequote\":(True,bool),\n \"escapechar\":(None,set_char),\n \"lineterminator\":(\"\\r\\n\",set_str),\n \"quotechar\":('\"',set_char),\n \"quoting\":(QUOTE_MINIMAL,set_quoting),\n \"skipinitialspace\":(False,bool),\n \"strict\":(False,bool),\n }\n \n \n notset=object()\n for name in Dialect.__slots__:\n name=name[1:]\n value=notset\n if name in kwargs:\n value=kwargs[name]\n elif dialect is not None:\n value=getattr(dialect,name,notset)\n \n \n if value is notset:\n value=attributes[name][0]\n if name =='quoting'and not self.quotechar:\n value=QUOTE_NONE\n else:\n converter=attributes[name][1]\n if converter:\n value=converter(value)\n \n setattr(self,'_'+name,value)\n \n if not self.delimiter:\n raise TypeError(\"delimiter must be set\")\n \n if self.quoting !=QUOTE_NONE and not self.quotechar:\n raise TypeError(\"quotechar must be set if quoting enabled\")\n \n if not self.lineterminator:\n raise TypeError(\"lineterminator must be set\")\n \n return self\n \n delimiter=property(lambda self:self._delimiter)\n doublequote=property(lambda self:self._doublequote)\n escapechar=property(lambda self:self._escapechar)\n lineterminator=property(lambda self:self._lineterminator)\n quotechar=property(lambda self:self._quotechar)\n quoting=property(lambda self:self._quoting)\n skipinitialspace=property(lambda self:self._skipinitialspace)\n strict=property(lambda self:self._strict)\n \n \ndef _call_dialect(dialect_inst,kwargs):\n return Dialect(dialect_inst,**kwargs)\n \ndef register_dialect(name,dialect=None,**kwargs):\n ''\n \n if not isinstance(name,str):\n raise TypeError(\"dialect name must be a string or unicode\")\n \n dialect=_call_dialect(dialect,kwargs)\n _dialects[name]=dialect\n \ndef unregister_dialect(name):\n ''\n \n try:\n del _dialects[name]\n except KeyError:\n raise Error(\"unknown dialect\")\n \ndef get_dialect(name):\n ''\n \n try:\n return _dialects[name]\n except KeyError:\n raise Error(\"unknown dialect\")\n \ndef list_dialects():\n ''\n \n return list(_dialects)\n \nclass Reader(object):\n ''\n\n\n \n \n \n (START_RECORD,START_FIELD,ESCAPED_CHAR,IN_FIELD,\n IN_QUOTED_FIELD,ESCAPE_IN_QUOTED_FIELD,QUOTE_IN_QUOTED_FIELD,\n EAT_CRNL)=range(8)\n \n def __init__(self,iterator,dialect=None,**kwargs):\n self.dialect=_call_dialect(dialect,kwargs)\n \n \n \n self._delimiter=self.dialect.delimiter if self.dialect.delimiter else '\\0'\n self._quotechar=self.dialect.quotechar if self.dialect.quotechar else '\\0'\n self._escapechar=self.dialect.escapechar if self.dialect.escapechar else '\\0'\n self._doublequote=self.dialect.doublequote\n self._quoting=self.dialect.quoting\n self._skipinitialspace=self.dialect.skipinitialspace\n self._strict=self.dialect.strict\n \n self.input_iter=iter(iterator)\n self.line_num=0\n \n self._parse_reset()\n \n def _parse_reset(self):\n self.field=''\n self.fields=[]\n self.state=self.START_RECORD\n self.numeric_field=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n self._parse_reset()\n while True:\n try:\n line=next(self.input_iter)\n except StopIteration:\n \n if len(self.field)>0:\n raise Error(\"newline inside string\")\n raise\n \n self.line_num +=1\n \n if '\\0'in line:\n raise Error(\"line contains NULL byte\")\n self._parse_process_char(line)\n self._parse_eol()\n \n if self.state ==self.START_RECORD:\n break\n \n fields=self.fields\n self.fields=[]\n return fields\n \n def _parse_process_char(self,line):\n pos=0\n while pos pos:\n self._parse_add_str(line[pos:pos2])\n pos=pos2\n self._parse_save_field()\n self.state=self.EAT_CRNL\n break\n elif line[pos2]==self._escapechar[0]:\n \n if pos2 >pos:\n self._parse_add_str(line[pos:pos2])\n pos=pos2\n self.state=self.ESCAPED_CHAR\n break\n elif line[pos2]==self._delimiter[0]:\n \n if pos2 >pos:\n self._parse_add_str(line[pos:pos2])\n pos=pos2\n self._parse_save_field()\n self.state=self.START_FIELD\n break\n \n pos2 +=1\n else:\n if pos2 >pos:\n self._parse_add_str(line[pos:pos2])\n pos=pos2\n continue\n \n elif self.state ==self.START_RECORD:\n if line[pos]=='\\n'or line[pos]=='\\r':\n self.state=self.EAT_CRNL\n else:\n self.state=self.START_FIELD\n \n continue\n \n elif self.state ==self.START_FIELD:\n if line[pos]=='\\n'or line[pos]=='\\r':\n \n self._parse_save_field()\n self.state=self.EAT_CRNL\n elif(line[pos]==self._quotechar[0]\n and self._quoting !=QUOTE_NONE):\n \n self.state=self.IN_QUOTED_FIELD\n elif line[pos]==self._escapechar[0]:\n \n self.state=self.ESCAPED_CHAR\n elif self._skipinitialspace and line[pos]==' ':\n \n pass\n elif line[pos]==self._delimiter[0]:\n \n self._parse_save_field()\n else:\n \n if self._quoting ==QUOTE_NONNUMERIC:\n self.numeric_field=True\n self.state=self.IN_FIELD\n continue\n \n elif self.state ==self.ESCAPED_CHAR:\n self._parse_add_char(line[pos])\n self.state=self.IN_FIELD\n \n elif self.state ==self.IN_QUOTED_FIELD:\n if line[pos]==self._escapechar:\n \n self.state=self.ESCAPE_IN_QUOTED_FIELD\n elif(line[pos]==self._quotechar\n and self._quoting !=QUOTE_NONE):\n if self._doublequote:\n \n self.state=self.QUOTE_IN_QUOTED_FIELD\n else:\n \n self.state=self.IN_FIELD\n else:\n \n self._parse_add_char(line[pos])\n \n elif self.state ==self.ESCAPE_IN_QUOTED_FIELD:\n self._parse_add_char(line[pos])\n self.state=self.IN_QUOTED_FIELD\n \n elif self.state ==self.QUOTE_IN_QUOTED_FIELD:\n \n if(line[pos]==self._quotechar\n and self._quoting !=QUOTE_NONE):\n \n self._parse_add_char(line[pos])\n self.state=self.IN_QUOTED_FIELD\n elif line[pos]==self._delimiter[0]:\n \n self._parse_save_field()\n self.state=self.START_FIELD\n elif line[pos]=='\\r'or line[pos]=='\\n':\n \n self._parse_save_field()\n self.state=self.EAT_CRNL\n elif not self._strict:\n self._parse_add_char(line[pos])\n self.state=self.IN_FIELD\n else:\n raise Error(\"'%c' expected after '%c'\"%\n (self._delimiter,self._quotechar))\n \n elif self.state ==self.EAT_CRNL:\n if line[pos]=='\\r'or line[pos]=='\\n':\n pass\n else:\n raise Error(\"new-line character seen in unquoted field - \"\n \"do you need to open the file \"\n \"in universal-newline mode?\")\n \n else:\n raise RuntimeError(\"unknown state: %r\"%(self.state,))\n \n pos +=1\n \n def _parse_eol(self):\n if self.state ==self.EAT_CRNL:\n self.state=self.START_RECORD\n elif self.state ==self.START_RECORD:\n \n pass\n elif self.state ==self.IN_FIELD:\n \n \n self._parse_save_field()\n self.state=self.START_RECORD\n elif self.state ==self.START_FIELD:\n \n self._parse_save_field()\n self.state=self.START_RECORD\n elif self.state ==self.ESCAPED_CHAR:\n self._parse_add_char('\\n')\n self.state=self.IN_FIELD\n elif self.state ==self.IN_QUOTED_FIELD:\n pass\n elif self.state ==self.ESCAPE_IN_QUOTED_FIELD:\n self._parse_add_char('\\n')\n self.state=self.IN_QUOTED_FIELD\n elif self.state ==self.QUOTE_IN_QUOTED_FIELD:\n \n self._parse_save_field()\n self.state=self.START_RECORD\n else:\n raise RuntimeError(\"unknown state: %r\"%(self.state,))\n \n def _parse_save_field(self):\n field,self.field=self.field,''\n if self.numeric_field:\n self.numeric_field=False\n field=float(field)\n self.fields.append(field)\n \n def _parse_add_char(self,c):\n if len(self.field)+1 >_field_limit:\n raise Error(\"field larget than field limit (%d)\"%(_field_limit))\n self.field +=c\n \n def _parse_add_str(self,s):\n if len(self.field)+len(s)>_field_limit:\n raise Error(\"field larget than field limit (%d)\"%(_field_limit))\n self.field +=s\n \n \nclass Writer(object):\n ''\n\n\n \n \n def __init__(self,file,dialect=None,**kwargs):\n if not(hasattr(file,'write')and callable(file.write)):\n raise TypeError(\"argument 1 must have a 'write' method\")\n self.writeline=file.write\n self.dialect=_call_dialect(dialect,kwargs)\n \n def _join_reset(self):\n self.rec=[]\n self.num_fields=0\n \n def _join_append(self,field,quoted,quote_empty):\n dialect=self.dialect\n \n if self.num_fields >0:\n self.rec.append(dialect.delimiter)\n \n if dialect.quoting ==QUOTE_NONE:\n need_escape=tuple(dialect.lineterminator)+(\n dialect.escapechar,\n dialect.delimiter,dialect.quotechar)\n \n else:\n for c in tuple(dialect.lineterminator)+(\n dialect.delimiter,dialect.escapechar):\n if c and c in field:\n quoted=True\n \n need_escape=()\n if dialect.quotechar in field:\n if dialect.doublequote:\n field=field.replace(dialect.quotechar,\n dialect.quotechar *2)\n quoted=True\n else:\n need_escape=(dialect.quotechar,)\n \n \n for c in need_escape:\n if c and c in field:\n if not dialect.escapechar:\n raise Error(\"need to escape, but no escapechar set\")\n field=field.replace(c,dialect.escapechar+c)\n \n \n if field ==''and quote_empty:\n if dialect.quoting ==QUOTE_NONE:\n raise Error(\"single empty field record must be quoted\")\n quoted=1\n \n if quoted:\n field=dialect.quotechar+field+dialect.quotechar\n \n self.rec.append(field)\n self.num_fields +=1\n \n \n \n def writerow(self,row):\n dialect=self.dialect\n try:\n rowlen=len(row)\n except TypeError:\n raise Error(\"sequence expected\")\n \n \n self._join_reset()\n \n for field in row:\n quoted=False\n if dialect.quoting ==QUOTE_NONNUMERIC:\n try:\n float(field)\n except:\n quoted=True\n \n \n elif dialect.quoting ==QUOTE_ALL:\n quoted=True\n \n if field is None:\n self._join_append(\"\",quoted,rowlen ==1)\n else:\n self._join_append(str(field),quoted,rowlen ==1)\n \n \n self.rec.append(dialect.lineterminator)\n \n self.writeline(''.join(self.rec))\n \n def writerows(self,rows):\n for row in rows:\n self.writerow(row)\n \ndef reader(*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n return Reader(*args,**kwargs)\n \ndef writer(*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n return Writer(*args,**kwargs)\n \n \nundefined=object()\ndef field_size_limit(limit=undefined):\n ''\n\n\n\n \n \n global _field_limit\n old_limit=_field_limit\n \n if limit is not undefined:\n if not isinstance(limit,(int,long)):\n raise TypeError(\"int expected, got %s\"%\n (limit.__class__.__name__,))\n _field_limit=limit\n \n return old_limit\n", []], "_dummy_thread": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['error','start_new_thread','exit','get_ident','allocate_lock',\n'interrupt_main','LockType','RLock']\n\n\nTIMEOUT_MAX=2 **31\n\n\n\n\n\n\nerror=RuntimeError\n\ndef start_new_thread(function,args,kwargs={}):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if type(args)!=type(tuple()):\n raise TypeError(\"2nd arg must be a tuple\")\n if type(kwargs)!=type(dict()):\n raise TypeError(\"3rd arg must be a dict\")\n global _main\n _main=False\n try:\n function(*args,**kwargs)\n except SystemExit:\n pass\n except:\n import traceback\n traceback.print_exc()\n _main=True\n global _interrupt\n if _interrupt:\n _interrupt=False\n raise KeyboardInterrupt\n \ndef exit():\n ''\n raise SystemExit\n \ndef get_ident():\n ''\n\n\n\n\n \n return 1\n \ndef allocate_lock():\n ''\n return LockType()\n \ndef stack_size(size=None):\n ''\n if size is not None:\n raise error(\"setting thread stack size not supported\")\n return 0\n \ndef _set_sentinel():\n ''\n return LockType()\n \nclass LockType(object):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self):\n self.locked_status=False\n \n def acquire(self,waitflag=None,timeout=-1):\n ''\n\n\n\n\n\n\n\n\n \n if waitflag is None or waitflag:\n self.locked_status=True\n return True\n else:\n if not self.locked_status:\n self.locked_status=True\n return True\n else:\n if timeout >0:\n import time\n time.sleep(timeout)\n return False\n \n __enter__=acquire\n \n def __exit__(self,typ,val,tb):\n self.release()\n \n def release(self):\n ''\n \n \n if not self.locked_status:\n raise error\n self.locked_status=False\n return True\n \n def locked(self):\n return self.locked_status\n \n def __repr__(self):\n return \"<%s %s.%s object at %s>\"%(\n \"locked\"if self.locked_status else \"unlocked\",\n self.__class__.__module__,\n self.__class__.__qualname__,\n hex(id(self))\n )\n \n \nclass RLock(LockType):\n ''\n\n\n\n\n\n \n def __init__(self):\n super().__init__()\n self._levels=0\n \n def acquire(self,waitflag=None,timeout=-1):\n ''\n \n locked=super().acquire(waitflag,timeout)\n if locked:\n self._levels +=1\n return locked\n \n def release(self):\n ''\n \n if self._levels ==0:\n raise error\n if self._levels ==1:\n super().release()\n self._levels -=1\n \n \n_interrupt=False\n\n_main=True\n\ndef interrupt_main():\n ''\n \n if _main:\n raise KeyboardInterrupt\n else:\n global _interrupt\n _interrupt=True\n", ["time", "traceback"]], "_frozen_importlib": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_bootstrap_external=None\n_thread=None\nimport _weakref\n\nimport _imp\nimport sys\n\ndef _wrap(new,old):\n ''\n for replace in['__module__','__name__','__qualname__','__doc__']:\n if hasattr(old,replace):\n setattr(new,replace,getattr(old,replace))\n new.__dict__.update(old.__dict__)\n \n \ndef _new_module(name):\n return type(sys)(name)\n \n \n \n \n \n \n_module_locks={}\n\n_blocking_on={}\n\n\nclass _DeadlockError(RuntimeError):\n pass\n \n \nclass _ModuleLock:\n ''\n\n\n \n \n def __init__(self,name):\n self.lock=_thread.allocate_lock()\n self.wakeup=_thread.allocate_lock()\n self.name=name\n self.owner=None\n self.count=0\n self.waiters=0\n \n def has_deadlock(self):\n \n me=_thread.get_ident()\n tid=self.owner\n while True:\n lock=_blocking_on.get(tid)\n if lock is None:\n return False\n tid=lock.owner\n if tid ==me:\n return True\n \n def acquire(self):\n ''\n\n\n\n \n tid=_thread.get_ident()\n _blocking_on[tid]=self\n try:\n while True:\n with self.lock:\n if self.count ==0 or self.owner ==tid:\n self.owner=tid\n self.count +=1\n return True\n if self.has_deadlock():\n raise _DeadlockError('deadlock detected by %r'%self)\n if self.wakeup.acquire(False):\n self.waiters +=1\n \n self.wakeup.acquire()\n self.wakeup.release()\n finally:\n del _blocking_on[tid]\n \n def release(self):\n tid=_thread.get_ident()\n with self.lock:\n if self.owner !=tid:\n raise RuntimeError('cannot release un-acquired lock')\n assert self.count >0\n self.count -=1\n if self.count ==0:\n self.owner=None\n if self.waiters:\n self.waiters -=1\n self.wakeup.release()\n \n def __repr__(self):\n return '_ModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _DummyModuleLock:\n ''\n \n \n def __init__(self,name):\n self.name=name\n self.count=0\n \n def acquire(self):\n self.count +=1\n return True\n \n def release(self):\n if self.count ==0:\n raise RuntimeError('cannot release un-acquired lock')\n self.count -=1\n \n def __repr__(self):\n return '_DummyModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _ModuleLockManager:\n\n def __init__(self,name):\n self._name=name\n self._lock=None\n \n def __enter__(self):\n self._lock=_get_module_lock(self._name)\n self._lock.acquire()\n \n def __exit__(self,*args,**kwargs):\n self._lock.release()\n \n \n \n \ndef _get_module_lock(name):\n ''\n\n\n \n \n _imp.acquire_lock()\n try:\n try:\n lock=_module_locks[name]()\n except KeyError:\n lock=None\n \n if lock is None:\n if _thread is None:\n lock=_DummyModuleLock(name)\n else:\n lock=_ModuleLock(name)\n \n def cb(ref,name=name):\n _imp.acquire_lock()\n try:\n \n \n \n if _module_locks.get(name)is ref:\n del _module_locks[name]\n finally:\n _imp.release_lock()\n \n _module_locks[name]=_weakref.ref(lock,cb)\n finally:\n _imp.release_lock()\n \n return lock\n \n \ndef _lock_unlock_module(name):\n ''\n\n\n\n \n lock=_get_module_lock(name)\n try:\n lock.acquire()\n except _DeadlockError:\n \n \n pass\n else:\n lock.release()\n \n \ndef _call_with_frames_removed(f,*args,**kwds):\n ''\n\n\n\n\n\n \n return f(*args,**kwds)\n \n \ndef _verbose_message(message,*args,verbosity=1):\n ''\n if sys.flags.verbose >=verbosity:\n if not message.startswith(('#','import ')):\n message='# '+message\n print(message.format(*args),file=sys.stderr)\n \n \ndef _requires_builtin(fxn):\n ''\n def _requires_builtin_wrapper(self,fullname):\n if fullname not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_builtin_wrapper,fxn)\n return _requires_builtin_wrapper\n \n \ndef _requires_frozen(fxn):\n ''\n def _requires_frozen_wrapper(self,fullname):\n if not _imp.is_frozen(fullname):\n raise ImportError('{!r} is not a frozen module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_frozen_wrapper,fxn)\n return _requires_frozen_wrapper\n \n \n \ndef _load_module_shim(self,fullname):\n ''\n\n\n\n \n spec=spec_from_loader(fullname,self)\n if fullname in sys.modules:\n module=sys.modules[fullname]\n _exec(spec,module)\n return sys.modules[fullname]\n else:\n return _load(spec)\n \n \n \ndef _module_repr(module):\n\n loader=getattr(module,'__loader__',None)\n if hasattr(loader,'module_repr'):\n \n \n \n try:\n return loader.module_repr(module)\n except Exception:\n pass\n try:\n spec=module.__spec__\n except AttributeError:\n pass\n else:\n if spec is not None:\n return _module_repr_from_spec(spec)\n \n \n \n try:\n name=module.__name__\n except AttributeError:\n name='?'\n try:\n filename=module.__file__\n except AttributeError:\n if loader is None:\n return ''.format(name)\n else:\n return ''.format(name,loader)\n else:\n return ''.format(name,filename)\n \n \nclass _installed_safely:\n\n def __init__(self,module):\n self._module=module\n self._spec=module.__spec__\n \n def __enter__(self):\n \n \n \n self._spec._initializing=True\n sys.modules[self._spec.name]=self._module\n \n def __exit__(self,*args):\n try:\n spec=self._spec\n if any(arg is not None for arg in args):\n try:\n del sys.modules[spec.name]\n except KeyError:\n pass\n else:\n _verbose_message('import {!r} # {!r}',spec.name,spec.loader)\n finally:\n self._spec._initializing=False\n \n \nclass ModuleSpec:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,name,loader,*,origin=None,loader_state=None,\n is_package=None):\n self.name=name\n self.loader=loader\n self.origin=origin\n self.loader_state=loader_state\n self.submodule_search_locations=[]if is_package else None\n \n \n self._set_fileattr=False\n self._cached=None\n \n def __repr__(self):\n args=['name={!r}'.format(self.name),\n 'loader={!r}'.format(self.loader)]\n if self.origin is not None:\n args.append('origin={!r}'.format(self.origin))\n if self.submodule_search_locations is not None:\n args.append('submodule_search_locations={}'\n .format(self.submodule_search_locations))\n return '{}({})'.format(self.__class__.__name__,', '.join(args))\n \n def __eq__(self,other):\n smsl=self.submodule_search_locations\n try:\n return(self.name ==other.name and\n self.loader ==other.loader and\n self.origin ==other.origin and\n smsl ==other.submodule_search_locations and\n self.cached ==other.cached and\n self.has_location ==other.has_location)\n except AttributeError:\n return False\n \n @property\n def cached(self):\n if self._cached is None:\n if self.origin is not None and self._set_fileattr:\n if _bootstrap_external is None:\n raise NotImplementedError\n self._cached=_bootstrap_external._get_cached(self.origin)\n return self._cached\n \n @cached.setter\n def cached(self,cached):\n self._cached=cached\n \n @property\n def parent(self):\n ''\n if self.submodule_search_locations is None:\n return self.name.rpartition('.')[0]\n else:\n return self.name\n \n @property\n def has_location(self):\n return self._set_fileattr\n \n @has_location.setter\n def has_location(self,value):\n self._set_fileattr=bool(value)\n \n \ndef spec_from_loader(name,loader,*,origin=None,is_package=None):\n ''\n if hasattr(loader,'get_filename'):\n if _bootstrap_external is None:\n raise NotImplementedError\n spec_from_file_location=_bootstrap_external.spec_from_file_location\n \n if is_package is None:\n return spec_from_file_location(name,loader=loader)\n search=[]if is_package else None\n return spec_from_file_location(name,loader=loader,\n submodule_search_locations=search)\n \n if is_package is None:\n if hasattr(loader,'is_package'):\n try:\n is_package=loader.is_package(name)\n except ImportError:\n is_package=None\n else:\n \n is_package=False\n \n return ModuleSpec(name,loader,origin=origin,is_package=is_package)\n \n \ndef _spec_from_module(module,loader=None,origin=None):\n\n try:\n spec=module.__spec__\n except AttributeError:\n pass\n else:\n if spec is not None:\n return spec\n \n name=module.__name__\n if loader is None:\n try:\n loader=module.__loader__\n except AttributeError:\n \n pass\n try:\n location=module.__file__\n except AttributeError:\n location=None\n if origin is None:\n if location is None:\n try:\n origin=loader._ORIGIN\n except AttributeError:\n origin=None\n else:\n origin=location\n try:\n cached=module.__cached__\n except AttributeError:\n cached=None\n try:\n submodule_search_locations=list(module.__path__)\n except AttributeError:\n submodule_search_locations=None\n \n spec=ModuleSpec(name,loader,origin=origin)\n spec._set_fileattr=False if location is None else True\n spec.cached=cached\n spec.submodule_search_locations=submodule_search_locations\n return spec\n \n \ndef _init_module_attrs(spec,module,*,override=False):\n\n\n\n if(override or getattr(module,'__name__',None)is None):\n try:\n module.__name__=spec.name\n except AttributeError:\n pass\n \n if override or getattr(module,'__loader__',None)is None:\n loader=spec.loader\n if loader is None:\n \n if spec.submodule_search_locations is not None:\n if _bootstrap_external is None:\n raise NotImplementedError\n _NamespaceLoader=_bootstrap_external._NamespaceLoader\n \n loader=_NamespaceLoader.__new__(_NamespaceLoader)\n loader._path=spec.submodule_search_locations\n spec.loader=loader\n \n \n \n \n \n \n \n \n \n \n module.__file__=None\n try:\n module.__loader__=loader\n except AttributeError:\n pass\n \n if override or getattr(module,'__package__',None)is None:\n try:\n module.__package__=spec.parent\n except AttributeError:\n pass\n \n try:\n module.__spec__=spec\n except AttributeError:\n pass\n \n if override or getattr(module,'__path__',None)is None:\n if spec.submodule_search_locations is not None:\n try:\n module.__path__=spec.submodule_search_locations\n except AttributeError:\n pass\n \n if spec.has_location:\n if override or getattr(module,'__file__',None)is None:\n try:\n module.__file__=spec.origin\n except AttributeError:\n pass\n \n if override or getattr(module,'__cached__',None)is None:\n if spec.cached is not None:\n try:\n module.__cached__=spec.cached\n except AttributeError:\n pass\n return module\n \n \ndef module_from_spec(spec):\n ''\n \n module=None\n if hasattr(spec.loader,'create_module'):\n \n \n module=spec.loader.create_module(spec)\n elif hasattr(spec.loader,'exec_module'):\n raise ImportError('loaders that define exec_module() '\n 'must also define create_module()')\n if module is None:\n module=_new_module(spec.name)\n _init_module_attrs(spec,module)\n return module\n \n \ndef _module_repr_from_spec(spec):\n ''\n \n name='?'if spec.name is None else spec.name\n if spec.origin is None:\n if spec.loader is None:\n return ''.format(name)\n else:\n return ''.format(name,spec.loader)\n else:\n if spec.has_location:\n return ''.format(name,spec.origin)\n else:\n return ''.format(spec.name,spec.origin)\n \n \n \ndef _exec(spec,module):\n ''\n name=spec.name\n with _ModuleLockManager(name):\n if sys.modules.get(name)is not module:\n msg='module {!r} not in sys.modules'.format(name)\n raise ImportError(msg,name=name)\n if spec.loader is None:\n if spec.submodule_search_locations is None:\n raise ImportError('missing loader',name=spec.name)\n \n _init_module_attrs(spec,module,override=True)\n return module\n _init_module_attrs(spec,module,override=True)\n if not hasattr(spec.loader,'exec_module'):\n \n \n \n spec.loader.load_module(name)\n else:\n spec.loader.exec_module(module)\n return sys.modules[name]\n \n \ndef _load_backward_compatible(spec):\n\n\n\n spec.loader.load_module(spec.name)\n \n module=sys.modules[spec.name]\n if getattr(module,'__loader__',None)is None:\n try:\n module.__loader__=spec.loader\n except AttributeError:\n pass\n if getattr(module,'__package__',None)is None:\n try:\n \n \n \n module.__package__=module.__name__\n if not hasattr(module,'__path__'):\n module.__package__=spec.name.rpartition('.')[0]\n except AttributeError:\n pass\n if getattr(module,'__spec__',None)is None:\n try:\n module.__spec__=spec\n except AttributeError:\n pass\n return module\n \ndef _load_unlocked(spec):\n\n if spec.loader is not None:\n \n if not hasattr(spec.loader,'exec_module'):\n return _load_backward_compatible(spec)\n \n module=module_from_spec(spec)\n with _installed_safely(module):\n if spec.loader is None:\n if spec.submodule_search_locations is None:\n raise ImportError('missing loader',name=spec.name)\n \n else:\n spec.loader.exec_module(module)\n \n \n \n \n return sys.modules[spec.name]\n \n \n \ndef _load(spec):\n ''\n\n\n\n\n\n\n \n with _ModuleLockManager(spec.name):\n return _load_unlocked(spec)\n \n \n \n \nclass BuiltinImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(module):\n ''\n\n\n\n \n return ''.format(module.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n if path is not None:\n return None\n if _imp.is_builtin(fullname):\n return spec_from_loader(fullname,cls,origin='built-in')\n else:\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None):\n ''\n\n\n\n\n\n \n spec=cls.find_spec(fullname,path)\n return spec.loader if spec is not None else None\n \n @classmethod\n def create_module(self,spec):\n ''\n if spec.name not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(spec.name),\n name=spec.name)\n return _call_with_frames_removed(_imp.create_builtin,spec)\n \n @classmethod\n def exec_module(self,module):\n ''\n _call_with_frames_removed(_imp.exec_builtin,module)\n \n @classmethod\n @_requires_builtin\n def get_code(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def is_package(cls,fullname):\n ''\n return False\n \n load_module=classmethod(_load_module_shim)\n \n \nclass FrozenImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(m):\n ''\n\n\n\n \n return ''.format(m.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n if _imp.is_frozen(fullname):\n return spec_from_loader(fullname,cls,origin='frozen')\n else:\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None):\n ''\n\n\n\n \n return cls if _imp.is_frozen(fullname)else None\n \n @classmethod\n def create_module(cls,spec):\n ''\n \n @staticmethod\n def exec_module(module):\n name=module.__spec__.name\n if not _imp.is_frozen(name):\n raise ImportError('{!r} is not a frozen module'.format(name),\n name=name)\n code=_call_with_frames_removed(_imp.get_frozen_object,name)\n exec(code,module.__dict__)\n \n @classmethod\n def load_module(cls,fullname):\n ''\n\n\n\n \n return _load_module_shim(cls,fullname)\n \n @classmethod\n @_requires_frozen\n def get_code(cls,fullname):\n ''\n return _imp.get_frozen_object(fullname)\n \n @classmethod\n @_requires_frozen\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_frozen\n def is_package(cls,fullname):\n ''\n return _imp.is_frozen_package(fullname)\n \n \n \n \nclass _ImportLockContext:\n\n ''\n \n def __enter__(self):\n ''\n _imp.acquire_lock()\n \n def __exit__(self,exc_type,exc_value,exc_traceback):\n ''\n _imp.release_lock()\n \n \ndef _resolve_name(name,package,level):\n ''\n bits=package.rsplit('.',level -1)\n if len(bits)= 0')\n if level >0:\n if not isinstance(package,str):\n raise TypeError('__package__ not set to a string')\n elif not package:\n raise ImportError('attempted relative import with no known parent '\n 'package')\n if not name and level ==0:\n raise ValueError('Empty module name')\n \n \n_ERR_MSG_PREFIX='No module named '\n_ERR_MSG=_ERR_MSG_PREFIX+'{!r}'\n\ndef _find_and_load_unlocked(name,import_):\n path=None\n parent=name.rpartition('.')[0]\n if parent:\n if parent not in sys.modules:\n _call_with_frames_removed(import_,parent)\n \n if name in sys.modules:\n return sys.modules[name]\n parent_module=sys.modules[parent]\n try:\n path=parent_module.__path__\n except AttributeError:\n msg=(_ERR_MSG+'; {!r} is not a package').format(name,parent)\n raise ModuleNotFoundError(msg,name=name)from None\n spec=_find_spec(name,path)\n if spec is None:\n raise ModuleNotFoundError(_ERR_MSG.format(name),name=name)\n else:\n module=_load_unlocked(spec)\n if parent:\n \n parent_module=sys.modules[parent]\n setattr(parent_module,name.rpartition('.')[2],module)\n return module\n \n \n_NEEDS_LOADING=object()\n\n\ndef _find_and_load(name,import_):\n ''\n with _ModuleLockManager(name):\n module=sys.modules.get(name,_NEEDS_LOADING)\n if module is _NEEDS_LOADING:\n return _find_and_load_unlocked(name,import_)\n \n if module is None:\n message=('import of {} halted; '\n 'None in sys.modules'.format(name))\n raise ModuleNotFoundError(message,name=name)\n \n _lock_unlock_module(name)\n return module\n \n \ndef _gcd_import(name,package=None,level=0):\n ''\n\n\n\n\n\n\n \n _sanity_check(name,package,level)\n if level >0:\n name=_resolve_name(name,package,level)\n return _find_and_load(name,_gcd_import)\n \n \ndef _handle_fromlist(module,fromlist,import_,*,recursive=False):\n ''\n\n\n\n\n\n \n \n \n if hasattr(module,'__path__'):\n for x in fromlist:\n if not isinstance(x,str):\n if recursive:\n where=module.__name__+'.__all__'\n else:\n where=\"``from list''\"\n raise TypeError(f\"Item in {where} must be str, \"\n f\"not {type(x).__name__}\")\n elif x =='*':\n if not recursive and hasattr(module,'__all__'):\n _handle_fromlist(module,module.__all__,import_,\n recursive=True)\n elif not hasattr(module,x):\n from_name='{}.{}'.format(module.__name__,x)\n try:\n _call_with_frames_removed(import_,from_name)\n except ModuleNotFoundError as exc:\n \n \n \n if(exc.name ==from_name and\n sys.modules.get(from_name,_NEEDS_LOADING)is not None):\n continue\n raise\n return module\n \n \ndef _calc___package__(globals):\n ''\n\n\n\n\n \n package=globals.get('__package__')\n spec=globals.get('__spec__')\n if package is not None:\n if spec is not None and package !=spec.parent:\n _warnings.warn(\"__package__ != __spec__.parent \"\n f\"({package !r} != {spec.parent !r})\",\n ImportWarning,stacklevel=3)\n return package\n elif spec is not None:\n return spec.parent\n else:\n _warnings.warn(\"can't resolve package from __spec__ or __package__, \"\n \"falling back on __name__ and __path__\",\n ImportWarning,stacklevel=3)\n package=globals['__name__']\n if '__path__'not in globals:\n package=package.rpartition('.')[0]\n return package\n \n \ndef __import__(name,globals=None,locals=None,fromlist=(),level=0):\n ''\n\n\n\n\n\n\n\n\n \n if level ==0:\n module=_gcd_import(name)\n else:\n globals_=globals if globals is not None else{}\n package=_calc___package__(globals_)\n module=_gcd_import(name,package,level)\n if not fromlist:\n \n \n if level ==0:\n return _gcd_import(name.partition('.')[0])\n elif not name:\n return module\n else:\n \n \n cut_off=len(name)-len(name.partition('.')[0])\n \n \n return sys.modules[module.__name__[:len(module.__name__)-cut_off]]\n else:\n return _handle_fromlist(module,fromlist,_gcd_import)\n \n \ndef _builtin_from_name(name):\n spec=BuiltinImporter.find_spec(name)\n if spec is None:\n raise ImportError('no built-in module named '+name)\n return _load_unlocked(spec)\n \n \nmodule_type=type(sys)\nfor name,module in sys.modules.items():\n if isinstance(module,module_type):\n if name in sys.builtin_module_names:\n loader=BuiltinImporter\n elif _imp.is_frozen(name):\n loader=FrozenImporter\n else:\n continue\n spec=_spec_from_module(module,loader)\n _init_module_attrs(spec,module)\n \n \nself_module=sys.modules[__name__]\n\n\nfor builtin_name in('_warnings',):\n if builtin_name not in sys.modules:\n builtin_module=_builtin_from_name(builtin_name)\n else:\n builtin_module=sys.modules[builtin_name]\n setattr(self_module,builtin_name,builtin_module)\n \n \ndef _install(sys_module,_imp_module):\n ''\n _setup(sys_module,_imp_module)\n \n sys.meta_path.append(BuiltinImporter)\n sys.meta_path.append(FrozenImporter)\n \n \ndef _install_external_importers():\n ''\n global _bootstrap_external\n import _frozen_importlib_external\n _bootstrap_external=_frozen_importlib_external\n _frozen_importlib_external._install(sys.modules[__name__])\n \n", ["_frozen_importlib_external", "_imp", "_weakref", "sys"]], "_functools": [".py", "from reprlib import recursive_repr\n\nclass partial:\n ''\n\n \n \n __slots__=\"func\",\"args\",\"keywords\",\"__dict__\",\"__weakref__\"\n \n def __new__(*args,**keywords):\n if not args:\n raise TypeError(\"descriptor '__new__' of partial needs an argument\")\n if len(args)<2:\n raise TypeError(\"type 'partial' takes at least one argument\")\n cls,func,*args=args\n if not callable(func):\n raise TypeError(\"the first argument must be callable\")\n args=tuple(args)\n \n if hasattr(func,\"func\")and isinstance(func.args,tuple):\n args=func.args+args\n tmpkw=func.keywords.copy()\n tmpkw.update(keywords)\n keywords=tmpkw\n del tmpkw\n func=func.func\n \n self=super(partial,cls).__new__(cls)\n \n self.func=func\n self.args=args\n self.keywords=keywords\n return self\n \n def __call__(*args,**keywords):\n if not args:\n raise TypeError(\"descriptor '__call__' of partial needs an argument\")\n self,*args=args\n newkeywords=self.keywords.copy()\n newkeywords.update(keywords)\n return self.func(*self.args,*args,**newkeywords)\n \n @recursive_repr()\n def __repr__(self):\n qualname=type(self).__qualname__\n args=[repr(self.func)]\n args.extend(repr(x)for x in self.args)\n args.extend(f\"{k}={v !r}\"for(k,v)in self.keywords.items())\n if type(self).__module__ ==\"functools\":\n return f\"functools.{qualname}({', '.join(args)})\"\n return f\"{qualname}({', '.join(args)})\"\n \n def __reduce__(self):\n return type(self),(self.func,),(self.func,self.args,\n self.keywords or None,self.__dict__ or None)\n \n def __setstate__(self,state):\n if not isinstance(state,tuple):\n raise TypeError(\"argument to __setstate__ must be a tuple\")\n if len(state)!=4:\n raise TypeError(f\"expected 4 items in state, got {len(state)}\")\n func,args,kwds,namespace=state\n if(not callable(func)or not isinstance(args,tuple)or\n (kwds is not None and not isinstance(kwds,dict))or\n (namespace is not None and not isinstance(namespace,dict))):\n raise TypeError(\"invalid partial state\")\n \n args=tuple(args)\n if kwds is None:\n kwds={}\n elif type(kwds)is not dict:\n kwds=dict(kwds)\n if namespace is None:\n namespace={}\n \n self.__dict__=namespace\n self.func=func\n self.args=args\n self.keywords=kwds\n \ndef reduce(func,iterable,initializer=None):\n args=iter(iterable)\n if initializer is not None:\n res=initializer\n else:\n res=next(args)\n while True:\n try:\n res=func(res,next(args))\n except StopIteration:\n return res\n", ["reprlib"]], "_imp": [".py", "''\nimport sys\n\ndef _fix_co_filename(*args,**kw):\n ''\n\n\n\n \n pass\n \ndef acquire_lock(*args,**kw):\n ''\n\n \n pass\n \ncheck_hash_based_pycs=\"\"\"default\"\"\"\n\ndef create_builtin(spec):\n ''\n return __import__(spec.name)\n \ndef create_dynamic(*args,**kw):\n ''\n pass\n \ndef exec_builtin(*args,**kw):\n ''\n pass\n \ndef exec_dynamic(*args,**kw):\n ''\n pass\n \ndef extension_suffixes(*args,**kw):\n ''\n return[]\n \ndef get_frozen_object(*args,**kw):\n ''\n pass\n \ndef init_frozen(*args,**kw):\n ''\n pass\n \ndef is_builtin(module_name):\n\n return module_name in __BRYTHON__.builtin_module_names\n \ndef is_frozen(*args,**kw):\n ''\n return False\n \ndef is_frozen_package(*args,**kw):\n ''\n pass\n \ndef lock_held(*args,**kw):\n ''\n \n return False\n \ndef release_lock(*args,**kw):\n ''\n \n pass\n \ndef source_hash(*args,**kw):\n pass\n", ["sys"]], "_io": [".py", "''\n\n\n\nimport os\nimport abc\nimport codecs\nimport errno\n\ntry:\n from _thread import allocate_lock as Lock\nexcept ImportError:\n from _dummy_thread import allocate_lock as Lock\n \n \nfrom _io_classes import *\nimport _io_classes\n_IOBase=_io_classes._IOBase\n_RawIOBase=_io_classes._RawIOBase\n_BufferedIOBase=_io_classes._BufferedIOBase\n_TextIOBase=_io_classes._TextIOBase\n\nSEEK_SET=0\nSEEK_CUR=1\nSEEK_END=2\n\nvalid_seek_flags={0,1,2}\nif hasattr(os,'SEEK_HOLE'):\n valid_seek_flags.add(os.SEEK_HOLE)\n valid_seek_flags.add(os.SEEK_DATA)\n \n \nDEFAULT_BUFFER_SIZE=8 *1024\n\n\n\n\n\n\nBlockingIOError=BlockingIOError\n\n\ndef __open(file,mode=\"r\",buffering=-1,encoding=None,errors=None,\nnewline=None,closefd=True,opener=None):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not isinstance(file,(str,bytes,int)):\n raise TypeError(\"invalid file: %r\"%file)\n if not isinstance(mode,str):\n raise TypeError(\"invalid mode: %r\"%mode)\n if not isinstance(buffering,int):\n raise TypeError(\"invalid buffering: %r\"%buffering)\n if encoding is not None and not isinstance(encoding,str):\n raise TypeError(\"invalid encoding: %r\"%encoding)\n if errors is not None and not isinstance(errors,str):\n raise TypeError(\"invalid errors: %r\"%errors)\n modes=set(mode)\n if modes -set(\"axrwb+tU\")or len(mode)>len(modes):\n raise ValueError(\"invalid mode: %r\"%mode)\n creating=\"x\"in modes\n reading=\"r\"in modes\n writing=\"w\"in modes\n appending=\"a\"in modes\n updating=\"+\"in modes\n text=\"t\"in modes\n binary=\"b\"in modes\n if \"U\"in modes:\n if creating or writing or appending:\n raise ValueError(\"can't use U and writing mode at once\")\n reading=True\n if text and binary:\n raise ValueError(\"can't have text and binary mode at once\")\n if creating+reading+writing+appending >1:\n raise ValueError(\"can't have read/write/append mode at once\")\n if not(creating or reading or writing or appending):\n raise ValueError(\"must have exactly one of read/write/append mode\")\n if binary and encoding is not None:\n raise ValueError(\"binary mode doesn't take an encoding argument\")\n if binary and errors is not None:\n raise ValueError(\"binary mode doesn't take an errors argument\")\n if binary and newline is not None:\n raise ValueError(\"binary mode doesn't take a newline argument\")\n raw=FileIO(file,\n (creating and \"x\"or \"\")+\n (reading and \"r\"or \"\")+\n (writing and \"w\"or \"\")+\n (appending and \"a\"or \"\")+\n (updating and \"+\"or \"\"),\n closefd,opener=opener)\n line_buffering=False\n if buffering ==1 or buffering <0 and raw.isatty():\n buffering=-1\n line_buffering=True\n if buffering <0:\n buffering=DEFAULT_BUFFER_SIZE\n try:\n bs=os.fstat(raw.fileno()).st_blksize\n except(os.error,AttributeError):\n pass\n else:\n if bs >1:\n buffering=bs\n if buffering <0:\n raise ValueError(\"invalid buffering size\")\n if buffering ==0:\n if binary:\n return raw\n raise ValueError(\"can't have unbuffered text I/O\")\n if updating:\n buffer=BufferedRandom(raw,buffering)\n elif creating or writing or appending:\n buffer=BufferedWriter(raw,buffering)\n elif reading:\n buffer=BufferedReader(raw,buffering)\n else:\n raise ValueError(\"unknown mode: %r\"%mode)\n if binary:\n return buffer\n text=TextIOWrapper(buffer,encoding,errors,newline,line_buffering)\n text.mode=mode\n return text\n \nopen=__open\n\ndef open_code(file):\n return __builtins__.open(file,encoding=\"utf-8\")\n \ndef text_encoding(encoding,stacklevel=2):\n if encoding is None:\n return \"locale\"\n return encoding\n \nclass DocDescriptor:\n ''\n \n def __get__(self,obj,typ):\n return(\n \"open(file, mode='r', buffering=-1, encoding=None, \"\n \"errors=None, newline=None, closefd=True)\\n\\n\"+\n open.__doc__)\n \nclass OpenWrapper:\n ''\n\n\n\n\n\n \n __doc__=DocDescriptor()\n \n def __new__(cls,*args,**kwargs):\n return open(*args,**kwargs)\n \n \n \n \nclass UnsupportedOperation(ValueError,IOError):\n pass\n \n", ["_dummy_thread", "_io_classes", "_thread", "abc", "codecs", "errno", "os"]], "_markupbase": [".py", "''\n\n\n\n\n\n\nimport re\n\n_declname_match=re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\\s*').match\n_declstringlit_match=re.compile(r'(\\'[^\\']*\\'|\"[^\"]*\")\\s*').match\n_commentclose=re.compile(r'--\\s*>')\n_markedsectionclose=re.compile(r']\\s*]\\s*>')\n\n\n\n\n_msmarkedsectionclose=re.compile(r']\\s*>')\n\ndel re\n\n\nclass ParserBase:\n ''\n \n \n def __init__(self):\n if self.__class__ is ParserBase:\n raise RuntimeError(\n \"_markupbase.ParserBase must be subclassed\")\n \n def reset(self):\n self.lineno=1\n self.offset=0\n \n def getpos(self):\n ''\n return self.lineno,self.offset\n \n \n \n \n \n def updatepos(self,i,j):\n if i >=j:\n return j\n rawdata=self.rawdata\n nlines=rawdata.count(\"\\n\",i,j)\n if nlines:\n self.lineno=self.lineno+nlines\n pos=rawdata.rindex(\"\\n\",i,j)\n self.offset=j -(pos+1)\n else:\n self.offset=self.offset+j -i\n return j\n \n _decl_otherchars=''\n \n \n def parse_declaration(self,i):\n \n \n \n \n \n \n \n \n \n \n rawdata=self.rawdata\n j=i+2\n assert rawdata[i:j]==\"\":\n \n return j+1\n if rawdata[j:j+1]in(\"-\",\"\"):\n \n \n return -1\n \n n=len(rawdata)\n if rawdata[j:j+2]=='--':\n \n return self.parse_comment(i)\n elif rawdata[j]=='[':\n \n \n \n \n return self.parse_marked_section(i)\n else:\n decltype,j=self._scan_name(j,i)\n if j <0:\n return j\n if decltype ==\"doctype\":\n self._decl_otherchars=''\n while j \":\n \n data=rawdata[i+2:j]\n if decltype ==\"doctype\":\n self.handle_decl(data)\n else:\n \n \n \n \n self.unknown_decl(data)\n return j+1\n if c in \"\\\"'\":\n m=_declstringlit_match(rawdata,j)\n if not m:\n return -1\n j=m.end()\n elif c in \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\":\n name,j=self._scan_name(j,i)\n elif c in self._decl_otherchars:\n j=j+1\n elif c ==\"[\":\n \n if decltype ==\"doctype\":\n j=self._parse_doctype_subset(j+1,i)\n elif decltype in{\"attlist\",\"linktype\",\"link\",\"element\"}:\n \n \n \n \n raise AssertionError(\"unsupported '[' char in %s declaration\"%decltype)\n else:\n raise AssertionError(\"unexpected '[' char in declaration\")\n else:\n raise AssertionError(\"unexpected %r char in declaration\"%rawdata[j])\n if j <0:\n return j\n return -1\n \n \n \n def parse_marked_section(self,i,report=1):\n rawdata=self.rawdata\n assert rawdata[i:i+3]=='n:\n \n return -1\n if rawdata[j:j+4]==\"\n \n \"\"\"%(self.OutputString(attrs).replace('\"',r'\\\"'))\n \n def OutputString(self,attrs=None):\n \n \n result=[]\n append=result.append\n \n \n append(\"%s=%s\"%(self.key,self.coded_value))\n \n \n if attrs is None:\n attrs=self._reserved\n items=sorted(self.items())\n for key,value in items:\n if value ==\"\":\n continue\n if key not in attrs:\n continue\n if key ==\"expires\"and isinstance(value,int):\n append(\"%s=%s\"%(self._reserved[key],_getdate(value)))\n elif key ==\"max-age\"and isinstance(value,int):\n append(\"%s=%d\"%(self._reserved[key],value))\n elif key ==\"comment\"and isinstance(value,str):\n append(\"%s=%s\"%(self._reserved[key],_quote(value)))\n elif key in self._flags:\n if value:\n append(str(self._reserved[key]))\n else:\n append(\"%s=%s\"%(self._reserved[key],value))\n \n \n return _semispacejoin(result)\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \n \n \n \n \n \n \n \n \n \n_LegalKeyChars=r\"\\w\\d!#%&'~_`><@,:/\\$\\*\\+\\-\\.\\^\\|\\)\\(\\?\\}\\{\\=\"\n_LegalValueChars=_LegalKeyChars+r'\\[\\]'\n_CookiePattern=re.compile(r\"\"\"\n \\s* # Optional whitespace at start of cookie\n (?P # Start of group 'key'\n [\"\"\"+_LegalKeyChars+r\"\"\"]+? # Any word of at least one letter\n ) # End of group 'key'\n ( # Optional group: there may not be a value.\n \\s*=\\s* # Equal Sign\n (?P # Start of group 'val'\n \"(?:[^\\\\\"]|\\\\.)*\" # Any doublequoted string\n | # or\n \\w{3},\\s[\\w\\d\\s-]{9,11}\\s[\\d:]{8}\\sGMT # Special case for \"expires\" attr\n | # or\n [\"\"\"+_LegalValueChars+r\"\"\"]* # Any word or empty string\n ) # End of group 'val'\n )? # End of optional value group\n \\s* # Any number of spaces.\n (\\s+|;|$) # Ending either at space, semicolon, or EOS.\n \"\"\",re.ASCII |re.VERBOSE)\n\n\n\n\n\nclass BaseCookie(dict):\n ''\n \n def value_decode(self,val):\n ''\n\n\n\n\n \n return val,val\n \n def value_encode(self,val):\n ''\n\n\n\n \n strval=str(val)\n return strval,strval\n \n def __init__(self,input=None):\n if input:\n self.load(input)\n \n def __set(self,key,real_value,coded_value):\n ''\n M=self.get(key,Morsel())\n M.set(key,real_value,coded_value)\n dict.__setitem__(self,key,M)\n \n def __setitem__(self,key,value):\n ''\n if isinstance(value,Morsel):\n \n dict.__setitem__(self,key,value)\n else:\n rval,cval=self.value_encode(value)\n self.__set(key,rval,cval)\n \n def output(self,attrs=None,header=\"Set-Cookie:\",sep=\"\\015\\012\"):\n ''\n result=[]\n items=sorted(self.items())\n for key,value in items:\n result.append(value.output(attrs,header))\n return sep.join(result)\n \n __str__=output\n \n def __repr__(self):\n l=[]\n items=sorted(self.items())\n for key,value in items:\n l.append('%s=%s'%(key,repr(value.value)))\n return '<%s: %s>'%(self.__class__.__name__,_spacejoin(l))\n \n def js_output(self,attrs=None):\n ''\n result=[]\n items=sorted(self.items())\n for key,value in items:\n result.append(value.js_output(attrs))\n return _nulljoin(result)\n \n def load(self,rawdata):\n ''\n\n\n\n \n if isinstance(rawdata,str):\n self.__parse_string(rawdata)\n else:\n \n for key,value in rawdata.items():\n self[key]=value\n return\n \n def __parse_string(self,str,patt=_CookiePattern):\n i=0\n n=len(str)\n parsed_items=[]\n morsel_seen=False\n \n TYPE_ATTRIBUTE=1\n TYPE_KEYVALUE=2\n \n \n \n \n while 0 <=i \"%(self.__class__.__name__,self._name_)\n \n CONNECT='CONNECT','Establish a connection to the server.'\n DELETE='DELETE','Remove the target.'\n GET='GET','Retrieve the target.'\n HEAD='HEAD','Same as GET, but only retrieve the status line and header section.'\n OPTIONS='OPTIONS','Describe the communication options for the target.'\n PATCH='PATCH','Apply partial modifications to a target.'\n POST='POST','Perform target-specific processing with the request payload.'\n PUT='PUT','Replace the target with the request payload.'\n TRACE='TRACE','Perform a message loop-back test along the path to the target.'\n", ["enum"], 1], "importlib.abc": [".py", "''\nfrom. import _bootstrap_external\nfrom. import machinery\ntry:\n import _frozen_importlib\nexcept ImportError as exc:\n if exc.name !='_frozen_importlib':\n raise\n _frozen_importlib=None\ntry:\n import _frozen_importlib_external\nexcept ImportError:\n _frozen_importlib_external=_bootstrap_external\nfrom._abc import Loader\nimport abc\nimport warnings\n\nfrom.resources import abc as _resources_abc\n\n\n__all__=[\n'Loader','MetaPathFinder','PathEntryFinder',\n'ResourceLoader','InspectLoader','ExecutionLoader',\n'FileLoader','SourceLoader',\n]\n\n\ndef __getattr__(name):\n ''\n\n\n \n if name in _resources_abc.__all__:\n obj=getattr(_resources_abc,name)\n warnings._deprecated(f\"{__name__}.{name}\",remove=(3,14))\n globals()[name]=obj\n return obj\n raise AttributeError(f'module {__name__ !r} has no attribute {name !r}')\n \n \ndef _register(abstract_cls,*classes):\n for cls in classes:\n abstract_cls.register(cls)\n if _frozen_importlib is not None:\n try:\n frozen_cls=getattr(_frozen_importlib,cls.__name__)\n except AttributeError:\n frozen_cls=getattr(_frozen_importlib_external,cls.__name__)\n abstract_cls.register(frozen_cls)\n \n \nclass MetaPathFinder(metaclass=abc.ABCMeta):\n\n ''\n \n \n \n \n def invalidate_caches(self):\n ''\n\n \n \n_register(MetaPathFinder,machinery.BuiltinImporter,machinery.FrozenImporter,\nmachinery.PathFinder,machinery.WindowsRegistryFinder)\n\n\nclass PathEntryFinder(metaclass=abc.ABCMeta):\n\n ''\n \n def invalidate_caches(self):\n ''\n\n \n \n_register(PathEntryFinder,machinery.FileFinder)\n\n\nclass ResourceLoader(Loader):\n\n ''\n\n\n\n\n \n \n @abc.abstractmethod\n def get_data(self,path):\n ''\n \n raise OSError\n \n \nclass InspectLoader(Loader):\n\n ''\n\n\n\n\n \n \n def is_package(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n def get_code(self,fullname):\n ''\n\n\n\n\n\n \n source=self.get_source(fullname)\n if source is None:\n return None\n return self.source_to_code(source)\n \n @abc.abstractmethod\n def get_source(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n @staticmethod\n def source_to_code(data,path=''):\n ''\n\n\n \n return compile(data,path,'exec',dont_inherit=True)\n \n exec_module=_bootstrap_external._LoaderBasics.exec_module\n load_module=_bootstrap_external._LoaderBasics.load_module\n \n_register(InspectLoader,machinery.BuiltinImporter,machinery.FrozenImporter,machinery.NamespaceLoader)\n\n\nclass ExecutionLoader(InspectLoader):\n\n ''\n\n\n\n\n \n \n @abc.abstractmethod\n def get_filename(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n def get_code(self,fullname):\n ''\n\n\n\n \n source=self.get_source(fullname)\n if source is None:\n return None\n try:\n path=self.get_filename(fullname)\n except ImportError:\n return self.source_to_code(source)\n else:\n return self.source_to_code(source,path)\n \n_register(\nExecutionLoader,\nmachinery.ExtensionFileLoader,\nmachinery.AppleFrameworkLoader,\n)\n\n\nclass FileLoader(_bootstrap_external.FileLoader,ResourceLoader,ExecutionLoader):\n\n ''\n \n \n_register(FileLoader,machinery.SourceFileLoader,\nmachinery.SourcelessFileLoader)\n\n\nclass SourceLoader(_bootstrap_external.SourceLoader,ResourceLoader,ExecutionLoader):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def path_mtime(self,path):\n ''\n if self.path_stats.__func__ is SourceLoader.path_stats:\n raise OSError\n return int(self.path_stats(path)['mtime'])\n \n def path_stats(self,path):\n ''\n\n\n\n\n \n if self.path_mtime.__func__ is SourceLoader.path_mtime:\n raise OSError\n return{'mtime':self.path_mtime(path)}\n \n def set_data(self,path,data):\n ''\n\n\n\n\n\n\n \n \n_register(SourceLoader,machinery.SourceFileLoader)\n", ["_frozen_importlib", "_frozen_importlib_external", "abc", "importlib", "importlib._abc", "importlib._bootstrap_external", "importlib.machinery", "importlib.resources", "importlib.resources.abc", "warnings"]], "importlib.machinery": [".py", "''\n\nfrom._bootstrap import ModuleSpec\nfrom._bootstrap import BuiltinImporter\nfrom._bootstrap import FrozenImporter\nfrom._bootstrap_external import(SOURCE_SUFFIXES,DEBUG_BYTECODE_SUFFIXES,\nOPTIMIZED_BYTECODE_SUFFIXES,BYTECODE_SUFFIXES,\nEXTENSION_SUFFIXES)\nfrom._bootstrap_external import WindowsRegistryFinder\nfrom._bootstrap_external import PathFinder\nfrom._bootstrap_external import FileFinder\nfrom._bootstrap_external import SourceFileLoader\nfrom._bootstrap_external import SourcelessFileLoader\nfrom._bootstrap_external import ExtensionFileLoader\nfrom._bootstrap_external import AppleFrameworkLoader\nfrom._bootstrap_external import NamespaceLoader\n\n\ndef all_suffixes():\n ''\n return SOURCE_SUFFIXES+BYTECODE_SUFFIXES+EXTENSION_SUFFIXES\n", ["importlib._bootstrap", "importlib._bootstrap_external"]], "importlib.readers": [".py", "''\n\n\n\n\n\n\nfrom.resources.readers import(\nFileReader,ZipReader,MultiplexedPath,NamespaceReader,\n)\n\n__all__=['FileReader','ZipReader','MultiplexedPath','NamespaceReader']\n", ["importlib.resources.readers"]], "importlib.simple": [".py", "''\n\n\n\n\n\n\nfrom.resources.simple import(\nSimpleReader,ResourceHandle,ResourceContainer,TraversableReader,\n)\n\n__all__=[\n'SimpleReader','ResourceHandle','ResourceContainer','TraversableReader',\n]\n", ["importlib.resources.simple"]], "importlib.util": [".py", "''\nfrom._abc import Loader\nfrom._bootstrap import module_from_spec\nfrom._bootstrap import _resolve_name\nfrom._bootstrap import spec_from_loader\nfrom._bootstrap import _find_spec\nfrom._bootstrap_external import MAGIC_NUMBER\nfrom._bootstrap_external import _RAW_MAGIC_NUMBER\nfrom._bootstrap_external import cache_from_source\nfrom._bootstrap_external import decode_source\nfrom._bootstrap_external import source_from_cache\nfrom._bootstrap_external import spec_from_file_location\n\nfrom contextlib import contextmanager\nimport _imp\nimport functools\nimport sys\nimport types\nimport warnings\n\n\ndef source_hash(source_bytes):\n ''\n return _imp.source_hash(_RAW_MAGIC_NUMBER,source_bytes)\n \n \ndef resolve_name(name,package):\n ''\n if not name.startswith('.'):\n return name\n elif not package:\n raise ImportError(f'no package specified for {repr(name)} '\n '(required for relative module names)')\n level=0\n for character in name:\n if character !='.':\n break\n level +=1\n return _resolve_name(name[level:],package,level)\n \n \ndef _find_spec_from_path(name,path=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if name not in sys.modules:\n return _find_spec(name,path)\n else:\n module=sys.modules[name]\n if module is None:\n return None\n try:\n spec=module.__spec__\n except AttributeError:\n raise ValueError('{}.__spec__ is not set'.format(name))from None\n else:\n if spec is None:\n raise ValueError('{}.__spec__ is None'.format(name))\n return spec\n \n \ndef find_spec(name,package=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n fullname=resolve_name(name,package)if name.startswith('.')else name\n if fullname not in sys.modules:\n parent_name=fullname.rpartition('.')[0]\n if parent_name:\n parent=__import__(parent_name,fromlist=['__path__'])\n try:\n parent_path=parent.__path__\n except AttributeError as e:\n raise ModuleNotFoundError(\n f\"__path__ attribute not found on {parent_name !r} \"\n f\"while trying to find {fullname !r}\",name=fullname)from e\n else:\n parent_path=None\n return _find_spec(fullname,parent_path)\n else:\n module=sys.modules[fullname]\n if module is None:\n return None\n try:\n spec=module.__spec__\n except AttributeError:\n raise ValueError('{}.__spec__ is not set'.format(name))from None\n else:\n if spec is None:\n raise ValueError('{}.__spec__ is None'.format(name))\n return spec\n \n \n@contextmanager\ndef _module_to_load(name):\n is_reload=name in sys.modules\n \n module=sys.modules.get(name)\n if not is_reload:\n \n \n \n module=type(sys)(name)\n \n \n module.__initializing__=True\n sys.modules[name]=module\n try:\n yield module\n except Exception:\n if not is_reload:\n try:\n del sys.modules[name]\n except KeyError:\n pass\n finally:\n module.__initializing__=False\n \n \ndef set_package(fxn):\n ''\n\n\n\n \n @functools.wraps(fxn)\n def set_package_wrapper(*args,**kwargs):\n warnings.warn('The import system now takes care of this automatically; '\n 'this decorator is slated for removal in Python 3.12',\n DeprecationWarning,stacklevel=2)\n module=fxn(*args,**kwargs)\n if getattr(module,'__package__',None)is None:\n module.__package__=module.__name__\n if not hasattr(module,'__path__'):\n module.__package__=module.__package__.rpartition('.')[0]\n return module\n return set_package_wrapper\n \n \ndef set_loader(fxn):\n ''\n\n\n\n \n @functools.wraps(fxn)\n def set_loader_wrapper(self,*args,**kwargs):\n warnings.warn('The import system now takes care of this automatically; '\n 'this decorator is slated for removal in Python 3.12',\n DeprecationWarning,stacklevel=2)\n module=fxn(self,*args,**kwargs)\n if getattr(module,'__loader__',None)is None:\n module.__loader__=self\n return module\n return set_loader_wrapper\n \n \ndef module_for_loader(fxn):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n warnings.warn('The import system now takes care of this automatically; '\n 'this decorator is slated for removal in Python 3.12',\n DeprecationWarning,stacklevel=2)\n @functools.wraps(fxn)\n def module_for_loader_wrapper(self,fullname,*args,**kwargs):\n with _module_to_load(fullname)as module:\n module.__loader__=self\n try:\n is_package=self.is_package(fullname)\n except(ImportError,AttributeError):\n pass\n else:\n if is_package:\n module.__package__=fullname\n else:\n module.__package__=fullname.rpartition('.')[0]\n \n return fxn(self,module,*args,**kwargs)\n \n return module_for_loader_wrapper\n \n \nclass _LazyModule(types.ModuleType):\n\n ''\n \n def __getattribute__(self,attr):\n ''\n \n \n \n self.__class__=types.ModuleType\n \n \n original_name=self.__spec__.name\n \n \n attrs_then=self.__spec__.loader_state['__dict__']\n attrs_now=self.__dict__\n attrs_updated={}\n for key,value in attrs_now.items():\n \n \n if key not in attrs_then:\n attrs_updated[key]=value\n elif id(attrs_now[key])!=id(attrs_then[key]):\n attrs_updated[key]=value\n self.__spec__.loader.exec_module(self)\n \n \n if original_name in sys.modules:\n if id(self)!=id(sys.modules[original_name]):\n raise ValueError(f\"module object for {original_name !r} \"\n \"substituted in sys.modules during a lazy \"\n \"load\")\n \n \n self.__dict__.update(attrs_updated)\n return getattr(self,attr)\n \n def __delattr__(self,attr):\n ''\n \n \n self.__getattribute__(attr)\n delattr(self,attr)\n \n \nclass LazyLoader(Loader):\n\n ''\n \n @staticmethod\n def __check_eager_loader(loader):\n if not hasattr(loader,'exec_module'):\n raise TypeError('loader must define exec_module()')\n \n @classmethod\n def factory(cls,loader):\n ''\n cls.__check_eager_loader(loader)\n return lambda *args,**kwargs:cls(loader(*args,**kwargs))\n \n def __init__(self,loader):\n self.__check_eager_loader(loader)\n self.loader=loader\n \n def create_module(self,spec):\n return self.loader.create_module(spec)\n \n def exec_module(self,module):\n ''\n module.__spec__.loader=self.loader\n module.__loader__=self.loader\n \n \n \n \n loader_state={}\n loader_state['__dict__']=module.__dict__.copy()\n loader_state['__class__']=module.__class__\n module.__spec__.loader_state=loader_state\n module.__class__=_LazyModule\n", ["_imp", "contextlib", "functools", "importlib._abc", "importlib._bootstrap", "importlib._bootstrap_external", "sys", "types", "warnings"]], "importlib._abc": [".py", "''\nfrom. import _bootstrap\nimport abc\n\n\nclass Loader(metaclass=abc.ABCMeta):\n\n ''\n \n def create_module(self,spec):\n ''\n\n\n\n\n \n \n return None\n \n \n \n \n def load_module(self,fullname):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not hasattr(self,'exec_module'):\n raise ImportError\n \n return _bootstrap._load_module_shim(self,fullname)\n", ["abc", "importlib", "importlib._bootstrap"]], "importlib._bootstrap": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_bootstrap_external=None\n_thread=None\nimport _weakref\n\ndef _wrap(new,old):\n ''\n for replace in['__module__','__name__','__qualname__','__doc__']:\n if hasattr(old,replace):\n setattr(new,replace,getattr(old,replace))\n new.__dict__.update(old.__dict__)\n \n \ndef _new_module(name):\n return type(sys)(name)\n \n \n \n \n \n \n_module_locks={}\n\n_blocking_on={}\n\n\nclass _DeadlockError(RuntimeError):\n pass\n \n \nclass _ModuleLock:\n ''\n\n\n \n \n def __init__(self,name):\n self.lock=_thread.allocate_lock()\n self.wakeup=_thread.allocate_lock()\n self.name=name\n self.owner=None\n self.count=0\n self.waiters=0\n \n def has_deadlock(self):\n \n me=_thread.get_ident()\n tid=self.owner\n while True:\n lock=_blocking_on.get(tid)\n if lock is None:\n return False\n tid=lock.owner\n if tid ==me:\n return True\n \n def acquire(self):\n ''\n\n\n\n \n tid=_thread.get_ident()\n _blocking_on[tid]=self\n try:\n while True:\n with self.lock:\n if self.count ==0 or self.owner ==tid:\n self.owner=tid\n self.count +=1\n return True\n if self.has_deadlock():\n raise _DeadlockError('deadlock detected by %r'%self)\n if self.wakeup.acquire(False):\n self.waiters +=1\n \n self.wakeup.acquire()\n self.wakeup.release()\n finally:\n del _blocking_on[tid]\n \n def release(self):\n tid=_thread.get_ident()\n with self.lock:\n if self.owner !=tid:\n raise RuntimeError('cannot release un-acquired lock')\n assert self.count >0\n self.count -=1\n if self.count ==0:\n self.owner=None\n if self.waiters:\n self.waiters -=1\n self.wakeup.release()\n \n def __repr__(self):\n return '_ModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _DummyModuleLock:\n ''\n \n \n def __init__(self,name):\n self.name=name\n self.count=0\n \n def acquire(self):\n self.count +=1\n return True\n \n def release(self):\n if self.count ==0:\n raise RuntimeError('cannot release un-acquired lock')\n self.count -=1\n \n def __repr__(self):\n return '_DummyModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _ModuleLockManager:\n\n def __init__(self,name):\n self._name=name\n self._lock=None\n \n def __enter__(self):\n self._lock=_get_module_lock(self._name)\n self._lock.acquire()\n \n def __exit__(self,*args,**kwargs):\n self._lock.release()\n \n \n \n \ndef _get_module_lock(name):\n ''\n\n\n \n \n _imp.acquire_lock()\n try:\n try:\n lock=_module_locks[name]()\n except KeyError:\n lock=None\n \n if lock is None:\n if _thread is None:\n lock=_DummyModuleLock(name)\n else:\n lock=_ModuleLock(name)\n \n def cb(ref,name=name):\n _imp.acquire_lock()\n try:\n \n \n \n if _module_locks.get(name)is ref:\n del _module_locks[name]\n finally:\n _imp.release_lock()\n \n _module_locks[name]=_weakref.ref(lock,cb)\n finally:\n _imp.release_lock()\n \n return lock\n \n \ndef _lock_unlock_module(name):\n ''\n\n\n\n \n lock=_get_module_lock(name)\n try:\n lock.acquire()\n except _DeadlockError:\n \n \n pass\n else:\n lock.release()\n \n \ndef _call_with_frames_removed(f,*args,**kwds):\n ''\n\n\n\n\n\n \n return f(*args,**kwds)\n \n \ndef _verbose_message(message,*args,verbosity=1):\n ''\n if sys.flags.verbose >=verbosity:\n if not message.startswith(('#','import ')):\n message='# '+message\n print(message.format(*args),file=sys.stderr)\n \n \ndef _requires_builtin(fxn):\n ''\n def _requires_builtin_wrapper(self,fullname):\n if fullname not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_builtin_wrapper,fxn)\n return _requires_builtin_wrapper\n \n \ndef _requires_frozen(fxn):\n ''\n def _requires_frozen_wrapper(self,fullname):\n if not _imp.is_frozen(fullname):\n raise ImportError('{!r} is not a frozen module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_frozen_wrapper,fxn)\n return _requires_frozen_wrapper\n \n \n \ndef _load_module_shim(self,fullname):\n ''\n\n\n\n \n spec=spec_from_loader(fullname,self)\n if fullname in sys.modules:\n module=sys.modules[fullname]\n _exec(spec,module)\n return sys.modules[fullname]\n else:\n return _load(spec)\n \n \n \ndef _module_repr(module):\n\n loader=getattr(module,'__loader__',None)\n if hasattr(loader,'module_repr'):\n \n \n \n try:\n return loader.module_repr(module)\n except Exception:\n pass\n try:\n spec=module.__spec__\n except AttributeError:\n pass\n else:\n if spec is not None:\n return _module_repr_from_spec(spec)\n \n \n \n try:\n name=module.__name__\n except AttributeError:\n name='?'\n try:\n filename=module.__file__\n except AttributeError:\n if loader is None:\n return ''.format(name)\n else:\n return ''.format(name,loader)\n else:\n return ''.format(name,filename)\n \n \nclass _installed_safely:\n\n def __init__(self,module):\n self._module=module\n self._spec=module.__spec__\n \n def __enter__(self):\n \n \n \n self._spec._initializing=True\n sys.modules[self._spec.name]=self._module\n \n def __exit__(self,*args):\n try:\n spec=self._spec\n if any(arg is not None for arg in args):\n try:\n del sys.modules[spec.name]\n except KeyError:\n pass\n else:\n _verbose_message('import {!r} # {!r}',spec.name,spec.loader)\n finally:\n self._spec._initializing=False\n \n \nclass ModuleSpec:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,name,loader,*,origin=None,loader_state=None,\n is_package=None):\n self.name=name\n self.loader=loader\n self.origin=origin\n self.loader_state=loader_state\n self.submodule_search_locations=[]if is_package else None\n \n \n self._set_fileattr=False\n self._cached=None\n \n def __repr__(self):\n args=['name={!r}'.format(self.name),\n 'loader={!r}'.format(self.loader)]\n if self.origin is not None:\n args.append('origin={!r}'.format(self.origin))\n if self.submodule_search_locations is not None:\n args.append('submodule_search_locations={}'\n .format(self.submodule_search_locations))\n return '{}({})'.format(self.__class__.__name__,', '.join(args))\n \n def __eq__(self,other):\n smsl=self.submodule_search_locations\n try:\n return(self.name ==other.name and\n self.loader ==other.loader and\n self.origin ==other.origin and\n smsl ==other.submodule_search_locations and\n self.cached ==other.cached and\n self.has_location ==other.has_location)\n except AttributeError:\n return False\n \n @property\n def cached(self):\n if self._cached is None:\n if self.origin is not None and self._set_fileattr:\n if _bootstrap_external is None:\n raise NotImplementedError\n self._cached=_bootstrap_external._get_cached(self.origin)\n return self._cached\n \n @cached.setter\n def cached(self,cached):\n self._cached=cached\n \n @property\n def parent(self):\n ''\n if self.submodule_search_locations is None:\n return self.name.rpartition('.')[0]\n else:\n return self.name\n \n @property\n def has_location(self):\n return self._set_fileattr\n \n @has_location.setter\n def has_location(self,value):\n self._set_fileattr=bool(value)\n \n \ndef spec_from_loader(name,loader,*,origin=None,is_package=None):\n ''\n if hasattr(loader,'get_filename'):\n if _bootstrap_external is None:\n raise NotImplementedError\n spec_from_file_location=_bootstrap_external.spec_from_file_location\n \n if is_package is None:\n return spec_from_file_location(name,loader=loader)\n search=[]if is_package else None\n return spec_from_file_location(name,loader=loader,\n submodule_search_locations=search)\n \n if is_package is None:\n if hasattr(loader,'is_package'):\n try:\n is_package=loader.is_package(name)\n except ImportError:\n is_package=None\n else:\n \n is_package=False\n \n return ModuleSpec(name,loader,origin=origin,is_package=is_package)\n \n \ndef _spec_from_module(module,loader=None,origin=None):\n\n try:\n spec=module.__spec__\n except AttributeError:\n pass\n else:\n if spec is not None:\n return spec\n \n name=module.__name__\n if loader is None:\n try:\n loader=module.__loader__\n except AttributeError:\n \n pass\n try:\n location=module.__file__\n except AttributeError:\n location=None\n if origin is None:\n if location is None:\n try:\n origin=loader._ORIGIN\n except AttributeError:\n origin=None\n else:\n origin=location\n try:\n cached=module.__cached__\n except AttributeError:\n cached=None\n try:\n submodule_search_locations=list(module.__path__)\n except AttributeError:\n submodule_search_locations=None\n \n spec=ModuleSpec(name,loader,origin=origin)\n spec._set_fileattr=False if location is None else True\n spec.cached=cached\n spec.submodule_search_locations=submodule_search_locations\n return spec\n \n \ndef _init_module_attrs(spec,module,*,override=False):\n\n\n\n if(override or getattr(module,'__name__',None)is None):\n try:\n module.__name__=spec.name\n except AttributeError:\n pass\n \n if override or getattr(module,'__loader__',None)is None:\n loader=spec.loader\n if loader is None:\n \n if spec.submodule_search_locations is not None:\n if _bootstrap_external is None:\n raise NotImplementedError\n _NamespaceLoader=_bootstrap_external._NamespaceLoader\n \n loader=_NamespaceLoader.__new__(_NamespaceLoader)\n loader._path=spec.submodule_search_locations\n spec.loader=loader\n \n \n \n \n \n \n \n \n \n \n module.__file__=None\n try:\n module.__loader__=loader\n except AttributeError:\n pass\n \n if override or getattr(module,'__package__',None)is None:\n try:\n module.__package__=spec.parent\n except AttributeError:\n pass\n \n try:\n module.__spec__=spec\n except AttributeError:\n pass\n \n if override or getattr(module,'__path__',None)is None:\n if spec.submodule_search_locations is not None:\n try:\n module.__path__=spec.submodule_search_locations\n except AttributeError:\n pass\n \n if spec.has_location:\n if override or getattr(module,'__file__',None)is None:\n try:\n module.__file__=spec.origin\n except AttributeError:\n pass\n \n if override or getattr(module,'__cached__',None)is None:\n if spec.cached is not None:\n try:\n module.__cached__=spec.cached\n except AttributeError:\n pass\n return module\n \n \ndef module_from_spec(spec):\n ''\n \n module=None\n if hasattr(spec.loader,'create_module'):\n \n \n module=spec.loader.create_module(spec)\n elif hasattr(spec.loader,'exec_module'):\n raise ImportError('loaders that define exec_module() '\n 'must also define create_module()')\n if module is None:\n module=_new_module(spec.name)\n _init_module_attrs(spec,module)\n return module\n \n \ndef _module_repr_from_spec(spec):\n ''\n \n name='?'if spec.name is None else spec.name\n if spec.origin is None:\n if spec.loader is None:\n return ''.format(name)\n else:\n return ''.format(name,spec.loader)\n else:\n if spec.has_location:\n return ''.format(name,spec.origin)\n else:\n return ''.format(spec.name,spec.origin)\n \n \n \ndef _exec(spec,module):\n ''\n name=spec.name\n with _ModuleLockManager(name):\n if sys.modules.get(name)is not module:\n msg='module {!r} not in sys.modules'.format(name)\n raise ImportError(msg,name=name)\n if spec.loader is None:\n if spec.submodule_search_locations is None:\n raise ImportError('missing loader',name=spec.name)\n \n _init_module_attrs(spec,module,override=True)\n return module\n _init_module_attrs(spec,module,override=True)\n if not hasattr(spec.loader,'exec_module'):\n \n \n \n spec.loader.load_module(name)\n else:\n spec.loader.exec_module(module)\n return sys.modules[name]\n \n \ndef _load_backward_compatible(spec):\n\n\n\n spec.loader.load_module(spec.name)\n \n module=sys.modules[spec.name]\n if getattr(module,'__loader__',None)is None:\n try:\n module.__loader__=spec.loader\n except AttributeError:\n pass\n if getattr(module,'__package__',None)is None:\n try:\n \n \n \n module.__package__=module.__name__\n if not hasattr(module,'__path__'):\n module.__package__=spec.name.rpartition('.')[0]\n except AttributeError:\n pass\n if getattr(module,'__spec__',None)is None:\n try:\n module.__spec__=spec\n except AttributeError:\n pass\n return module\n \ndef _load_unlocked(spec):\n\n if spec.loader is not None:\n \n if not hasattr(spec.loader,'exec_module'):\n return _load_backward_compatible(spec)\n \n module=module_from_spec(spec)\n with _installed_safely(module):\n if spec.loader is None:\n if spec.submodule_search_locations is None:\n raise ImportError('missing loader',name=spec.name)\n \n else:\n spec.loader.exec_module(module)\n \n \n \n \n return sys.modules[spec.name]\n \n \n \ndef _load(spec):\n ''\n\n\n\n\n\n\n \n with _ModuleLockManager(spec.name):\n return _load_unlocked(spec)\n \n \n \n \nclass BuiltinImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(module):\n ''\n\n\n\n \n return ''.format(module.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n if path is not None:\n return None\n if _imp.is_builtin(fullname):\n return spec_from_loader(fullname,cls,origin='built-in')\n else:\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None):\n ''\n\n\n\n\n\n \n spec=cls.find_spec(fullname,path)\n return spec.loader if spec is not None else None\n \n @classmethod\n def create_module(self,spec):\n ''\n if spec.name not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(spec.name),\n name=spec.name)\n return _call_with_frames_removed(_imp.create_builtin,spec)\n \n @classmethod\n def exec_module(self,module):\n ''\n _call_with_frames_removed(_imp.exec_builtin,module)\n \n @classmethod\n @_requires_builtin\n def get_code(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def is_package(cls,fullname):\n ''\n return False\n \n load_module=classmethod(_load_module_shim)\n \n \nclass FrozenImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(m):\n ''\n\n\n\n \n return ''.format(m.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n if _imp.is_frozen(fullname):\n return spec_from_loader(fullname,cls,origin='frozen')\n else:\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None):\n ''\n\n\n\n \n return cls if _imp.is_frozen(fullname)else None\n \n @classmethod\n def create_module(cls,spec):\n ''\n \n @staticmethod\n def exec_module(module):\n name=module.__spec__.name\n if not _imp.is_frozen(name):\n raise ImportError('{!r} is not a frozen module'.format(name),\n name=name)\n code=_call_with_frames_removed(_imp.get_frozen_object,name)\n exec(code,module.__dict__)\n \n @classmethod\n def load_module(cls,fullname):\n ''\n\n\n\n \n return _load_module_shim(cls,fullname)\n \n @classmethod\n @_requires_frozen\n def get_code(cls,fullname):\n ''\n return _imp.get_frozen_object(fullname)\n \n @classmethod\n @_requires_frozen\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_frozen\n def is_package(cls,fullname):\n ''\n return _imp.is_frozen_package(fullname)\n \n \n \n \nclass _ImportLockContext:\n\n ''\n \n def __enter__(self):\n ''\n _imp.acquire_lock()\n \n def __exit__(self,exc_type,exc_value,exc_traceback):\n ''\n _imp.release_lock()\n \n \ndef _resolve_name(name,package,level):\n ''\n bits=package.rsplit('.',level -1)\n if len(bits)= 0')\n if level >0:\n if not isinstance(package,str):\n raise TypeError('__package__ not set to a string')\n elif not package:\n raise ImportError('attempted relative import with no known parent '\n 'package')\n if not name and level ==0:\n raise ValueError('Empty module name')\n \n \n_ERR_MSG_PREFIX='No module named '\n_ERR_MSG=_ERR_MSG_PREFIX+'{!r}'\n\ndef _find_and_load_unlocked(name,import_):\n path=None\n parent=name.rpartition('.')[0]\n if parent:\n if parent not in sys.modules:\n _call_with_frames_removed(import_,parent)\n \n if name in sys.modules:\n return sys.modules[name]\n parent_module=sys.modules[parent]\n try:\n path=parent_module.__path__\n except AttributeError:\n msg=(_ERR_MSG+'; {!r} is not a package').format(name,parent)\n raise ModuleNotFoundError(msg,name=name)from None\n spec=_find_spec(name,path)\n if spec is None:\n raise ModuleNotFoundError(_ERR_MSG.format(name),name=name)\n else:\n module=_load_unlocked(spec)\n if parent:\n \n parent_module=sys.modules[parent]\n setattr(parent_module,name.rpartition('.')[2],module)\n return module\n \n \n_NEEDS_LOADING=object()\n\n\ndef _find_and_load(name,import_):\n ''\n with _ModuleLockManager(name):\n module=sys.modules.get(name,_NEEDS_LOADING)\n if module is _NEEDS_LOADING:\n return _find_and_load_unlocked(name,import_)\n \n if module is None:\n message=('import of {} halted; '\n 'None in sys.modules'.format(name))\n raise ModuleNotFoundError(message,name=name)\n \n _lock_unlock_module(name)\n return module\n \n \ndef _gcd_import(name,package=None,level=0):\n ''\n\n\n\n\n\n\n \n _sanity_check(name,package,level)\n if level >0:\n name=_resolve_name(name,package,level)\n return _find_and_load(name,_gcd_import)\n \n \ndef _handle_fromlist(module,fromlist,import_,*,recursive=False):\n ''\n\n\n\n\n\n \n \n \n if hasattr(module,'__path__'):\n for x in fromlist:\n if not isinstance(x,str):\n if recursive:\n where=module.__name__+'.__all__'\n else:\n where=\"``from list''\"\n raise TypeError(f\"Item in {where} must be str, \"\n f\"not {type(x).__name__}\")\n elif x =='*':\n if not recursive and hasattr(module,'__all__'):\n _handle_fromlist(module,module.__all__,import_,\n recursive=True)\n elif not hasattr(module,x):\n from_name='{}.{}'.format(module.__name__,x)\n try:\n _call_with_frames_removed(import_,from_name)\n except ModuleNotFoundError as exc:\n \n \n \n if(exc.name ==from_name and\n sys.modules.get(from_name,_NEEDS_LOADING)is not None):\n continue\n raise\n return module\n \n \ndef _calc___package__(globals):\n ''\n\n\n\n\n \n package=globals.get('__package__')\n spec=globals.get('__spec__')\n if package is not None:\n if spec is not None and package !=spec.parent:\n _warnings.warn(\"__package__ != __spec__.parent \"\n f\"({package !r} != {spec.parent !r})\",\n ImportWarning,stacklevel=3)\n return package\n elif spec is not None:\n return spec.parent\n else:\n _warnings.warn(\"can't resolve package from __spec__ or __package__, \"\n \"falling back on __name__ and __path__\",\n ImportWarning,stacklevel=3)\n package=globals['__name__']\n if '__path__'not in globals:\n package=package.rpartition('.')[0]\n return package\n \n \ndef __import__(name,globals=None,locals=None,fromlist=(),level=0):\n ''\n\n\n\n\n\n\n\n\n \n if level ==0:\n module=_gcd_import(name)\n else:\n globals_=globals if globals is not None else{}\n package=_calc___package__(globals_)\n module=_gcd_import(name,package,level)\n if not fromlist:\n \n \n if level ==0:\n return _gcd_import(name.partition('.')[0])\n elif not name:\n return module\n else:\n \n \n cut_off=len(name)-len(name.partition('.')[0])\n \n \n return sys.modules[module.__name__[:len(module.__name__)-cut_off]]\n else:\n return _handle_fromlist(module,fromlist,_gcd_import)\n \n \ndef _builtin_from_name(name):\n spec=BuiltinImporter.find_spec(name)\n if spec is None:\n raise ImportError('no built-in module named '+name)\n return _load_unlocked(spec)\n \n \ndef _setup(sys_module,_imp_module):\n ''\n\n\n\n\n\n \n global _imp,sys\n _imp=_imp_module\n sys=sys_module\n \n \n module_type=type(sys)\n for name,module in sys.modules.items():\n if isinstance(module,module_type):\n if name in sys.builtin_module_names:\n loader=BuiltinImporter\n elif _imp.is_frozen(name):\n loader=FrozenImporter\n else:\n continue\n spec=_spec_from_module(module,loader)\n _init_module_attrs(spec,module)\n \n \n self_module=sys.modules[__name__]\n \n \n for builtin_name in('_warnings',):\n if builtin_name not in sys.modules:\n builtin_module=_builtin_from_name(builtin_name)\n else:\n builtin_module=sys.modules[builtin_name]\n setattr(self_module,builtin_name,builtin_module)\n \n \ndef _install(sys_module,_imp_module):\n ''\n _setup(sys_module,_imp_module)\n \n sys.meta_path.append(BuiltinImporter)\n sys.meta_path.append(FrozenImporter)\n \n \ndef _install_external_importers():\n ''\n global _bootstrap_external\n import _frozen_importlib_external\n _bootstrap_external=_frozen_importlib_external\n _frozen_importlib_external._install(sys.modules[__name__])\n", ["_frozen_importlib_external", "_weakref"]], "importlib._bootstrap_external": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_bootstrap=None\n\n\nimport _imp\nimport _io\nimport sys\nimport _warnings\nimport marshal\n\n\n_MS_WINDOWS=(sys.platform =='win32')\nif _MS_WINDOWS:\n import nt as _os\n import winreg\nelse:\n import posix as _os\n \n \nif _MS_WINDOWS:\n path_separators=['\\\\','/']\nelse:\n path_separators=['/']\n \nassert all(len(sep)==1 for sep in path_separators)\npath_sep=path_separators[0]\npath_sep_tuple=tuple(path_separators)\npath_separators=''.join(path_separators)\n_pathseps_with_colon={f':{s}'for s in path_separators}\n\n\n\n_CASE_INSENSITIVE_PLATFORMS_STR_KEY='win',\n_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY='cygwin','darwin','ios','tvos','watchos'\n_CASE_INSENSITIVE_PLATFORMS=(_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY\n+_CASE_INSENSITIVE_PLATFORMS_STR_KEY)\n\n\ndef _make_relax_case():\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY):\n key='PYTHONCASEOK'\n else:\n key=b'PYTHONCASEOK'\n \n def _relax_case():\n ''\n return not sys.flags.ignore_environment and key in _os.environ\n else:\n def _relax_case():\n ''\n return False\n return _relax_case\n \n_relax_case=_make_relax_case()\n\n\ndef _pack_uint32(x):\n ''\n return(int(x)&0xFFFFFFFF).to_bytes(4,'little')\n \n \ndef _unpack_uint64(data):\n ''\n assert len(data)==8\n return int.from_bytes(data,'little')\n \ndef _unpack_uint32(data):\n ''\n assert len(data)==4\n return int.from_bytes(data,'little')\n \ndef _unpack_uint16(data):\n ''\n assert len(data)==2\n return int.from_bytes(data,'little')\n \n \nif _MS_WINDOWS:\n def _path_join(*path_parts):\n ''\n if not path_parts:\n return \"\"\n if len(path_parts)==1:\n return path_parts[0]\n root=\"\"\n path=[]\n for new_root,tail in map(_os._path_splitroot,path_parts):\n if new_root.startswith(path_sep_tuple)or new_root.endswith(path_sep_tuple):\n root=new_root.rstrip(path_separators)or root\n path=[path_sep+tail]\n elif new_root.endswith(':'):\n if root.casefold()!=new_root.casefold():\n \n \n root=new_root\n path=[tail]\n else:\n path.append(tail)\n else:\n root=new_root or root\n path.append(tail)\n path=[p.rstrip(path_separators)for p in path if p]\n if len(path)==1 and not path[0]:\n \n return root+path_sep\n return root+path_sep.join(path)\n \nelse:\n def _path_join(*path_parts):\n ''\n return path_sep.join([part.rstrip(path_separators)\n for part in path_parts if part])\n \n \ndef _path_split(path):\n ''\n i=max(path.rfind(p)for p in path_separators)\n if i <0:\n return '',path\n return path[:i],path[i+1:]\n \n \ndef _path_stat(path):\n ''\n\n\n\n\n \n return _os.stat(path)\n \n \ndef _path_is_mode_type(path,mode):\n ''\n try:\n stat_info=_path_stat(path)\n except OSError:\n return False\n return(stat_info.st_mode&0o170000)==mode\n \n \ndef _path_isfile(path):\n ''\n return _path_is_mode_type(path,0o100000)\n \n \ndef _path_isdir(path):\n ''\n if not path:\n path=_os.getcwd()\n return _path_is_mode_type(path,0o040000)\n \n \nif _MS_WINDOWS:\n def _path_isabs(path):\n ''\n if not path:\n return False\n root=_os._path_splitroot(path)[0].replace('/','\\\\')\n return len(root)>1 and(root.startswith('\\\\\\\\')or root.endswith('\\\\'))\n \nelse:\n def _path_isabs(path):\n ''\n return path.startswith(path_separators)\n \n \ndef _path_abspath(path):\n ''\n if not _path_isabs(path):\n for sep in path_separators:\n path=path.removeprefix(f\".{sep}\")\n return _path_join(_os.getcwd(),path)\n else:\n return path\n \n \ndef _write_atomic(path,data,mode=0o666):\n ''\n\n \n \n path_tmp=f'{path}.{id(path)}'\n fd=_os.open(path_tmp,\n _os.O_EXCL |_os.O_CREAT |_os.O_WRONLY,mode&0o666)\n try:\n \n \n with _io.FileIO(fd,'wb')as file:\n file.write(data)\n _os.replace(path_tmp,path)\n except OSError:\n try:\n _os.unlink(path_tmp)\n except OSError:\n pass\n raise\n \n \n_code_type=type(_write_atomic.__code__)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nMAGIC_NUMBER=(3570).to_bytes(2,'little')+b'\\r\\n'\n\n_RAW_MAGIC_NUMBER=int.from_bytes(MAGIC_NUMBER,'little')\n\n_PYCACHE='__pycache__'\n_OPT='opt-'\n\nSOURCE_SUFFIXES=['.py']\nif _MS_WINDOWS:\n SOURCE_SUFFIXES.append('.pyw')\n \nEXTENSION_SUFFIXES=_imp.extension_suffixes()\n\nBYTECODE_SUFFIXES=['.pyc']\n\nDEBUG_BYTECODE_SUFFIXES=OPTIMIZED_BYTECODE_SUFFIXES=BYTECODE_SUFFIXES\n\ndef cache_from_source(path,debug_override=None,*,optimization=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if debug_override is not None:\n _warnings.warn('the debug_override parameter is deprecated; use '\n \"'optimization' instead\",DeprecationWarning)\n if optimization is not None:\n message='debug_override or optimization must be set to None'\n raise TypeError(message)\n optimization=''if debug_override else 1\n path=_os.fspath(path)\n head,tail=_path_split(path)\n base,sep,rest=tail.rpartition('.')\n tag=sys.implementation.cache_tag\n if tag is None:\n raise NotImplementedError('sys.implementation.cache_tag is None')\n almost_filename=''.join([(base if base else rest),sep,tag])\n if optimization is None:\n if sys.flags.optimize ==0:\n optimization=''\n else:\n optimization=sys.flags.optimize\n optimization=str(optimization)\n if optimization !='':\n if not optimization.isalnum():\n raise ValueError(f'{optimization !r} is not alphanumeric')\n almost_filename=f'{almost_filename}.{_OPT}{optimization}'\n filename=almost_filename+BYTECODE_SUFFIXES[0]\n if sys.pycache_prefix is not None:\n \n \n \n \n \n \n \n \n head=_path_abspath(head)\n \n \n \n \n if head[1]==':'and head[0]not in path_separators:\n head=head[2:]\n \n \n \n return _path_join(\n sys.pycache_prefix,\n head.lstrip(path_separators),\n filename,\n )\n return _path_join(head,_PYCACHE,filename)\n \n \ndef source_from_cache(path):\n ''\n\n\n\n\n\n\n \n if sys.implementation.cache_tag is None:\n raise NotImplementedError('sys.implementation.cache_tag is None')\n path=_os.fspath(path)\n head,pycache_filename=_path_split(path)\n found_in_pycache_prefix=False\n if sys.pycache_prefix is not None:\n stripped_path=sys.pycache_prefix.rstrip(path_separators)\n if head.startswith(stripped_path+path_sep):\n head=head[len(stripped_path):]\n found_in_pycache_prefix=True\n if not found_in_pycache_prefix:\n head,pycache=_path_split(head)\n if pycache !=_PYCACHE:\n raise ValueError(f'{_PYCACHE} not bottom-level directory in '\n f'{path !r}')\n dot_count=pycache_filename.count('.')\n if dot_count not in{2,3}:\n raise ValueError(f'expected only 2 or 3 dots in {pycache_filename !r}')\n elif dot_count ==3:\n optimization=pycache_filename.rsplit('.',2)[-2]\n if not optimization.startswith(_OPT):\n raise ValueError(\"optimization portion of filename does not start \"\n f\"with {_OPT !r}\")\n opt_level=optimization[len(_OPT):]\n if not opt_level.isalnum():\n raise ValueError(f\"optimization level {optimization !r} is not an \"\n \"alphanumeric value\")\n base_filename=pycache_filename.partition('.')[0]\n return _path_join(head,base_filename+SOURCE_SUFFIXES[0])\n \n \ndef _get_sourcefile(bytecode_path):\n ''\n\n\n\n\n \n if len(bytecode_path)==0:\n return None\n rest,_,extension=bytecode_path.rpartition('.')\n if not rest or extension.lower()[-3:-1]!='py':\n return bytecode_path\n try:\n source_path=source_from_cache(bytecode_path)\n except(NotImplementedError,ValueError):\n source_path=bytecode_path[:-1]\n return source_path if _path_isfile(source_path)else bytecode_path\n \n \ndef _get_cached(filename):\n if filename.endswith(tuple(SOURCE_SUFFIXES)):\n try:\n return cache_from_source(filename)\n except NotImplementedError:\n pass\n elif filename.endswith(tuple(BYTECODE_SUFFIXES)):\n return filename\n else:\n return None\n \n \ndef _calc_mode(path):\n ''\n try:\n mode=_path_stat(path).st_mode\n except OSError:\n mode=0o666\n \n \n mode |=0o200\n return mode\n \n \ndef _check_name(method):\n ''\n\n\n\n\n\n \n def _check_name_wrapper(self,name=None,*args,**kwargs):\n if name is None:\n name=self.name\n elif self.name !=name:\n raise ImportError('loader for %s cannot handle %s'%\n (self.name,name),name=name)\n return method(self,name,*args,**kwargs)\n \n \n \n if _bootstrap is not None:\n _wrap=_bootstrap._wrap\n else:\n def _wrap(new,old):\n for replace in['__module__','__name__','__qualname__','__doc__']:\n if hasattr(old,replace):\n setattr(new,replace,getattr(old,replace))\n new.__dict__.update(old.__dict__)\n \n _wrap(_check_name_wrapper,method)\n return _check_name_wrapper\n \n \ndef _classify_pyc(data,name,exc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n magic=data[:4]\n if magic !=MAGIC_NUMBER:\n message=f'bad magic number in {name !r}: {magic !r}'\n _bootstrap._verbose_message('{}',message)\n raise ImportError(message,**exc_details)\n if len(data)<16:\n message=f'reached EOF while reading pyc header of {name !r}'\n _bootstrap._verbose_message('{}',message)\n raise EOFError(message)\n flags=_unpack_uint32(data[4:8])\n \n if flags&~0b11:\n message=f'invalid flags {flags !r} in {name !r}'\n raise ImportError(message,**exc_details)\n return flags\n \n \ndef _validate_timestamp_pyc(data,source_mtime,source_size,name,\nexc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if _unpack_uint32(data[8:12])!=(source_mtime&0xFFFFFFFF):\n message=f'bytecode is stale for {name !r}'\n _bootstrap._verbose_message('{}',message)\n raise ImportError(message,**exc_details)\n if(source_size is not None and\n _unpack_uint32(data[12:16])!=(source_size&0xFFFFFFFF)):\n raise ImportError(f'bytecode is stale for {name !r}',**exc_details)\n \n \ndef _validate_hash_pyc(data,source_hash,name,exc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if data[8:16]!=source_hash:\n raise ImportError(\n f'hash in bytecode doesn\\'t match hash of source {name !r}',\n **exc_details,\n )\n \n \ndef _compile_bytecode(data,name=None,bytecode_path=None,source_path=None):\n ''\n code=marshal.loads(data)\n if isinstance(code,_code_type):\n _bootstrap._verbose_message('code object from {!r}',bytecode_path)\n if source_path is not None:\n _imp._fix_co_filename(code,source_path)\n return code\n else:\n raise ImportError(f'Non-code object in {bytecode_path !r}',\n name=name,path=bytecode_path)\n \n \ndef _code_to_timestamp_pyc(code,mtime=0,source_size=0):\n ''\n data=bytearray(MAGIC_NUMBER)\n data.extend(_pack_uint32(0))\n data.extend(_pack_uint32(mtime))\n data.extend(_pack_uint32(source_size))\n data.extend(marshal.dumps(code))\n return data\n \n \ndef _code_to_hash_pyc(code,source_hash,checked=True):\n ''\n data=bytearray(MAGIC_NUMBER)\n flags=0b1 |checked <<1\n data.extend(_pack_uint32(flags))\n assert len(source_hash)==8\n data.extend(source_hash)\n data.extend(marshal.dumps(code))\n return data\n \n \ndef decode_source(source_bytes):\n ''\n\n\n \n import tokenize\n source_bytes_readline=_io.BytesIO(source_bytes).readline\n encoding=tokenize.detect_encoding(source_bytes_readline)\n newline_decoder=_io.IncrementalNewlineDecoder(None,True)\n return newline_decoder.decode(source_bytes.decode(encoding[0]))\n \n \n \n \n_POPULATE=object()\n\n\ndef spec_from_file_location(name,location=None,*,loader=None,\nsubmodule_search_locations=_POPULATE):\n ''\n\n\n\n\n\n\n\n\n \n if location is None:\n \n \n \n location=''\n if hasattr(loader,'get_filename'):\n \n try:\n location=loader.get_filename(name)\n except ImportError:\n pass\n else:\n location=_os.fspath(location)\n try:\n location=_path_abspath(location)\n except OSError:\n pass\n \n \n \n \n \n \n \n spec=_bootstrap.ModuleSpec(name,loader,origin=location)\n spec._set_fileattr=True\n \n \n if loader is None:\n for loader_class,suffixes in _get_supported_file_loaders():\n if location.endswith(tuple(suffixes)):\n loader=loader_class(name,location)\n spec.loader=loader\n break\n else:\n return None\n \n \n if submodule_search_locations is _POPULATE:\n \n if hasattr(loader,'is_package'):\n try:\n is_package=loader.is_package(name)\n except ImportError:\n pass\n else:\n if is_package:\n spec.submodule_search_locations=[]\n else:\n spec.submodule_search_locations=submodule_search_locations\n if spec.submodule_search_locations ==[]:\n if location:\n dirname=_path_split(location)[0]\n spec.submodule_search_locations.append(dirname)\n \n return spec\n \n \ndef _bless_my_loader(module_globals):\n ''\n\n\n \n \n \n \n \n \n \n \n if not isinstance(module_globals,dict):\n return None\n \n missing=object()\n loader=module_globals.get('__loader__',None)\n spec=module_globals.get('__spec__',missing)\n \n if loader is None:\n if spec is missing:\n \n \n return None\n elif spec is None:\n raise ValueError('Module globals is missing a __spec__.loader')\n \n spec_loader=getattr(spec,'loader',missing)\n \n if spec_loader in(missing,None):\n if loader is None:\n exc=AttributeError if spec_loader is missing else ValueError\n raise exc('Module globals is missing a __spec__.loader')\n _warnings.warn(\n 'Module globals is missing a __spec__.loader',\n DeprecationWarning)\n spec_loader=loader\n \n assert spec_loader is not None\n if loader is not None and loader !=spec_loader:\n _warnings.warn(\n 'Module globals; __loader__ != __spec__.loader',\n DeprecationWarning)\n return loader\n \n return spec_loader\n \n \n \n \nclass WindowsRegistryFinder:\n\n ''\n \n REGISTRY_KEY=(\n 'Software\\\\Python\\\\PythonCore\\\\{sys_version}'\n '\\\\Modules\\\\{fullname}')\n REGISTRY_KEY_DEBUG=(\n 'Software\\\\Python\\\\PythonCore\\\\{sys_version}'\n '\\\\Modules\\\\{fullname}\\\\Debug')\n DEBUG_BUILD=(_MS_WINDOWS and '_d.pyd'in EXTENSION_SUFFIXES)\n \n @staticmethod\n def _open_registry(key):\n try:\n return winreg.OpenKey(winreg.HKEY_CURRENT_USER,key)\n except OSError:\n return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,key)\n \n @classmethod\n def _search_registry(cls,fullname):\n if cls.DEBUG_BUILD:\n registry_key=cls.REGISTRY_KEY_DEBUG\n else:\n registry_key=cls.REGISTRY_KEY\n key=registry_key.format(fullname=fullname,\n sys_version='%d.%d'%sys.version_info[:2])\n try:\n with cls._open_registry(key)as hkey:\n filepath=winreg.QueryValue(hkey,'')\n except OSError:\n return None\n return filepath\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n filepath=cls._search_registry(fullname)\n if filepath is None:\n return None\n try:\n _path_stat(filepath)\n except OSError:\n return None\n for loader,suffixes in _get_supported_file_loaders():\n if filepath.endswith(tuple(suffixes)):\n spec=_bootstrap.spec_from_loader(fullname,\n loader(fullname,filepath),\n origin=filepath)\n return spec\n \n \nclass _LoaderBasics:\n\n ''\n \n \n def is_package(self,fullname):\n ''\n \n filename=_path_split(self.get_filename(fullname))[1]\n filename_base=filename.rsplit('.',1)[0]\n tail_name=fullname.rpartition('.')[2]\n return filename_base =='__init__'and tail_name !='__init__'\n \n def create_module(self,spec):\n ''\n \n def exec_module(self,module):\n ''\n code=self.get_code(module.__name__)\n if code is None:\n raise ImportError(f'cannot load module {module.__name__ !r} when '\n 'get_code() returns None')\n _bootstrap._call_with_frames_removed(exec,code,module.__dict__)\n \n def load_module(self,fullname):\n ''\n \n return _bootstrap._load_module_shim(self,fullname)\n \n \nclass SourceLoader(_LoaderBasics):\n\n def path_mtime(self,path):\n ''\n\n\n\n \n raise OSError\n \n def path_stats(self,path):\n ''\n\n\n\n\n\n\n\n\n\n \n return{'mtime':self.path_mtime(path)}\n \n def _cache_bytecode(self,source_path,cache_path,data):\n ''\n\n\n\n\n \n \n return self.set_data(cache_path,data)\n \n def set_data(self,path,data):\n ''\n\n\n \n \n \n def get_source(self,fullname):\n ''\n path=self.get_filename(fullname)\n try:\n source_bytes=self.get_data(path)\n except OSError as exc:\n raise ImportError('source not available through get_data()',\n name=fullname)from exc\n return decode_source(source_bytes)\n \n def source_to_code(self,data,path,*,_optimize=-1):\n ''\n\n\n \n return _bootstrap._call_with_frames_removed(compile,data,path,'exec',\n dont_inherit=True,optimize=_optimize)\n \n def get_code(self,fullname):\n ''\n\n\n\n\n \n source_path=self.get_filename(fullname)\n source_mtime=None\n source_bytes=None\n source_hash=None\n hash_based=False\n check_source=True\n try:\n bytecode_path=cache_from_source(source_path)\n except NotImplementedError:\n bytecode_path=None\n else:\n try:\n st=self.path_stats(source_path)\n except OSError:\n pass\n else:\n source_mtime=int(st['mtime'])\n try:\n data=self.get_data(bytecode_path)\n except OSError:\n pass\n else:\n exc_details={\n 'name':fullname,\n 'path':bytecode_path,\n }\n try:\n flags=_classify_pyc(data,fullname,exc_details)\n bytes_data=memoryview(data)[16:]\n hash_based=flags&0b1 !=0\n if hash_based:\n check_source=flags&0b10 !=0\n if(_imp.check_hash_based_pycs !='never'and\n (check_source or\n _imp.check_hash_based_pycs =='always')):\n source_bytes=self.get_data(source_path)\n source_hash=_imp.source_hash(\n _RAW_MAGIC_NUMBER,\n source_bytes,\n )\n _validate_hash_pyc(data,source_hash,fullname,\n exc_details)\n else:\n _validate_timestamp_pyc(\n data,\n source_mtime,\n st['size'],\n fullname,\n exc_details,\n )\n except(ImportError,EOFError):\n pass\n else:\n _bootstrap._verbose_message('{} matches {}',bytecode_path,\n source_path)\n return _compile_bytecode(bytes_data,name=fullname,\n bytecode_path=bytecode_path,\n source_path=source_path)\n if source_bytes is None:\n source_bytes=self.get_data(source_path)\n code_object=self.source_to_code(source_bytes,source_path)\n _bootstrap._verbose_message('code object from {}',source_path)\n if(not sys.dont_write_bytecode and bytecode_path is not None and\n source_mtime is not None):\n if hash_based:\n if source_hash is None:\n source_hash=_imp.source_hash(_RAW_MAGIC_NUMBER,\n source_bytes)\n data=_code_to_hash_pyc(code_object,source_hash,check_source)\n else:\n data=_code_to_timestamp_pyc(code_object,source_mtime,\n len(source_bytes))\n try:\n self._cache_bytecode(source_path,bytecode_path,data)\n except NotImplementedError:\n pass\n return code_object\n \n \nclass FileLoader:\n\n ''\n \n \n def __init__(self,fullname,path):\n ''\n \n self.name=fullname\n self.path=path\n \n def __eq__(self,other):\n return(self.__class__ ==other.__class__ and\n self.__dict__ ==other.__dict__)\n \n def __hash__(self):\n return hash(self.name)^hash(self.path)\n \n @_check_name\n def load_module(self,fullname):\n ''\n\n\n\n \n \n \n \n return super(FileLoader,self).load_module(fullname)\n \n @_check_name\n def get_filename(self,fullname):\n ''\n return self.path\n \n def get_data(self,path):\n ''\n if isinstance(self,(SourceLoader,ExtensionFileLoader)):\n with _io.open_code(str(path))as file:\n return file.read()\n else:\n with _io.FileIO(path,'r')as file:\n return file.read()\n \n @_check_name\n def get_resource_reader(self,module):\n from importlib.readers import FileReader\n return FileReader(self)\n \n \nclass SourceFileLoader(FileLoader,SourceLoader):\n\n ''\n \n def path_stats(self,path):\n ''\n st=_path_stat(path)\n return{'mtime':st.st_mtime,'size':st.st_size}\n \n def _cache_bytecode(self,source_path,bytecode_path,data):\n \n mode=_calc_mode(source_path)\n return self.set_data(bytecode_path,data,_mode=mode)\n \n def set_data(self,path,data,*,_mode=0o666):\n ''\n parent,filename=_path_split(path)\n path_parts=[]\n \n while parent and not _path_isdir(parent):\n parent,part=_path_split(parent)\n path_parts.append(part)\n \n for part in reversed(path_parts):\n parent=_path_join(parent,part)\n try:\n _os.mkdir(parent)\n except FileExistsError:\n \n continue\n except OSError as exc:\n \n \n _bootstrap._verbose_message('could not create {!r}: {!r}',\n parent,exc)\n return\n try:\n _write_atomic(path,data,_mode)\n _bootstrap._verbose_message('created {!r}',path)\n except OSError as exc:\n \n _bootstrap._verbose_message('could not create {!r}: {!r}',path,\n exc)\n \n \nclass SourcelessFileLoader(FileLoader,_LoaderBasics):\n\n ''\n \n def get_code(self,fullname):\n path=self.get_filename(fullname)\n data=self.get_data(path)\n \n \n exc_details={\n 'name':fullname,\n 'path':path,\n }\n _classify_pyc(data,fullname,exc_details)\n return _compile_bytecode(\n memoryview(data)[16:],\n name=fullname,\n bytecode_path=path,\n )\n \n def get_source(self,fullname):\n ''\n return None\n \n \nclass ExtensionFileLoader(FileLoader,_LoaderBasics):\n\n ''\n\n\n\n \n \n def __init__(self,name,path):\n self.name=name\n self.path=path\n \n def __eq__(self,other):\n return(self.__class__ ==other.__class__ and\n self.__dict__ ==other.__dict__)\n \n def __hash__(self):\n return hash(self.name)^hash(self.path)\n \n def create_module(self,spec):\n ''\n module=_bootstrap._call_with_frames_removed(\n _imp.create_dynamic,spec)\n _bootstrap._verbose_message('extension module {!r} loaded from {!r}',\n spec.name,self.path)\n return module\n \n def exec_module(self,module):\n ''\n _bootstrap._call_with_frames_removed(_imp.exec_dynamic,module)\n _bootstrap._verbose_message('extension module {!r} executed from {!r}',\n self.name,self.path)\n \n def is_package(self,fullname):\n ''\n file_name=_path_split(self.path)[1]\n return any(file_name =='__init__'+suffix\n for suffix in EXTENSION_SUFFIXES)\n \n def get_code(self,fullname):\n ''\n return None\n \n def get_source(self,fullname):\n ''\n return None\n \n @_check_name\n def get_filename(self,fullname):\n ''\n return self.path\n \n \nclass _NamespacePath:\n ''\n\n\n\n \n \n \n \n _epoch=0\n \n def __init__(self,name,path,path_finder):\n self._name=name\n self._path=path\n self._last_parent_path=tuple(self._get_parent_path())\n self._last_epoch=self._epoch\n self._path_finder=path_finder\n \n def _find_parent_path_names(self):\n ''\n parent,dot,me=self._name.rpartition('.')\n if dot =='':\n \n return 'sys','path'\n \n \n return parent,'__path__'\n \n def _get_parent_path(self):\n parent_module_name,path_attr_name=self._find_parent_path_names()\n return getattr(sys.modules[parent_module_name],path_attr_name)\n \n def _recalculate(self):\n \n parent_path=tuple(self._get_parent_path())\n if parent_path !=self._last_parent_path or self._epoch !=self._last_epoch:\n spec=self._path_finder(self._name,parent_path)\n \n \n if spec is not None and spec.loader is None:\n if spec.submodule_search_locations:\n self._path=spec.submodule_search_locations\n self._last_parent_path=parent_path\n self._last_epoch=self._epoch\n return self._path\n \n def __iter__(self):\n return iter(self._recalculate())\n \n def __getitem__(self,index):\n return self._recalculate()[index]\n \n def __setitem__(self,index,path):\n self._path[index]=path\n \n def __len__(self):\n return len(self._recalculate())\n \n def __repr__(self):\n return f'_NamespacePath({self._path !r})'\n \n def __contains__(self,item):\n return item in self._recalculate()\n \n def append(self,item):\n self._path.append(item)\n \n \n \n \n \nclass NamespaceLoader:\n def __init__(self,name,path,path_finder):\n self._path=_NamespacePath(name,path,path_finder)\n \n def is_package(self,fullname):\n return True\n \n def get_source(self,fullname):\n return ''\n \n def get_code(self,fullname):\n return compile('','','exec',dont_inherit=True)\n \n def create_module(self,spec):\n ''\n \n def exec_module(self,module):\n pass\n \n def load_module(self,fullname):\n ''\n\n\n\n \n \n _bootstrap._verbose_message('namespace module loaded with path {!r}',\n self._path)\n \n return _bootstrap._load_module_shim(self,fullname)\n \n def get_resource_reader(self,module):\n from importlib.readers import NamespaceReader\n return NamespaceReader(self._path)\n \n \n \n_NamespaceLoader=NamespaceLoader\n\n\n\n\nclass PathFinder:\n\n ''\n \n @staticmethod\n def invalidate_caches():\n ''\n \n for name,finder in list(sys.path_importer_cache.items()):\n \n \n if finder is None or not _path_isabs(name):\n del sys.path_importer_cache[name]\n elif hasattr(finder,'invalidate_caches'):\n finder.invalidate_caches()\n \n \n _NamespacePath._epoch +=1\n \n from importlib.metadata import MetadataPathFinder\n MetadataPathFinder.invalidate_caches()\n \n @staticmethod\n def _path_hooks(path):\n ''\n if sys.path_hooks is not None and not sys.path_hooks:\n _warnings.warn('sys.path_hooks is empty',ImportWarning)\n for hook in sys.path_hooks:\n try:\n return hook(path)\n except ImportError:\n continue\n else:\n return None\n \n @classmethod\n def _path_importer_cache(cls,path):\n ''\n\n\n\n\n \n if path =='':\n try:\n path=_os.getcwd()\n except FileNotFoundError:\n \n \n return None\n try:\n finder=sys.path_importer_cache[path]\n except KeyError:\n finder=cls._path_hooks(path)\n sys.path_importer_cache[path]=finder\n return finder\n \n @classmethod\n def _get_spec(cls,fullname,path,target=None):\n ''\n \n \n namespace_path=[]\n for entry in path:\n if not isinstance(entry,str):\n continue\n finder=cls._path_importer_cache(entry)\n if finder is not None:\n spec=finder.find_spec(fullname,target)\n if spec is None:\n continue\n if spec.loader is not None:\n return spec\n portions=spec.submodule_search_locations\n if portions is None:\n raise ImportError('spec missing loader')\n \n \n \n \n namespace_path.extend(portions)\n else:\n spec=_bootstrap.ModuleSpec(fullname,None)\n spec.submodule_search_locations=namespace_path\n return spec\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n ''\n\n\n \n if path is None:\n path=sys.path\n spec=cls._get_spec(fullname,path,target)\n if spec is None:\n return None\n elif spec.loader is None:\n namespace_path=spec.submodule_search_locations\n if namespace_path:\n \n \n spec.origin=None\n spec.submodule_search_locations=_NamespacePath(fullname,namespace_path,cls._get_spec)\n return spec\n else:\n return None\n else:\n return spec\n \n @staticmethod\n def find_distributions(*args,**kwargs):\n ''\n\n\n\n\n\n\n \n from importlib.metadata import MetadataPathFinder\n return MetadataPathFinder.find_distributions(*args,**kwargs)\n \n \nclass FileFinder:\n\n ''\n\n\n\n\n \n \n def __init__(self,path,*loader_details):\n ''\n\n \n loaders=[]\n for loader,suffixes in loader_details:\n loaders.extend((suffix,loader)for suffix in suffixes)\n self._loaders=loaders\n \n if not path or path =='.':\n self.path=_os.getcwd()\n else:\n self.path=_path_abspath(path)\n self._path_mtime=-1\n self._path_cache=set()\n self._relaxed_path_cache=set()\n \n def invalidate_caches(self):\n ''\n self._path_mtime=-1\n \n def _get_spec(self,loader_class,fullname,path,smsl,target):\n loader=loader_class(fullname,path)\n return spec_from_file_location(fullname,path,loader=loader,\n submodule_search_locations=smsl)\n \n def find_spec(self,fullname,target=None):\n ''\n\n\n \n is_namespace=False\n tail_module=fullname.rpartition('.')[2]\n try:\n mtime=_path_stat(self.path or _os.getcwd()).st_mtime\n except OSError:\n mtime=-1\n if mtime !=self._path_mtime:\n self._fill_cache()\n self._path_mtime=mtime\n \n if _relax_case():\n cache=self._relaxed_path_cache\n cache_module=tail_module.lower()\n else:\n cache=self._path_cache\n cache_module=tail_module\n \n if cache_module in cache:\n base_path=_path_join(self.path,tail_module)\n for suffix,loader_class in self._loaders:\n init_filename='__init__'+suffix\n full_path=_path_join(base_path,init_filename)\n if _path_isfile(full_path):\n return self._get_spec(loader_class,fullname,full_path,[base_path],target)\n else:\n \n \n is_namespace=_path_isdir(base_path)\n \n for suffix,loader_class in self._loaders:\n try:\n full_path=_path_join(self.path,tail_module+suffix)\n except ValueError:\n return None\n _bootstrap._verbose_message('trying {}',full_path,verbosity=2)\n if cache_module+suffix in cache:\n if _path_isfile(full_path):\n return self._get_spec(loader_class,fullname,full_path,\n None,target)\n if is_namespace:\n _bootstrap._verbose_message('possible namespace for {}',base_path)\n spec=_bootstrap.ModuleSpec(fullname,None)\n spec.submodule_search_locations=[base_path]\n return spec\n return None\n \n def _fill_cache(self):\n ''\n path=self.path\n try:\n contents=_os.listdir(path or _os.getcwd())\n except(FileNotFoundError,PermissionError,NotADirectoryError):\n \n \n contents=[]\n \n \n if not sys.platform.startswith('win'):\n self._path_cache=set(contents)\n else:\n \n \n \n \n \n lower_suffix_contents=set()\n for item in contents:\n name,dot,suffix=item.partition('.')\n if dot:\n new_name=f'{name}.{suffix.lower()}'\n else:\n new_name=name\n lower_suffix_contents.add(new_name)\n self._path_cache=lower_suffix_contents\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):\n self._relaxed_path_cache={fn.lower()for fn in contents}\n \n @classmethod\n def path_hook(cls,*loader_details):\n ''\n\n\n\n\n\n\n \n def path_hook_for_FileFinder(path):\n ''\n if not _path_isdir(path):\n raise ImportError('only directories are supported',path=path)\n return cls(path,*loader_details)\n \n return path_hook_for_FileFinder\n \n def __repr__(self):\n return f'FileFinder({self.path !r})'\n \n \nclass AppleFrameworkLoader(ExtensionFileLoader):\n ''\n\n \n def create_module(self,spec):\n \n \n \n \n if spec.origin.endswith(\".fwork\"):\n with _io.FileIO(spec.origin,'r')as file:\n framework_binary=file.read().decode().strip()\n bundle_path=_path_split(sys.executable)[0]\n spec.origin=_path_join(bundle_path,framework_binary)\n \n \n \n \n if self.path.endswith(\".fwork\"):\n path=self.path\n else:\n with _io.FileIO(self.path+\".origin\",'r')as file:\n origin=file.read().decode().strip()\n bundle_path=_path_split(sys.executable)[0]\n path=_path_join(bundle_path,origin)\n \n module=_bootstrap._call_with_frames_removed(_imp.create_dynamic,spec)\n \n _bootstrap._verbose_message(\n \"Apple framework extension module {!r} loaded from {!r} (path {!r})\",\n spec.name,\n spec.origin,\n path,\n )\n \n \n module.__file__=path\n \n return module\n \n \n \ndef _fix_up_module(ns,name,pathname,cpathname=None):\n\n loader=ns.get('__loader__')\n spec=ns.get('__spec__')\n if not loader:\n if spec:\n loader=spec.loader\n elif pathname ==cpathname:\n loader=SourcelessFileLoader(name,pathname)\n else:\n loader=SourceFileLoader(name,pathname)\n if not spec:\n spec=spec_from_file_location(name,pathname,loader=loader)\n if cpathname:\n spec.cached=_path_abspath(cpathname)\n try:\n ns['__spec__']=spec\n ns['__loader__']=loader\n ns['__file__']=pathname\n ns['__cached__']=cpathname\n except Exception:\n \n pass\n \n \ndef _get_supported_file_loaders():\n ''\n\n\n \n if sys.platform in{\"ios\",\"tvos\",\"watchos\"}:\n extension_loaders=[(AppleFrameworkLoader,[\n suffix.replace(\".so\",\".fwork\")\n for suffix in _imp.extension_suffixes()\n ])]\n else:\n extension_loaders=[]\n extension_loaders.append((ExtensionFileLoader,_imp.extension_suffixes()))\n source=SourceFileLoader,SOURCE_SUFFIXES\n bytecode=SourcelessFileLoader,BYTECODE_SUFFIXES\n return extension_loaders+[source,bytecode]\n \n \ndef _set_bootstrap_module(_bootstrap_module):\n global _bootstrap\n _bootstrap=_bootstrap_module\n \n \ndef _install(_bootstrap_module):\n ''\n _set_bootstrap_module(_bootstrap_module)\n supported_loaders=_get_supported_file_loaders()\n sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])\n sys.meta_path.append(PathFinder)\n", ["_imp", "_io", "_warnings", "importlib.metadata", "importlib.readers", "marshal", "nt", "posix", "sys", "tokenize", "winreg"]], "importlib": [".py", "''\n__all__=['__import__','import_module','invalidate_caches','reload']\n\n\n\n\n\n\n\n\n\nimport _imp\nimport sys\n\ntry:\n import _frozen_importlib as _bootstrap\nexcept ImportError:\n from. import _bootstrap\n _bootstrap._setup(sys,_imp)\nelse:\n\n\n _bootstrap.__name__='importlib._bootstrap'\n _bootstrap.__package__='importlib'\n try:\n _bootstrap.__file__=__file__.replace('__init__.py','_bootstrap.py')\n except NameError:\n \n \n pass\n sys.modules['importlib._bootstrap']=_bootstrap\n \ntry:\n import _frozen_importlib_external as _bootstrap_external\nexcept ImportError:\n from. import _bootstrap_external\n _bootstrap_external._set_bootstrap_module(_bootstrap)\n _bootstrap._bootstrap_external=_bootstrap_external\nelse:\n _bootstrap_external.__name__='importlib._bootstrap_external'\n _bootstrap_external.__package__='importlib'\n try:\n _bootstrap_external.__file__=__file__.replace('__init__.py','_bootstrap_external.py')\n except NameError:\n \n \n pass\n sys.modules['importlib._bootstrap_external']=_bootstrap_external\n \n \n_pack_uint32=_bootstrap_external._pack_uint32\n_unpack_uint32=_bootstrap_external._unpack_uint32\n\n\n\n\n\n\n\nfrom._bootstrap import __import__\n\n\ndef invalidate_caches():\n ''\n \n for finder in sys.meta_path:\n if hasattr(finder,'invalidate_caches'):\n finder.invalidate_caches()\n \n \ndef import_module(name,package=None):\n ''\n\n\n\n\n\n \n level=0\n if name.startswith('.'):\n if not package:\n raise TypeError(\"the 'package' argument is required to perform a \"\n f\"relative import for {name !r}\")\n for character in name:\n if character !='.':\n break\n level +=1\n return _bootstrap._gcd_import(name[level:],package,level)\n \n \n_RELOADING={}\n\n\ndef reload(module):\n ''\n\n\n\n \n try:\n name=module.__spec__.name\n except AttributeError:\n try:\n name=module.__name__\n except AttributeError:\n raise TypeError(\"reload() argument must be a module\")\n \n if sys.modules.get(name)is not module:\n raise ImportError(f\"module {name} not in sys.modules\",name=name)\n if name in _RELOADING:\n return _RELOADING[name]\n _RELOADING[name]=module\n try:\n parent_name=name.rpartition('.')[0]\n if parent_name:\n try:\n parent=sys.modules[parent_name]\n except KeyError:\n raise ImportError(f\"parent {parent_name !r} not in sys.modules\",\n name=parent_name)from None\n else:\n pkgpath=parent.__path__\n else:\n pkgpath=None\n target=module\n spec=module.__spec__=_bootstrap._find_spec(name,pkgpath,target)\n if spec is None:\n raise ModuleNotFoundError(f\"spec not found for the module {name !r}\",name=name)\n _bootstrap._exec(spec,module)\n \n return sys.modules[name]\n finally:\n try:\n del _RELOADING[name]\n except KeyError:\n pass\n", ["_frozen_importlib", "_frozen_importlib_external", "_imp", "importlib", "importlib._bootstrap", "importlib._bootstrap_external", "sys"], 1], "importlib.metadata._adapters": [".py", "import functools\nimport warnings\nimport re\nimport textwrap\nimport email.message\n\nfrom._text import FoldedCase\n\n\n\n_warn=functools.partial(\nwarnings.warn,\n\"Implicit None on return values is deprecated and will raise KeyErrors.\",\nDeprecationWarning,\nstacklevel=2,\n)\n\n\nclass Message(email.message.Message):\n multiple_use_keys=set(\n map(\n FoldedCase,\n [\n 'Classifier',\n 'Obsoletes-Dist',\n 'Platform',\n 'Project-URL',\n 'Provides-Dist',\n 'Provides-Extra',\n 'Requires-Dist',\n 'Requires-External',\n 'Supported-Platform',\n 'Dynamic',\n ],\n )\n )\n ''\n\n \n \n def __new__(cls,orig:email.message.Message):\n res=super().__new__(cls)\n vars(res).update(vars(orig))\n return res\n \n def __init__(self,*args,**kwargs):\n self._headers=self._repair_headers()\n \n \n def __iter__(self):\n return super().__iter__()\n \n def __getitem__(self,item):\n ''\n\n\n \n res=super().__getitem__(item)\n if res is None:\n _warn()\n return res\n \n def _repair_headers(self):\n def redent(value):\n ''\n if not value or '\\n'not in value:\n return value\n return textwrap.dedent(' '*8+value)\n \n headers=[(key,redent(value))for key,value in vars(self)['_headers']]\n if self._payload:\n headers.append(('Description',self.get_payload()))\n return headers\n \n @property\n def json(self):\n ''\n\n\n \n \n def transform(key):\n value=self.get_all(key)if key in self.multiple_use_keys else self[key]\n if key =='Keywords':\n value=re.split(r'\\s+',value)\n tk=key.lower().replace('-','_')\n return tk,value\n \n return dict(map(transform,map(FoldedCase,self)))\n", ["email.message", "functools", "importlib.metadata._text", "re", "textwrap", "warnings"]], "importlib.metadata._collections": [".py", "import collections\n\n\n\nclass FreezableDefaultDict(collections.defaultdict):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __missing__(self,key):\n return getattr(self,'_frozen',super().__missing__)(key)\n \n def freeze(self):\n self._frozen=lambda key:self.default_factory()\n \n \nclass Pair(collections.namedtuple('Pair','name value')):\n @classmethod\n def parse(cls,text):\n return cls(*map(str.strip,text.split(\"=\",1)))\n", ["collections"]], "importlib.metadata._functools": [".py", "import types\nimport functools\n\n\n\ndef method_cache(method,cache_wrapper=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n cache_wrapper=cache_wrapper or functools.lru_cache()\n \n def wrapper(self,*args,**kwargs):\n \n bound_method=types.MethodType(method,self)\n cached_method=cache_wrapper(bound_method)\n setattr(self,method.__name__,cached_method)\n return cached_method(*args,**kwargs)\n \n \n wrapper.cache_clear=lambda:None\n \n return wrapper\n \n \n \ndef pass_none(func):\n ''\n\n\n\n\n\n\n \n \n @functools.wraps(func)\n def wrapper(param,*args,**kwargs):\n if param is not None:\n return func(param,*args,**kwargs)\n \n return wrapper\n", ["functools", "types"]], "importlib.metadata._itertools": [".py", "from itertools import filterfalse\n\n\ndef unique_everseen(iterable,key=None):\n ''\n \n \n seen=set()\n seen_add=seen.add\n if key is None:\n for element in filterfalse(seen.__contains__,iterable):\n seen_add(element)\n yield element\n else:\n for element in iterable:\n k=key(element)\n if k not in seen:\n seen_add(k)\n yield element\n \n \n \ndef always_iterable(obj,base_type=(str,bytes)):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if obj is None:\n return iter(())\n \n if(base_type is not None)and isinstance(obj,base_type):\n return iter((obj,))\n \n try:\n return iter(obj)\n except TypeError:\n return iter((obj,))\n", ["itertools"]], "importlib.metadata._meta": [".py", "from __future__ import annotations\n\nimport os\nfrom typing import Protocol\nfrom typing import Any,Dict,Iterator,List,Optional,TypeVar,Union,overload\n\n\n_T=TypeVar(\"_T\")\n\n\nclass PackageMetadata(Protocol):\n def __len__(self)->int:...\n \n def __contains__(self,item:str)->bool:...\n \n def __getitem__(self,key:str)->str:...\n \n def __iter__(self)->Iterator[str]:...\n \n @overload\n def get(\n self,name:str,failobj:None=None\n )->Optional[str]:...\n \n @overload\n def get(self,name:str,failobj:_T)->Union[str,_T]:...\n \n \n @overload\n def get_all(\n self,name:str,failobj:None=None\n )->Optional[List[Any]]:...\n \n @overload\n def get_all(self,name:str,failobj:_T)->Union[List[Any],_T]:\n ''\n\n \n \n @property\n def json(self)->Dict[str,Union[str,List[str]]]:\n ''\n\n \n \n \nclass SimplePath(Protocol):\n ''\n\n \n \n def joinpath(\n self,other:Union[str,os.PathLike[str]]\n )->SimplePath:...\n \n def __truediv__(\n self,other:Union[str,os.PathLike[str]]\n )->SimplePath:...\n \n @property\n def parent(self)->SimplePath:...\n \n def read_text(self,encoding=None)->str:...\n \n def read_bytes(self)->bytes:...\n \n def exists(self)->bool:...\n", ["__future__", "os", "typing"]], "importlib.metadata._text": [".py", "import re\n\nfrom._functools import method_cache\n\n\n\nclass FoldedCase(str):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __lt__(self,other):\n return self.lower()other.lower()\n \n def __eq__(self,other):\n return self.lower()==other.lower()\n \n def __ne__(self,other):\n return self.lower()!=other.lower()\n \n def __hash__(self):\n return hash(self.lower())\n \n def __contains__(self,other):\n return super().lower().__contains__(other.lower())\n \n def in_(self,other):\n ''\n return self in FoldedCase(other)\n \n \n @method_cache\n def lower(self):\n return super().lower()\n \n def index(self,sub):\n return self.lower().index(sub.lower())\n \n def split(self,splitter=' ',maxsplit=0):\n pattern=re.compile(re.escape(splitter),re.I)\n return pattern.split(self,maxsplit)\n", ["importlib.metadata._functools", "re"]], "importlib.metadata": [".py", "from __future__ import annotations\n\nimport os\nimport re\nimport abc\nimport sys\nimport json\nimport email\nimport types\nimport inspect\nimport pathlib\nimport zipfile\nimport operator\nimport textwrap\nimport warnings\nimport functools\nimport itertools\nimport posixpath\nimport collections\n\nfrom. import _meta\nfrom._collections import FreezableDefaultDict,Pair\nfrom._functools import method_cache,pass_none\nfrom._itertools import always_iterable,unique_everseen\nfrom._meta import PackageMetadata,SimplePath\n\nfrom contextlib import suppress\nfrom importlib import import_module\nfrom importlib.abc import MetaPathFinder\nfrom itertools import starmap\nfrom typing import Any,Iterable,List,Mapping,Match,Optional,Set,cast\n\n__all__=[\n'Distribution',\n'DistributionFinder',\n'PackageMetadata',\n'PackageNotFoundError',\n'distribution',\n'distributions',\n'entry_points',\n'files',\n'metadata',\n'packages_distributions',\n'requires',\n'version',\n]\n\n\nclass PackageNotFoundError(ModuleNotFoundError):\n ''\n \n def __str__(self)->str:\n return f\"No package metadata was found for {self.name}\"\n \n @property\n def name(self)->str:\n (name,)=self.args\n return name\n \n \nclass Sectioned:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n _sample=textwrap.dedent(\n \"\"\"\n [sec1]\n # comments ignored\n a = 1\n b = 2\n\n [sec2]\n a = 2\n \"\"\"\n ).lstrip()\n \n @classmethod\n def section_pairs(cls,text):\n return(\n section._replace(value=Pair.parse(section.value))\n for section in cls.read(text,filter_=cls.valid)\n if section.name is not None\n )\n \n @staticmethod\n def read(text,filter_=None):\n lines=filter(filter_,map(str.strip,text.splitlines()))\n name=None\n for value in lines:\n section_match=value.startswith('[')and value.endswith(']')\n if section_match:\n name=value.strip('[]')\n continue\n yield Pair(name,value)\n \n @staticmethod\n def valid(line:str):\n return line and not line.startswith('#')\n \n \nclass EntryPoint:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n pattern=re.compile(\n r'(?P[\\w.]+)\\s*'\n r'(:\\s*(?P[\\w.]+)\\s*)?'\n r'((?P\\[.*\\])\\s*)?$'\n )\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n name:str\n value:str\n group:str\n \n dist:Optional[Distribution]=None\n \n def __init__(self,name:str,value:str,group:str)->None:\n vars(self).update(name=name,value=value,group=group)\n \n def load(self)->Any:\n ''\n\n\n \n match=cast(Match,self.pattern.match(self.value))\n module=import_module(match.group('module'))\n attrs=filter(None,(match.group('attr')or '').split('.'))\n return functools.reduce(getattr,attrs,module)\n \n @property\n def module(self)->str:\n match=self.pattern.match(self.value)\n assert match is not None\n return match.group('module')\n \n @property\n def attr(self)->str:\n match=self.pattern.match(self.value)\n assert match is not None\n return match.group('attr')\n \n @property\n def extras(self)->List[str]:\n match=self.pattern.match(self.value)\n assert match is not None\n return re.findall(r'\\w+',match.group('extras')or '')\n \n def _for(self,dist):\n vars(self).update(dist=dist)\n return self\n \n def matches(self,**params):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n attrs=(getattr(self,param)for param in params)\n return all(map(operator.eq,params.values(),attrs))\n \n def _key(self):\n return self.name,self.value,self.group\n \n def __lt__(self,other):\n return self._key()int:\n return hash(self._key())\n \n \nclass EntryPoints(tuple):\n ''\n\n \n \n __slots__=()\n \n def __getitem__(self,name:str)->EntryPoint:\n ''\n\n \n try:\n return next(iter(self.select(name=name)))\n except StopIteration:\n raise KeyError(name)\n \n def __repr__(self):\n ''\n\n\n \n return '%s(%r)'%(self.__class__.__name__,tuple(self))\n \n def select(self,**params)->EntryPoints:\n ''\n\n\n \n return EntryPoints(ep for ep in self if ep.matches(**params))\n \n @property\n def names(self)->Set[str]:\n ''\n\n \n return{ep.name for ep in self}\n \n @property\n def groups(self)->Set[str]:\n ''\n\n \n return{ep.group for ep in self}\n \n @classmethod\n def _from_text_for(cls,text,dist):\n return cls(ep._for(dist)for ep in cls._from_text(text))\n \n @staticmethod\n def _from_text(text):\n return(\n EntryPoint(name=item.value.name,value=item.value.value,group=item.name)\n for item in Sectioned.section_pairs(text or '')\n )\n \n \nclass PackagePath(pathlib.PurePosixPath):\n ''\n \n hash:Optional[FileHash]\n size:int\n dist:Distribution\n \n def read_text(self,encoding:str='utf-8')->str:\n return self.locate().read_text(encoding=encoding)\n \n def read_binary(self)->bytes:\n return self.locate().read_bytes()\n \n def locate(self)->SimplePath:\n ''\n return self.dist.locate_file(self)\n \n \nclass FileHash:\n def __init__(self,spec:str)->None:\n self.mode,_,self.value=spec.partition('=')\n \n def __repr__(self)->str:\n return f''\n \n \nclass DeprecatedNonAbstract:\n\n def __new__(cls,*args,**kwargs):\n all_names={\n name for subclass in inspect.getmro(cls)for name in vars(subclass)\n }\n abstract={\n name\n for name in all_names\n if getattr(getattr(cls,name),'__isabstractmethod__',False)\n }\n if abstract:\n warnings.warn(\n f\"Unimplemented abstract methods {abstract}\",\n DeprecationWarning,\n stacklevel=2,\n )\n return super().__new__(cls)\n \n \nclass Distribution(DeprecatedNonAbstract):\n ''\n\n\n\n\n\n\n\n \n \n @abc.abstractmethod\n def read_text(self,filename)->Optional[str]:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n @abc.abstractmethod\n def locate_file(self,path:str |os.PathLike[str])->SimplePath:\n ''\n\n\n \n \n @classmethod\n def from_name(cls,name:str)->Distribution:\n ''\n\n\n\n\n\n\n\n \n if not name:\n raise ValueError(\"A distribution name is required.\")\n try:\n return next(iter(cls.discover(name=name)))\n except StopIteration:\n raise PackageNotFoundError(name)\n \n @classmethod\n def discover(\n cls,*,context:Optional[DistributionFinder.Context]=None,**kwargs\n )->Iterable[Distribution]:\n ''\n\n\n\n\n\n\n\n \n if context and kwargs:\n raise ValueError(\"cannot accept context and kwargs\")\n context=context or DistributionFinder.Context(**kwargs)\n return itertools.chain.from_iterable(\n resolver(context)for resolver in cls._discover_resolvers()\n )\n \n @staticmethod\n def at(path:str |os.PathLike[str])->Distribution:\n ''\n\n\n\n \n return PathDistribution(pathlib.Path(path))\n \n @staticmethod\n def _discover_resolvers():\n ''\n declared=(\n getattr(finder,'find_distributions',None)for finder in sys.meta_path\n )\n return filter(None,declared)\n \n @property\n def metadata(self)->_meta.PackageMetadata:\n ''\n\n\n\n\n\n\n\n \n \n from. import _adapters\n \n opt_text=(\n self.read_text('METADATA')\n or self.read_text('PKG-INFO')\n \n \n \n or self.read_text('')\n )\n text=cast(str,opt_text)\n return _adapters.Message(email.message_from_string(text))\n \n @property\n def name(self)->str:\n ''\n return self.metadata['Name']\n \n @property\n def _normalized_name(self):\n ''\n return Prepared.normalize(self.name)\n \n @property\n def version(self)->str:\n ''\n return self.metadata['Version']\n \n @property\n def entry_points(self)->EntryPoints:\n ''\n\n\n\n\n \n return EntryPoints._from_text_for(self.read_text('entry_points.txt'),self)\n \n @property\n def files(self)->Optional[List[PackagePath]]:\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n def make_file(name,hash=None,size_str=None):\n result=PackagePath(name)\n result.hash=FileHash(hash)if hash else None\n result.size=int(size_str)if size_str else None\n result.dist=self\n return result\n \n @pass_none\n def make_files(lines):\n \n \n import csv\n \n return starmap(make_file,csv.reader(lines))\n \n @pass_none\n def skip_missing_files(package_paths):\n return list(filter(lambda path:path.locate().exists(),package_paths))\n \n return skip_missing_files(\n make_files(\n self._read_files_distinfo()\n or self._read_files_egginfo_installed()\n or self._read_files_egginfo_sources()\n )\n )\n \n def _read_files_distinfo(self):\n ''\n\n \n text=self.read_text('RECORD')\n return text and text.splitlines()\n \n def _read_files_egginfo_installed(self):\n ''\n\n\n\n\n\n\n\n\n \n text=self.read_text('installed-files.txt')\n \n \n \n subdir=getattr(self,'_path',None)\n if not text or not subdir:\n return\n \n paths=(\n (subdir /name)\n .resolve()\n .relative_to(self.locate_file('').resolve())\n .as_posix()\n for name in text.splitlines()\n )\n return map('\"{}\"'.format,paths)\n \n def _read_files_egginfo_sources(self):\n ''\n\n\n\n\n\n\n\n\n\n \n text=self.read_text('SOURCES.txt')\n return text and map('\"{}\"'.format,text.splitlines())\n \n @property\n def requires(self)->Optional[List[str]]:\n ''\n reqs=self._read_dist_info_reqs()or self._read_egg_info_reqs()\n return reqs and list(reqs)\n \n def _read_dist_info_reqs(self):\n return self.metadata.get_all('Requires-Dist')\n \n def _read_egg_info_reqs(self):\n source=self.read_text('requires.txt')\n return pass_none(self._deps_from_requires_text)(source)\n \n @classmethod\n def _deps_from_requires_text(cls,source):\n return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))\n \n @staticmethod\n def _convert_egg_info_reqs_to_simple_reqs(sections):\n ''\n\n\n\n\n\n\n\n \n \n def make_condition(name):\n return name and f'extra == \"{name}\"'\n \n def quoted_marker(section):\n section=section or ''\n extra,sep,markers=section.partition(':')\n if extra and markers:\n markers=f'({markers})'\n conditions=list(filter(None,[markers,make_condition(extra)]))\n return '; '+' and '.join(conditions)if conditions else ''\n \n def url_req_space(req):\n ''\n\n\n \n \n return ' '*('@'in req)\n \n for section in sections:\n space=url_req_space(section.value)\n yield section.value+space+quoted_marker(section.name)\n \n @property\n def origin(self):\n return self._load_json('direct_url.json')\n \n def _load_json(self,filename):\n return pass_none(json.loads)(\n self.read_text(filename),\n object_hook=lambda data:types.SimpleNamespace(**data),\n )\n \n \nclass DistributionFinder(MetaPathFinder):\n ''\n\n\n\n\n \n \n class Context:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n name=None\n ''\n\n\n \n \n def __init__(self,**kwargs):\n vars(self).update(kwargs)\n \n @property\n def path(self)->List[str]:\n ''\n\n\n\n\n\n \n return vars(self).get('path',sys.path)\n \n @abc.abstractmethod\n def find_distributions(self,context=Context())->Iterable[Distribution]:\n ''\n\n\n\n\n\n \n \n \nclass FastPath:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n @functools.lru_cache()\n def __new__(cls,root):\n return super().__new__(cls)\n \n def __init__(self,root):\n self.root=root\n \n def joinpath(self,child):\n return pathlib.Path(self.root,child)\n \n def children(self):\n with suppress(Exception):\n return os.listdir(self.root or '.')\n with suppress(Exception):\n return self.zip_children()\n return[]\n \n def zip_children(self):\n zip_path=zipfile.Path(self.root)\n names=zip_path.root.namelist()\n self.joinpath=zip_path.joinpath\n \n return dict.fromkeys(child.split(posixpath.sep,1)[0]for child in names)\n \n def search(self,name):\n return self.lookup(self.mtime).search(name)\n \n @property\n def mtime(self):\n with suppress(OSError):\n return os.stat(self.root).st_mtime\n self.lookup.cache_clear()\n \n @method_cache\n def lookup(self,mtime):\n return Lookup(self)\n \n \nclass Lookup:\n ''\n\n \n \n def __init__(self,path:FastPath):\n ''\n\n\n\n\n\n \n \n base=os.path.basename(path.root).lower()\n base_is_egg=base.endswith(\".egg\")\n self.infos=FreezableDefaultDict(list)\n self.eggs=FreezableDefaultDict(list)\n \n for child in path.children():\n low=child.lower()\n if low.endswith((\".dist-info\",\".egg-info\")):\n \n name=low.rpartition(\".\")[0].partition(\"-\")[0]\n normalized=Prepared.normalize(name)\n self.infos[normalized].append(path.joinpath(child))\n elif base_is_egg and low ==\"egg-info\":\n name=base.rpartition(\".\")[0].partition(\"-\")[0]\n legacy_normalized=Prepared.legacy_normalize(name)\n self.eggs[legacy_normalized].append(path.joinpath(child))\n \n self.infos.freeze()\n self.eggs.freeze()\n \n def search(self,prepared:Prepared):\n ''\n\n \n infos=(\n self.infos[prepared.normalized]\n if prepared\n else itertools.chain.from_iterable(self.infos.values())\n )\n eggs=(\n self.eggs[prepared.legacy_normalized]\n if prepared\n else itertools.chain.from_iterable(self.eggs.values())\n )\n return itertools.chain(infos,eggs)\n \n \nclass Prepared:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n normalized=None\n legacy_normalized=None\n \n def __init__(self,name:Optional[str]):\n self.name=name\n if name is None:\n return\n self.normalized=self.normalize(name)\n self.legacy_normalized=self.legacy_normalize(name)\n \n @staticmethod\n def normalize(name):\n ''\n\n \n return re.sub(r\"[-_.]+\",\"-\",name).lower().replace('-','_')\n \n @staticmethod\n def legacy_normalize(name):\n ''\n\n\n \n return name.lower().replace('-','_')\n \n def __bool__(self):\n return bool(self.name)\n \n \nclass MetadataPathFinder(DistributionFinder):\n @classmethod\n def find_distributions(\n cls,context=DistributionFinder.Context()\n )->Iterable[PathDistribution]:\n ''\n\n\n\n\n\n\n \n found=cls._search_paths(context.name,context.path)\n return map(PathDistribution,found)\n \n @classmethod\n def _search_paths(cls,name,paths):\n ''\n prepared=Prepared(name)\n return itertools.chain.from_iterable(\n path.search(prepared)for path in map(FastPath,paths)\n )\n \n @classmethod\n def invalidate_caches(cls)->None:\n FastPath.__new__.cache_clear()\n \n \nclass PathDistribution(Distribution):\n def __init__(self,path:SimplePath)->None:\n ''\n\n\n \n self._path=path\n \n def read_text(self,filename:str |os.PathLike[str])->Optional[str]:\n with suppress(\n FileNotFoundError,\n IsADirectoryError,\n KeyError,\n NotADirectoryError,\n PermissionError,\n ):\n return self._path.joinpath(filename).read_text(encoding='utf-8')\n \n return None\n \n read_text.__doc__=Distribution.read_text.__doc__\n \n def locate_file(self,path:str |os.PathLike[str])->SimplePath:\n return self._path.parent /path\n \n @property\n def _normalized_name(self):\n ''\n\n\n \n stem=os.path.basename(str(self._path))\n return(\n pass_none(Prepared.normalize)(self._name_from_stem(stem))\n or super()._normalized_name\n )\n \n @staticmethod\n def _name_from_stem(stem):\n ''\n\n\n\n\n\n\n\n \n filename,ext=os.path.splitext(stem)\n if ext not in('.dist-info','.egg-info'):\n return\n name,sep,rest=filename.partition('-')\n return name\n \n \ndef distribution(distribution_name:str)->Distribution:\n ''\n\n\n\n \n return Distribution.from_name(distribution_name)\n \n \ndef distributions(**kwargs)->Iterable[Distribution]:\n ''\n\n\n \n return Distribution.discover(**kwargs)\n \n \ndef metadata(distribution_name:str)->_meta.PackageMetadata:\n ''\n\n\n\n \n return Distribution.from_name(distribution_name).metadata\n \n \ndef version(distribution_name:str)->str:\n ''\n\n\n\n\n \n return distribution(distribution_name).version\n \n \n_unique=functools.partial(\nunique_everseen,\nkey=operator.attrgetter('_normalized_name'),\n)\n''\n\n\n\n\ndef entry_points(**params)->EntryPoints:\n ''\n\n\n\n\n\n\n \n eps=itertools.chain.from_iterable(\n dist.entry_points for dist in _unique(distributions())\n )\n return EntryPoints(eps).select(**params)\n \n \ndef files(distribution_name:str)->Optional[List[PackagePath]]:\n ''\n\n\n\n \n return distribution(distribution_name).files\n \n \ndef requires(distribution_name:str)->Optional[List[str]]:\n ''\n\n\n\n\n \n return distribution(distribution_name).requires\n \n \ndef packages_distributions()->Mapping[str,List[str]]:\n ''\n\n\n\n\n\n\n\n \n pkg_to_dist=collections.defaultdict(list)\n for dist in distributions():\n for pkg in _top_level_declared(dist)or _top_level_inferred(dist):\n pkg_to_dist[pkg].append(dist.metadata['Name'])\n return dict(pkg_to_dist)\n \n \ndef _top_level_declared(dist):\n return(dist.read_text('top_level.txt')or '').split()\n \n \ndef _topmost(name:PackagePath)->Optional[str]:\n ''\n\n \n top,*rest=name.parts\n return top if rest else None\n \n \ndef _get_toplevel_name(name:PackagePath)->str:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _topmost(name)or(\n \n inspect.getmodulename(name)\n or str(name)\n )\n \n \ndef _top_level_inferred(dist):\n opt_names=set(map(_get_toplevel_name,always_iterable(dist.files)))\n \n def importable_name(name):\n return '.'not in name\n \n return filter(importable_name,opt_names)\n", ["__future__", "abc", "collections", "contextlib", "csv", "email", "functools", "importlib", "importlib.abc", "importlib.metadata", "importlib.metadata._adapters", "importlib.metadata._collections", "importlib.metadata._functools", "importlib.metadata._itertools", "importlib.metadata._meta", "inspect", "itertools", "json", "operator", "os", "pathlib", "posixpath", "re", "sys", "textwrap", "types", "typing", "warnings", "zipfile"], 1], "importlib.resources.abc": [".py", "import abc\nimport io\nimport itertools\nimport os\nimport pathlib\nfrom typing import Any,BinaryIO,Iterable,Iterator,NoReturn,Text,Optional\nfrom typing import runtime_checkable,Protocol\nfrom typing import Union\n\n\nStrPath=Union[str,os.PathLike[str]]\n\n__all__=[\"ResourceReader\",\"Traversable\",\"TraversableResources\"]\n\n\nclass ResourceReader(metaclass=abc.ABCMeta):\n ''\n \n @abc.abstractmethod\n def open_resource(self,resource:Text)->BinaryIO:\n ''\n\n\n\n \n \n \n \n raise FileNotFoundError\n \n @abc.abstractmethod\n def resource_path(self,resource:Text)->Text:\n ''\n\n\n\n\n \n \n \n \n raise FileNotFoundError\n \n @abc.abstractmethod\n def is_resource(self,path:Text)->bool:\n ''\n\n\n \n raise FileNotFoundError\n \n @abc.abstractmethod\n def contents(self)->Iterable[str]:\n ''\n raise FileNotFoundError\n \n \nclass TraversalError(Exception):\n pass\n \n \n@runtime_checkable\nclass Traversable(Protocol):\n ''\n\n\n\n\n\n \n \n @abc.abstractmethod\n def iterdir(self)->Iterator[\"Traversable\"]:\n ''\n\n \n \n def read_bytes(self)->bytes:\n ''\n\n \n with self.open('rb')as strm:\n return strm.read()\n \n def read_text(self,encoding:Optional[str]=None)->str:\n ''\n\n \n with self.open(encoding=encoding)as strm:\n return strm.read()\n \n @abc.abstractmethod\n def is_dir(self)->bool:\n ''\n\n \n \n @abc.abstractmethod\n def is_file(self)->bool:\n ''\n\n \n \n def joinpath(self,*descendants:StrPath)->\"Traversable\":\n ''\n\n\n\n\n\n \n if not descendants:\n return self\n names=itertools.chain.from_iterable(\n path.parts for path in map(pathlib.PurePosixPath,descendants)\n )\n target=next(names)\n matches=(\n traversable for traversable in self.iterdir()if traversable.name ==target\n )\n try:\n match=next(matches)\n except StopIteration:\n raise TraversalError(\n \"Target not found during traversal.\",target,list(names)\n )\n return match.joinpath(*names)\n \n def __truediv__(self,child:StrPath)->\"Traversable\":\n ''\n\n \n return self.joinpath(child)\n \n @abc.abstractmethod\n def open(self,mode='r',*args,**kwargs):\n ''\n\n\n\n\n\n \n \n @property\n @abc.abstractmethod\n def name(self)->str:\n ''\n\n \n \n \nclass TraversableResources(ResourceReader):\n ''\n\n\n \n \n @abc.abstractmethod\n def files(self)->\"Traversable\":\n ''\n \n def open_resource(self,resource:StrPath)->io.BufferedReader:\n return self.files().joinpath(resource).open('rb')\n \n def resource_path(self,resource:Any)->NoReturn:\n raise FileNotFoundError(resource)\n \n def is_resource(self,path:StrPath)->bool:\n return self.files().joinpath(path).is_file()\n \n def contents(self)->Iterator[str]:\n return(item.name for item in self.files().iterdir())\n", ["abc", "io", "itertools", "os", "pathlib", "typing"]], "importlib.resources.readers": [".py", "import collections\nimport itertools\nimport pathlib\nimport operator\nimport zipfile\n\nfrom. import abc\n\nfrom._itertools import only\n\n\ndef remove_duplicates(items):\n return iter(collections.OrderedDict.fromkeys(items))\n \n \nclass FileReader(abc.TraversableResources):\n def __init__(self,loader):\n self.path=pathlib.Path(loader.path).parent\n \n def resource_path(self,resource):\n ''\n\n\n\n \n return str(self.path.joinpath(resource))\n \n def files(self):\n return self.path\n \n \nclass ZipReader(abc.TraversableResources):\n def __init__(self,loader,module):\n _,_,name=module.rpartition('.')\n self.prefix=loader.prefix.replace('\\\\','/')+name+'/'\n self.archive=loader.archive\n \n def open_resource(self,resource):\n try:\n return super().open_resource(resource)\n except KeyError as exc:\n raise FileNotFoundError(exc.args[0])\n \n def is_resource(self,path):\n ''\n\n\n \n target=self.files().joinpath(path)\n return target.is_file()and target.exists()\n \n def files(self):\n return zipfile.Path(self.archive,self.prefix)\n \n \nclass MultiplexedPath(abc.Traversable):\n ''\n\n\n\n\n \n \n def __init__(self,*paths):\n self._paths=list(map(pathlib.Path,remove_duplicates(paths)))\n if not self._paths:\n message='MultiplexedPath must contain at least one path'\n raise FileNotFoundError(message)\n if not all(path.is_dir()for path in self._paths):\n raise NotADirectoryError('MultiplexedPath only supports directories')\n \n def iterdir(self):\n children=(child for path in self._paths for child in path.iterdir())\n by_name=operator.attrgetter('name')\n groups=itertools.groupby(sorted(children,key=by_name),key=by_name)\n return map(self._follow,(locs for name,locs in groups))\n \n def read_bytes(self):\n raise FileNotFoundError(f'{self} is not a file')\n \n def read_text(self,*args,**kwargs):\n raise FileNotFoundError(f'{self} is not a file')\n \n def is_dir(self):\n return True\n \n def is_file(self):\n return False\n \n def joinpath(self,*descendants):\n try:\n return super().joinpath(*descendants)\n except abc.TraversalError:\n \n \n return self._paths[0].joinpath(*descendants)\n \n @classmethod\n def _follow(cls,children):\n ''\n\n\n\n\n\n \n subdirs,one_dir,one_file=itertools.tee(children,3)\n \n try:\n return only(one_dir)\n except ValueError:\n try:\n return cls(*subdirs)\n except NotADirectoryError:\n return next(one_file)\n \n def open(self,*args,**kwargs):\n raise FileNotFoundError(f'{self} is not a file')\n \n @property\n def name(self):\n return self._paths[0].name\n \n def __repr__(self):\n paths=', '.join(f\"'{path}'\"for path in self._paths)\n return f'MultiplexedPath({paths})'\n \n \nclass NamespaceReader(abc.TraversableResources):\n def __init__(self,namespace_path):\n if 'NamespacePath'not in str(namespace_path):\n raise ValueError('Invalid path')\n self.path=MultiplexedPath(*list(namespace_path))\n \n def resource_path(self,resource):\n ''\n\n\n\n \n return str(self.path.joinpath(resource))\n \n def files(self):\n return self.path\n", ["collections", "importlib.resources", "importlib.resources._itertools", "importlib.resources.abc", "itertools", "operator", "pathlib", "zipfile"]], "importlib.resources.simple": [".py", "''\n\n\n\nimport abc\nimport io\nimport itertools\nfrom typing import BinaryIO,List\n\nfrom.abc import Traversable,TraversableResources\n\n\nclass SimpleReader(abc.ABC):\n ''\n\n\n \n \n @property\n @abc.abstractmethod\n def package(self)->str:\n ''\n\n \n \n @abc.abstractmethod\n def children(self)->List['SimpleReader']:\n ''\n\n\n \n \n @abc.abstractmethod\n def resources(self)->List[str]:\n ''\n\n \n \n @abc.abstractmethod\n def open_binary(self,resource:str)->BinaryIO:\n ''\n\n \n \n @property\n def name(self):\n return self.package.split('.')[-1]\n \n \nclass ResourceContainer(Traversable):\n ''\n\n \n \n def __init__(self,reader:SimpleReader):\n self.reader=reader\n \n def is_dir(self):\n return True\n \n def is_file(self):\n return False\n \n def iterdir(self):\n files=(ResourceHandle(self,name)for name in self.reader.resources)\n dirs=map(ResourceContainer,self.reader.children())\n return itertools.chain(files,dirs)\n \n def open(self,*args,**kwargs):\n raise IsADirectoryError()\n \n \nclass ResourceHandle(Traversable):\n ''\n\n \n \n def __init__(self,parent:ResourceContainer,name:str):\n self.parent=parent\n self.name=name\n \n def is_file(self):\n return True\n \n def is_dir(self):\n return False\n \n def open(self,mode='r',*args,**kwargs):\n stream=self.parent.reader.open_binary(self.name)\n if 'b'not in mode:\n stream=io.TextIOWrapper(stream,*args,**kwargs)\n return stream\n \n def joinpath(self,name):\n raise RuntimeError(\"Cannot traverse into a resource\")\n \n \nclass TraversableReader(TraversableResources,SimpleReader):\n ''\n\n\n\n \n \n def files(self):\n return ResourceContainer(self)\n", ["abc", "importlib.resources.abc", "io", "itertools", "typing"]], "importlib.resources._adapters": [".py", "from contextlib import suppress\nfrom io import TextIOWrapper\n\nfrom. import abc\n\n\nclass SpecLoaderAdapter:\n ''\n\n \n \n def __init__(self,spec,adapter=lambda spec:spec.loader):\n self.spec=spec\n self.loader=adapter(spec)\n \n def __getattr__(self,name):\n return getattr(self.spec,name)\n \n \nclass TraversableResourcesLoader:\n ''\n\n \n \n def __init__(self,spec):\n self.spec=spec\n \n def get_resource_reader(self,name):\n return CompatibilityFiles(self.spec)._native()\n \n \ndef _io_wrapper(file,mode='r',*args,**kwargs):\n if mode =='r':\n return TextIOWrapper(file,*args,**kwargs)\n elif mode =='rb':\n return file\n raise ValueError(f\"Invalid mode value '{mode}', only 'r' and 'rb' are supported\")\n \n \nclass CompatibilityFiles:\n ''\n\n\n \n \n class SpecPath(abc.Traversable):\n ''\n\n\n \n \n def __init__(self,spec,reader):\n self._spec=spec\n self._reader=reader\n \n def iterdir(self):\n if not self._reader:\n return iter(())\n return iter(\n CompatibilityFiles.ChildPath(self._reader,path)\n for path in self._reader.contents()\n )\n \n def is_file(self):\n return False\n \n is_dir=is_file\n \n def joinpath(self,other):\n if not self._reader:\n return CompatibilityFiles.OrphanPath(other)\n return CompatibilityFiles.ChildPath(self._reader,other)\n \n @property\n def name(self):\n return self._spec.name\n \n def open(self,mode='r',*args,**kwargs):\n return _io_wrapper(self._reader.open_resource(None),mode,*args,**kwargs)\n \n class ChildPath(abc.Traversable):\n ''\n\n\n \n \n def __init__(self,reader,name):\n self._reader=reader\n self._name=name\n \n def iterdir(self):\n return iter(())\n \n def is_file(self):\n return self._reader.is_resource(self.name)\n \n def is_dir(self):\n return not self.is_file()\n \n def joinpath(self,other):\n return CompatibilityFiles.OrphanPath(self.name,other)\n \n @property\n def name(self):\n return self._name\n \n def open(self,mode='r',*args,**kwargs):\n return _io_wrapper(\n self._reader.open_resource(self.name),mode,*args,**kwargs\n )\n \n class OrphanPath(abc.Traversable):\n ''\n\n\n \n \n def __init__(self,*path_parts):\n if len(path_parts)<1:\n raise ValueError('Need at least one path part to construct a path')\n self._path=path_parts\n \n def iterdir(self):\n return iter(())\n \n def is_file(self):\n return False\n \n is_dir=is_file\n \n def joinpath(self,other):\n return CompatibilityFiles.OrphanPath(*self._path,other)\n \n @property\n def name(self):\n return self._path[-1]\n \n def open(self,mode='r',*args,**kwargs):\n raise FileNotFoundError(\"Can't open orphan path\")\n \n def __init__(self,spec):\n self.spec=spec\n \n @property\n def _reader(self):\n with suppress(AttributeError):\n return self.spec.loader.get_resource_reader(self.spec.name)\n \n def _native(self):\n ''\n\n \n reader=self._reader\n return reader if hasattr(reader,'files')else self\n \n def __getattr__(self,attr):\n return getattr(self._reader,attr)\n \n def files(self):\n return CompatibilityFiles.SpecPath(self.spec,self._reader)\n \n \ndef wrap_spec(package):\n ''\n\n\n \n return SpecLoaderAdapter(package.__spec__,TraversableResourcesLoader)\n", ["contextlib", "importlib.resources", "importlib.resources.abc", "io"]], "importlib.resources._common": [".py", "import os\nimport pathlib\nimport tempfile\nimport functools\nimport contextlib\nimport types\nimport importlib\nimport inspect\nimport warnings\nimport itertools\n\nfrom typing import Union,Optional,cast\nfrom.abc import ResourceReader,Traversable\n\nPackage=Union[types.ModuleType,str]\nAnchor=Package\n\n\ndef package_to_anchor(func):\n ''\n\n\n\n\n\n\n\n \n undefined=object()\n \n @functools.wraps(func)\n def wrapper(anchor=undefined,package=undefined):\n if package is not undefined:\n if anchor is not undefined:\n return func(anchor,package)\n warnings.warn(\n \"First parameter to files is renamed to 'anchor'\",\n DeprecationWarning,\n stacklevel=2,\n )\n return func(package)\n elif anchor is undefined:\n return func()\n return func(anchor)\n \n return wrapper\n \n \n@package_to_anchor\ndef files(anchor:Optional[Anchor]=None)->Traversable:\n ''\n\n \n return from_package(resolve(anchor))\n \n \ndef get_resource_reader(package:types.ModuleType)->Optional[ResourceReader]:\n ''\n\n \n \n \n \n \n \n spec=package.__spec__\n reader=getattr(spec.loader,'get_resource_reader',None)\n if reader is None:\n return None\n return reader(spec.name)\n \n \n@functools.singledispatch\ndef resolve(cand:Optional[Anchor])->types.ModuleType:\n return cast(types.ModuleType,cand)\n \n \n@resolve.register\ndef _(cand:str)->types.ModuleType:\n return importlib.import_module(cand)\n \n \n@resolve.register\ndef _(cand:None)->types.ModuleType:\n return resolve(_infer_caller().f_globals['__name__'])\n \n \ndef _infer_caller():\n ''\n\n \n \n def is_this_file(frame_info):\n return frame_info.filename ==__file__\n \n def is_wrapper(frame_info):\n return frame_info.function =='wrapper'\n \n not_this_file=itertools.filterfalse(is_this_file,inspect.stack())\n \n callers=itertools.filterfalse(is_wrapper,not_this_file)\n return next(callers).frame\n \n \ndef from_package(package:types.ModuleType):\n ''\n\n\n \n \n from._adapters import wrap_spec\n \n spec=wrap_spec(package)\n reader=spec.loader.get_resource_reader(spec.name)\n return reader.files()\n \n \n@contextlib.contextmanager\ndef _tempfile(\nreader,\nsuffix='',\n\n\n*,\n_os_remove=os.remove,\n):\n\n\n\n fd,raw_path=tempfile.mkstemp(suffix=suffix)\n try:\n try:\n os.write(fd,reader())\n finally:\n os.close(fd)\n del reader\n yield pathlib.Path(raw_path)\n finally:\n try:\n _os_remove(raw_path)\n except FileNotFoundError:\n pass\n \n \ndef _temp_file(path):\n return _tempfile(path.read_bytes,suffix=path.name)\n \n \ndef _is_present_dir(path:Traversable)->bool:\n ''\n\n\n\n\n\n \n with contextlib.suppress(FileNotFoundError):\n return path.is_dir()\n return False\n \n \n@functools.singledispatch\ndef as_file(path):\n ''\n\n\n \n return _temp_dir(path)if _is_present_dir(path)else _temp_file(path)\n \n \n@as_file.register(pathlib.Path)\n@contextlib.contextmanager\ndef _(path):\n ''\n\n \n yield path\n \n \n@contextlib.contextmanager\ndef _temp_path(dir:tempfile.TemporaryDirectory):\n ''\n\n \n with dir as result:\n yield pathlib.Path(result)\n \n \n@contextlib.contextmanager\ndef _temp_dir(path):\n ''\n\n\n \n assert path.is_dir()\n with _temp_path(tempfile.TemporaryDirectory())as temp_dir:\n yield _write_contents(temp_dir,path)\n \n \ndef _write_contents(target,source):\n child=target.joinpath(source.name)\n if source.is_dir():\n child.mkdir()\n for item in source.iterdir():\n _write_contents(child,item)\n else:\n child.write_bytes(source.read_bytes())\n return child\n", ["contextlib", "functools", "importlib", "importlib.resources._adapters", "importlib.resources.abc", "inspect", "itertools", "os", "pathlib", "tempfile", "types", "typing", "warnings"]], "importlib.resources._itertools": [".py", "\ndef only(iterable,default=None,too_long=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n it=iter(iterable)\n first_value=next(it,default)\n \n try:\n second_value=next(it)\n except StopIteration:\n pass\n else:\n msg=(\n 'Expected exactly one item in iterable, but got {!r}, {!r}, '\n 'and perhaps more.'.format(first_value,second_value)\n )\n raise too_long or ValueError(msg)\n \n return first_value\n", []], "importlib.resources._legacy": [".py", "import functools\nimport os\nimport pathlib\nimport types\nimport warnings\n\nfrom typing import Union,Iterable,ContextManager,BinaryIO,TextIO,Any\n\nfrom. import _common\n\nPackage=Union[types.ModuleType,str]\nResource=str\n\n\ndef deprecated(func):\n @functools.wraps(func)\n def wrapper(*args,**kwargs):\n warnings.warn(\n f\"{func.__name__} is deprecated. Use files() instead. \"\n \"Refer to https://importlib-resources.readthedocs.io\"\n \"/en/latest/using.html#migrating-from-legacy for migration advice.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return func(*args,**kwargs)\n \n return wrapper\n \n \ndef normalize_path(path:Any)->str:\n ''\n\n\n \n str_path=str(path)\n parent,file_name=os.path.split(str_path)\n if parent:\n raise ValueError(f'{path !r} must be only a file name')\n return file_name\n \n \n@deprecated\ndef open_binary(package:Package,resource:Resource)->BinaryIO:\n ''\n return(_common.files(package)/normalize_path(resource)).open('rb')\n \n \n@deprecated\ndef read_binary(package:Package,resource:Resource)->bytes:\n ''\n return(_common.files(package)/normalize_path(resource)).read_bytes()\n \n \n@deprecated\ndef open_text(\npackage:Package,\nresource:Resource,\nencoding:str='utf-8',\nerrors:str='strict',\n)->TextIO:\n ''\n return(_common.files(package)/normalize_path(resource)).open(\n 'r',encoding=encoding,errors=errors\n )\n \n \n@deprecated\ndef read_text(\npackage:Package,\nresource:Resource,\nencoding:str='utf-8',\nerrors:str='strict',\n)->str:\n ''\n\n\n\n \n with open_text(package,resource,encoding,errors)as fp:\n return fp.read()\n \n \n@deprecated\ndef contents(package:Package)->Iterable[str]:\n ''\n\n\n\n\n \n return[path.name for path in _common.files(package).iterdir()]\n \n \n@deprecated\ndef is_resource(package:Package,name:str)->bool:\n ''\n\n\n \n resource=normalize_path(name)\n return any(\n traversable.name ==resource and traversable.is_file()\n for traversable in _common.files(package).iterdir()\n )\n \n \n@deprecated\ndef path(\npackage:Package,\nresource:Resource,\n)->ContextManager[pathlib.Path]:\n ''\n\n\n\n\n\n\n \n return _common.as_file(_common.files(package)/normalize_path(resource))\n", ["functools", "importlib.resources", "importlib.resources._common", "os", "pathlib", "types", "typing", "warnings"]], "importlib.resources": [".py", "''\n\nfrom._common import(\nas_file,\nfiles,\nPackage,\nAnchor,\n)\n\nfrom._functional import(\ncontents,\nis_resource,\nopen_binary,\nopen_text,\npath,\nread_binary,\nread_text,\n)\n\nfrom.abc import ResourceReader\n\n\n__all__=[\n'Package',\n'Anchor',\n'ResourceReader',\n'as_file',\n'files',\n'contents',\n'is_resource',\n'open_binary',\n'open_text',\n'path',\n'read_binary',\n'read_text',\n]\n", ["importlib.resources._common", "importlib.resources._functional", "importlib.resources.abc"], 1], "json.encoder": [".py", "''\n\nimport re\n\ntry:\n from _json import encode_basestring_ascii as c_encode_basestring_ascii\nexcept ImportError:\n c_encode_basestring_ascii=None\ntry:\n from _json import encode_basestring as c_encode_basestring\nexcept ImportError:\n c_encode_basestring=None\ntry:\n from _json import make_encoder as c_make_encoder\nexcept ImportError:\n c_make_encoder=None\n \nESCAPE=re.compile(r'[\\x00-\\x1f\\\\\"\\b\\f\\n\\r\\t]')\nESCAPE_ASCII=re.compile(r'([\\\\\"]|[^\\ -~])')\nHAS_UTF8=re.compile(b'[\\x80-\\xff]')\nESCAPE_DCT={\n'\\\\':'\\\\\\\\',\n'\"':'\\\\\"',\n'\\b':'\\\\b',\n'\\f':'\\\\f',\n'\\n':'\\\\n',\n'\\r':'\\\\r',\n'\\t':'\\\\t',\n}\nfor i in range(0x20):\n ESCAPE_DCT.setdefault(chr(i),'\\\\u{0:04x}'.format(i))\n \ndel i\n\nINFINITY=float('inf')\n\ndef py_encode_basestring(s):\n ''\n\n \n def replace(match):\n return ESCAPE_DCT[match.group(0)]\n return '\"'+ESCAPE.sub(replace,s)+'\"'\n \n \nencode_basestring=(c_encode_basestring or py_encode_basestring)\n\n\ndef py_encode_basestring_ascii(s):\n ''\n\n \n def replace(match):\n s=match.group(0)\n try:\n return ESCAPE_DCT[s]\n except KeyError:\n n=ord(s)\n if n <0x10000:\n return '\\\\u{0:04x}'.format(n)\n \n else:\n \n n -=0x10000\n s1=0xd800 |((n >>10)&0x3ff)\n s2=0xdc00 |(n&0x3ff)\n return '\\\\u{0:04x}\\\\u{1:04x}'.format(s1,s2)\n return '\"'+ESCAPE_ASCII.sub(replace,s)+'\"'\n \n \nencode_basestring_ascii=(\nc_encode_basestring_ascii or py_encode_basestring_ascii)\n\nclass JSONEncoder(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item_separator=', '\n key_separator=': '\n def __init__(self,*,skipkeys=False,ensure_ascii=True,\n check_circular=True,allow_nan=True,sort_keys=False,\n indent=None,separators=None,default=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.skipkeys=skipkeys\n self.ensure_ascii=ensure_ascii\n self.check_circular=check_circular\n self.allow_nan=allow_nan\n self.sort_keys=sort_keys\n self.indent=indent\n if separators is not None:\n self.item_separator,self.key_separator=separators\n elif indent is not None:\n self.item_separator=','\n if default is not None:\n self.default=default\n \n def default(self,o):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f'Object of type {o.__class__.__name__} '\n f'is not JSON serializable')\n \n def encode(self,o):\n ''\n\n\n\n\n\n \n \n if isinstance(o,str):\n if self.ensure_ascii:\n return encode_basestring_ascii(o)\n else:\n return encode_basestring(o)\n \n \n \n chunks=self.iterencode(o,_one_shot=True)\n if not isinstance(chunks,(list,tuple)):\n chunks=list(chunks)\n return ''.join(chunks)\n \n def iterencode(self,o,_one_shot=False):\n ''\n\n\n\n\n\n\n\n \n if self.check_circular:\n markers={}\n else:\n markers=None\n if self.ensure_ascii:\n _encoder=encode_basestring_ascii\n else:\n _encoder=encode_basestring\n \n def floatstr(o,allow_nan=self.allow_nan,\n _repr=float.__repr__,_inf=INFINITY,_neginf=-INFINITY):\n \n \n \n \n if o !=o:\n text='NaN'\n elif o ==_inf:\n text='Infinity'\n elif o ==_neginf:\n text='-Infinity'\n else:\n return _repr(o)\n \n if not allow_nan:\n raise ValueError(\n \"Out of range float values are not JSON compliant: \"+\n repr(o))\n \n return text\n \n \n if(_one_shot and c_make_encoder is not None\n and self.indent is None):\n _iterencode=c_make_encoder(\n markers,self.default,_encoder,self.indent,\n self.key_separator,self.item_separator,self.sort_keys,\n self.skipkeys,self.allow_nan)\n else:\n _iterencode=_make_iterencode(\n markers,self.default,_encoder,self.indent,floatstr,\n self.key_separator,self.item_separator,self.sort_keys,\n self.skipkeys,_one_shot)\n return _iterencode(o,0)\n \ndef _make_iterencode(markers,_default,_encoder,_indent,_floatstr,\n_key_separator,_item_separator,_sort_keys,_skipkeys,_one_shot,\n\nValueError=ValueError,\ndict=dict,\nfloat=float,\nid=id,\nint=int,\nisinstance=isinstance,\nlist=list,\nstr=str,\ntuple=tuple,\n_intstr=int.__repr__,\n):\n\n if _indent is not None and not isinstance(_indent,str):\n _indent=' '*_indent\n \n def _iterencode_list(lst,_current_indent_level):\n if not lst:\n yield '[]'\n return\n if markers is not None:\n markerid=id(lst)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=lst\n buf='['\n if _indent is not None:\n _current_indent_level +=1\n newline_indent='\\n'+_indent *_current_indent_level\n separator=_item_separator+newline_indent\n buf +=newline_indent\n else:\n newline_indent=None\n separator=_item_separator\n first=True\n for value in lst:\n if first:\n first=False\n else:\n buf=separator\n if isinstance(value,str):\n yield buf+_encoder(value)\n elif value is None:\n yield buf+'null'\n elif value is True:\n yield buf+'true'\n elif value is False:\n yield buf+'false'\n elif isinstance(value,int):\n \n \n \n yield buf+_intstr(value)\n elif isinstance(value,float):\n \n yield buf+_floatstr(value)\n else:\n yield buf\n if isinstance(value,(list,tuple)):\n chunks=_iterencode_list(value,_current_indent_level)\n elif isinstance(value,dict):\n chunks=_iterencode_dict(value,_current_indent_level)\n else:\n chunks=_iterencode(value,_current_indent_level)\n yield from chunks\n if newline_indent is not None:\n _current_indent_level -=1\n yield '\\n'+_indent *_current_indent_level\n yield ']'\n if markers is not None:\n del markers[markerid]\n \n def _iterencode_dict(dct,_current_indent_level):\n if not dct:\n yield '{}'\n return\n if markers is not None:\n markerid=id(dct)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=dct\n yield '{'\n if _indent is not None:\n _current_indent_level +=1\n newline_indent='\\n'+_indent *_current_indent_level\n item_separator=_item_separator+newline_indent\n yield newline_indent\n else:\n newline_indent=None\n item_separator=_item_separator\n first=True\n if _sort_keys:\n items=sorted(dct.items())\n else:\n items=dct.items()\n for key,value in items:\n if isinstance(key,str):\n pass\n \n \n elif isinstance(key,float):\n \n key=_floatstr(key)\n elif key is True:\n key='true'\n elif key is False:\n key='false'\n elif key is None:\n key='null'\n elif isinstance(key,int):\n \n key=_intstr(key)\n elif _skipkeys:\n continue\n else:\n raise TypeError(f'keys must be str, int, float, bool or None, '\n f'not {key.__class__.__name__}')\n if first:\n first=False\n else:\n yield item_separator\n yield _encoder(key)\n yield _key_separator\n if isinstance(value,str):\n yield _encoder(value)\n elif value is None:\n yield 'null'\n elif value is True:\n yield 'true'\n elif value is False:\n yield 'false'\n elif isinstance(value,int):\n \n yield _intstr(value)\n elif isinstance(value,float):\n \n yield _floatstr(value)\n else:\n if isinstance(value,(list,tuple)):\n chunks=_iterencode_list(value,_current_indent_level)\n elif isinstance(value,dict):\n chunks=_iterencode_dict(value,_current_indent_level)\n else:\n chunks=_iterencode(value,_current_indent_level)\n yield from chunks\n if newline_indent is not None:\n _current_indent_level -=1\n yield '\\n'+_indent *_current_indent_level\n yield '}'\n if markers is not None:\n del markers[markerid]\n \n def _iterencode(o,_current_indent_level):\n if isinstance(o,str):\n yield _encoder(o)\n elif o is None:\n yield 'null'\n elif o is True:\n yield 'true'\n elif o is False:\n yield 'false'\n elif isinstance(o,int):\n \n yield _intstr(o)\n elif isinstance(o,float):\n \n yield _floatstr(o)\n elif isinstance(o,(list,tuple)):\n yield from _iterencode_list(o,_current_indent_level)\n elif isinstance(o,dict):\n yield from _iterencode_dict(o,_current_indent_level)\n else:\n if markers is not None:\n markerid=id(o)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=o\n o=_default(o)\n yield from _iterencode(o,_current_indent_level)\n if markers is not None:\n del markers[markerid]\n return _iterencode\n", ["_json", "re"]], "json": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__='2.0.9'\n__all__=[\n'dump','dumps','load','loads',\n'JSONDecoder','JSONDecodeError','JSONEncoder',\n]\n\n__author__='Bob Ippolito '\n\n\n\n\n\nclass codecs:\n\n BOM_UTF8=b'\\xef\\xbb\\xbf'\n BOM_LE=BOM_UTF16_LE=b'\\xff\\xfe'\n BOM_BE=BOM_UTF16_BE=b'\\xfe\\xff'\n BOM_UTF32_LE=b'\\xff\\xfe\\x00\\x00'\n BOM_UTF32_BE=b'\\x00\\x00\\xfe\\xff'\n \n \nimport _json\nfrom.encoder import JSONEncoder\n\nJSONDecoder=_json.JSONDecoder\n\nclass decoder:\n JSONDecoder=_json.JSONDecoder\n \nclass JSONDecodeError(ValueError):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,msg,doc,pos):\n lineno=doc.count('\\n',0,pos)+1\n colno=pos -doc.rfind('\\n',0,pos)\n errmsg='%s: line %d column %d (char %d)'%(msg,lineno,colno,pos)\n ValueError.__init__(self,errmsg)\n self.msg=msg\n self.doc=doc\n self.pos=pos\n self.lineno=lineno\n self.colno=colno\n \n def __reduce__(self):\n return self.__class__,(self.msg,self.doc,self.pos)\n \ndef dump(obj,fp,**kw):\n fp.write(dumps(obj,**kw))\n \ndef dumps(obj,*,skipkeys=False,ensure_ascii=True,check_circular=True,\nallow_nan=True,cls=None,indent=None,separators=None,\ndefault=None,sort_keys=False,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if cls is None:\n return _json.dumps(obj,1,\n skipkeys=skipkeys,ensure_ascii=ensure_ascii,\n check_circular=check_circular,allow_nan=allow_nan,indent=indent,\n separators=separators,default=default,sort_keys=sort_keys,\n **kw)\n return cls(\n skipkeys=skipkeys,ensure_ascii=ensure_ascii,\n check_circular=check_circular,allow_nan=allow_nan,indent=indent,\n separators=separators,default=default,sort_keys=sort_keys,\n **kw).encode(obj)\n \ndef detect_encoding(b):\n bstartswith=b.startswith\n if bstartswith((codecs.BOM_UTF32_BE,codecs.BOM_UTF32_LE)):\n return 'utf-32'\n if bstartswith((codecs.BOM_UTF16_BE,codecs.BOM_UTF16_LE)):\n return 'utf-16'\n if bstartswith(codecs.BOM_UTF8):\n return 'utf-8-sig'\n \n if len(b)>=4:\n if not b[0]:\n \n \n return 'utf-16-be'if b[1]else 'utf-32-be'\n if not b[1]:\n \n \n \n return 'utf-16-le'if b[2]or b[3]else 'utf-32-le'\n elif len(b)==2:\n if not b[0]:\n \n return 'utf-16-be'\n if not b[1]:\n \n return 'utf-16-le'\n \n return 'utf-8'\n \n \ndef load(fp,*,cls=None,object_hook=None,parse_float=None,\nparse_int=None,parse_constant=None,object_pairs_hook=None,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return loads(fp.read(),\n cls=cls,object_hook=object_hook,\n parse_float=parse_float,parse_int=parse_int,\n parse_constant=parse_constant,object_pairs_hook=object_pairs_hook,**kw)\n \n \ndef loads(s,*,cls=None,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(s,str):\n if s.startswith('\\ufeff'):\n raise JSONDecodeError(\"Unexpected UTF-8 BOM (decode using utf-8-sig)\",\n s,0)\n else:\n if not isinstance(s,(bytes,bytearray)):\n raise TypeError(f'the JSON object must be str, bytes or bytearray, '\n f'not {s.__class__.__name__}')\n s=s.decode(detect_encoding(s),'surrogatepass')\n \n \n if \"encoding\"in kw:\n import warnings\n warnings.warn(\n \"'encoding' is ignored and deprecated. It will be removed in Python 3.9\",\n DeprecationWarning,\n stacklevel=2\n )\n del kw['encoding']\n \n if cls is None:\n \n \n return _json.loads(s,**kw)\n if object_hook is not None:\n kw['object_hook']=object_hook\n if object_pairs_hook is not None:\n kw['object_pairs_hook']=object_pairs_hook\n if parse_float is not None:\n kw['parse_float']=parse_float\n if parse_int is not None:\n kw['parse_int']=parse_int\n if parse_constant is not None:\n kw['parse_constant']=parse_constant\n return cls(**kw).decode(s)\n", ["_json", "json.encoder", "warnings"], 1], "logging.brython_handlers": [".py", "import logging\n\nfrom browser.ajax import ajax\n\n\nclass XMLHTTPHandler(logging.Handler):\n ''\n\n\n \n def __init__(self,url,method=\"GET\"):\n ''\n\n\n \n logging.Handler.__init__(self)\n method=method.upper()\n if method not in[\"GET\",\"POST\"]:\n raise ValueError(\"method must be GET or POST\")\n self.url=url\n self.method=method\n \n def mapLogRecord(self,record):\n ''\n\n\n\n \n return record.__dict__\n \n def emit(self,record):\n ''\n\n\n\n \n try:\n req=ajax.open(self.method,self.url,sync=False)\n req.send(self.mapLogRecord(record))\n except:\n self.handleError(record)\n", ["browser.ajax", "logging"]], "logging.config": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\"\nConfiguration functions for the logging package for Python. The core package\nis based on PEP 282 and comments thereto in comp.lang.python, and influenced\nby Apache's log4j system.\n\nCopyright (C) 2001-2022 Vinay Sajip. All Rights Reserved.\n\nTo use, simply 'import logging' and log away!\n\"\"\"\n\nimport errno\nimport functools\nimport io\nimport logging\nimport logging.handlers\nimport os\nimport queue\nimport re\nimport struct\nimport threading\nimport traceback\n\nfrom socketserver import ThreadingTCPServer,StreamRequestHandler\n\n\nDEFAULT_LOGGING_CONFIG_PORT=9030\n\nRESET_ERROR=errno.ECONNRESET\n\n\n\n\n\n\n_listener=None\n\ndef fileConfig(fname,defaults=None,disable_existing_loggers=True,encoding=None):\n ''\n\n\n\n\n\n\n \n import configparser\n \n if isinstance(fname,str):\n if not os.path.exists(fname):\n raise FileNotFoundError(f\"{fname} doesn't exist\")\n elif not os.path.getsize(fname):\n raise RuntimeError(f'{fname} is an empty file')\n \n if isinstance(fname,configparser.RawConfigParser):\n cp=fname\n else:\n try:\n cp=configparser.ConfigParser(defaults)\n if hasattr(fname,'readline'):\n cp.read_file(fname)\n else:\n encoding=io.text_encoding(encoding)\n cp.read(fname,encoding=encoding)\n except configparser.ParsingError as e:\n raise RuntimeError(f'{fname} is invalid: {e}')\n \n formatters=_create_formatters(cp)\n \n \n with logging._lock:\n _clearExistingHandlers()\n \n \n handlers=_install_handlers(cp,formatters)\n _install_loggers(cp,handlers,disable_existing_loggers)\n \n \ndef _resolve(name):\n ''\n name=name.split('.')\n used=name.pop(0)\n found=__import__(used)\n for n in name:\n used=used+'.'+n\n try:\n found=getattr(found,n)\n except AttributeError:\n __import__(used)\n found=getattr(found,n)\n return found\n \ndef _strip_spaces(alist):\n return map(str.strip,alist)\n \ndef _create_formatters(cp):\n ''\n flist=cp[\"formatters\"][\"keys\"]\n if not len(flist):\n return{}\n flist=flist.split(\",\")\n flist=_strip_spaces(flist)\n formatters={}\n for form in flist:\n sectname=\"formatter_%s\"%form\n fs=cp.get(sectname,\"format\",raw=True,fallback=None)\n dfs=cp.get(sectname,\"datefmt\",raw=True,fallback=None)\n stl=cp.get(sectname,\"style\",raw=True,fallback='%')\n defaults=cp.get(sectname,\"defaults\",raw=True,fallback=None)\n \n c=logging.Formatter\n class_name=cp[sectname].get(\"class\")\n if class_name:\n c=_resolve(class_name)\n \n if defaults is not None:\n defaults=eval(defaults,vars(logging))\n f=c(fs,dfs,stl,defaults=defaults)\n else:\n f=c(fs,dfs,stl)\n formatters[form]=f\n return formatters\n \n \ndef _install_handlers(cp,formatters):\n ''\n hlist=cp[\"handlers\"][\"keys\"]\n if not len(hlist):\n return{}\n hlist=hlist.split(\",\")\n hlist=_strip_spaces(hlist)\n handlers={}\n fixups=[]\n for hand in hlist:\n section=cp[\"handler_%s\"%hand]\n klass=section[\"class\"]\n fmt=section.get(\"formatter\",\"\")\n try:\n klass=eval(klass,vars(logging))\n except(AttributeError,NameError):\n klass=_resolve(klass)\n args=section.get(\"args\",'()')\n args=eval(args,vars(logging))\n kwargs=section.get(\"kwargs\",'{}')\n kwargs=eval(kwargs,vars(logging))\n h=klass(*args,**kwargs)\n h.name=hand\n if \"level\"in section:\n level=section[\"level\"]\n h.setLevel(level)\n if len(fmt):\n h.setFormatter(formatters[fmt])\n if issubclass(klass,logging.handlers.MemoryHandler):\n target=section.get(\"target\",\"\")\n if len(target):\n fixups.append((h,target))\n handlers[hand]=h\n \n for h,t in fixups:\n h.setTarget(handlers[t])\n return handlers\n \ndef _handle_existing_loggers(existing,child_loggers,disable_existing):\n ''\n\n\n\n\n\n\n\n\n \n root=logging.root\n for log in existing:\n logger=root.manager.loggerDict[log]\n if log in child_loggers:\n if not isinstance(logger,logging.PlaceHolder):\n logger.setLevel(logging.NOTSET)\n logger.handlers=[]\n logger.propagate=True\n else:\n logger.disabled=disable_existing\n \ndef _install_loggers(cp,handlers,disable_existing):\n ''\n \n \n llist=cp[\"loggers\"][\"keys\"]\n llist=llist.split(\",\")\n llist=list(_strip_spaces(llist))\n llist.remove(\"root\")\n section=cp[\"logger_root\"]\n root=logging.root\n log=root\n if \"level\"in section:\n level=section[\"level\"]\n log.setLevel(level)\n for h in root.handlers[:]:\n root.removeHandler(h)\n hlist=section[\"handlers\"]\n if len(hlist):\n hlist=hlist.split(\",\")\n hlist=_strip_spaces(hlist)\n for hand in hlist:\n log.addHandler(handlers[hand])\n \n \n \n \n \n \n \n \n \n \n existing=list(root.manager.loggerDict.keys())\n \n \n \n \n existing.sort()\n \n \n child_loggers=[]\n \n for log in llist:\n section=cp[\"logger_%s\"%log]\n qn=section[\"qualname\"]\n propagate=section.getint(\"propagate\",fallback=1)\n logger=logging.getLogger(qn)\n if qn in existing:\n i=existing.index(qn)+1\n prefixed=qn+\".\"\n pflen=len(prefixed)\n num_existing=len(existing)\n while i [a-z]+)://(?P.*)$')\n \n WORD_PATTERN=re.compile(r'^\\s*(\\w+)\\s*')\n DOT_PATTERN=re.compile(r'^\\.\\s*(\\w+)\\s*')\n INDEX_PATTERN=re.compile(r'^\\[([^\\[\\]]*)\\]\\s*')\n DIGIT_PATTERN=re.compile(r'^\\d+$')\n \n value_converters={\n 'ext':'ext_convert',\n 'cfg':'cfg_convert',\n }\n \n \n importer=staticmethod(__import__)\n \n def __init__(self,config):\n self.config=ConvertingDict(config)\n self.config.configurator=self\n \n def resolve(self,s):\n ''\n\n\n \n name=s.split('.')\n used=name.pop(0)\n try:\n found=self.importer(used)\n for frag in name:\n used +='.'+frag\n try:\n found=getattr(found,frag)\n except AttributeError:\n self.importer(used)\n found=getattr(found,frag)\n return found\n except ImportError as e:\n v=ValueError('Cannot resolve %r: %s'%(s,e))\n raise v from e\n \n def ext_convert(self,value):\n ''\n return self.resolve(value)\n \n def cfg_convert(self,value):\n ''\n rest=value\n m=self.WORD_PATTERN.match(rest)\n if m is None:\n raise ValueError(\"Unable to convert %r\"%value)\n else:\n rest=rest[m.end():]\n d=self.config[m.groups()[0]]\n \n while rest:\n m=self.DOT_PATTERN.match(rest)\n if m:\n d=d[m.groups()[0]]\n else:\n m=self.INDEX_PATTERN.match(rest)\n if m:\n idx=m.groups()[0]\n if not self.DIGIT_PATTERN.match(idx):\n d=d[idx]\n else:\n try:\n n=int(idx)\n d=d[n]\n except TypeError:\n d=d[idx]\n if m:\n rest=rest[m.end():]\n else:\n raise ValueError('Unable to convert '\n '%r at %r'%(value,rest))\n \n return d\n \n def convert(self,value):\n ''\n\n\n\n \n if not isinstance(value,ConvertingDict)and isinstance(value,dict):\n value=ConvertingDict(value)\n value.configurator=self\n elif not isinstance(value,ConvertingList)and isinstance(value,list):\n value=ConvertingList(value)\n value.configurator=self\n elif not isinstance(value,ConvertingTuple)and\\\n isinstance(value,tuple)and not hasattr(value,'_fields'):\n value=ConvertingTuple(value)\n value.configurator=self\n elif isinstance(value,str):\n m=self.CONVERT_PATTERN.match(value)\n if m:\n d=m.groupdict()\n prefix=d['prefix']\n converter=self.value_converters.get(prefix,None)\n if converter:\n suffix=d['suffix']\n converter=getattr(self,converter)\n value=converter(suffix)\n return value\n \n def configure_custom(self,config):\n ''\n c=config.pop('()')\n if not callable(c):\n c=self.resolve(c)\n \n kwargs={k:config[k]for k in config if(k !='.'and valid_ident(k))}\n result=c(**kwargs)\n props=config.pop('.',None)\n if props:\n for name,value in props.items():\n setattr(result,name,value)\n return result\n \n def as_tuple(self,value):\n ''\n if isinstance(value,list):\n value=tuple(value)\n return value\n \nclass DictConfigurator(BaseConfigurator):\n ''\n\n\n \n \n def configure(self):\n ''\n \n config=self.config\n if 'version'not in config:\n raise ValueError(\"dictionary doesn't specify a version\")\n if config['version']!=1:\n raise ValueError(\"Unsupported version: %s\"%config['version'])\n incremental=config.pop('incremental',False)\n EMPTY_DICT={}\n with logging._lock:\n if incremental:\n handlers=config.get('handlers',EMPTY_DICT)\n for name in handlers:\n if name not in logging._handlers:\n raise ValueError('No handler found with '\n 'name %r'%name)\n else:\n try:\n handler=logging._handlers[name]\n handler_config=handlers[name]\n level=handler_config.get('level',None)\n if level:\n handler.setLevel(logging._checkLevel(level))\n except Exception as e:\n raise ValueError('Unable to configure handler '\n '%r'%name)from e\n loggers=config.get('loggers',EMPTY_DICT)\n for name in loggers:\n try:\n self.configure_logger(name,loggers[name],True)\n except Exception as e:\n raise ValueError('Unable to configure logger '\n '%r'%name)from e\n root=config.get('root',None)\n if root:\n try:\n self.configure_root(root,True)\n except Exception as e:\n raise ValueError('Unable to configure root '\n 'logger')from e\n else:\n disable_existing=config.pop('disable_existing_loggers',True)\n \n _clearExistingHandlers()\n \n \n formatters=config.get('formatters',EMPTY_DICT)\n for name in formatters:\n try:\n formatters[name]=self.configure_formatter(\n formatters[name])\n except Exception as e:\n raise ValueError('Unable to configure '\n 'formatter %r'%name)from e\n \n filters=config.get('filters',EMPTY_DICT)\n for name in filters:\n try:\n filters[name]=self.configure_filter(filters[name])\n except Exception as e:\n raise ValueError('Unable to configure '\n 'filter %r'%name)from e\n \n \n \n \n handlers=config.get('handlers',EMPTY_DICT)\n deferred=[]\n for name in sorted(handlers):\n try:\n handler=self.configure_handler(handlers[name])\n handler.name=name\n handlers[name]=handler\n except Exception as e:\n if ' not configured yet'in str(e.__cause__):\n deferred.append(name)\n else:\n raise ValueError('Unable to configure handler '\n '%r'%name)from e\n \n \n for name in deferred:\n try:\n handler=self.configure_handler(handlers[name])\n handler.name=name\n handlers[name]=handler\n except Exception as e:\n raise ValueError('Unable to configure handler '\n '%r'%name)from e\n \n \n \n \n \n \n \n \n \n \n \n root=logging.root\n existing=list(root.manager.loggerDict.keys())\n \n \n \n \n existing.sort()\n \n \n child_loggers=[]\n \n loggers=config.get('loggers',EMPTY_DICT)\n for name in loggers:\n if name in existing:\n i=existing.index(name)+1\n prefixed=name+\".\"\n pflen=len(prefixed)\n num_existing=len(existing)\n while i L\",chunk)[0]\n chunk=self.connection.recv(slen)\n while len(chunk)0:\n mode='a'\n if \"b\"not in mode:\n encoding=io.text_encoding(encoding)\n BaseRotatingHandler.__init__(self,filename,mode,encoding=encoding,\n delay=delay,errors=errors)\n self.maxBytes=maxBytes\n self.backupCount=backupCount\n \n def doRollover(self):\n ''\n\n \n if self.stream:\n self.stream.close()\n self.stream=None\n if self.backupCount >0:\n for i in range(self.backupCount -1,0,-1):\n sfn=self.rotation_filename(\"%s.%d\"%(self.baseFilename,i))\n dfn=self.rotation_filename(\"%s.%d\"%(self.baseFilename,\n i+1))\n if os.path.exists(sfn):\n if os.path.exists(dfn):\n os.remove(dfn)\n os.rename(sfn,dfn)\n dfn=self.rotation_filename(self.baseFilename+\".1\")\n if os.path.exists(dfn):\n os.remove(dfn)\n self.rotate(self.baseFilename,dfn)\n if not self.delay:\n self.stream=self._open()\n \n def shouldRollover(self,record):\n ''\n\n\n\n\n \n \n if os.path.exists(self.baseFilename)and not os.path.isfile(self.baseFilename):\n return False\n if self.stream is None:\n self.stream=self._open()\n if self.maxBytes >0:\n msg=\"%s\\n\"%self.format(record)\n self.stream.seek(0,2)\n if self.stream.tell()+len(msg)>=self.maxBytes:\n return True\n return False\n \nclass TimedRotatingFileHandler(BaseRotatingHandler):\n ''\n\n\n\n\n\n \n def __init__(self,filename,when='h',interval=1,backupCount=0,\n encoding=None,delay=False,utc=False,atTime=None,\n errors=None):\n encoding=io.text_encoding(encoding)\n BaseRotatingHandler.__init__(self,filename,'a',encoding=encoding,\n delay=delay,errors=errors)\n self.when=when.upper()\n self.backupCount=backupCount\n self.utc=utc\n self.atTime=atTime\n \n \n \n \n \n \n \n \n \n \n \n \n if self.when =='S':\n self.interval=1\n self.suffix=\"%Y-%m-%d_%H-%M-%S\"\n extMatch=r\"(?'6':\n raise ValueError(\"Invalid day specified for weekly rollover: %s\"%self.when)\n self.dayOfWeek=int(self.when[1])\n self.suffix=\"%Y-%m-%d\"\n extMatch=r\"(?=self.rolloverAt:\n \n if os.path.exists(self.baseFilename)and not os.path.isfile(self.baseFilename):\n \n \n self.rolloverAt=self.computeRollover(t)\n return False\n \n return True\n return False\n \n def getFilesToDelete(self):\n ''\n\n\n\n \n dirName,baseName=os.path.split(self.baseFilename)\n fileNames=os.listdir(dirName)\n result=[]\n if self.namer is None:\n prefix=baseName+'.'\n plen=len(prefix)\n for fileName in fileNames:\n if fileName[:plen]==prefix:\n suffix=fileName[plen:]\n if self.extMatch.fullmatch(suffix):\n result.append(os.path.join(dirName,fileName))\n else:\n for fileName in fileNames:\n \n \n \n \n m=self.extMatch.search(fileName)\n while m:\n dfn=self.namer(self.baseFilename+\".\"+m[0])\n if os.path.basename(dfn)==fileName:\n result.append(os.path.join(dirName,fileName))\n break\n m=self.extMatch.search(fileName,m.start()+1)\n \n if len(result)0:\n for s in self.getFilesToDelete():\n os.remove(s)\n if not self.delay:\n self.stream=self._open()\n self.rolloverAt=self.computeRollover(currentTime)\n \nclass WatchedFileHandler(logging.FileHandler):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,filename,mode='a',encoding=None,delay=False,\n errors=None):\n if \"b\"not in mode:\n encoding=io.text_encoding(encoding)\n logging.FileHandler.__init__(self,filename,mode=mode,\n encoding=encoding,delay=delay,\n errors=errors)\n self.dev,self.ino=-1,-1\n self._statstream()\n \n def _statstream(self):\n if self.stream is None:\n return\n sres=os.fstat(self.stream.fileno())\n self.dev=sres.st_dev\n self.ino=sres.st_ino\n \n def reopenIfNeeded(self):\n ''\n\n\n\n\n\n \n if self.stream is None:\n return\n \n \n \n \n \n try:\n \n sres=os.stat(self.baseFilename)\n \n \n reopen=(sres.st_dev !=self.dev or sres.st_ino !=self.ino)\n except FileNotFoundError:\n reopen=True\n \n if not reopen:\n return\n \n \n self.stream.flush()\n self.stream.close()\n self.stream=None\n \n \n self.stream=self._open()\n self._statstream()\n \n def emit(self,record):\n ''\n\n\n\n\n \n self.reopenIfNeeded()\n logging.FileHandler.emit(self,record)\n \n \nclass SocketHandler(logging.Handler):\n ''\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,host,port):\n ''\n\n\n\n\n\n \n logging.Handler.__init__(self)\n self.host=host\n self.port=port\n if port is None:\n self.address=host\n else:\n self.address=(host,port)\n self.sock=None\n self.closeOnError=False\n self.retryTime=None\n \n \n \n self.retryStart=1.0\n self.retryMax=30.0\n self.retryFactor=2.0\n \n def makeSocket(self,timeout=1):\n ''\n\n\n \n if self.port is not None:\n result=socket.create_connection(self.address,timeout=timeout)\n else:\n result=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)\n result.settimeout(timeout)\n try:\n result.connect(self.address)\n except OSError:\n result.close()\n raise\n return result\n \n def createSocket(self):\n ''\n\n\n\n \n now=time.time()\n \n \n \n if self.retryTime is None:\n attempt=True\n else:\n attempt=(now >=self.retryTime)\n if attempt:\n try:\n self.sock=self.makeSocket()\n self.retryTime=None\n except OSError:\n \n if self.retryTime is None:\n self.retryPeriod=self.retryStart\n else:\n self.retryPeriod=self.retryPeriod *self.retryFactor\n if self.retryPeriod >self.retryMax:\n self.retryPeriod=self.retryMax\n self.retryTime=now+self.retryPeriod\n \n def send(self,s):\n ''\n\n\n\n\n \n if self.sock is None:\n self.createSocket()\n \n \n \n if self.sock:\n try:\n self.sock.sendall(s)\n except OSError:\n self.sock.close()\n self.sock=None\n \n def makePickle(self,record):\n ''\n\n\n \n ei=record.exc_info\n if ei:\n \n dummy=self.format(record)\n \n \n \n d=dict(record.__dict__)\n d['msg']=record.getMessage()\n d['args']=None\n d['exc_info']=None\n \n d.pop('message',None)\n s=pickle.dumps(d,1)\n slen=struct.pack(\">L\",len(s))\n return slen+s\n \n def handleError(self,record):\n ''\n\n\n\n\n\n \n if self.closeOnError and self.sock:\n self.sock.close()\n self.sock=None\n else:\n logging.Handler.handleError(self,record)\n \n def emit(self,record):\n ''\n\n\n\n\n\n\n \n try:\n s=self.makePickle(record)\n self.send(s)\n except Exception:\n self.handleError(record)\n \n def close(self):\n ''\n\n \n with self.lock:\n sock=self.sock\n if sock:\n self.sock=None\n sock.close()\n logging.Handler.close(self)\n \nclass DatagramHandler(SocketHandler):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,host,port):\n ''\n\n \n SocketHandler.__init__(self,host,port)\n self.closeOnError=False\n \n def makeSocket(self):\n ''\n\n\n \n if self.port is None:\n family=socket.AF_UNIX\n else:\n family=socket.AF_INET\n s=socket.socket(family,socket.SOCK_DGRAM)\n return s\n \n def send(self,s):\n ''\n\n\n\n\n\n \n if self.sock is None:\n self.createSocket()\n self.sock.sendto(s,self.address)\n \nclass SysLogHandler(logging.Handler):\n ''\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n LOG_EMERG=0\n LOG_ALERT=1\n LOG_CRIT=2\n LOG_ERR=3\n LOG_WARNING=4\n LOG_NOTICE=5\n LOG_INFO=6\n LOG_DEBUG=7\n \n \n LOG_KERN=0\n LOG_USER=1\n LOG_MAIL=2\n LOG_DAEMON=3\n LOG_AUTH=4\n LOG_SYSLOG=5\n LOG_LPR=6\n LOG_NEWS=7\n LOG_UUCP=8\n LOG_CRON=9\n LOG_AUTHPRIV=10\n LOG_FTP=11\n LOG_NTP=12\n LOG_SECURITY=13\n LOG_CONSOLE=14\n LOG_SOLCRON=15\n \n \n LOG_LOCAL0=16\n LOG_LOCAL1=17\n LOG_LOCAL2=18\n LOG_LOCAL3=19\n LOG_LOCAL4=20\n LOG_LOCAL5=21\n LOG_LOCAL6=22\n LOG_LOCAL7=23\n \n priority_names={\n \"alert\":LOG_ALERT,\n \"crit\":LOG_CRIT,\n \"critical\":LOG_CRIT,\n \"debug\":LOG_DEBUG,\n \"emerg\":LOG_EMERG,\n \"err\":LOG_ERR,\n \"error\":LOG_ERR,\n \"info\":LOG_INFO,\n \"notice\":LOG_NOTICE,\n \"panic\":LOG_EMERG,\n \"warn\":LOG_WARNING,\n \"warning\":LOG_WARNING,\n }\n \n facility_names={\n \"auth\":LOG_AUTH,\n \"authpriv\":LOG_AUTHPRIV,\n \"console\":LOG_CONSOLE,\n \"cron\":LOG_CRON,\n \"daemon\":LOG_DAEMON,\n \"ftp\":LOG_FTP,\n \"kern\":LOG_KERN,\n \"lpr\":LOG_LPR,\n \"mail\":LOG_MAIL,\n \"news\":LOG_NEWS,\n \"ntp\":LOG_NTP,\n \"security\":LOG_SECURITY,\n \"solaris-cron\":LOG_SOLCRON,\n \"syslog\":LOG_SYSLOG,\n \"user\":LOG_USER,\n \"uucp\":LOG_UUCP,\n \"local0\":LOG_LOCAL0,\n \"local1\":LOG_LOCAL1,\n \"local2\":LOG_LOCAL2,\n \"local3\":LOG_LOCAL3,\n \"local4\":LOG_LOCAL4,\n \"local5\":LOG_LOCAL5,\n \"local6\":LOG_LOCAL6,\n \"local7\":LOG_LOCAL7,\n }\n \n \n \n priority_map={\n \"DEBUG\":\"debug\",\n \"INFO\":\"info\",\n \"WARNING\":\"warning\",\n \"ERROR\":\"error\",\n \"CRITICAL\":\"critical\"\n }\n \n def __init__(self,address=('localhost',SYSLOG_UDP_PORT),\n facility=LOG_USER,socktype=None):\n ''\n\n\n\n\n\n\n\n\n\n \n logging.Handler.__init__(self)\n \n self.address=address\n self.facility=facility\n self.socktype=socktype\n self.socket=None\n self.createSocket()\n \n def _connect_unixsocket(self,address):\n use_socktype=self.socktype\n if use_socktype is None:\n use_socktype=socket.SOCK_DGRAM\n self.socket=socket.socket(socket.AF_UNIX,use_socktype)\n try:\n self.socket.connect(address)\n \n self.socktype=use_socktype\n except OSError:\n self.socket.close()\n if self.socktype is not None:\n \n raise\n use_socktype=socket.SOCK_STREAM\n self.socket=socket.socket(socket.AF_UNIX,use_socktype)\n try:\n self.socket.connect(address)\n \n self.socktype=use_socktype\n except OSError:\n self.socket.close()\n raise\n \n def createSocket(self):\n ''\n\n\n\n\n\n \n address=self.address\n socktype=self.socktype\n \n if isinstance(address,str):\n self.unixsocket=True\n \n \n \n \n try:\n self._connect_unixsocket(address)\n except OSError:\n pass\n else:\n self.unixsocket=False\n if socktype is None:\n socktype=socket.SOCK_DGRAM\n host,port=address\n ress=socket.getaddrinfo(host,port,0,socktype)\n if not ress:\n raise OSError(\"getaddrinfo returns an empty list\")\n for res in ress:\n af,socktype,proto,_,sa=res\n err=sock=None\n try:\n sock=socket.socket(af,socktype,proto)\n if socktype ==socket.SOCK_STREAM:\n sock.connect(sa)\n break\n except OSError as exc:\n err=exc\n if sock is not None:\n sock.close()\n if err is not None:\n raise err\n self.socket=sock\n self.socktype=socktype\n \n def encodePriority(self,facility,priority):\n ''\n\n\n\n\n \n if isinstance(facility,str):\n facility=self.facility_names[facility]\n if isinstance(priority,str):\n priority=self.priority_names[priority]\n return(facility <<3)|priority\n \n def close(self):\n ''\n\n \n with self.lock:\n sock=self.socket\n if sock:\n self.socket=None\n sock.close()\n logging.Handler.close(self)\n \n def mapPriority(self,levelName):\n ''\n\n\n\n\n\n \n return self.priority_map.get(levelName,\"warning\")\n \n ident=''\n append_nul=True\n \n def emit(self,record):\n ''\n\n\n\n\n \n try:\n msg=self.format(record)\n if self.ident:\n msg=self.ident+msg\n if self.append_nul:\n msg +='\\000'\n \n \n \n prio='<%d>'%self.encodePriority(self.facility,\n self.mapPriority(record.levelname))\n prio=prio.encode('utf-8')\n \n msg=msg.encode('utf-8')\n msg=prio+msg\n \n if not self.socket:\n self.createSocket()\n \n if self.unixsocket:\n try:\n self.socket.send(msg)\n except OSError:\n self.socket.close()\n self._connect_unixsocket(self.address)\n self.socket.send(msg)\n elif self.socktype ==socket.SOCK_DGRAM:\n self.socket.sendto(msg,self.address)\n else:\n self.socket.sendall(msg)\n except Exception:\n self.handleError(record)\n \nclass SMTPHandler(logging.Handler):\n ''\n\n \n def __init__(self,mailhost,fromaddr,toaddrs,subject,\n credentials=None,secure=None,timeout=5.0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n logging.Handler.__init__(self)\n if isinstance(mailhost,(list,tuple)):\n self.mailhost,self.mailport=mailhost\n else:\n self.mailhost,self.mailport=mailhost,None\n if isinstance(credentials,(list,tuple)):\n self.username,self.password=credentials\n else:\n self.username=None\n self.fromaddr=fromaddr\n if isinstance(toaddrs,str):\n toaddrs=[toaddrs]\n self.toaddrs=toaddrs\n self.subject=subject\n self.secure=secure\n self.timeout=timeout\n \n def getSubject(self,record):\n ''\n\n\n\n\n \n return self.subject\n \n def emit(self,record):\n ''\n\n\n\n \n try:\n import smtplib\n from email.message import EmailMessage\n import email.utils\n \n port=self.mailport\n if not port:\n port=smtplib.SMTP_PORT\n smtp=smtplib.SMTP(self.mailhost,port,timeout=self.timeout)\n msg=EmailMessage()\n msg['From']=self.fromaddr\n msg['To']=','.join(self.toaddrs)\n msg['Subject']=self.getSubject(record)\n msg['Date']=email.utils.localtime()\n msg.set_content(self.format(record))\n if self.username:\n if self.secure is not None:\n smtp.ehlo()\n smtp.starttls(*self.secure)\n smtp.ehlo()\n smtp.login(self.username,self.password)\n smtp.send_message(msg)\n smtp.quit()\n except Exception:\n self.handleError(record)\n \nclass NTEventLogHandler(logging.Handler):\n ''\n\n\n\n\n\n\n\n \n def __init__(self,appname,dllname=None,logtype=\"Application\"):\n logging.Handler.__init__(self)\n try:\n import win32evtlogutil,win32evtlog\n self.appname=appname\n self._welu=win32evtlogutil\n if not dllname:\n dllname=os.path.split(self._welu.__file__)\n dllname=os.path.split(dllname[0])\n dllname=os.path.join(dllname[0],r'win32service.pyd')\n self.dllname=dllname\n self.logtype=logtype\n \n \n \n try:\n self._welu.AddSourceToRegistry(appname,dllname,logtype)\n except Exception as e:\n \n \n if getattr(e,'winerror',None)!=5:\n raise\n self.deftype=win32evtlog.EVENTLOG_ERROR_TYPE\n self.typemap={\n logging.DEBUG:win32evtlog.EVENTLOG_INFORMATION_TYPE,\n logging.INFO:win32evtlog.EVENTLOG_INFORMATION_TYPE,\n logging.WARNING:win32evtlog.EVENTLOG_WARNING_TYPE,\n logging.ERROR:win32evtlog.EVENTLOG_ERROR_TYPE,\n logging.CRITICAL:win32evtlog.EVENTLOG_ERROR_TYPE,\n }\n except ImportError:\n print(\"The Python Win32 extensions for NT (service, event \"\\\n \"logging) appear not to be available.\")\n self._welu=None\n \n def getMessageID(self,record):\n ''\n\n\n\n\n\n \n return 1\n \n def getEventCategory(self,record):\n ''\n\n\n\n\n \n return 0\n \n def getEventType(self,record):\n ''\n\n\n\n\n\n\n\n\n \n return self.typemap.get(record.levelno,self.deftype)\n \n def emit(self,record):\n ''\n\n\n\n\n \n if self._welu:\n try:\n id=self.getMessageID(record)\n cat=self.getEventCategory(record)\n type=self.getEventType(record)\n msg=self.format(record)\n self._welu.ReportEvent(self.appname,id,cat,type,[msg])\n except Exception:\n self.handleError(record)\n \n def close(self):\n ''\n\n\n\n\n\n\n\n \n \n logging.Handler.close(self)\n \nclass HTTPHandler(logging.Handler):\n ''\n\n\n \n def __init__(self,host,url,method=\"GET\",secure=False,credentials=None,\n context=None):\n ''\n\n\n \n logging.Handler.__init__(self)\n method=method.upper()\n if method not in[\"GET\",\"POST\"]:\n raise ValueError(\"method must be GET or POST\")\n if not secure and context is not None:\n raise ValueError(\"context parameter only makes sense \"\n \"with secure=True\")\n self.host=host\n self.url=url\n self.method=method\n self.secure=secure\n self.credentials=credentials\n self.context=context\n \n def mapLogRecord(self,record):\n ''\n\n\n\n \n return record.__dict__\n \n def getConnection(self,host,secure):\n ''\n\n\n\n\n \n import http.client\n if secure:\n connection=http.client.HTTPSConnection(host,context=self.context)\n else:\n connection=http.client.HTTPConnection(host)\n return connection\n \n def emit(self,record):\n ''\n\n\n\n \n try:\n import urllib.parse\n host=self.host\n h=self.getConnection(host,self.secure)\n url=self.url\n data=urllib.parse.urlencode(self.mapLogRecord(record))\n if self.method ==\"GET\":\n if(url.find('?')>=0):\n sep='&'\n else:\n sep='?'\n url=url+\"%c%s\"%(sep,data)\n h.putrequest(self.method,url)\n \n \n i=host.find(\":\")\n if i >=0:\n host=host[:i]\n \n \n \n if self.method ==\"POST\":\n h.putheader(\"Content-type\",\n \"application/x-www-form-urlencoded\")\n h.putheader(\"Content-length\",str(len(data)))\n if self.credentials:\n import base64\n s=('%s:%s'%self.credentials).encode('utf-8')\n s='Basic '+base64.b64encode(s).strip().decode('ascii')\n h.putheader('Authorization',s)\n h.endheaders()\n if self.method ==\"POST\":\n h.send(data.encode('utf-8'))\n h.getresponse()\n except Exception:\n self.handleError(record)\n \nclass BufferingHandler(logging.Handler):\n ''\n\n\n\n \n def __init__(self,capacity):\n ''\n\n \n logging.Handler.__init__(self)\n self.capacity=capacity\n self.buffer=[]\n \n def shouldFlush(self,record):\n ''\n\n\n\n\n \n return(len(self.buffer)>=self.capacity)\n \n def emit(self,record):\n ''\n\n\n\n\n \n self.buffer.append(record)\n if self.shouldFlush(record):\n self.flush()\n \n def flush(self):\n ''\n\n\n\n \n with self.lock:\n self.buffer.clear()\n \n def close(self):\n ''\n\n\n\n \n try:\n self.flush()\n finally:\n logging.Handler.close(self)\n \nclass MemoryHandler(BufferingHandler):\n ''\n\n\n\n \n def __init__(self,capacity,flushLevel=logging.ERROR,target=None,\n flushOnClose=True):\n ''\n\n\n\n\n\n\n\n\n\n\n \n BufferingHandler.__init__(self,capacity)\n self.flushLevel=flushLevel\n self.target=target\n \n self.flushOnClose=flushOnClose\n \n def shouldFlush(self,record):\n ''\n\n \n return(len(self.buffer)>=self.capacity)or\\\n (record.levelno >=self.flushLevel)\n \n def setTarget(self,target):\n ''\n\n \n with self.lock:\n self.target=target\n \n def flush(self):\n ''\n\n\n\n\n\n \n with self.lock:\n if self.target:\n for record in self.buffer:\n self.target.handle(record)\n self.buffer.clear()\n \n def close(self):\n ''\n\n\n \n try:\n if self.flushOnClose:\n self.flush()\n finally:\n with self.lock:\n self.target=None\n BufferingHandler.close(self)\n \n \nclass QueueHandler(logging.Handler):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,queue):\n ''\n\n \n logging.Handler.__init__(self)\n self.queue=queue\n self.listener=None\n \n def enqueue(self,record):\n ''\n\n\n\n\n\n \n self.queue.put_nowait(record)\n \n def prepare(self,record):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n msg=self.format(record)\n \n record=copy.copy(record)\n record.message=msg\n record.msg=msg\n record.args=None\n record.exc_info=None\n record.exc_text=None\n record.stack_info=None\n return record\n \n def emit(self,record):\n ''\n\n\n\n \n try:\n self.enqueue(self.prepare(record))\n except Exception:\n self.handleError(record)\n \n \nclass QueueListener(object):\n ''\n\n\n\n \n _sentinel=None\n \n def __init__(self,queue,*handlers,respect_handler_level=False):\n ''\n\n\n \n self.queue=queue\n self.handlers=handlers\n self._thread=None\n self.respect_handler_level=respect_handler_level\n \n def dequeue(self,block):\n ''\n\n\n\n\n \n return self.queue.get(block)\n \n def start(self):\n ''\n\n\n\n\n \n self._thread=t=threading.Thread(target=self._monitor)\n t.daemon=True\n t.start()\n \n def prepare(self,record):\n ''\n\n\n\n\n\n \n return record\n \n def handle(self,record):\n ''\n\n\n\n\n \n record=self.prepare(record)\n for handler in self.handlers:\n if not self.respect_handler_level:\n process=True\n else:\n process=record.levelno >=handler.level\n if process:\n handler.handle(record)\n \n def _monitor(self):\n ''\n\n\n\n\n\n \n q=self.queue\n has_task_done=hasattr(q,'task_done')\n while True:\n try:\n record=self.dequeue(True)\n if record is self._sentinel:\n if has_task_done:\n q.task_done()\n break\n self.handle(record)\n if has_task_done:\n q.task_done()\n except queue.Empty:\n break\n \n def enqueue_sentinel(self):\n ''\n\n\n\n\n\n \n self.queue.put_nowait(self._sentinel)\n \n def stop(self):\n ''\n\n\n\n\n\n \n if self._thread:\n self.enqueue_sentinel()\n self._thread.join()\n self._thread=None\n", ["base64", "copy", "email.message", "email.utils", "http.client", "io", "logging", "os", "pickle", "queue", "re", "smtplib", "socket", "struct", "threading", "time", "urllib.parse", "win32evtlog", "win32evtlogutil"]], "logging": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\"\nLogging package for Python. Based on PEP 282 and comments thereto in\ncomp.lang.python.\n\nCopyright (C) 2001-2022 Vinay Sajip. All Rights Reserved.\n\nTo use, simply 'import logging' and log away!\n\"\"\"\n\nimport sys,os,time,io,re,traceback,warnings,weakref,collections.abc\n\nfrom types import GenericAlias\nfrom string import Template\nfrom string import Formatter as StrFormatter\n\n\n__all__=['BASIC_FORMAT','BufferingFormatter','CRITICAL','DEBUG','ERROR',\n'FATAL','FileHandler','Filter','Formatter','Handler','INFO',\n'LogRecord','Logger','LoggerAdapter','NOTSET','NullHandler',\n'StreamHandler','WARN','WARNING','addLevelName','basicConfig',\n'captureWarnings','critical','debug','disable','error',\n'exception','fatal','getLevelName','getLogger','getLoggerClass',\n'info','log','makeLogRecord','setLoggerClass','shutdown',\n'warning','getLogRecordFactory','setLogRecordFactory',\n'lastResort','raiseExceptions','getLevelNamesMapping',\n'getHandlerByName','getHandlerNames']\n\nimport threading\n\n__author__=\"Vinay Sajip \"\n__status__=\"production\"\n\n__version__=\"0.5.1.2\"\n__date__=\"07 February 2010\"\n\n\n\n\n\n\n\n\n_startTime=time.time_ns()\n\n\n\n\n\nraiseExceptions=True\n\n\n\n\nlogThreads=True\n\n\n\n\nlogMultiprocessing=True\n\n\n\n\nlogProcesses=True\n\n\n\n\nlogAsyncioTasks=True\n\n\n\n\n\n\n\n\n\n\n\n\nCRITICAL=50\nFATAL=CRITICAL\nERROR=40\nWARNING=30\nWARN=WARNING\nINFO=20\nDEBUG=10\nNOTSET=0\n\n_levelToName={\nCRITICAL:'CRITICAL',\nERROR:'ERROR',\nWARNING:'WARNING',\nINFO:'INFO',\nDEBUG:'DEBUG',\nNOTSET:'NOTSET',\n}\n_nameToLevel={\n'CRITICAL':CRITICAL,\n'FATAL':FATAL,\n'ERROR':ERROR,\n'WARN':WARNING,\n'WARNING':WARNING,\n'INFO':INFO,\n'DEBUG':DEBUG,\n'NOTSET':NOTSET,\n}\n\ndef getLevelNamesMapping():\n return _nameToLevel.copy()\n \ndef getLevelName(level):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n result=_levelToName.get(level)\n if result is not None:\n return result\n result=_nameToLevel.get(level)\n if result is not None:\n return result\n return \"Level %s\"%level\n \ndef addLevelName(level,levelName):\n ''\n\n\n\n \n with _lock:\n _levelToName[level]=levelName\n _nameToLevel[levelName]=level\n \nif hasattr(sys,\"_getframe\"):\n currentframe=lambda:sys._getframe(1)\nelse:\n def currentframe():\n ''\n try:\n raise Exception\n except Exception as exc:\n return exc.__traceback__.tb_frame.f_back\n \n \n \n \n \n \n \n \n \n \n \n \n \n_srcfile=os.path.normcase(addLevelName.__code__.co_filename)\n\n\n\n\n\n\n\n\ndef _is_internal_frame(frame):\n ''\n filename=os.path.normcase(frame.f_code.co_filename)\n return filename ==_srcfile or(\n \"importlib\"in filename and \"_bootstrap\"in filename\n )\n \n \ndef _checkLevel(level):\n if isinstance(level,int):\n rv=level\n elif str(level)==level:\n if level not in _nameToLevel:\n raise ValueError(\"Unknown level: %r\"%level)\n rv=_nameToLevel[level]\n else:\n raise TypeError(\"Level not an integer or a valid string: %r\"\n %(level,))\n return rv\n \n \n \n \n \n \n \n \n \n \n \n \n \n_lock=threading.RLock()\n\ndef _prepareFork():\n ''\n\n\n\n \n \n \n try:\n _lock.acquire()\n except BaseException:\n _lock.release()\n raise\n \ndef _afterFork():\n ''\n\n\n\n \n _lock.release()\n \n \n \n \nif not hasattr(os,'register_at_fork'):\n def _register_at_fork_reinit_lock(instance):\n pass\nelse:\n\n\n\n _at_fork_reinit_lock_weakset=weakref.WeakSet()\n \n def _register_at_fork_reinit_lock(instance):\n with _lock:\n _at_fork_reinit_lock_weakset.add(instance)\n \n def _after_at_fork_child_reinit_locks():\n for handler in _at_fork_reinit_lock_weakset:\n handler._at_fork_reinit()\n \n \n \n _lock._at_fork_reinit()\n \n os.register_at_fork(before=_prepareFork,\n after_in_child=_after_at_fork_child_reinit_locks,\n after_in_parent=_afterFork)\n \n \n \n \n \n \nclass LogRecord(object):\n ''\n\n\n\n\n\n\n\n\n\n \n def __init__(self,name,level,pathname,lineno,\n msg,args,exc_info,func=None,sinfo=None,**kwargs):\n ''\n\n \n ct=time.time_ns()\n self.name=name\n self.msg=msg\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if(args and len(args)==1 and isinstance(args[0],collections.abc.Mapping)\n and args[0]):\n args=args[0]\n self.args=args\n self.levelname=getLevelName(level)\n self.levelno=level\n self.pathname=pathname\n try:\n self.filename=os.path.basename(pathname)\n self.module=os.path.splitext(self.filename)[0]\n except(TypeError,ValueError,AttributeError):\n self.filename=pathname\n self.module=\"Unknown module\"\n self.exc_info=exc_info\n self.exc_text=None\n self.stack_info=sinfo\n self.lineno=lineno\n self.funcName=func\n self.created=ct /1e9\n \n \n \n \n self.msecs=(ct %1_000_000_000)//1_000_000+0.0\n \n self.relativeCreated=(ct -_startTime)/1e6\n if logThreads:\n self.thread=threading.get_ident()\n self.threadName=threading.current_thread().name\n else:\n self.thread=None\n self.threadName=None\n if not logMultiprocessing:\n self.processName=None\n else:\n self.processName='MainProcess'\n mp=sys.modules.get('multiprocessing')\n if mp is not None:\n \n \n \n \n try:\n self.processName=mp.current_process().name\n except Exception:\n pass\n if logProcesses and hasattr(os,'getpid'):\n self.process=os.getpid()\n else:\n self.process=None\n \n self.taskName=None\n if logAsyncioTasks:\n asyncio=sys.modules.get('asyncio')\n if asyncio:\n try:\n self.taskName=asyncio.current_task().get_name()\n except Exception:\n pass\n \n def __repr__(self):\n return ''%(self.name,self.levelno,\n self.pathname,self.lineno,self.msg)\n \n def getMessage(self):\n ''\n\n\n\n\n \n msg=str(self.msg)\n if self.args:\n msg=msg %self.args\n return msg\n \n \n \n \n_logRecordFactory=LogRecord\n\ndef setLogRecordFactory(factory):\n ''\n\n\n\n\n \n global _logRecordFactory\n _logRecordFactory=factory\n \ndef getLogRecordFactory():\n ''\n\n \n \n return _logRecordFactory\n \ndef makeLogRecord(dict):\n ''\n\n\n\n\n \n rv=_logRecordFactory(None,None,\"\",0,\"\",(),None,None)\n rv.__dict__.update(dict)\n return rv\n \n \n \n \n \n_str_formatter=StrFormatter()\ndel StrFormatter\n\n\nclass PercentStyle(object):\n\n default_format='%(message)s'\n asctime_format='%(asctime)s'\n asctime_search='%(asctime)'\n validation_pattern=re.compile(r'%\\(\\w+\\)[#0+ -]*(\\*|\\d+)?(\\.(\\*|\\d+))?[diouxefgcrsa%]',re.I)\n \n def __init__(self,fmt,*,defaults=None):\n self._fmt=fmt or self.default_format\n self._defaults=defaults\n \n def usesTime(self):\n return self._fmt.find(self.asctime_search)>=0\n \n def validate(self):\n ''\n if not self.validation_pattern.search(self._fmt):\n raise ValueError(\"Invalid format '%s' for '%s' style\"%(self._fmt,self.default_format[0]))\n \n def _format(self,record):\n if defaults :=self._defaults:\n values=defaults |record.__dict__\n else:\n values=record.__dict__\n return self._fmt %values\n \n def format(self,record):\n try:\n return self._format(record)\n except KeyError as e:\n raise ValueError('Formatting field not found in record: %s'%e)\n \n \nclass StrFormatStyle(PercentStyle):\n default_format='{message}'\n asctime_format='{asctime}'\n asctime_search='{asctime'\n \n fmt_spec=re.compile(r'^(.?[<>=^])?[+ -]?#?0?(\\d+|{\\w+})?[,_]?(\\.(\\d+|{\\w+}))?[bcdefgnosx%]?$',re.I)\n field_spec=re.compile(r'^(\\d+|\\w+)(\\.\\w+|\\[[^]]+\\])*$')\n \n def _format(self,record):\n if defaults :=self._defaults:\n values=defaults |record.__dict__\n else:\n values=record.__dict__\n return self._fmt.format(**values)\n \n def validate(self):\n ''\n fields=set()\n try:\n for _,fieldname,spec,conversion in _str_formatter.parse(self._fmt):\n if fieldname:\n if not self.field_spec.match(fieldname):\n raise ValueError('invalid field name/expression: %r'%fieldname)\n fields.add(fieldname)\n if conversion and conversion not in 'rsa':\n raise ValueError('invalid conversion: %r'%conversion)\n if spec and not self.fmt_spec.match(spec):\n raise ValueError('bad specifier: %r'%spec)\n except ValueError as e:\n raise ValueError('invalid format: %s'%e)\n if not fields:\n raise ValueError('invalid format: no fields')\n \n \nclass StringTemplateStyle(PercentStyle):\n default_format='${message}'\n asctime_format='${asctime}'\n asctime_search='${asctime}'\n \n def __init__(self,*args,**kwargs):\n super().__init__(*args,**kwargs)\n self._tpl=Template(self._fmt)\n \n def usesTime(self):\n fmt=self._fmt\n return fmt.find('$asctime')>=0 or fmt.find(self.asctime_search)>=0\n \n def validate(self):\n pattern=Template.pattern\n fields=set()\n for m in pattern.finditer(self._fmt):\n d=m.groupdict()\n if d['named']:\n fields.add(d['named'])\n elif d['braced']:\n fields.add(d['braced'])\n elif m.group(0)=='$':\n raise ValueError('invalid format: bare \\'$\\' not allowed')\n if not fields:\n raise ValueError('invalid format: no fields')\n \n def _format(self,record):\n if defaults :=self._defaults:\n values=defaults |record.__dict__\n else:\n values=record.__dict__\n return self._tpl.substitute(**values)\n \n \nBASIC_FORMAT=\"%(levelname)s:%(name)s:%(message)s\"\n\n_STYLES={\n'%':(PercentStyle,BASIC_FORMAT),\n'{':(StrFormatStyle,'{levelname}:{name}:{message}'),\n'$':(StringTemplateStyle,'${levelname}:${name}:${message}'),\n}\n\nclass Formatter(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n converter=time.localtime\n \n def __init__(self,fmt=None,datefmt=None,style='%',validate=True,*,\n defaults=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if style not in _STYLES:\n raise ValueError('Style must be one of: %s'%','.join(\n _STYLES.keys()))\n self._style=_STYLES[style][0](fmt,defaults=defaults)\n if validate:\n self._style.validate()\n \n self._fmt=self._style._fmt\n self.datefmt=datefmt\n \n default_time_format='%Y-%m-%d %H:%M:%S'\n default_msec_format='%s,%03d'\n \n def formatTime(self,record,datefmt=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n ct=self.converter(record.created)\n if datefmt:\n s=time.strftime(datefmt,ct)\n else:\n s=time.strftime(self.default_time_format,ct)\n if self.default_msec_format:\n s=self.default_msec_format %(s,record.msecs)\n return s\n \n def formatException(self,ei):\n ''\n\n\n\n\n \n sio=io.StringIO()\n tb=ei[2]\n \n \n \n traceback.print_exception(ei[0],ei[1],tb,limit=None,file=sio)\n s=sio.getvalue()\n sio.close()\n if s[-1:]==\"\\n\":\n s=s[:-1]\n return s\n \n def usesTime(self):\n ''\n\n \n return self._style.usesTime()\n \n def formatMessage(self,record):\n return self._style.format(record)\n \n def formatStack(self,stack_info):\n ''\n\n\n\n\n\n\n\n\n \n return stack_info\n \n def format(self,record):\n ''\n\n\n\n\n\n\n\n\n\n\n \n record.message=record.getMessage()\n if self.usesTime():\n record.asctime=self.formatTime(record,self.datefmt)\n s=self.formatMessage(record)\n if record.exc_info:\n \n \n if not record.exc_text:\n record.exc_text=self.formatException(record.exc_info)\n if record.exc_text:\n if s[-1:]!=\"\\n\":\n s=s+\"\\n\"\n s=s+record.exc_text\n if record.stack_info:\n if s[-1:]!=\"\\n\":\n s=s+\"\\n\"\n s=s+self.formatStack(record.stack_info)\n return s\n \n \n \n \n_defaultFormatter=Formatter()\n\nclass BufferingFormatter(object):\n ''\n\n \n def __init__(self,linefmt=None):\n ''\n\n\n \n if linefmt:\n self.linefmt=linefmt\n else:\n self.linefmt=_defaultFormatter\n \n def formatHeader(self,records):\n ''\n\n \n return \"\"\n \n def formatFooter(self,records):\n ''\n\n \n return \"\"\n \n def format(self,records):\n ''\n\n \n rv=\"\"\n if len(records)>0:\n rv=rv+self.formatHeader(records)\n for record in records:\n rv=rv+self.linefmt.format(record)\n rv=rv+self.formatFooter(records)\n return rv\n \n \n \n \n \nclass Filter(object):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,name=''):\n ''\n\n\n\n\n\n \n self.name=name\n self.nlen=len(name)\n \n def filter(self,record):\n ''\n\n\n\n\n \n if self.nlen ==0:\n return True\n elif self.name ==record.name:\n return True\n elif record.name.find(self.name,0,self.nlen)!=0:\n return False\n return(record.name[self.nlen]==\".\")\n \nclass Filterer(object):\n ''\n\n\n \n def __init__(self):\n ''\n\n \n self.filters=[]\n \n def addFilter(self,filter):\n ''\n\n \n if not(filter in self.filters):\n self.filters.append(filter)\n \n def removeFilter(self,filter):\n ''\n\n \n if filter in self.filters:\n self.filters.remove(filter)\n \n def filter(self,record):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n for f in self.filters:\n if hasattr(f,'filter'):\n result=f.filter(record)\n else:\n result=f(record)\n if not result:\n return False\n if isinstance(result,LogRecord):\n record=result\n return record\n \n \n \n \n \n_handlers=weakref.WeakValueDictionary()\n_handlerList=[]\n\ndef _removeHandlerRef(wr):\n ''\n\n \n \n \n \n \n handlers,lock=_handlerList,_lock\n if lock and handlers:\n with lock:\n try:\n handlers.remove(wr)\n except ValueError:\n pass\n \ndef _addHandlerRef(handler):\n ''\n\n \n with _lock:\n _handlerList.append(weakref.ref(handler,_removeHandlerRef))\n \n \ndef getHandlerByName(name):\n ''\n\n\n \n return _handlers.get(name)\n \n \ndef getHandlerNames():\n ''\n\n \n return frozenset(_handlers)\n \n \nclass Handler(Filterer):\n ''\n\n\n\n\n\n\n \n def __init__(self,level=NOTSET):\n ''\n\n\n \n Filterer.__init__(self)\n self._name=None\n self.level=_checkLevel(level)\n self.formatter=None\n self._closed=False\n \n _addHandlerRef(self)\n self.createLock()\n \n def get_name(self):\n return self._name\n \n def set_name(self,name):\n with _lock:\n if self._name in _handlers:\n del _handlers[self._name]\n self._name=name\n if name:\n _handlers[name]=self\n \n name=property(get_name,set_name)\n \n def createLock(self):\n ''\n\n \n self.lock=threading.RLock()\n _register_at_fork_reinit_lock(self)\n \n def _at_fork_reinit(self):\n self.lock._at_fork_reinit()\n \n def acquire(self):\n ''\n\n \n if self.lock:\n self.lock.acquire()\n \n def release(self):\n ''\n\n \n if self.lock:\n self.lock.release()\n \n def setLevel(self,level):\n ''\n\n \n self.level=_checkLevel(level)\n \n def format(self,record):\n ''\n\n\n\n\n \n if self.formatter:\n fmt=self.formatter\n else:\n fmt=_defaultFormatter\n return fmt.format(record)\n \n def emit(self,record):\n ''\n\n\n\n\n \n raise NotImplementedError('emit must be implemented '\n 'by Handler subclasses')\n \n def handle(self,record):\n ''\n\n\n\n\n\n\n\n\n \n rv=self.filter(record)\n if isinstance(rv,LogRecord):\n record=rv\n if rv:\n with self.lock:\n self.emit(record)\n return rv\n \n def setFormatter(self,fmt):\n ''\n\n \n self.formatter=fmt\n \n def flush(self):\n ''\n\n\n\n\n \n pass\n \n def close(self):\n ''\n\n\n\n\n\n\n \n \n with _lock:\n self._closed=True\n if self._name and self._name in _handlers:\n del _handlers[self._name]\n \n def handleError(self,record):\n ''\n\n\n\n\n\n\n\n\n\n \n if raiseExceptions and sys.stderr:\n exc=sys.exception()\n try:\n sys.stderr.write('--- Logging error ---\\n')\n traceback.print_exception(exc,limit=None,file=sys.stderr)\n sys.stderr.write('Call stack:\\n')\n \n \n frame=exc.__traceback__.tb_frame\n while(frame and os.path.dirname(frame.f_code.co_filename)==\n __path__[0]):\n frame=frame.f_back\n if frame:\n traceback.print_stack(frame,file=sys.stderr)\n else:\n \n sys.stderr.write('Logged from file %s, line %s\\n'%(\n record.filename,record.lineno))\n \n try:\n sys.stderr.write('Message: %r\\n'\n 'Arguments: %s\\n'%(record.msg,\n record.args))\n except RecursionError:\n raise\n except Exception:\n sys.stderr.write('Unable to print the message and arguments'\n ' - possible formatting error.\\nUse the'\n ' traceback above to help find the error.\\n'\n )\n except OSError:\n pass\n finally:\n del exc\n \n def __repr__(self):\n level=getLevelName(self.level)\n return '<%s (%s)>'%(self.__class__.__name__,level)\n \nclass StreamHandler(Handler):\n ''\n\n\n\n \n \n terminator='\\n'\n \n def __init__(self,stream=None):\n ''\n\n\n\n \n Handler.__init__(self)\n if stream is None:\n stream=sys.stderr\n self.stream=stream\n \n def flush(self):\n ''\n\n \n with self.lock:\n if self.stream and hasattr(self.stream,\"flush\"):\n self.stream.flush()\n \n def emit(self,record):\n ''\n\n\n\n\n\n\n\n\n \n try:\n msg=self.format(record)\n stream=self.stream\n \n stream.write(msg+self.terminator)\n self.flush()\n except RecursionError:\n raise\n except Exception:\n self.handleError(record)\n \n def setStream(self,stream):\n ''\n\n\n\n\n\n \n if stream is self.stream:\n result=None\n else:\n result=self.stream\n with self.lock:\n self.flush()\n self.stream=stream\n return result\n \n def __repr__(self):\n level=getLevelName(self.level)\n name=getattr(self.stream,'name','')\n \n name=str(name)\n if name:\n name +=' '\n return '<%s %s(%s)>'%(self.__class__.__name__,name,level)\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass FileHandler(StreamHandler):\n ''\n\n \n def __init__(self,filename,mode='a',encoding=None,delay=False,errors=None):\n ''\n\n \n \n filename=os.fspath(filename)\n \n \n self.baseFilename=os.path.abspath(filename)\n self.mode=mode\n self.encoding=encoding\n if \"b\"not in mode:\n self.encoding=io.text_encoding(encoding)\n self.errors=errors\n self.delay=delay\n \n \n \n self._builtin_open=open\n if delay:\n \n \n Handler.__init__(self)\n self.stream=None\n else:\n StreamHandler.__init__(self,self._open())\n \n def close(self):\n ''\n\n \n with self.lock:\n try:\n if self.stream:\n try:\n self.flush()\n finally:\n stream=self.stream\n self.stream=None\n if hasattr(stream,\"close\"):\n stream.close()\n finally:\n \n \n \n \n StreamHandler.close(self)\n \n def _open(self):\n ''\n\n\n \n open_func=self._builtin_open\n return open_func(self.baseFilename,self.mode,\n encoding=self.encoding,errors=self.errors)\n \n def emit(self,record):\n ''\n\n\n\n\n\n\n\n \n if self.stream is None:\n if self.mode !='w'or not self._closed:\n self.stream=self._open()\n if self.stream:\n StreamHandler.emit(self,record)\n \n def __repr__(self):\n level=getLevelName(self.level)\n return '<%s %s (%s)>'%(self.__class__.__name__,self.baseFilename,level)\n \n \nclass _StderrHandler(StreamHandler):\n ''\n\n\n\n \n def __init__(self,level=NOTSET):\n ''\n\n \n Handler.__init__(self,level)\n \n @property\n def stream(self):\n return sys.stderr\n \n \n_defaultLastResort=_StderrHandler(WARNING)\nlastResort=_defaultLastResort\n\n\n\n\n\nclass PlaceHolder(object):\n ''\n\n\n\n \n def __init__(self,alogger):\n ''\n\n \n self.loggerMap={alogger:None}\n \n def append(self,alogger):\n ''\n\n \n if alogger not in self.loggerMap:\n self.loggerMap[alogger]=None\n \n \n \n \n \ndef setLoggerClass(klass):\n ''\n\n\n\n \n if klass !=Logger:\n if not issubclass(klass,Logger):\n raise TypeError(\"logger not derived from logging.Logger: \"\n +klass.__name__)\n global _loggerClass\n _loggerClass=klass\n \ndef getLoggerClass():\n ''\n\n \n return _loggerClass\n \nclass Manager(object):\n ''\n\n\n \n def __init__(self,rootnode):\n ''\n\n \n self.root=rootnode\n self.disable=0\n self.emittedNoHandlerWarning=False\n self.loggerDict={}\n self.loggerClass=None\n self.logRecordFactory=None\n \n @property\n def disable(self):\n return self._disable\n \n @disable.setter\n def disable(self,value):\n self._disable=_checkLevel(value)\n \n def getLogger(self,name):\n ''\n\n\n\n\n\n\n\n\n \n rv=None\n if not isinstance(name,str):\n raise TypeError('A logger name must be a string')\n with _lock:\n if name in self.loggerDict:\n rv=self.loggerDict[name]\n if isinstance(rv,PlaceHolder):\n ph=rv\n rv=(self.loggerClass or _loggerClass)(name)\n rv.manager=self\n self.loggerDict[name]=rv\n self._fixupChildren(ph,rv)\n self._fixupParents(rv)\n else:\n rv=(self.loggerClass or _loggerClass)(name)\n rv.manager=self\n self.loggerDict[name]=rv\n self._fixupParents(rv)\n return rv\n \n def setLoggerClass(self,klass):\n ''\n\n \n if klass !=Logger:\n if not issubclass(klass,Logger):\n raise TypeError(\"logger not derived from logging.Logger: \"\n +klass.__name__)\n self.loggerClass=klass\n \n def setLogRecordFactory(self,factory):\n ''\n\n\n \n self.logRecordFactory=factory\n \n def _fixupParents(self,alogger):\n ''\n\n\n \n name=alogger.name\n i=name.rfind(\".\")\n rv=None\n while(i >0)and not rv:\n substr=name[:i]\n if substr not in self.loggerDict:\n self.loggerDict[substr]=PlaceHolder(alogger)\n else:\n obj=self.loggerDict[substr]\n if isinstance(obj,Logger):\n rv=obj\n else:\n assert isinstance(obj,PlaceHolder)\n obj.append(alogger)\n i=name.rfind(\".\",0,i -1)\n if not rv:\n rv=self.root\n alogger.parent=rv\n \n def _fixupChildren(self,ph,alogger):\n ''\n\n\n \n name=alogger.name\n namelen=len(name)\n for c in ph.loggerMap.keys():\n \n if c.parent.name[:namelen]!=name:\n alogger.parent=c.parent\n c.parent=alogger\n \n def _clear_cache(self):\n ''\n\n\n \n \n with _lock:\n for logger in self.loggerDict.values():\n if isinstance(logger,Logger):\n logger._cache.clear()\n self.root._cache.clear()\n \n \n \n \n \nclass Logger(Filterer):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,name,level=NOTSET):\n ''\n\n \n Filterer.__init__(self)\n self.name=name\n self.level=_checkLevel(level)\n self.parent=None\n self.propagate=True\n self.handlers=[]\n self.disabled=False\n self._cache={}\n \n def setLevel(self,level):\n ''\n\n \n self.level=_checkLevel(level)\n self.manager._clear_cache()\n \n def debug(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(DEBUG):\n self._log(DEBUG,msg,args,**kwargs)\n \n def info(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(INFO):\n self._log(INFO,msg,args,**kwargs)\n \n def warning(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(WARNING):\n self._log(WARNING,msg,args,**kwargs)\n \n def error(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(ERROR):\n self._log(ERROR,msg,args,**kwargs)\n \n def exception(self,msg,*args,exc_info=True,**kwargs):\n ''\n\n \n self.error(msg,*args,exc_info=exc_info,**kwargs)\n \n def critical(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(CRITICAL):\n self._log(CRITICAL,msg,args,**kwargs)\n \n def fatal(self,msg,*args,**kwargs):\n ''\n\n \n self.critical(msg,*args,**kwargs)\n \n def log(self,level,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if not isinstance(level,int):\n if raiseExceptions:\n raise TypeError(\"level must be an integer\")\n else:\n return\n if self.isEnabledFor(level):\n self._log(level,msg,args,**kwargs)\n \n def findCaller(self,stack_info=False,stacklevel=1):\n ''\n\n\n \n f=currentframe()\n \n \n if f is None:\n return \"(unknown file)\",0,\"(unknown function)\",None\n while stacklevel >0:\n next_f=f.f_back\n if next_f is None:\n \n \n break\n \n \n \n \n f=next_f\n if not _is_internal_frame(f):\n stacklevel -=1\n co=f.f_code\n sinfo=None\n if stack_info:\n with io.StringIO()as sio:\n sio.write(\"Stack (most recent call last):\\n\")\n traceback.print_stack(f,file=sio)\n sinfo=sio.getvalue()\n if sinfo[-1]=='\\n':\n sinfo=sinfo[:-1]\n return co.co_filename,f.f_lineno,co.co_name,sinfo\n \n def makeRecord(self,name,level,fn,lno,msg,args,exc_info,\n func=None,extra=None,sinfo=None):\n ''\n\n\n \n rv=_logRecordFactory(name,level,fn,lno,msg,args,exc_info,func,\n sinfo)\n if extra is not None:\n for key in extra:\n if(key in[\"message\",\"asctime\"])or(key in rv.__dict__):\n raise KeyError(\"Attempt to overwrite %r in LogRecord\"%key)\n rv.__dict__[key]=extra[key]\n return rv\n \n def _log(self,level,msg,args,exc_info=None,extra=None,stack_info=False,\n stacklevel=1):\n ''\n\n\n \n sinfo=None\n if _srcfile:\n \n \n \n try:\n fn,lno,func,sinfo=self.findCaller(stack_info,stacklevel)\n except ValueError:\n fn,lno,func=\"(unknown file)\",0,\"(unknown function)\"\n else:\n fn,lno,func=\"(unknown file)\",0,\"(unknown function)\"\n if exc_info:\n if isinstance(exc_info,BaseException):\n exc_info=(type(exc_info),exc_info,exc_info.__traceback__)\n elif not isinstance(exc_info,tuple):\n exc_info=sys.exc_info()\n record=self.makeRecord(self.name,level,fn,lno,msg,args,\n exc_info,func,extra,sinfo)\n self.handle(record)\n \n def handle(self,record):\n ''\n\n\n\n\n \n if self.disabled:\n return\n maybe_record=self.filter(record)\n if not maybe_record:\n return\n if isinstance(maybe_record,LogRecord):\n record=maybe_record\n self.callHandlers(record)\n \n def addHandler(self,hdlr):\n ''\n\n \n with _lock:\n if not(hdlr in self.handlers):\n self.handlers.append(hdlr)\n \n def removeHandler(self,hdlr):\n ''\n\n \n with _lock:\n if hdlr in self.handlers:\n self.handlers.remove(hdlr)\n \n def hasHandlers(self):\n ''\n\n\n\n\n\n\n\n \n c=self\n rv=False\n while c:\n if c.handlers:\n rv=True\n break\n if not c.propagate:\n break\n else:\n c=c.parent\n return rv\n \n def callHandlers(self,record):\n ''\n\n\n\n\n\n\n\n \n c=self\n found=0\n while c:\n for hdlr in c.handlers:\n found=found+1\n if record.levelno >=hdlr.level:\n hdlr.handle(record)\n if not c.propagate:\n c=None\n else:\n c=c.parent\n if(found ==0):\n if lastResort:\n if record.levelno >=lastResort.level:\n lastResort.handle(record)\n elif raiseExceptions and not self.manager.emittedNoHandlerWarning:\n sys.stderr.write(\"No handlers could be found for logger\"\n \" \\\"%s\\\"\\n\"%self.name)\n self.manager.emittedNoHandlerWarning=True\n \n def getEffectiveLevel(self):\n ''\n\n\n\n\n \n logger=self\n while logger:\n if logger.level:\n return logger.level\n logger=logger.parent\n return NOTSET\n \n def isEnabledFor(self,level):\n ''\n\n \n if self.disabled:\n return False\n \n try:\n return self._cache[level]\n except KeyError:\n with _lock:\n if self.manager.disable >=level:\n is_enabled=self._cache[level]=False\n else:\n is_enabled=self._cache[level]=(\n level >=self.getEffectiveLevel()\n )\n return is_enabled\n \n def getChild(self,suffix):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self.root is not self:\n suffix='.'.join((self.name,suffix))\n return self.manager.getLogger(suffix)\n \n def getChildren(self):\n \n def _hierlevel(logger):\n if logger is logger.manager.root:\n return 0\n return 1+logger.name.count('.')\n \n d=self.manager.loggerDict\n with _lock:\n \n \n \n return set(item for item in d.values()\n if isinstance(item,Logger)and item.parent is self and\n _hierlevel(item)==1+_hierlevel(item.parent))\n \n def __repr__(self):\n level=getLevelName(self.getEffectiveLevel())\n return '<%s %s (%s)>'%(self.__class__.__name__,self.name,level)\n \n def __reduce__(self):\n if getLogger(self.name)is not self:\n import pickle\n raise pickle.PicklingError('logger cannot be pickled')\n return getLogger,(self.name,)\n \n \nclass RootLogger(Logger):\n ''\n\n\n\n \n def __init__(self,level):\n ''\n\n \n Logger.__init__(self,\"root\",level)\n \n def __reduce__(self):\n return getLogger,()\n \n_loggerClass=Logger\n\nclass LoggerAdapter(object):\n ''\n\n\n \n \n def __init__(self,logger,extra=None,merge_extra=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.logger=logger\n self.extra=extra\n self.merge_extra=merge_extra\n \n def process(self,msg,kwargs):\n ''\n\n\n\n\n\n\n\n \n if self.merge_extra and \"extra\"in kwargs:\n kwargs[\"extra\"]={**self.extra,**kwargs[\"extra\"]}\n else:\n kwargs[\"extra\"]=self.extra\n return msg,kwargs\n \n \n \n \n def debug(self,msg,*args,**kwargs):\n ''\n\n \n self.log(DEBUG,msg,*args,**kwargs)\n \n def info(self,msg,*args,**kwargs):\n ''\n\n \n self.log(INFO,msg,*args,**kwargs)\n \n def warning(self,msg,*args,**kwargs):\n ''\n\n \n self.log(WARNING,msg,*args,**kwargs)\n \n def error(self,msg,*args,**kwargs):\n ''\n\n \n self.log(ERROR,msg,*args,**kwargs)\n \n def exception(self,msg,*args,exc_info=True,**kwargs):\n ''\n\n \n self.log(ERROR,msg,*args,exc_info=exc_info,**kwargs)\n \n def critical(self,msg,*args,**kwargs):\n ''\n\n \n self.log(CRITICAL,msg,*args,**kwargs)\n \n def log(self,level,msg,*args,**kwargs):\n ''\n\n\n \n if self.isEnabledFor(level):\n msg,kwargs=self.process(msg,kwargs)\n self.logger.log(level,msg,*args,**kwargs)\n \n def isEnabledFor(self,level):\n ''\n\n \n return self.logger.isEnabledFor(level)\n \n def setLevel(self,level):\n ''\n\n \n self.logger.setLevel(level)\n \n def getEffectiveLevel(self):\n ''\n\n \n return self.logger.getEffectiveLevel()\n \n def hasHandlers(self):\n ''\n\n \n return self.logger.hasHandlers()\n \n def _log(self,level,msg,args,**kwargs):\n ''\n\n \n return self.logger._log(level,msg,args,**kwargs)\n \n @property\n def manager(self):\n return self.logger.manager\n \n @manager.setter\n def manager(self,value):\n self.logger.manager=value\n \n @property\n def name(self):\n return self.logger.name\n \n def __repr__(self):\n logger=self.logger\n level=getLevelName(logger.getEffectiveLevel())\n return '<%s %s (%s)>'%(self.__class__.__name__,logger.name,level)\n \n __class_getitem__=classmethod(GenericAlias)\n \nroot=RootLogger(WARNING)\nLogger.root=root\nLogger.manager=Manager(Logger.root)\n\n\n\n\n\ndef basicConfig(**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n with _lock:\n force=kwargs.pop('force',False)\n encoding=kwargs.pop('encoding',None)\n errors=kwargs.pop('errors','backslashreplace')\n if force:\n for h in root.handlers[:]:\n root.removeHandler(h)\n h.close()\n if len(root.handlers)==0:\n handlers=kwargs.pop(\"handlers\",None)\n if handlers is None:\n if \"stream\"in kwargs and \"filename\"in kwargs:\n raise ValueError(\"'stream' and 'filename' should not be \"\n \"specified together\")\n else:\n if \"stream\"in kwargs or \"filename\"in kwargs:\n raise ValueError(\"'stream' or 'filename' should not be \"\n \"specified together with 'handlers'\")\n if handlers is None:\n filename=kwargs.pop(\"filename\",None)\n mode=kwargs.pop(\"filemode\",'a')\n if filename:\n if 'b'in mode:\n errors=None\n else:\n encoding=io.text_encoding(encoding)\n h=FileHandler(filename,mode,\n encoding=encoding,errors=errors)\n else:\n stream=kwargs.pop(\"stream\",None)\n h=StreamHandler(stream)\n handlers=[h]\n dfs=kwargs.pop(\"datefmt\",None)\n style=kwargs.pop(\"style\",'%')\n if style not in _STYLES:\n raise ValueError('Style must be one of: %s'%','.join(\n _STYLES.keys()))\n fs=kwargs.pop(\"format\",_STYLES[style][1])\n fmt=Formatter(fs,dfs,style)\n for h in handlers:\n if h.formatter is None:\n h.setFormatter(fmt)\n root.addHandler(h)\n level=kwargs.pop(\"level\",None)\n if level is not None:\n root.setLevel(level)\n if kwargs:\n keys=', '.join(kwargs.keys())\n raise ValueError('Unrecognised argument(s): %s'%keys)\n \n \n \n \n \n \ndef getLogger(name=None):\n ''\n\n\n\n \n if not name or isinstance(name,str)and name ==root.name:\n return root\n return Logger.manager.getLogger(name)\n \ndef critical(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.critical(msg,*args,**kwargs)\n \ndef fatal(msg,*args,**kwargs):\n ''\n\n \n critical(msg,*args,**kwargs)\n \ndef error(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.error(msg,*args,**kwargs)\n \ndef exception(msg,*args,exc_info=True,**kwargs):\n ''\n\n\n\n \n error(msg,*args,exc_info=exc_info,**kwargs)\n \ndef warning(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.warning(msg,*args,**kwargs)\n \ndef info(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.info(msg,*args,**kwargs)\n \ndef debug(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.debug(msg,*args,**kwargs)\n \ndef log(level,msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.log(level,msg,*args,**kwargs)\n \ndef disable(level=CRITICAL):\n ''\n\n \n root.manager.disable=level\n root.manager._clear_cache()\n \ndef shutdown(handlerList=_handlerList):\n ''\n\n\n\n\n \n for wr in reversed(handlerList[:]):\n \n \n try:\n h=wr()\n if h:\n try:\n h.acquire()\n \n \n \n if getattr(h,'flushOnClose',True):\n h.flush()\n h.close()\n except(OSError,ValueError):\n \n \n \n \n pass\n finally:\n h.release()\n except:\n if raiseExceptions:\n raise\n \n \n \nimport atexit\natexit.register(shutdown)\n\n\n\nclass NullHandler(Handler):\n ''\n\n\n\n\n\n\n\n \n def handle(self,record):\n ''\n \n def emit(self,record):\n ''\n \n def createLock(self):\n self.lock=None\n \n def _at_fork_reinit(self):\n pass\n \n \n \n_warnings_showwarning=None\n\ndef _showwarning(message,category,filename,lineno,file=None,line=None):\n ''\n\n\n\n\n\n \n if file is not None:\n if _warnings_showwarning is not None:\n _warnings_showwarning(message,category,filename,lineno,file,line)\n else:\n s=warnings.formatwarning(message,category,filename,lineno,line)\n logger=getLogger(\"py.warnings\")\n if not logger.handlers:\n logger.addHandler(NullHandler())\n \n \n logger.warning(str(s))\n \ndef captureWarnings(capture):\n ''\n\n\n\n \n global _warnings_showwarning\n if capture:\n if _warnings_showwarning is None:\n _warnings_showwarning=warnings.showwarning\n warnings.showwarning=_showwarning\n else:\n if _warnings_showwarning is not None:\n warnings.showwarning=_warnings_showwarning\n _warnings_showwarning=None\n", ["atexit", "collections.abc", "io", "os", "pickle", "re", "string", "sys", "threading", "time", "traceback", "types", "warnings", "weakref"], 1], "multiprocessing.connection": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['Client','Listener','Pipe']\n\nfrom queue import Queue\n\n\nfamilies=[None]\n\n\nclass Listener(object):\n\n def __init__(self,address=None,family=None,backlog=1):\n self._backlog_queue=Queue(backlog)\n \n def accept(self):\n return Connection(*self._backlog_queue.get())\n \n def close(self):\n self._backlog_queue=None\n \n address=property(lambda self:self._backlog_queue)\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,exc_tb):\n self.close()\n \n \ndef Client(address):\n _in,_out=Queue(),Queue()\n address.put((_out,_in))\n return Connection(_in,_out)\n \n \ndef Pipe(duplex=True):\n a,b=Queue(),Queue()\n return Connection(a,b),Connection(b,a)\n \n \nclass Connection(object):\n\n def __init__(self,_in,_out):\n self._out=_out\n self._in=_in\n self.send=self.send_bytes=_out.put\n self.recv=self.recv_bytes=_in.get\n \n def poll(self,timeout=0.0):\n if self._in.qsize()>0:\n return True\n if timeout <=0.0:\n return False\n self._in.not_empty.acquire()\n self._in.not_empty.wait(timeout)\n self._in.not_empty.release()\n return self._in.qsize()>0\n \n def close(self):\n pass\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,exc_tb):\n self.close()\n", ["queue"]], "multiprocessing.pool": [".py", "\n\n\n\n\n\n\n\n\n__all__=['Pool']\n\n\n\n\n\nimport threading\nimport queue\nimport itertools\nimport collections\nimport time\n\nfrom multiprocessing import Process,cpu_count,TimeoutError\nfrom multiprocessing.util import Finalize,debug\n\n\n\n\n\nRUN=0\nCLOSE=1\nTERMINATE=2\n\n\n\n\n\njob_counter=itertools.count()\n\ndef mapstar(args):\n return list(map(*args))\n \ndef starmapstar(args):\n return list(itertools.starmap(args[0],args[1]))\n \n \n \n \n \nclass MaybeEncodingError(Exception):\n ''\n \n \n def __init__(self,exc,value):\n self.exc=repr(exc)\n self.value=repr(value)\n super(MaybeEncodingError,self).__init__(self.exc,self.value)\n \n def __str__(self):\n return \"Error sending result: '%s'. Reason: '%s'\"%(self.value,\n self.exc)\n \n def __repr__(self):\n return \"\"%str(self)\n \n \ndef worker(inqueue,outqueue,initializer=None,initargs=(),maxtasks=None):\n assert maxtasks is None or(type(maxtasks)==int and maxtasks >0)\n put=outqueue.put\n get=inqueue.get\n if hasattr(inqueue,'_writer'):\n inqueue._writer.close()\n outqueue._reader.close()\n \n if initializer is not None:\n initializer(*initargs)\n \n completed=0\n while maxtasks is None or(maxtasks and completed 1\n task_batches=Pool._get_tasks(func,iterable,chunksize)\n result=IMapIterator(self._cache)\n self._taskqueue.put((((result._job,i,mapstar,(x,),{})\n for i,x in enumerate(task_batches)),result._set_length))\n return(item for chunk in result for item in chunk)\n \n def imap_unordered(self,func,iterable,chunksize=1):\n ''\n\n \n if self._state !=RUN:\n raise ValueError(\"Pool not running\")\n if chunksize ==1:\n result=IMapUnorderedIterator(self._cache)\n self._taskqueue.put((((result._job,i,func,(x,),{})\n for i,x in enumerate(iterable)),result._set_length))\n return result\n else:\n assert chunksize >1\n task_batches=Pool._get_tasks(func,iterable,chunksize)\n result=IMapUnorderedIterator(self._cache)\n self._taskqueue.put((((result._job,i,mapstar,(x,),{})\n for i,x in enumerate(task_batches)),result._set_length))\n return(item for chunk in result for item in chunk)\n \n def apply_async(self,func,args=(),kwds={},callback=None,\n error_callback=None):\n ''\n\n \n if self._state !=RUN:\n raise ValueError(\"Pool not running\")\n result=ApplyResult(self._cache,callback,error_callback)\n self._taskqueue.put(([(result._job,None,func,args,kwds)],None))\n return result\n \n def map_async(self,func,iterable,chunksize=None,callback=None,\n error_callback=None):\n ''\n\n \n return self._map_async(func,iterable,mapstar,chunksize,callback,\n error_callback)\n \n def _map_async(self,func,iterable,mapper,chunksize=None,callback=None,\n error_callback=None):\n ''\n\n \n if self._state !=RUN:\n raise ValueError(\"Pool not running\")\n if not hasattr(iterable,'__len__'):\n iterable=list(iterable)\n \n if chunksize is None:\n chunksize,extra=divmod(len(iterable),len(self._pool)*4)\n if extra:\n chunksize +=1\n if len(iterable)==0:\n chunksize=0\n \n task_batches=Pool._get_tasks(func,iterable,chunksize)\n result=MapResult(self._cache,chunksize,len(iterable),callback,\n error_callback=error_callback)\n self._taskqueue.put((((result._job,i,mapper,(x,),{})\n for i,x in enumerate(task_batches)),None))\n return result\n \n @staticmethod\n def _handle_workers(pool):\n thread=threading.current_thread()\n \n \n \n while thread._state ==RUN or(pool._cache and thread._state !=TERMINATE):\n pool._maintain_pool()\n time.sleep(0.1)\n \n pool._taskqueue.put(None)\n debug('worker handler exiting')\n \n @staticmethod\n def _handle_tasks(taskqueue,put,outqueue,pool):\n thread=threading.current_thread()\n \n for taskseq,set_length in iter(taskqueue.get,None):\n i=-1\n for i,task in enumerate(taskseq):\n if thread._state:\n debug('task handler found thread._state != RUN')\n break\n try:\n put(task)\n except IOError:\n debug('could not put task on queue')\n break\n else:\n if set_length:\n debug('doing set_length()')\n set_length(i+1)\n continue\n break\n else:\n debug('task handler got sentinel')\n \n \n try:\n \n debug('task handler sending sentinel to result handler')\n outqueue.put(None)\n \n \n debug('task handler sending sentinel to workers')\n for p in pool:\n put(None)\n except IOError:\n debug('task handler got IOError when sending sentinels')\n \n debug('task handler exiting')\n \n @staticmethod\n def _handle_results(outqueue,get,cache):\n thread=threading.current_thread()\n \n while 1:\n try:\n task=get()\n except(IOError,EOFError):\n debug('result handler got EOFError/IOError -- exiting')\n return\n \n if thread._state:\n assert thread._state ==TERMINATE\n debug('result handler found thread._state=TERMINATE')\n break\n \n if task is None:\n debug('result handler got sentinel')\n break\n \n job,i,obj=task\n try:\n cache[job]._set(i,obj)\n except KeyError:\n pass\n \n while cache and thread._state !=TERMINATE:\n try:\n task=get()\n except(IOError,EOFError):\n debug('result handler got EOFError/IOError -- exiting')\n return\n \n if task is None:\n debug('result handler ignoring extra sentinel')\n continue\n job,i,obj=task\n try:\n cache[job]._set(i,obj)\n except KeyError:\n pass\n \n if hasattr(outqueue,'_reader'):\n debug('ensuring that outqueue is not full')\n \n \n \n try:\n for i in range(10):\n if not outqueue._reader.poll():\n break\n get()\n except(IOError,EOFError):\n pass\n \n debug('result handler exiting: len(cache)=%s, thread._state=%s',\n len(cache),thread._state)\n \n @staticmethod\n def _get_tasks(func,it,size):\n it=iter(it)\n while 1:\n x=tuple(itertools.islice(it,size))\n if not x:\n return\n yield(func,x)\n \n def __reduce__(self):\n raise NotImplementedError(\n 'pool objects cannot be passed between processes or pickled'\n )\n \n def close(self):\n debug('closing pool')\n if self._state ==RUN:\n self._state=CLOSE\n self._worker_handler._state=CLOSE\n \n def terminate(self):\n debug('terminating pool')\n self._state=TERMINATE\n self._worker_handler._state=TERMINATE\n self._terminate()\n \n def join(self):\n debug('joining pool')\n assert self._state in(CLOSE,TERMINATE)\n self._worker_handler.join()\n self._task_handler.join()\n self._result_handler.join()\n for p in self._pool:\n p.join()\n \n @staticmethod\n def _help_stuff_finish(inqueue,task_handler,size):\n \n debug('removing tasks from inqueue until task handler finished')\n inqueue._rlock.acquire()\n while task_handler.is_alive()and inqueue._reader.poll():\n inqueue._reader.recv()\n time.sleep(0)\n \n @classmethod\n def _terminate_pool(cls,taskqueue,inqueue,outqueue,pool,\n worker_handler,task_handler,result_handler,cache):\n \n debug('finalizing pool')\n \n worker_handler._state=TERMINATE\n task_handler._state=TERMINATE\n \n debug('helping task handler/workers to finish')\n cls._help_stuff_finish(inqueue,task_handler,len(pool))\n \n assert result_handler.is_alive()or len(cache)==0\n \n result_handler._state=TERMINATE\n outqueue.put(None)\n \n \n \n debug('joining worker handler')\n if threading.current_thread()is not worker_handler:\n worker_handler.join()\n \n \n if pool and hasattr(pool[0],'terminate'):\n debug('terminating workers')\n for p in pool:\n if p.exitcode is None:\n p.terminate()\n \n debug('joining task handler')\n if threading.current_thread()is not task_handler:\n task_handler.join()\n \n debug('joining result handler')\n if threading.current_thread()is not result_handler:\n result_handler.join()\n \n if pool and hasattr(pool[0],'terminate'):\n debug('joining pool workers')\n for p in pool:\n if p.is_alive():\n \n debug('cleaning up worker %d'%p.pid)\n p.join()\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_val,exc_tb):\n self.terminate()\n \n \n \n \n \nclass ApplyResult(object):\n\n def __init__(self,cache,callback,error_callback):\n self._event=threading.Event()\n self._job=next(job_counter)\n self._cache=cache\n self._callback=callback\n self._error_callback=error_callback\n cache[self._job]=self\n \n def ready(self):\n return self._event.is_set()\n \n def successful(self):\n assert self.ready()\n return self._success\n \n def wait(self,timeout=None):\n self._event.wait(timeout)\n \n def get(self,timeout=None):\n self.wait(timeout)\n if not self.ready():\n raise TimeoutError\n if self._success:\n return self._value\n else:\n raise self._value\n \n def _set(self,i,obj):\n self._success,self._value=obj\n if self._callback and self._success:\n self._callback(self._value)\n if self._error_callback and not self._success:\n self._error_callback(self._value)\n self._event.set()\n del self._cache[self._job]\n \nAsyncResult=ApplyResult\n\n\n\n\n\nclass MapResult(ApplyResult):\n\n def __init__(self,cache,chunksize,length,callback,error_callback):\n ApplyResult.__init__(self,cache,callback,\n error_callback=error_callback)\n self._success=True\n self._value=[None]*length\n self._chunksize=chunksize\n if chunksize <=0:\n self._number_left=0\n self._event.set()\n del cache[self._job]\n else:\n self._number_left=length //chunksize+bool(length %chunksize)\n \n def _set(self,i,success_result):\n success,result=success_result\n if success:\n self._value[i *self._chunksize:(i+1)*self._chunksize]=result\n self._number_left -=1\n if self._number_left ==0:\n if self._callback:\n self._callback(self._value)\n del self._cache[self._job]\n self._event.set()\n else:\n self._success=False\n self._value=result\n if self._error_callback:\n self._error_callback(self._value)\n del self._cache[self._job]\n self._event.set()\n \n \n \n \n \nclass IMapIterator(object):\n\n def __init__(self,cache):\n self._cond=threading.Condition(threading.Lock())\n self._job=next(job_counter)\n self._cache=cache\n self._items=collections.deque()\n self._index=0\n self._length=None\n self._unsorted={}\n cache[self._job]=self\n \n def __iter__(self):\n return self\n \n def next(self,timeout=None):\n self._cond.acquire()\n try:\n try:\n item=self._items.popleft()\n except IndexError:\n if self._index ==self._length:\n raise StopIteration\n self._cond.wait(timeout)\n try:\n item=self._items.popleft()\n except IndexError:\n if self._index ==self._length:\n raise StopIteration\n raise TimeoutError\n finally:\n self._cond.release()\n \n success,value=item\n if success:\n return value\n raise value\n \n __next__=next\n \n def _set(self,i,obj):\n self._cond.acquire()\n try:\n if self._index ==i:\n self._items.append(obj)\n self._index +=1\n while self._index in self._unsorted:\n obj=self._unsorted.pop(self._index)\n self._items.append(obj)\n self._index +=1\n self._cond.notify()\n else:\n self._unsorted[i]=obj\n \n if self._index ==self._length:\n del self._cache[self._job]\n finally:\n self._cond.release()\n \n def _set_length(self,length):\n self._cond.acquire()\n try:\n self._length=length\n if self._index ==self._length:\n self._cond.notify()\n del self._cache[self._job]\n finally:\n self._cond.release()\n \n \n \n \n \nclass IMapUnorderedIterator(IMapIterator):\n\n def _set(self,i,obj):\n self._cond.acquire()\n try:\n self._items.append(obj)\n self._index +=1\n self._cond.notify()\n if self._index ==self._length:\n del self._cache[self._job]\n finally:\n self._cond.release()\n \n \n \n \n \nclass ThreadPool(Pool):\n\n from.dummy import Process\n \n def __init__(self,processes=None,initializer=None,initargs=()):\n Pool.__init__(self,processes,initializer,initargs)\n \n def _setup_queues(self):\n self._inqueue=queue.Queue()\n self._outqueue=queue.Queue()\n self._quick_put=self._inqueue.put\n self._quick_get=self._outqueue.get\n \n @staticmethod\n def _help_stuff_finish(inqueue,task_handler,size):\n \n inqueue.not_empty.acquire()\n try:\n inqueue.queue.clear()\n inqueue.queue.extend([None]*size)\n inqueue.not_empty.notify_all()\n finally:\n inqueue.not_empty.release()\n", ["collections", "itertools", "multiprocessing", "multiprocessing.Process", "multiprocessing.dummy", "multiprocessing.queues", "multiprocessing.util", "queue", "threading", "time"]], "multiprocessing.process": [".py", "\n\n\n\n\n\n\n\n\n__all__=['Process','current_process','active_children']\n\n\n\n\n\nimport os\nimport sys\nimport signal\nimport itertools\nfrom _weakrefset import WeakSet\n\n\nfrom _multiprocessing import Process\n\n\n\n\ntry:\n ORIGINAL_DIR=os.path.abspath(os.getcwd())\nexcept OSError:\n ORIGINAL_DIR=None\n \n \n \n \n \ndef current_process():\n ''\n\n \n return _current_process\n \ndef active_children():\n ''\n\n \n _cleanup()\n return list(_current_process._children)\n \n \n \n \n \ndef _cleanup():\n\n for p in list(_current_process._children):\n if p._popen.poll()is not None:\n _current_process._children.discard(p)\n \n \n \n \n \n \n \n \n \n \n \n \nclass AuthenticationString(bytes):\n def __reduce__(self):\n from.forking import Popen\n if not Popen.thread_is_spawning():\n raise TypeError(\n 'Pickling an AuthenticationString object is '\n 'disallowed for security reasons'\n )\n return AuthenticationString,(bytes(self),)\n \n \n \n \n \nclass _MainProcess(Process):\n\n def __init__(self):\n self._identity=()\n self._daemonic=False\n self._name='MainProcess'\n self._parent_pid=None\n self._popen=None\n self._counter=itertools.count(1)\n self._children=set()\n self._authkey=AuthenticationString(os.urandom(32))\n self._tempdir=None\n \n_current_process=_MainProcess()\ndel _MainProcess\n\n\n\n\n\n_exitcode_to_name={}\n\nfor name,signum in list(signal.__dict__.items()):\n if name[:3]=='SIG'and '_'not in name:\n _exitcode_to_name[-signum]=name\n \n \n_dangling=WeakSet()\n", ["_multiprocessing", "_weakrefset", "itertools", "multiprocessing.forking", "os", "signal", "sys"]], "multiprocessing.util": [".py", "\n\n\n\n\n\n\n\n\nimport sys\nimport functools\nimport os\nimport itertools\nimport weakref\nimport atexit\nimport threading\n\nfrom subprocess import _args_from_interpreter_flags\n\nfrom multiprocessing.process import current_process,active_children\n\n__all__=[\n'sub_debug','debug','info','sub_warning','get_logger',\n'log_to_stderr','get_temp_dir','register_after_fork',\n'is_exiting','Finalize','ForkAwareThreadLock','ForkAwareLocal',\n'SUBDEBUG','SUBWARNING',\n]\n\n\n\n\n\nNOTSET=0\nSUBDEBUG=5\nDEBUG=10\nINFO=20\nSUBWARNING=25\n\nLOGGER_NAME='multiprocessing'\nDEFAULT_LOGGING_FORMAT='[%(levelname)s/%(processName)s] %(message)s'\n\n_logger=None\n_log_to_stderr=False\n\ndef sub_debug(msg,*args):\n if _logger:\n _logger.log(SUBDEBUG,msg,*args)\n \ndef debug(msg,*args):\n if _logger:\n _logger.log(DEBUG,msg,*args)\n \ndef info(msg,*args):\n if _logger:\n _logger.log(INFO,msg,*args)\n \ndef sub_warning(msg,*args):\n if _logger:\n _logger.log(SUBWARNING,msg,*args)\n \ndef get_logger():\n ''\n\n \n global _logger\n import logging\n \n logging._acquireLock()\n try:\n if not _logger:\n \n _logger=logging.getLogger(LOGGER_NAME)\n _logger.propagate=0\n logging.addLevelName(SUBDEBUG,'SUBDEBUG')\n logging.addLevelName(SUBWARNING,'SUBWARNING')\n \n \n if hasattr(atexit,'unregister'):\n atexit.unregister(_exit_function)\n atexit.register(_exit_function)\n else:\n atexit._exithandlers.remove((_exit_function,(),{}))\n atexit._exithandlers.append((_exit_function,(),{}))\n \n finally:\n logging._releaseLock()\n \n return _logger\n \ndef log_to_stderr(level=None):\n ''\n\n \n global _log_to_stderr\n import logging\n \n logger=get_logger()\n formatter=logging.Formatter(DEFAULT_LOGGING_FORMAT)\n handler=logging.StreamHandler()\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n \n if level:\n logger.setLevel(level)\n _log_to_stderr=True\n return _logger\n \n \n \n \n \ndef get_temp_dir():\n\n if current_process()._tempdir is None:\n import shutil,tempfile\n tempdir=tempfile.mkdtemp(prefix='pymp-')\n info('created temp directory %s',tempdir)\n Finalize(None,shutil.rmtree,args=[tempdir],exitpriority=-100)\n current_process()._tempdir=tempdir\n return current_process()._tempdir\n \n \n \n \n \n_afterfork_registry=weakref.WeakValueDictionary()\n_afterfork_counter=itertools.count()\n\ndef _run_after_forkers():\n items=list(_afterfork_registry.items())\n items.sort()\n for(index,ident,func),obj in items:\n try:\n func(obj)\n except Exception as e:\n info('after forker raised exception %s',e)\n \ndef register_after_fork(obj,func):\n _afterfork_registry[(next(_afterfork_counter),id(obj),func)]=obj\n \n \n \n \n \n_finalizer_registry={}\n_finalizer_counter=itertools.count()\n\n\nclass Finalize(object):\n ''\n\n \n def __init__(self,obj,callback,args=(),kwargs=None,exitpriority=None):\n assert exitpriority is None or type(exitpriority)is int\n \n if obj is not None:\n self._weakref=weakref.ref(obj,self)\n else:\n assert exitpriority is not None\n \n self._callback=callback\n self._args=args\n self._kwargs=kwargs or{}\n self._key=(exitpriority,next(_finalizer_counter))\n self._pid=os.getpid()\n \n _finalizer_registry[self._key]=self\n \n def __call__(self,wr=None,\n \n \n _finalizer_registry=_finalizer_registry,\n sub_debug=sub_debug,getpid=os.getpid):\n ''\n\n \n try:\n del _finalizer_registry[self._key]\n except KeyError:\n sub_debug('finalizer no longer registered')\n else:\n if self._pid !=getpid():\n sub_debug('finalizer ignored because different process')\n res=None\n else:\n sub_debug('finalizer calling %s with args %s and kwargs %s',\n self._callback,self._args,self._kwargs)\n res=self._callback(*self._args,**self._kwargs)\n self._weakref=self._callback=self._args=\\\n self._kwargs=self._key=None\n return res\n \n def cancel(self):\n ''\n\n \n try:\n del _finalizer_registry[self._key]\n except KeyError:\n pass\n else:\n self._weakref=self._callback=self._args=\\\n self._kwargs=self._key=None\n \n def still_active(self):\n ''\n\n \n return self._key in _finalizer_registry\n \n def __repr__(self):\n try:\n obj=self._weakref()\n except(AttributeError,TypeError):\n obj=None\n \n if obj is None:\n return ''\n \n x=''\n \n \ndef _run_finalizers(minpriority=None):\n ''\n\n\n\n\n \n if _finalizer_registry is None:\n \n \n \n return\n \n if minpriority is None:\n f=lambda p:p[0][0]is not None\n else:\n f=lambda p:p[0][0]is not None and p[0][0]>=minpriority\n \n items=[x for x in list(_finalizer_registry.items())if f(x)]\n items.sort(reverse=True)\n \n for key,finalizer in items:\n sub_debug('calling %s',finalizer)\n try:\n finalizer()\n except Exception:\n import traceback\n traceback.print_exc()\n \n if minpriority is None:\n _finalizer_registry.clear()\n \n \n \n \n \ndef is_exiting():\n ''\n\n \n return _exiting or _exiting is None\n \n_exiting=False\n\ndef _exit_function(info=info,debug=debug,_run_finalizers=_run_finalizers,\nactive_children=active_children,\ncurrent_process=current_process):\n\n\n\n\n global _exiting\n \n if not _exiting:\n _exiting=True\n \n info('process shutting down')\n debug('running all \"atexit\" finalizers with priority >= 0')\n _run_finalizers(0)\n \n if current_process()is not None:\n \n \n \n \n \n \n \n \n \n \n \n \n \n for p in active_children():\n if p._daemonic:\n info('calling terminate() for daemon %s',p.name)\n p._popen.terminate()\n \n for p in active_children():\n info('calling join() for process %s',p.name)\n p.join()\n \n debug('running the remaining \"atexit\" finalizers')\n _run_finalizers()\n \natexit.register(_exit_function)\n\n\n\n\n\nclass ForkAwareThreadLock(object):\n def __init__(self):\n self._reset()\n register_after_fork(self,ForkAwareThreadLock._reset)\n \n def _reset(self):\n self._lock=threading.Lock()\n self.acquire=self._lock.acquire\n self.release=self._lock.release\n \nclass ForkAwareLocal(threading.local):\n def __init__(self):\n register_after_fork(self,lambda obj:obj.__dict__.clear())\n def __reduce__(self):\n return type(self),()\n", ["atexit", "functools", "itertools", "logging", "multiprocessing.process", "os", "shutil", "subprocess", "sys", "tempfile", "threading", "traceback", "weakref"]], "multiprocessing": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__='0.70a1'\n\n__all__=[\n'Process','current_process','active_children','freeze_support',\n'Manager','Pipe','cpu_count','log_to_stderr','get_logger',\n'allow_connection_pickling','BufferTooShort','TimeoutError',\n'Lock','RLock','Semaphore','BoundedSemaphore','Condition',\n'Event','Barrier','Queue','SimpleQueue','JoinableQueue','Pool',\n'Value','Array','RawValue','RawArray','SUBDEBUG','SUBWARNING',\n]\n\n__author__='R. Oudkerk (r.m.oudkerk@gmail.com)'\n\n\n\n\n\nimport os\nimport sys\n\nfrom multiprocessing.process import Process,current_process,active_children\nfrom multiprocessing.util import SUBDEBUG,SUBWARNING\n\n\n\n\n\nclass ProcessError(Exception):\n pass\n \nclass BufferTooShort(ProcessError):\n pass\n \nclass TimeoutError(ProcessError):\n pass\n \nclass AuthenticationError(ProcessError):\n pass\n \nimport _multiprocessing\n\n\n\n\n\ndef Manager():\n ''\n\n\n\n\n \n from multiprocessing.managers import SyncManager\n m=SyncManager()\n m.start()\n return m\n \n \n \n \n \n \n \n \n \ndef cpu_count():\n ''\n\n \n if sys.platform =='win32':\n try:\n num=int(os.environ['NUMBER_OF_PROCESSORS'])\n except(ValueError,KeyError):\n num=0\n elif 'bsd'in sys.platform or sys.platform =='darwin':\n comm='/sbin/sysctl -n hw.ncpu'\n if sys.platform =='darwin':\n comm='/usr'+comm\n try:\n with os.popen(comm)as p:\n num=int(p.read())\n except ValueError:\n num=0\n else:\n try:\n num=os.sysconf('SC_NPROCESSORS_ONLN')\n except(ValueError,OSError,AttributeError):\n num=0\n \n if num >=1:\n return num\n else:\n raise NotImplementedError('cannot determine number of cpus')\n \ndef freeze_support():\n ''\n\n\n \n if sys.platform =='win32'and getattr(sys,'frozen',False):\n from multiprocessing.forking import freeze_support\n freeze_support()\n \ndef get_logger():\n ''\n\n \n from multiprocessing.util import get_logger\n return get_logger()\n \ndef log_to_stderr(level=None):\n ''\n\n \n from multiprocessing.util import log_to_stderr\n return log_to_stderr(level)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef Lock():\n ''\n\n \n from multiprocessing.synchronize import Lock\n return Lock()\n \ndef RLock():\n ''\n\n \n from multiprocessing.synchronize import RLock\n return RLock()\n \ndef Condition(lock=None):\n ''\n\n \n from multiprocessing.synchronize import Condition\n return Condition(lock)\n \ndef Semaphore(value=1):\n ''\n\n \n from multiprocessing.synchronize import Semaphore\n return Semaphore(value)\n \ndef BoundedSemaphore(value=1):\n ''\n\n \n from multiprocessing.synchronize import BoundedSemaphore\n return BoundedSemaphore(value)\n \ndef Event():\n ''\n\n \n from multiprocessing.synchronize import Event\n return Event()\n \ndef Barrier(parties,action=None,timeout=None):\n ''\n\n \n from multiprocessing.synchronize import Barrier\n return Barrier(parties,action,timeout)\n \ndef Queue(maxsize=0):\n ''\n\n \n from multiprocessing.queues import Queue\n return Queue(maxsize)\n \ndef JoinableQueue(maxsize=0):\n ''\n\n \n from multiprocessing.queues import JoinableQueue\n return JoinableQueue(maxsize)\n \ndef SimpleQueue():\n ''\n\n \n from multiprocessing.queues import SimpleQueue\n return SimpleQueue()\n \ndef Pool(processes=None,initializer=None,initargs=(),maxtasksperchild=None):\n ''\n\n \n from multiprocessing.pool import Pool\n return Pool(processes,initializer,initargs,maxtasksperchild)\n \ndef RawValue(typecode_or_type,*args):\n ''\n\n \n from multiprocessing.sharedctypes import RawValue\n return RawValue(typecode_or_type,*args)\n \ndef RawArray(typecode_or_type,size_or_initializer):\n ''\n\n \n from multiprocessing.sharedctypes import RawArray\n return RawArray(typecode_or_type,size_or_initializer)\n \ndef Value(typecode_or_type,*args,lock=True):\n ''\n\n \n from multiprocessing.sharedctypes import Value\n return Value(typecode_or_type,*args,lock=lock)\n \ndef Array(typecode_or_type,size_or_initializer,*,lock=True):\n ''\n\n \n from multiprocessing.sharedctypes import Array\n return Array(typecode_or_type,size_or_initializer,lock=lock)\n \n \n \n \n \nif sys.platform =='win32':\n\n def set_executable(executable):\n ''\n\n\n\n \n from multiprocessing.forking import set_executable\n set_executable(executable)\n \n __all__ +=['set_executable']\n", ["_multiprocessing", "multiprocessing.forking", "multiprocessing.managers", "multiprocessing.pool", "multiprocessing.process", "multiprocessing.queues", "multiprocessing.sharedctypes", "multiprocessing.synchronize", "multiprocessing.util", "os", "sys"], 1], "multiprocessing.dummy.connection": [".py", "\n\n\n\n\n\n\n\n\n__all__=['Client','Listener','Pipe']\n\nfrom queue import Queue\n\n\nfamilies=[None]\n\n\nclass Listener(object):\n\n def __init__(self,address=None,family=None,backlog=1):\n self._backlog_queue=Queue(backlog)\n \n def accept(self):\n return Connection(*self._backlog_queue.get())\n \n def close(self):\n self._backlog_queue=None\n \n @property\n def address(self):\n return self._backlog_queue\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,exc_tb):\n self.close()\n \n \ndef Client(address):\n _in,_out=Queue(),Queue()\n address.put((_out,_in))\n return Connection(_in,_out)\n \n \ndef Pipe(duplex=True):\n a,b=Queue(),Queue()\n return Connection(a,b),Connection(b,a)\n \n \nclass Connection(object):\n\n def __init__(self,_in,_out):\n self._out=_out\n self._in=_in\n self.send=self.send_bytes=_out.put\n self.recv=self.recv_bytes=_in.get\n \n def poll(self,timeout=0.0):\n if self._in.qsize()>0:\n return True\n if timeout <=0.0:\n return False\n with self._in.not_empty:\n self._in.not_empty.wait(timeout)\n return self._in.qsize()>0\n \n def close(self):\n pass\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,exc_tb):\n self.close()\n", ["queue"]], "multiprocessing.dummy": [".py", "\n\n\n\n\n\n\n\n\n__all__=[\n'Process','current_process','active_children','freeze_support',\n'Lock','RLock','Semaphore','BoundedSemaphore','Condition',\n'Event','Barrier','Queue','Manager','Pipe','Pool','JoinableQueue'\n]\n\n\n\n\n\nimport threading\nimport sys\nimport weakref\nimport array\n\nfrom.connection import Pipe\nfrom threading import Lock,RLock,Semaphore,BoundedSemaphore\nfrom threading import Event,Condition,Barrier\nfrom queue import Queue\n\n\n\n\n\nclass DummyProcess(threading.Thread):\n\n def __init__(self,group=None,target=None,name=None,args=(),kwargs={}):\n threading.Thread.__init__(self,group,target,name,args,kwargs)\n self._pid=None\n self._children=weakref.WeakKeyDictionary()\n self._start_called=False\n self._parent=current_process()\n \n def start(self):\n if self._parent is not current_process():\n raise RuntimeError(\n \"Parent is {0!r} but current_process is {1!r}\".format(\n self._parent,current_process()))\n self._start_called=True\n if hasattr(self._parent,'_children'):\n self._parent._children[self]=None\n threading.Thread.start(self)\n \n @property\n def exitcode(self):\n if self._start_called and not self.is_alive():\n return 0\n else:\n return None\n \n \n \n \n \nProcess=DummyProcess\ncurrent_process=threading.current_thread\ncurrent_process()._children=weakref.WeakKeyDictionary()\n\ndef active_children():\n children=current_process()._children\n for p in list(children):\n if not p.is_alive():\n children.pop(p,None)\n return list(children)\n \ndef freeze_support():\n pass\n \n \n \n \n \nclass Namespace(object):\n def __init__(self,/,**kwds):\n self.__dict__.update(kwds)\n def __repr__(self):\n items=list(self.__dict__.items())\n temp=[]\n for name,value in items:\n if not name.startswith('_'):\n temp.append('%s=%r'%(name,value))\n temp.sort()\n return '%s(%s)'%(self.__class__.__name__,', '.join(temp))\n \ndict=dict\nlist=list\n\ndef Array(typecode,sequence,lock=True):\n return array.array(typecode,sequence)\n \nclass Value(object):\n def __init__(self,typecode,value,lock=True):\n self._typecode=typecode\n self._value=value\n \n @property\n def value(self):\n return self._value\n \n @value.setter\n def value(self,value):\n self._value=value\n \n def __repr__(self):\n return '<%s(%r, %r)>'%(type(self).__name__,self._typecode,self._value)\n \ndef Manager():\n return sys.modules[__name__]\n \ndef shutdown():\n pass\n \ndef Pool(processes=None,initializer=None,initargs=()):\n from..pool import ThreadPool\n return ThreadPool(processes,initializer,initargs)\n \nJoinableQueue=Queue\n", ["array", "multiprocessing.dummy.connection", "multiprocessing.pool", "queue", "sys", "threading", "weakref"], 1], "pyexpat_utils.errors": [".py", "\nXML_ERROR_ABORTED=\"\"\"parsing aborted\"\"\"\n\nXML_ERROR_AMPLIFICATION_LIMIT_BREACH=\"\"\"limit on input amplification factor (from DTD and entities) breached\"\"\"\n\nXML_ERROR_ASYNC_ENTITY=\"\"\"asynchronous entity\"\"\"\n\nXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF=\"\"\"reference to external entity in attribute\"\"\"\n\nXML_ERROR_BAD_CHAR_REF=\"\"\"reference to invalid character number\"\"\"\n\nXML_ERROR_BINARY_ENTITY_REF=\"\"\"reference to binary entity\"\"\"\n\nXML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING=\"\"\"cannot change setting once parsing has begun\"\"\"\n\nXML_ERROR_DUPLICATE_ATTRIBUTE=\"\"\"duplicate attribute\"\"\"\n\nXML_ERROR_ENTITY_DECLARED_IN_PE=\"\"\"entity declared in parameter entity\"\"\"\n\nXML_ERROR_EXTERNAL_ENTITY_HANDLING=\"\"\"error in processing external entity reference\"\"\"\n\nXML_ERROR_FEATURE_REQUIRES_XML_DTD=\"\"\"requested feature requires XML_DTD support in Expat\"\"\"\n\nXML_ERROR_FINISHED=\"\"\"parsing finished\"\"\"\n\nXML_ERROR_INCOMPLETE_PE=\"\"\"incomplete markup in parameter entity\"\"\"\n\nXML_ERROR_INCORRECT_ENCODING=\"\"\"encoding specified in XML declaration is incorrect\"\"\"\n\nXML_ERROR_INVALID_ARGUMENT=\"\"\"invalid argument\"\"\"\n\nXML_ERROR_INVALID_TOKEN=\"\"\"not well-formed (invalid token)\"\"\"\n\nXML_ERROR_JUNK_AFTER_DOC_ELEMENT=\"\"\"junk after document element\"\"\"\n\nXML_ERROR_MISPLACED_XML_PI=\"\"\"XML or text declaration not at start of entity\"\"\"\n\nXML_ERROR_NOT_STANDALONE=\"\"\"document is not standalone\"\"\"\n\nXML_ERROR_NOT_SUSPENDED=\"\"\"parser not suspended\"\"\"\n\nXML_ERROR_NO_BUFFER=\"\"\"a successful prior call to function XML_GetBuffer is required\"\"\"\n\nXML_ERROR_NO_ELEMENTS=\"\"\"no element found\"\"\"\n\nXML_ERROR_NO_MEMORY=\"\"\"out of memory\"\"\"\n\nXML_ERROR_PARAM_ENTITY_REF=\"\"\"illegal parameter entity reference\"\"\"\n\nXML_ERROR_PARTIAL_CHAR=\"\"\"partial character\"\"\"\n\nXML_ERROR_PUBLICID=\"\"\"illegal character(s) in public id\"\"\"\n\nXML_ERROR_RECURSIVE_ENTITY_REF=\"\"\"recursive entity reference\"\"\"\n\nXML_ERROR_RESERVED_NAMESPACE_URI=\"\"\"prefix must not be bound to one of the reserved namespace names\"\"\"\n\nXML_ERROR_RESERVED_PREFIX_XML=\"\"\"reserved prefix (xml) must not be undeclared or bound to another namespace name\"\"\"\n\nXML_ERROR_RESERVED_PREFIX_XMLNS=\"\"\"reserved prefix (xmlns) must not be declared or undeclared\"\"\"\n\nXML_ERROR_SUSPENDED=\"\"\"parser suspended\"\"\"\n\nXML_ERROR_SUSPEND_PE=\"\"\"cannot suspend in external parameter entity\"\"\"\n\nXML_ERROR_SYNTAX=\"\"\"syntax error\"\"\"\n\nXML_ERROR_TAG_MISMATCH=\"\"\"mismatched tag\"\"\"\n\nXML_ERROR_TEXT_DECL=\"\"\"text declaration not well-formed\"\"\"\n\nXML_ERROR_UNBOUND_PREFIX=\"\"\"unbound prefix\"\"\"\n\nXML_ERROR_UNCLOSED_CDATA_SECTION=\"\"\"unclosed CDATA section\"\"\"\n\nXML_ERROR_UNCLOSED_TOKEN=\"\"\"unclosed token\"\"\"\n\nXML_ERROR_UNDECLARING_PREFIX=\"\"\"must not undeclare prefix\"\"\"\n\nXML_ERROR_UNDEFINED_ENTITY=\"\"\"undefined entity\"\"\"\n\nXML_ERROR_UNEXPECTED_STATE=\"\"\"unexpected parser state - please send a bug report\"\"\"\n\nXML_ERROR_UNKNOWN_ENCODING=\"\"\"unknown encoding\"\"\"\n\nXML_ERROR_XML_DECL=\"\"\"XML declaration not well-formed\"\"\"\n\n__name__=\"\"\"pyexpat.errors\"\"\"\n\ncodes={'out of memory':1,'syntax error':2,'no element found':3,'not well-formed (invalid token)':4,'unclosed token':5,'partial character':6,'mismatched tag':7,'duplicate attribute':8,'junk after document element':9,'illegal parameter entity reference':10,'undefined entity':11,'recursive entity reference':12,'asynchronous entity':13,'reference to invalid character number':14,'reference to binary entity':15,'reference to external entity in attribute':16,'XML or text declaration not at start of entity':17,'unknown encoding':18,'encoding specified in XML declaration is incorrect':19,'unclosed CDATA section':20,'error in processing external entity reference':21,'document is not standalone':22,'unexpected parser state - please send a bug report':23,'entity declared in parameter entity':24,'requested feature requires XML_DTD support in Expat':25,'cannot change setting once parsing has begun':26,'unbound prefix':27,'must not undeclare prefix':28,'incomplete markup in parameter entity':29,'XML declaration not well-formed':30,'text declaration not well-formed':31,'illegal character(s) in public id':32,'parser suspended':33,'parser not suspended':34,'parsing aborted':35,'parsing finished':36,'cannot suspend in external parameter entity':37,'reserved prefix (xml) must not be undeclared or bound to another namespace name':38,'reserved prefix (xmlns) must not be declared or undeclared':39,'prefix must not be bound to one of the reserved namespace names':40,'invalid argument':41,'a successful prior call to function XML_GetBuffer is required':42,'limit on input amplification factor (from DTD and entities) breached':43}\n\nmessages={1:'out of memory',2:'syntax error',3:'no element found',4:'not well-formed (invalid token)',5:'unclosed token',6:'partial character',7:'mismatched tag',8:'duplicate attribute',9:'junk after document element',10:'illegal parameter entity reference',11:'undefined entity',12:'recursive entity reference',13:'asynchronous entity',14:'reference to invalid character number',15:'reference to binary entity',16:'reference to external entity in attribute',17:'XML or text declaration not at start of entity',18:'unknown encoding',19:'encoding specified in XML declaration is incorrect',20:'unclosed CDATA section',21:'error in processing external entity reference',22:'document is not standalone',23:'unexpected parser state - please send a bug report',24:'entity declared in parameter entity',25:'requested feature requires XML_DTD support in Expat',26:'cannot change setting once parsing has begun',27:'unbound prefix',28:'must not undeclare prefix',29:'incomplete markup in parameter entity',30:'XML declaration not well-formed',31:'text declaration not well-formed',32:'illegal character(s) in public id',33:'parser suspended',34:'parser not suspended',35:'parsing aborted',36:'parsing finished',37:'cannot suspend in external parameter entity',38:'reserved prefix (xml) must not be undeclared or bound to another namespace name',39:'reserved prefix (xmlns) must not be declared or undeclared',40:'prefix must not be bound to one of the reserved namespace names',41:'invalid argument',42:'a successful prior call to function XML_GetBuffer is required',43:'limit on input amplification factor (from DTD and entities) breached'}\n", []], "pyexpat_utils": [".py", "", [], 1], "unittest.async_case": [".py", "import asyncio\nimport contextvars\nimport inspect\nimport warnings\n\nfrom.case import TestCase\n\n\nclass IsolatedAsyncioTestCase(TestCase):\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n loop_factory=None\n \n def __init__(self,methodName='runTest'):\n super().__init__(methodName)\n self._asyncioRunner=None\n self._asyncioTestContext=contextvars.copy_context()\n \n async def asyncSetUp(self):\n pass\n \n async def asyncTearDown(self):\n pass\n \n def addAsyncCleanup(self,func,/,*args,**kwargs):\n \n \n \n \n \n \n \n \n \n \n \n \n self.addCleanup(*(func,*args),**kwargs)\n \n async def enterAsyncContext(self,cm):\n ''\n\n\n\n \n \n \n cls=type(cm)\n try:\n enter=cls.__aenter__\n exit=cls.__aexit__\n except AttributeError:\n raise TypeError(f\"'{cls.__module__}.{cls.__qualname__}' object does \"\n f\"not support the asynchronous context manager protocol\"\n )from None\n result=await enter(cm)\n self.addAsyncCleanup(exit,cm,None,None,None)\n return result\n \n def _callSetUp(self):\n \n \n \n self._asyncioRunner.get_loop()\n self._asyncioTestContext.run(self.setUp)\n self._callAsync(self.asyncSetUp)\n \n def _callTestMethod(self,method):\n if self._callMaybeAsync(method)is not None:\n warnings.warn(f'It is deprecated to return a value that is not None from a '\n f'test case ({method})',DeprecationWarning,stacklevel=4)\n \n def _callTearDown(self):\n self._callAsync(self.asyncTearDown)\n self._asyncioTestContext.run(self.tearDown)\n \n def _callCleanup(self,function,*args,**kwargs):\n self._callMaybeAsync(function,*args,**kwargs)\n \n def _callAsync(self,func,/,*args,**kwargs):\n assert self._asyncioRunner is not None,'asyncio runner is not initialized'\n assert inspect.iscoroutinefunction(func),f'{func !r} is not an async function'\n return self._asyncioRunner.run(\n func(*args,**kwargs),\n context=self._asyncioTestContext\n )\n \n def _callMaybeAsync(self,func,/,*args,**kwargs):\n assert self._asyncioRunner is not None,'asyncio runner is not initialized'\n if inspect.iscoroutinefunction(func):\n return self._asyncioRunner.run(\n func(*args,**kwargs),\n context=self._asyncioTestContext,\n )\n else:\n return self._asyncioTestContext.run(func,*args,**kwargs)\n \n def _setupAsyncioRunner(self):\n assert self._asyncioRunner is None,'asyncio runner is already initialized'\n runner=asyncio.Runner(debug=True,loop_factory=self.loop_factory)\n self._asyncioRunner=runner\n \n def _tearDownAsyncioRunner(self):\n runner=self._asyncioRunner\n runner.close()\n \n def run(self,result=None):\n self._setupAsyncioRunner()\n try:\n return super().run(result)\n finally:\n self._tearDownAsyncioRunner()\n \n def debug(self):\n self._setupAsyncioRunner()\n super().debug()\n self._tearDownAsyncioRunner()\n \n def __del__(self):\n if self._asyncioRunner is not None:\n self._tearDownAsyncioRunner()\n", ["asyncio", "contextvars", "inspect", "unittest.case", "warnings"]], "unittest.case": [".py", "''\n\nimport sys\nimport functools\nimport difflib\nimport pprint\nimport re\nimport warnings\nimport collections\nimport contextlib\nimport traceback\nimport time\nimport types\n\nfrom. import result\nfrom.util import(strclass,safe_repr,_count_diff_all_purpose,\n_count_diff_hashable,_common_shorten_repr)\n\n__unittest=True\n\n_subtest_msg_sentinel=object()\n\nDIFF_OMITTED=('\\nDiff is %s characters long. '\n'Set self.maxDiff to None to see it.')\n\nclass SkipTest(Exception):\n ''\n\n\n\n\n \n \nclass _ShouldStop(Exception):\n ''\n\n \n \nclass _UnexpectedSuccess(Exception):\n ''\n\n \n \n \nclass _Outcome(object):\n def __init__(self,result=None):\n self.expecting_failure=False\n self.result=result\n self.result_supports_subtests=hasattr(result,\"addSubTest\")\n self.success=True\n self.expectedFailure=None\n \n @contextlib.contextmanager\n def testPartExecutor(self,test_case,subTest=False):\n old_success=self.success\n self.success=True\n try:\n yield\n except KeyboardInterrupt:\n raise\n except SkipTest as e:\n self.success=False\n _addSkip(self.result,test_case,str(e))\n except _ShouldStop:\n pass\n except:\n exc_info=sys.exc_info()\n if self.expecting_failure:\n self.expectedFailure=exc_info\n else:\n self.success=False\n if subTest:\n self.result.addSubTest(test_case.test_case,test_case,exc_info)\n else:\n _addError(self.result,test_case,exc_info)\n \n \n exc_info=None\n else:\n if subTest and self.success:\n self.result.addSubTest(test_case.test_case,test_case,None)\n finally:\n self.success=self.success and old_success\n \n \ndef _addSkip(result,test_case,reason):\n addSkip=getattr(result,'addSkip',None)\n if addSkip is not None:\n addSkip(test_case,reason)\n else:\n warnings.warn(\"TestResult has no addSkip method, skips not reported\",\n RuntimeWarning,2)\n result.addSuccess(test_case)\n \ndef _addError(result,test,exc_info):\n if result is not None and exc_info is not None:\n if issubclass(exc_info[0],test.failureException):\n result.addFailure(test,exc_info)\n else:\n result.addError(test,exc_info)\n \ndef _id(obj):\n return obj\n \n \ndef _enter_context(cm,addcleanup):\n\n\n cls=type(cm)\n try:\n enter=cls.__enter__\n exit=cls.__exit__\n except AttributeError:\n raise TypeError(f\"'{cls.__module__}.{cls.__qualname__}' object does \"\n f\"not support the context manager protocol\")from None\n result=enter(cm)\n addcleanup(exit,cm,None,None,None)\n return result\n \n \n_module_cleanups=[]\ndef addModuleCleanup(function,/,*args,**kwargs):\n ''\n \n _module_cleanups.append((function,args,kwargs))\n \ndef enterModuleContext(cm):\n ''\n return _enter_context(cm,addModuleCleanup)\n \n \ndef doModuleCleanups():\n ''\n \n exceptions=[]\n while _module_cleanups:\n function,args,kwargs=_module_cleanups.pop()\n try:\n function(*args,**kwargs)\n except Exception as exc:\n exceptions.append(exc)\n if exceptions:\n \n \n raise exceptions[0]\n \n \ndef skip(reason):\n ''\n\n \n def decorator(test_item):\n if not isinstance(test_item,type):\n @functools.wraps(test_item)\n def skip_wrapper(*args,**kwargs):\n raise SkipTest(reason)\n test_item=skip_wrapper\n \n test_item.__unittest_skip__=True\n test_item.__unittest_skip_why__=reason\n return test_item\n if isinstance(reason,types.FunctionType):\n test_item=reason\n reason=''\n return decorator(test_item)\n return decorator\n \ndef skipIf(condition,reason):\n ''\n\n \n if condition:\n return skip(reason)\n return _id\n \ndef skipUnless(condition,reason):\n ''\n\n \n if not condition:\n return skip(reason)\n return _id\n \ndef expectedFailure(test_item):\n test_item.__unittest_expecting_failure__=True\n return test_item\n \ndef _is_subtype(expected,basetype):\n if isinstance(expected,tuple):\n return all(_is_subtype(e,basetype)for e in expected)\n return isinstance(expected,type)and issubclass(expected,basetype)\n \nclass _BaseTestCaseContext:\n\n def __init__(self,test_case):\n self.test_case=test_case\n \n def _raiseFailure(self,standardMsg):\n msg=self.test_case._formatMessage(self.msg,standardMsg)\n raise self.test_case.failureException(msg)\n \nclass _AssertRaisesBaseContext(_BaseTestCaseContext):\n\n def __init__(self,expected,test_case,expected_regex=None):\n _BaseTestCaseContext.__init__(self,test_case)\n self.expected=expected\n self.test_case=test_case\n if expected_regex is not None:\n expected_regex=re.compile(expected_regex)\n self.expected_regex=expected_regex\n self.obj_name=None\n self.msg=None\n \n def handle(self,name,args,kwargs):\n ''\n\n\n\n\n \n try:\n if not _is_subtype(self.expected,self._base_type):\n raise TypeError('%s() arg 1 must be %s'%\n (name,self._base_type_str))\n if not args:\n self.msg=kwargs.pop('msg',None)\n if kwargs:\n raise TypeError('%r is an invalid keyword argument for '\n 'this function'%(next(iter(kwargs)),))\n return self\n \n callable_obj,*args=args\n try:\n self.obj_name=callable_obj.__name__\n except AttributeError:\n self.obj_name=str(callable_obj)\n with self:\n callable_obj(*args,**kwargs)\n finally:\n \n self=None\n \n \nclass _AssertRaisesContext(_AssertRaisesBaseContext):\n ''\n \n _base_type=BaseException\n _base_type_str='an exception type or tuple of exception types'\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,tb):\n if exc_type is None:\n try:\n exc_name=self.expected.__name__\n except AttributeError:\n exc_name=str(self.expected)\n if self.obj_name:\n self._raiseFailure(\"{} not raised by {}\".format(exc_name,\n self.obj_name))\n else:\n self._raiseFailure(\"{} not raised\".format(exc_name))\n else:\n traceback.clear_frames(tb)\n if not issubclass(exc_type,self.expected):\n \n return False\n \n self.exception=exc_value.with_traceback(None)\n if self.expected_regex is None:\n return True\n \n expected_regex=self.expected_regex\n if not expected_regex.search(str(exc_value)):\n self._raiseFailure('\"{}\" does not match \"{}\"'.format(\n expected_regex.pattern,str(exc_value)))\n return True\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \nclass _AssertWarnsContext(_AssertRaisesBaseContext):\n ''\n \n _base_type=Warning\n _base_type_str='a warning type or tuple of warning types'\n \n def __enter__(self):\n \n \n for v in list(sys.modules.values()):\n if getattr(v,'__warningregistry__',None):\n v.__warningregistry__={}\n self.warnings_manager=warnings.catch_warnings(record=True)\n self.warnings=self.warnings_manager.__enter__()\n warnings.simplefilter(\"always\",self.expected)\n return self\n \n def __exit__(self,exc_type,exc_value,tb):\n self.warnings_manager.__exit__(exc_type,exc_value,tb)\n if exc_type is not None:\n \n return\n try:\n exc_name=self.expected.__name__\n except AttributeError:\n exc_name=str(self.expected)\n first_matching=None\n for m in self.warnings:\n w=m.message\n if not isinstance(w,self.expected):\n continue\n if first_matching is None:\n first_matching=w\n if(self.expected_regex is not None and\n not self.expected_regex.search(str(w))):\n continue\n \n self.warning=w\n self.filename=m.filename\n self.lineno=m.lineno\n return\n \n if first_matching is not None:\n self._raiseFailure('\"{}\" does not match \"{}\"'.format(\n self.expected_regex.pattern,str(first_matching)))\n if self.obj_name:\n self._raiseFailure(\"{} not triggered by {}\".format(exc_name,\n self.obj_name))\n else:\n self._raiseFailure(\"{} not triggered\".format(exc_name))\n \n \nclass _AssertNotWarnsContext(_AssertWarnsContext):\n\n def __exit__(self,exc_type,exc_value,tb):\n self.warnings_manager.__exit__(exc_type,exc_value,tb)\n if exc_type is not None:\n \n return\n try:\n exc_name=self.expected.__name__\n except AttributeError:\n exc_name=str(self.expected)\n for m in self.warnings:\n w=m.message\n if isinstance(w,self.expected):\n self._raiseFailure(f\"{exc_name} triggered\")\n \n \nclass _OrderedChainMap(collections.ChainMap):\n def __iter__(self):\n seen=set()\n for mapping in self.maps:\n for k in mapping:\n if k not in seen:\n seen.add(k)\n yield k\n \n \nclass TestCase(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n failureException=AssertionError\n \n longMessage=True\n \n maxDiff=80 *8\n \n \n \n _diffThreshold=2 **16\n \n def __init_subclass__(cls,*args,**kwargs):\n \n cls._classSetupFailed=False\n cls._class_cleanups=[]\n super().__init_subclass__(*args,**kwargs)\n \n def __init__(self,methodName='runTest'):\n ''\n\n\n \n self._testMethodName=methodName\n self._outcome=None\n self._testMethodDoc='No test'\n try:\n testMethod=getattr(self,methodName)\n except AttributeError:\n if methodName !='runTest':\n \n \n raise ValueError(\"no such test method in %s: %s\"%\n (self.__class__,methodName))\n else:\n self._testMethodDoc=testMethod.__doc__\n self._cleanups=[]\n self._subtest=None\n \n \n \n \n self._type_equality_funcs={}\n self.addTypeEqualityFunc(dict,'assertDictEqual')\n self.addTypeEqualityFunc(list,'assertListEqual')\n self.addTypeEqualityFunc(tuple,'assertTupleEqual')\n self.addTypeEqualityFunc(set,'assertSetEqual')\n self.addTypeEqualityFunc(frozenset,'assertSetEqual')\n self.addTypeEqualityFunc(str,'assertMultiLineEqual')\n \n def addTypeEqualityFunc(self,typeobj,function):\n ''\n\n\n\n\n\n\n\n\n\n\n \n self._type_equality_funcs[typeobj]=function\n \n def addCleanup(self,function,/,*args,**kwargs):\n ''\n\n\n\n \n self._cleanups.append((function,args,kwargs))\n \n def enterContext(self,cm):\n ''\n\n\n\n \n return _enter_context(cm,self.addCleanup)\n \n @classmethod\n def addClassCleanup(cls,function,/,*args,**kwargs):\n ''\n \n cls._class_cleanups.append((function,args,kwargs))\n \n @classmethod\n def enterClassContext(cls,cm):\n ''\n return _enter_context(cm,cls.addClassCleanup)\n \n def setUp(self):\n ''\n pass\n \n def tearDown(self):\n ''\n pass\n \n @classmethod\n def setUpClass(cls):\n ''\n \n @classmethod\n def tearDownClass(cls):\n ''\n \n def countTestCases(self):\n return 1\n \n def defaultTestResult(self):\n return result.TestResult()\n \n def shortDescription(self):\n ''\n\n\n\n\n \n doc=self._testMethodDoc\n return doc.strip().split(\"\\n\")[0].strip()if doc else None\n \n \n def id(self):\n return \"%s.%s\"%(strclass(self.__class__),self._testMethodName)\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self._testMethodName ==other._testMethodName\n \n def __hash__(self):\n return hash((type(self),self._testMethodName))\n \n def __str__(self):\n return \"%s (%s.%s)\"%(self._testMethodName,strclass(self.__class__),self._testMethodName)\n \n def __repr__(self):\n return \"<%s testMethod=%s>\"%\\\n (strclass(self.__class__),self._testMethodName)\n \n @contextlib.contextmanager\n def subTest(self,msg=_subtest_msg_sentinel,**params):\n ''\n\n\n\n\n \n if self._outcome is None or not self._outcome.result_supports_subtests:\n yield\n return\n parent=self._subtest\n if parent is None:\n params_map=_OrderedChainMap(params)\n else:\n params_map=parent.params.new_child(params)\n self._subtest=_SubTest(self,msg,params_map)\n try:\n with self._outcome.testPartExecutor(self._subtest,subTest=True):\n yield\n if not self._outcome.success:\n result=self._outcome.result\n if result is not None and result.failfast:\n raise _ShouldStop\n elif self._outcome.expectedFailure:\n \n \n raise _ShouldStop\n finally:\n self._subtest=parent\n \n def _addExpectedFailure(self,result,exc_info):\n try:\n addExpectedFailure=result.addExpectedFailure\n except AttributeError:\n warnings.warn(\"TestResult has no addExpectedFailure method, reporting as passes\",\n RuntimeWarning)\n result.addSuccess(self)\n else:\n addExpectedFailure(self,exc_info)\n \n def _addUnexpectedSuccess(self,result):\n try:\n addUnexpectedSuccess=result.addUnexpectedSuccess\n except AttributeError:\n warnings.warn(\"TestResult has no addUnexpectedSuccess method, reporting as failure\",\n RuntimeWarning)\n \n \n try:\n raise _UnexpectedSuccess from None\n except _UnexpectedSuccess:\n result.addFailure(self,sys.exc_info())\n else:\n addUnexpectedSuccess(self)\n \n def _addDuration(self,result,elapsed):\n try:\n addDuration=result.addDuration\n except AttributeError:\n warnings.warn(\"TestResult has no addDuration method\",\n RuntimeWarning)\n else:\n addDuration(self,elapsed)\n \n def _callSetUp(self):\n self.setUp()\n \n def _callTestMethod(self,method):\n if method()is not None:\n warnings.warn(f'It is deprecated to return a value that is not None from a '\n f'test case ({method})',DeprecationWarning,stacklevel=3)\n \n def _callTearDown(self):\n self.tearDown()\n \n def _callCleanup(self,function,/,*args,**kwargs):\n function(*args,**kwargs)\n \n def run(self,result=None):\n if result is None:\n result=self.defaultTestResult()\n startTestRun=getattr(result,'startTestRun',None)\n stopTestRun=getattr(result,'stopTestRun',None)\n if startTestRun is not None:\n startTestRun()\n else:\n stopTestRun=None\n \n result.startTest(self)\n try:\n testMethod=getattr(self,self._testMethodName)\n if(getattr(self.__class__,\"__unittest_skip__\",False)or\n getattr(testMethod,\"__unittest_skip__\",False)):\n \n skip_why=(getattr(self.__class__,'__unittest_skip_why__','')\n or getattr(testMethod,'__unittest_skip_why__',''))\n _addSkip(result,self,skip_why)\n return result\n \n expecting_failure=(\n getattr(self,\"__unittest_expecting_failure__\",False)or\n getattr(testMethod,\"__unittest_expecting_failure__\",False)\n )\n outcome=_Outcome(result)\n start_time=time.perf_counter()\n try:\n self._outcome=outcome\n \n with outcome.testPartExecutor(self):\n self._callSetUp()\n if outcome.success:\n outcome.expecting_failure=expecting_failure\n with outcome.testPartExecutor(self):\n self._callTestMethod(testMethod)\n outcome.expecting_failure=False\n with outcome.testPartExecutor(self):\n self._callTearDown()\n self.doCleanups()\n self._addDuration(result,(time.perf_counter()-start_time))\n \n if outcome.success:\n if expecting_failure:\n if outcome.expectedFailure:\n self._addExpectedFailure(result,outcome.expectedFailure)\n else:\n self._addUnexpectedSuccess(result)\n else:\n result.addSuccess(self)\n return result\n finally:\n \n \n outcome.expectedFailure=None\n outcome=None\n \n \n self._outcome=None\n \n finally:\n result.stopTest(self)\n if stopTestRun is not None:\n stopTestRun()\n \n def doCleanups(self):\n ''\n \n outcome=self._outcome or _Outcome()\n while self._cleanups:\n function,args,kwargs=self._cleanups.pop()\n with outcome.testPartExecutor(self):\n self._callCleanup(function,*args,**kwargs)\n \n \n \n return outcome.success\n \n @classmethod\n def doClassCleanups(cls):\n ''\n \n cls.tearDown_exceptions=[]\n while cls._class_cleanups:\n function,args,kwargs=cls._class_cleanups.pop()\n try:\n function(*args,**kwargs)\n except Exception:\n cls.tearDown_exceptions.append(sys.exc_info())\n \n def __call__(self,*args,**kwds):\n return self.run(*args,**kwds)\n \n def debug(self):\n ''\n testMethod=getattr(self,self._testMethodName)\n if(getattr(self.__class__,\"__unittest_skip__\",False)or\n getattr(testMethod,\"__unittest_skip__\",False)):\n \n skip_why=(getattr(self.__class__,'__unittest_skip_why__','')\n or getattr(testMethod,'__unittest_skip_why__',''))\n raise SkipTest(skip_why)\n \n self._callSetUp()\n self._callTestMethod(testMethod)\n self._callTearDown()\n while self._cleanups:\n function,args,kwargs=self._cleanups.pop()\n self._callCleanup(function,*args,**kwargs)\n \n def skipTest(self,reason):\n ''\n raise SkipTest(reason)\n \n def fail(self,msg=None):\n ''\n raise self.failureException(msg)\n \n def assertFalse(self,expr,msg=None):\n ''\n if expr:\n msg=self._formatMessage(msg,\"%s is not false\"%safe_repr(expr))\n raise self.failureException(msg)\n \n def assertTrue(self,expr,msg=None):\n ''\n if not expr:\n msg=self._formatMessage(msg,\"%s is not true\"%safe_repr(expr))\n raise self.failureException(msg)\n \n def _formatMessage(self,msg,standardMsg):\n ''\n\n\n\n\n\n\n\n \n if not self.longMessage:\n return msg or standardMsg\n if msg is None:\n return standardMsg\n try:\n \n \n return '%s : %s'%(standardMsg,msg)\n except UnicodeDecodeError:\n return '%s : %s'%(safe_repr(standardMsg),safe_repr(msg))\n \n def assertRaises(self,expected_exception,*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertRaisesContext(expected_exception,self)\n try:\n return context.handle('assertRaises',args,kwargs)\n finally:\n \n context=None\n \n def assertWarns(self,expected_warning,*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertWarnsContext(expected_warning,self)\n return context.handle('assertWarns',args,kwargs)\n \n def _assertNotWarns(self,expected_warning,*args,**kwargs):\n ''\n context=_AssertNotWarnsContext(expected_warning,self)\n return context.handle('_assertNotWarns',args,kwargs)\n \n def assertLogs(self,logger=None,level=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n from._log import _AssertLogsContext\n return _AssertLogsContext(self,logger,level,no_logs=False)\n \n def assertNoLogs(self,logger=None,level=None):\n ''\n\n\n\n \n from._log import _AssertLogsContext\n return _AssertLogsContext(self,logger,level,no_logs=True)\n \n def _getAssertEqualityFunc(self,first,second):\n ''\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n if type(first)is type(second):\n asserter=self._type_equality_funcs.get(type(first))\n if asserter is not None:\n if isinstance(asserter,str):\n asserter=getattr(self,asserter)\n return asserter\n \n return self._baseAssertEqual\n \n def _baseAssertEqual(self,first,second,msg=None):\n ''\n if not first ==second:\n standardMsg='%s != %s'%_common_shorten_repr(first,second)\n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertEqual(self,first,second,msg=None):\n ''\n\n \n assertion_func=self._getAssertEqualityFunc(first,second)\n assertion_func(first,second,msg=msg)\n \n def assertNotEqual(self,first,second,msg=None):\n ''\n\n \n if not first !=second:\n msg=self._formatMessage(msg,'%s == %s'%(safe_repr(first),\n safe_repr(second)))\n raise self.failureException(msg)\n \n def assertAlmostEqual(self,first,second,places=None,msg=None,\n delta=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if first ==second:\n \n return\n if delta is not None and places is not None:\n raise TypeError(\"specify delta or places not both\")\n \n diff=abs(first -second)\n if delta is not None:\n if diff <=delta:\n return\n \n standardMsg='%s != %s within %s delta (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n safe_repr(delta),\n safe_repr(diff))\n else:\n if places is None:\n places=7\n \n if round(diff,places)==0:\n return\n \n standardMsg='%s != %s within %r places (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n places,\n safe_repr(diff))\n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertNotAlmostEqual(self,first,second,places=None,msg=None,\n delta=None):\n ''\n\n\n\n\n\n\n\n\n \n if delta is not None and places is not None:\n raise TypeError(\"specify delta or places not both\")\n diff=abs(first -second)\n if delta is not None:\n if not(first ==second)and diff >delta:\n return\n standardMsg='%s == %s within %s delta (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n safe_repr(delta),\n safe_repr(diff))\n else:\n if places is None:\n places=7\n if not(first ==second)and round(diff,places)!=0:\n return\n standardMsg='%s == %s within %r places'%(safe_repr(first),\n safe_repr(second),\n places)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertSequenceEqual(self,seq1,seq2,msg=None,seq_type=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if seq_type is not None:\n seq_type_name=seq_type.__name__\n if not isinstance(seq1,seq_type):\n raise self.failureException('First sequence is not a %s: %s'\n %(seq_type_name,safe_repr(seq1)))\n if not isinstance(seq2,seq_type):\n raise self.failureException('Second sequence is not a %s: %s'\n %(seq_type_name,safe_repr(seq2)))\n else:\n seq_type_name=\"sequence\"\n \n differing=None\n try:\n len1=len(seq1)\n except(TypeError,NotImplementedError):\n differing='First %s has no length. Non-sequence?'%(\n seq_type_name)\n \n if differing is None:\n try:\n len2=len(seq2)\n except(TypeError,NotImplementedError):\n differing='Second %s has no length. Non-sequence?'%(\n seq_type_name)\n \n if differing is None:\n if seq1 ==seq2:\n return\n \n differing='%ss differ: %s != %s\\n'%(\n (seq_type_name.capitalize(),)+\n _common_shorten_repr(seq1,seq2))\n \n for i in range(min(len1,len2)):\n try:\n item1=seq1[i]\n except(TypeError,IndexError,NotImplementedError):\n differing +=('\\nUnable to index element %d of first %s\\n'%\n (i,seq_type_name))\n break\n \n try:\n item2=seq2[i]\n except(TypeError,IndexError,NotImplementedError):\n differing +=('\\nUnable to index element %d of second %s\\n'%\n (i,seq_type_name))\n break\n \n if item1 !=item2:\n differing +=('\\nFirst differing element %d:\\n%s\\n%s\\n'%\n ((i,)+_common_shorten_repr(item1,item2)))\n break\n else:\n if(len1 ==len2 and seq_type is None and\n type(seq1)!=type(seq2)):\n \n return\n \n if len1 >len2:\n differing +=('\\nFirst %s contains %d additional '\n 'elements.\\n'%(seq_type_name,len1 -len2))\n try:\n differing +=('First extra element %d:\\n%s\\n'%\n (len2,safe_repr(seq1[len2])))\n except(TypeError,IndexError,NotImplementedError):\n differing +=('Unable to index element %d '\n 'of first %s\\n'%(len2,seq_type_name))\n elif len1 self._diffThreshold or\n len(second)>self._diffThreshold):\n self._baseAssertEqual(first,second,msg)\n \n \n \n \n \n first_presplit=first\n second_presplit=second\n if first and second:\n if first[-1]!='\\n'or second[-1]!='\\n':\n first_presplit +='\\n'\n second_presplit +='\\n'\n elif second and second[-1]!='\\n':\n second_presplit +='\\n'\n elif first and first[-1]!='\\n':\n first_presplit +='\\n'\n \n firstlines=first_presplit.splitlines(keepends=True)\n secondlines=second_presplit.splitlines(keepends=True)\n \n \n standardMsg='%s != %s'%_common_shorten_repr(first,second)\n diff='\\n'+''.join(difflib.ndiff(firstlines,secondlines))\n standardMsg=self._truncateMessage(standardMsg,diff)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertLess(self,a,b,msg=None):\n ''\n if not a b:\n standardMsg='%s not greater than %s'%(safe_repr(a),safe_repr(b))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertGreaterEqual(self,a,b,msg=None):\n ''\n if not a >=b:\n standardMsg='%s not greater than or equal to %s'%(safe_repr(a),safe_repr(b))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsNone(self,obj,msg=None):\n ''\n if obj is not None:\n standardMsg='%s is not None'%(safe_repr(obj),)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsNotNone(self,obj,msg=None):\n ''\n if obj is None:\n standardMsg='unexpectedly None'\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsInstance(self,obj,cls,msg=None):\n ''\n \n if not isinstance(obj,cls):\n standardMsg='%s is not an instance of %r'%(safe_repr(obj),cls)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertNotIsInstance(self,obj,cls,msg=None):\n ''\n if isinstance(obj,cls):\n standardMsg='%s is an instance of %r'%(safe_repr(obj),cls)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertRaisesRegex(self,expected_exception,expected_regex,\n *args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n context=_AssertRaisesContext(expected_exception,self,expected_regex)\n return context.handle('assertRaisesRegex',args,kwargs)\n \n def assertWarnsRegex(self,expected_warning,expected_regex,\n *args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertWarnsContext(expected_warning,self,expected_regex)\n return context.handle('assertWarnsRegex',args,kwargs)\n \n def assertRegex(self,text,expected_regex,msg=None):\n ''\n if isinstance(expected_regex,(str,bytes)):\n assert expected_regex,\"expected_regex must not be empty.\"\n expected_regex=re.compile(expected_regex)\n if not expected_regex.search(text):\n standardMsg=\"Regex didn't match: %r not found in %r\"%(\n expected_regex.pattern,text)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertNotRegex(self,text,unexpected_regex,msg=None):\n ''\n if isinstance(unexpected_regex,(str,bytes)):\n unexpected_regex=re.compile(unexpected_regex)\n match=unexpected_regex.search(text)\n if match:\n standardMsg='Regex matched: %r matches %r in %r'%(\n text[match.start():match.end()],\n unexpected_regex.pattern,\n text)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n \n \nclass FunctionTestCase(TestCase):\n ''\n\n\n\n\n\n \n \n def __init__(self,testFunc,setUp=None,tearDown=None,description=None):\n super(FunctionTestCase,self).__init__()\n self._setUpFunc=setUp\n self._tearDownFunc=tearDown\n self._testFunc=testFunc\n self._description=description\n \n def setUp(self):\n if self._setUpFunc is not None:\n self._setUpFunc()\n \n def tearDown(self):\n if self._tearDownFunc is not None:\n self._tearDownFunc()\n \n def runTest(self):\n self._testFunc()\n \n def id(self):\n return self._testFunc.__name__\n \n def __eq__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n \n return self._setUpFunc ==other._setUpFunc and\\\n self._tearDownFunc ==other._tearDownFunc and\\\n self._testFunc ==other._testFunc and\\\n self._description ==other._description\n \n def __hash__(self):\n return hash((type(self),self._setUpFunc,self._tearDownFunc,\n self._testFunc,self._description))\n \n def __str__(self):\n return \"%s (%s)\"%(strclass(self.__class__),\n self._testFunc.__name__)\n \n def __repr__(self):\n return \"<%s tec=%s>\"%(strclass(self.__class__),\n self._testFunc)\n \n def shortDescription(self):\n if self._description is not None:\n return self._description\n doc=self._testFunc.__doc__\n return doc and doc.split(\"\\n\")[0].strip()or None\n \n \nclass _SubTest(TestCase):\n\n def __init__(self,test_case,message,params):\n super().__init__()\n self._message=message\n self.test_case=test_case\n self.params=params\n self.failureException=test_case.failureException\n \n def runTest(self):\n raise NotImplementedError(\"subtests cannot be run directly\")\n \n def _subDescription(self):\n parts=[]\n if self._message is not _subtest_msg_sentinel:\n parts.append(\"[{}]\".format(self._message))\n if self.params:\n params_desc=', '.join(\n \"{}={!r}\".format(k,v)\n for(k,v)in self.params.items())\n parts.append(\"({})\".format(params_desc))\n return \" \".join(parts)or '()'\n \n def id(self):\n return \"{} {}\".format(self.test_case.id(),self._subDescription())\n \n def shortDescription(self):\n ''\n\n \n return self.test_case.shortDescription()\n \n def __str__(self):\n return \"{} {}\".format(self.test_case,self._subDescription())\n", ["collections", "contextlib", "difflib", "functools", "pprint", "re", "sys", "time", "traceback", "types", "unittest", "unittest._log", "unittest.result", "unittest.util", "warnings"]], "unittest.loader": [".py", "''\n\nimport os\nimport re\nimport sys\nimport traceback\nimport types\nimport functools\n\nfrom fnmatch import fnmatch,fnmatchcase\n\nfrom. import case,suite,util\n\n__unittest=True\n\n\n\n\nVALID_MODULE_NAME=re.compile(r'[_a-z]\\w*\\.py$',re.IGNORECASE)\n\n\nclass _FailedTest(case.TestCase):\n _testMethodName=None\n \n def __init__(self,method_name,exception):\n self._exception=exception\n super(_FailedTest,self).__init__(method_name)\n \n def __getattr__(self,name):\n if name !=self._testMethodName:\n return super(_FailedTest,self).__getattr__(name)\n def testFailure():\n raise self._exception\n return testFailure\n \n \ndef _make_failed_import_test(name,suiteClass):\n message='Failed to import test module: %s\\n%s'%(\n name,traceback.format_exc())\n return _make_failed_test(name,ImportError(message),suiteClass,message)\n \ndef _make_failed_load_tests(name,exception,suiteClass):\n message='Failed to call load_tests:\\n%s'%(traceback.format_exc(),)\n return _make_failed_test(\n name,exception,suiteClass,message)\n \ndef _make_failed_test(methodname,exception,suiteClass,message):\n test=_FailedTest(methodname,exception)\n return suiteClass((test,)),message\n \ndef _make_skipped_test(methodname,exception,suiteClass):\n @case.skip(str(exception))\n def testSkipped(self):\n pass\n attrs={methodname:testSkipped}\n TestClass=type(\"ModuleSkipped\",(case.TestCase,),attrs)\n return suiteClass((TestClass(methodname),))\n \ndef _splitext(path):\n return os.path.splitext(path)[0]\n \n \nclass TestLoader(object):\n ''\n\n\n \n testMethodPrefix='test'\n sortTestMethodsUsing=staticmethod(util.three_way_cmp)\n testNamePatterns=None\n suiteClass=suite.TestSuite\n _top_level_dir=None\n \n def __init__(self):\n super(TestLoader,self).__init__()\n self.errors=[]\n \n \n self._loading_packages=set()\n \n def loadTestsFromTestCase(self,testCaseClass):\n ''\n if issubclass(testCaseClass,suite.TestSuite):\n raise TypeError(\"Test cases should not be derived from \"\n \"TestSuite. Maybe you meant to derive from \"\n \"TestCase?\")\n if testCaseClass in(case.TestCase,case.FunctionTestCase):\n \n testCaseNames=[]\n else:\n testCaseNames=self.getTestCaseNames(testCaseClass)\n if not testCaseNames and hasattr(testCaseClass,'runTest'):\n testCaseNames=['runTest']\n loaded_suite=self.suiteClass(map(testCaseClass,testCaseNames))\n return loaded_suite\n \n def loadTestsFromModule(self,module,*,pattern=None):\n ''\n tests=[]\n for name in dir(module):\n obj=getattr(module,name)\n if(\n isinstance(obj,type)\n and issubclass(obj,case.TestCase)\n and obj not in(case.TestCase,case.FunctionTestCase)\n ):\n tests.append(self.loadTestsFromTestCase(obj))\n \n load_tests=getattr(module,'load_tests',None)\n tests=self.suiteClass(tests)\n if load_tests is not None:\n try:\n return load_tests(self,tests,pattern)\n except Exception as e:\n error_case,error_message=_make_failed_load_tests(\n module.__name__,e,self.suiteClass)\n self.errors.append(error_message)\n return error_case\n return tests\n \n def loadTestsFromName(self,name,module=None):\n ''\n\n\n\n\n\n\n \n parts=name.split('.')\n error_case,error_message=None,None\n if module is None:\n parts_copy=parts[:]\n while parts_copy:\n try:\n module_name='.'.join(parts_copy)\n module=__import__(module_name)\n break\n except ImportError:\n next_attribute=parts_copy.pop()\n \n error_case,error_message=_make_failed_import_test(\n next_attribute,self.suiteClass)\n if not parts_copy:\n \n self.errors.append(error_message)\n return error_case\n parts=parts[1:]\n obj=module\n for part in parts:\n try:\n parent,obj=obj,getattr(obj,part)\n except AttributeError as e:\n \n if(getattr(obj,'__path__',None)is not None\n and error_case is not None):\n \n \n \n \n \n self.errors.append(error_message)\n return error_case\n else:\n \n error_case,error_message=_make_failed_test(\n part,e,self.suiteClass,\n 'Failed to access attribute:\\n%s'%(\n traceback.format_exc(),))\n self.errors.append(error_message)\n return error_case\n \n if isinstance(obj,types.ModuleType):\n return self.loadTestsFromModule(obj)\n elif(\n isinstance(obj,type)\n and issubclass(obj,case.TestCase)\n and obj not in(case.TestCase,case.FunctionTestCase)\n ):\n return self.loadTestsFromTestCase(obj)\n elif(isinstance(obj,types.FunctionType)and\n isinstance(parent,type)and\n issubclass(parent,case.TestCase)):\n name=parts[-1]\n inst=parent(name)\n \n if not isinstance(getattr(inst,name),types.FunctionType):\n return self.suiteClass([inst])\n elif isinstance(obj,suite.TestSuite):\n return obj\n if callable(obj):\n test=obj()\n if isinstance(test,suite.TestSuite):\n return test\n elif isinstance(test,case.TestCase):\n return self.suiteClass([test])\n else:\n raise TypeError(\"calling %s returned %s, not a test\"%\n (obj,test))\n else:\n raise TypeError(\"don't know how to make test from: %s\"%obj)\n \n def loadTestsFromNames(self,names,module=None):\n ''\n\n \n suites=[self.loadTestsFromName(name,module)for name in names]\n return self.suiteClass(suites)\n \n def getTestCaseNames(self,testCaseClass):\n ''\n \n def shouldIncludeMethod(attrname):\n if not attrname.startswith(self.testMethodPrefix):\n return False\n testFunc=getattr(testCaseClass,attrname)\n if not callable(testFunc):\n return False\n fullName=f'%s.%s.%s'%(\n testCaseClass.__module__,testCaseClass.__qualname__,attrname\n )\n return self.testNamePatterns is None or\\\n any(fnmatchcase(fullName,pattern)for pattern in self.testNamePatterns)\n testFnNames=list(filter(shouldIncludeMethod,dir(testCaseClass)))\n if self.sortTestMethodsUsing:\n testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))\n return testFnNames\n \n def discover(self,start_dir,pattern='test*.py',top_level_dir=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n original_top_level_dir=self._top_level_dir\n set_implicit_top=False\n if top_level_dir is None and self._top_level_dir is not None:\n \n top_level_dir=self._top_level_dir\n elif top_level_dir is None:\n set_implicit_top=True\n top_level_dir=start_dir\n \n top_level_dir=os.path.abspath(top_level_dir)\n \n if not top_level_dir in sys.path:\n \n \n \n \n sys.path.insert(0,top_level_dir)\n self._top_level_dir=top_level_dir\n \n is_not_importable=False\n if os.path.isdir(os.path.abspath(start_dir)):\n start_dir=os.path.abspath(start_dir)\n if start_dir !=top_level_dir:\n is_not_importable=not os.path.isfile(os.path.join(start_dir,'__init__.py'))\n else:\n \n try:\n __import__(start_dir)\n except ImportError:\n is_not_importable=True\n else:\n the_module=sys.modules[start_dir]\n top_part=start_dir.split('.')[0]\n try:\n start_dir=os.path.abspath(\n os.path.dirname((the_module.__file__)))\n except AttributeError:\n if the_module.__name__ in sys.builtin_module_names:\n \n raise TypeError('Can not use builtin modules '\n 'as dotted module names')from None\n else:\n raise TypeError(\n f\"don't know how to discover from {the_module !r}\"\n )from None\n \n if set_implicit_top:\n self._top_level_dir=self._get_directory_containing_module(top_part)\n sys.path.remove(top_level_dir)\n \n if is_not_importable:\n raise ImportError('Start directory is not importable: %r'%start_dir)\n \n tests=list(self._find_tests(start_dir,pattern))\n self._top_level_dir=original_top_level_dir\n return self.suiteClass(tests)\n \n def _get_directory_containing_module(self,module_name):\n module=sys.modules[module_name]\n full_path=os.path.abspath(module.__file__)\n \n if os.path.basename(full_path).lower().startswith('__init__.py'):\n return os.path.dirname(os.path.dirname(full_path))\n else:\n \n \n \n return os.path.dirname(full_path)\n \n def _get_name_from_path(self,path):\n if path ==self._top_level_dir:\n return '.'\n path=_splitext(os.path.normpath(path))\n \n _relpath=os.path.relpath(path,self._top_level_dir)\n assert not os.path.isabs(_relpath),\"Path must be within the project\"\n assert not _relpath.startswith('..'),\"Path must be within the project\"\n \n name=_relpath.replace(os.path.sep,'.')\n return name\n \n def _get_module_from_name(self,name):\n __import__(name)\n return sys.modules[name]\n \n def _match_path(self,path,full_path,pattern):\n \n return fnmatch(path,pattern)\n \n def _find_tests(self,start_dir,pattern):\n ''\n \n name=self._get_name_from_path(start_dir)\n \n \n if name !='.'and name not in self._loading_packages:\n \n \n tests,should_recurse=self._find_test_path(start_dir,pattern)\n if tests is not None:\n yield tests\n if not should_recurse:\n \n \n return\n \n paths=sorted(os.listdir(start_dir))\n for path in paths:\n full_path=os.path.join(start_dir,path)\n tests,should_recurse=self._find_test_path(full_path,pattern)\n if tests is not None:\n yield tests\n if should_recurse:\n \n name=self._get_name_from_path(full_path)\n self._loading_packages.add(name)\n try:\n yield from self._find_tests(full_path,pattern)\n finally:\n self._loading_packages.discard(name)\n \n def _find_test_path(self,full_path,pattern):\n ''\n\n\n\n\n\n \n basename=os.path.basename(full_path)\n if os.path.isfile(full_path):\n if not VALID_MODULE_NAME.match(basename):\n \n return None,False\n if not self._match_path(basename,full_path,pattern):\n return None,False\n \n name=self._get_name_from_path(full_path)\n try:\n module=self._get_module_from_name(name)\n except case.SkipTest as e:\n return _make_skipped_test(name,e,self.suiteClass),False\n except:\n error_case,error_message=\\\n _make_failed_import_test(name,self.suiteClass)\n self.errors.append(error_message)\n return error_case,False\n else:\n mod_file=os.path.abspath(\n getattr(module,'__file__',full_path))\n realpath=_splitext(\n os.path.realpath(mod_file))\n fullpath_noext=_splitext(\n os.path.realpath(full_path))\n if realpath.lower()!=fullpath_noext.lower():\n module_dir=os.path.dirname(realpath)\n mod_name=_splitext(\n os.path.basename(full_path))\n expected_dir=os.path.dirname(full_path)\n msg=(\"%r module incorrectly imported from %r. Expected \"\n \"%r. Is this module globally installed?\")\n raise ImportError(\n msg %(mod_name,module_dir,expected_dir))\n return self.loadTestsFromModule(module,pattern=pattern),False\n elif os.path.isdir(full_path):\n if not os.path.isfile(os.path.join(full_path,'__init__.py')):\n return None,False\n \n load_tests=None\n tests=None\n name=self._get_name_from_path(full_path)\n try:\n package=self._get_module_from_name(name)\n except case.SkipTest as e:\n return _make_skipped_test(name,e,self.suiteClass),False\n except:\n error_case,error_message=\\\n _make_failed_import_test(name,self.suiteClass)\n self.errors.append(error_message)\n return error_case,False\n else:\n load_tests=getattr(package,'load_tests',None)\n \n self._loading_packages.add(name)\n try:\n tests=self.loadTestsFromModule(package,pattern=pattern)\n if load_tests is not None:\n \n return tests,False\n return tests,True\n finally:\n self._loading_packages.discard(name)\n else:\n return None,False\n \n \ndefaultTestLoader=TestLoader()\n", ["fnmatch", "functools", "os", "re", "sys", "traceback", "types", "unittest", "unittest.case", "unittest.suite", "unittest.util"]], "unittest.main": [".py", "''\n\nimport sys\nimport argparse\nimport os\n\nfrom. import loader,runner\nfrom.signals import installHandler\n\n__unittest=True\n_NO_TESTS_EXITCODE=5\n\nMAIN_EXAMPLES=\"\"\"\\\nExamples:\n %(prog)s test_module - run tests from test_module\n %(prog)s module.TestClass - run tests from module.TestClass\n %(prog)s module.Class.test_method - run specified test method\n %(prog)s path/to/test_file.py - run tests from test_file.py\n\"\"\"\n\nMODULE_EXAMPLES=\"\"\"\\\nExamples:\n %(prog)s - run default set of tests\n %(prog)s MyTestSuite - run suite 'MyTestSuite'\n %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething\n %(prog)s MyTestCase - run all 'test*' test methods\n in MyTestCase\n\"\"\"\n\ndef _convert_name(name):\n\n\n\n\n if os.path.isfile(name)and name.lower().endswith('.py'):\n if os.path.isabs(name):\n rel_path=os.path.relpath(name,os.getcwd())\n if os.path.isabs(rel_path)or rel_path.startswith(os.pardir):\n return name\n name=rel_path\n \n \n return os.path.normpath(name)[:-3].replace('\\\\','.').replace('/','.')\n return name\n \ndef _convert_names(names):\n return[_convert_name(name)for name in names]\n \n \ndef _convert_select_pattern(pattern):\n if not '*'in pattern:\n pattern='*%s*'%pattern\n return pattern\n \n \nclass TestProgram(object):\n ''\n\n \n \n module=None\n verbosity=1\n failfast=catchbreak=buffer=progName=warnings=testNamePatterns=None\n _discovery_parser=None\n \n def __init__(self,module='__main__',defaultTest=None,argv=None,\n testRunner=None,testLoader=loader.defaultTestLoader,\n exit=True,verbosity=1,failfast=None,catchbreak=None,\n buffer=None,warnings=None,*,tb_locals=False,\n durations=None):\n if isinstance(module,str):\n self.module=__import__(module)\n for part in module.split('.')[1:]:\n self.module=getattr(self.module,part)\n else:\n self.module=module\n if argv is None:\n argv=sys.argv\n \n self.exit=exit\n self.failfast=failfast\n self.catchbreak=catchbreak\n self.verbosity=verbosity\n self.buffer=buffer\n self.tb_locals=tb_locals\n self.durations=durations\n if warnings is None and not sys.warnoptions:\n \n \n \n self.warnings='default'\n else:\n \n \n \n \n \n self.warnings=warnings\n self.defaultTest=defaultTest\n self.testRunner=testRunner\n self.testLoader=testLoader\n self.progName=os.path.basename(argv[0])\n self.parseArgs(argv)\n self.runTests()\n \n def _print_help(self,*args,**kwargs):\n if self.module is None:\n print(self._main_parser.format_help())\n print(MAIN_EXAMPLES %{'prog':self.progName})\n self._discovery_parser.print_help()\n else:\n print(self._main_parser.format_help())\n print(MODULE_EXAMPLES %{'prog':self.progName})\n \n def parseArgs(self,argv):\n self._initArgParsers()\n if self.module is None:\n if len(argv)>1 and argv[1].lower()=='discover':\n self._do_discovery(argv[2:])\n return\n self._main_parser.parse_args(argv[1:],self)\n if not self.tests:\n \n \n self._do_discovery([])\n return\n else:\n self._main_parser.parse_args(argv[1:],self)\n \n if self.tests:\n self.testNames=_convert_names(self.tests)\n if __name__ =='__main__':\n \n self.module=None\n elif self.defaultTest is None:\n \n self.testNames=None\n elif isinstance(self.defaultTest,str):\n self.testNames=(self.defaultTest,)\n else:\n self.testNames=list(self.defaultTest)\n self.createTests()\n \n def createTests(self,from_discovery=False,Loader=None):\n if self.testNamePatterns:\n self.testLoader.testNamePatterns=self.testNamePatterns\n if from_discovery:\n loader=self.testLoader if Loader is None else Loader()\n self.test=loader.discover(self.start,self.pattern,self.top)\n elif self.testNames is None:\n self.test=self.testLoader.loadTestsFromModule(self.module)\n else:\n self.test=self.testLoader.loadTestsFromNames(self.testNames,\n self.module)\n \n def _initArgParsers(self):\n parent_parser=self._getParentArgParser()\n self._main_parser=self._getMainArgParser(parent_parser)\n self._discovery_parser=self._getDiscoveryArgParser(parent_parser)\n \n def _getParentArgParser(self):\n parser=argparse.ArgumentParser(add_help=False)\n \n parser.add_argument('-v','--verbose',dest='verbosity',\n action='store_const',const=2,\n help='Verbose output')\n parser.add_argument('-q','--quiet',dest='verbosity',\n action='store_const',const=0,\n help='Quiet output')\n parser.add_argument('--locals',dest='tb_locals',\n action='store_true',\n help='Show local variables in tracebacks')\n parser.add_argument('--durations',dest='durations',type=int,\n default=None,metavar=\"N\",\n help='Show the N slowest test cases (N=0 for all)')\n if self.failfast is None:\n parser.add_argument('-f','--failfast',dest='failfast',\n action='store_true',\n help='Stop on first fail or error')\n self.failfast=False\n if self.catchbreak is None:\n parser.add_argument('-c','--catch',dest='catchbreak',\n action='store_true',\n help='Catch Ctrl-C and display results so far')\n self.catchbreak=False\n if self.buffer is None:\n parser.add_argument('-b','--buffer',dest='buffer',\n action='store_true',\n help='Buffer stdout and stderr during tests')\n self.buffer=False\n if self.testNamePatterns is None:\n parser.add_argument('-k',dest='testNamePatterns',\n action='append',type=_convert_select_pattern,\n help='Only run tests which match the given substring')\n self.testNamePatterns=[]\n \n return parser\n \n def _getMainArgParser(self,parent):\n parser=argparse.ArgumentParser(parents=[parent])\n parser.prog=self.progName\n parser.print_help=self._print_help\n \n parser.add_argument('tests',nargs='*',\n help='a list of any number of test modules, '\n 'classes and test methods.')\n \n return parser\n \n def _getDiscoveryArgParser(self,parent):\n parser=argparse.ArgumentParser(parents=[parent])\n parser.prog='%s discover'%self.progName\n parser.epilog=('For test discovery all test modules must be '\n 'importable from the top level directory of the '\n 'project.')\n \n parser.add_argument('-s','--start-directory',dest='start',\n help=\"Directory to start discovery ('.' default)\")\n parser.add_argument('-p','--pattern',dest='pattern',\n help=\"Pattern to match tests ('test*.py' default)\")\n parser.add_argument('-t','--top-level-directory',dest='top',\n help='Top level directory of project (defaults to '\n 'start directory)')\n for arg in('start','pattern','top'):\n parser.add_argument(arg,nargs='?',\n default=argparse.SUPPRESS,\n help=argparse.SUPPRESS)\n \n return parser\n \n def _do_discovery(self,argv,Loader=None):\n self.start='.'\n self.pattern='test*.py'\n self.top=None\n if argv is not None:\n \n if self._discovery_parser is None:\n \n self._initArgParsers()\n self._discovery_parser.parse_args(argv,self)\n \n self.createTests(from_discovery=True,Loader=Loader)\n \n def runTests(self):\n if self.catchbreak:\n installHandler()\n if self.testRunner is None:\n self.testRunner=runner.TextTestRunner\n if isinstance(self.testRunner,type):\n try:\n try:\n testRunner=self.testRunner(verbosity=self.verbosity,\n failfast=self.failfast,\n buffer=self.buffer,\n warnings=self.warnings,\n tb_locals=self.tb_locals,\n durations=self.durations)\n except TypeError:\n \n testRunner=self.testRunner(verbosity=self.verbosity,\n failfast=self.failfast,\n buffer=self.buffer,\n warnings=self.warnings)\n except TypeError:\n \n testRunner=self.testRunner()\n else:\n \n testRunner=self.testRunner\n self.result=testRunner.run(self.test)\n if self.exit:\n if self.result.testsRun ==0 and len(self.result.skipped)==0:\n sys.exit(_NO_TESTS_EXITCODE)\n elif self.result.wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n \n \nmain=TestProgram\n", ["argparse", "os", "sys", "unittest", "unittest.loader", "unittest.runner", "unittest.signals"]], "unittest.mock": [".py", "\n\n\n\n\n\n__all__=(\n'Mock',\n'MagicMock',\n'patch',\n'sentinel',\n'DEFAULT',\n'ANY',\n'call',\n'create_autospec',\n'AsyncMock',\n'ThreadingMock',\n'FILTER_DIR',\n'NonCallableMock',\n'NonCallableMagicMock',\n'mock_open',\n'PropertyMock',\n'seal',\n)\n\n\nimport asyncio\nimport contextlib\nimport io\nimport inspect\nimport pprint\nimport sys\nimport builtins\nimport pkgutil\nfrom asyncio import iscoroutinefunction\nimport threading\nfrom types import CodeType,ModuleType,MethodType\nfrom unittest.util import safe_repr\nfrom functools import wraps,partial\nfrom threading import RLock\n\n\nclass InvalidSpecError(Exception):\n ''\n \n \n_builtins={name for name in dir(builtins)if not name.startswith('_')}\n\nFILTER_DIR=True\n\n\n\n_safe_super=super\n\ndef _is_async_obj(obj):\n if _is_instance_mock(obj)and not isinstance(obj,AsyncMock):\n return False\n if hasattr(obj,'__func__'):\n obj=getattr(obj,'__func__')\n return iscoroutinefunction(obj)or inspect.isawaitable(obj)\n \n \ndef _is_async_func(func):\n if getattr(func,'__code__',None):\n return iscoroutinefunction(func)\n else:\n return False\n \n \ndef _is_instance_mock(obj):\n\n\n return issubclass(type(obj),NonCallableMock)\n \n \ndef _is_exception(obj):\n return(\n isinstance(obj,BaseException)or\n isinstance(obj,type)and issubclass(obj,BaseException)\n )\n \n \ndef _extract_mock(obj):\n\n\n if isinstance(obj,FunctionTypes)and hasattr(obj,'mock'):\n return obj.mock\n else:\n return obj\n \n \ndef _get_signature_object(func,as_instance,eat_self):\n ''\n\n\n\n \n if isinstance(func,type)and not as_instance:\n \n func=func.__init__\n \n eat_self=True\n elif isinstance(func,(classmethod,staticmethod)):\n if isinstance(func,classmethod):\n \n eat_self=True\n \n func=func.__func__\n elif not isinstance(func,FunctionTypes):\n \n \n try:\n func=func.__call__\n except AttributeError:\n return None\n if eat_self:\n sig_func=partial(func,None)\n else:\n sig_func=func\n try:\n return func,inspect.signature(sig_func)\n except ValueError:\n \n return None\n \n \ndef _check_signature(func,mock,skipfirst,instance=False):\n sig=_get_signature_object(func,instance,skipfirst)\n if sig is None:\n return\n func,sig=sig\n def checksig(self,/,*args,**kwargs):\n sig.bind(*args,**kwargs)\n _copy_func_details(func,checksig)\n type(mock)._mock_check_sig=checksig\n type(mock).__signature__=sig\n \n \ndef _copy_func_details(func,funcopy):\n\n\n for attribute in(\n '__name__','__doc__','__text_signature__',\n '__module__','__defaults__','__kwdefaults__',\n ):\n try:\n setattr(funcopy,attribute,getattr(func,attribute))\n except AttributeError:\n pass\n \n \ndef _callable(obj):\n if isinstance(obj,type):\n return True\n if isinstance(obj,(staticmethod,classmethod,MethodType)):\n return _callable(obj.__func__)\n if getattr(obj,'__call__',None)is not None:\n return True\n return False\n \n \ndef _is_list(obj):\n\n\n return type(obj)in(list,tuple)\n \n \ndef _instance_callable(obj):\n ''\n \n if not isinstance(obj,type):\n \n return getattr(obj,'__call__',None)is not None\n \n \n \n for base in(obj,)+obj.__mro__:\n if base.__dict__.get('__call__')is not None:\n return True\n return False\n \n \ndef _set_signature(mock,original,instance=False):\n\n\n\n\n skipfirst=isinstance(original,type)\n result=_get_signature_object(original,instance,skipfirst)\n if result is None:\n return mock\n func,sig=result\n def checksig(*args,**kwargs):\n sig.bind(*args,**kwargs)\n _copy_func_details(func,checksig)\n \n name=original.__name__\n if not name.isidentifier():\n name='funcopy'\n context={'_checksig_':checksig,'mock':mock}\n src=\"\"\"def %s(*args, **kwargs):\n _checksig_(*args, **kwargs)\n return mock(*args, **kwargs)\"\"\"%name\n exec(src,context)\n funcopy=context[name]\n _setup_func(funcopy,mock,sig)\n return funcopy\n \ndef _set_async_signature(mock,original,instance=False,is_async_mock=False):\n\n\n\n\n skipfirst=isinstance(original,type)\n func,sig=_get_signature_object(original,instance,skipfirst)\n def checksig(*args,**kwargs):\n sig.bind(*args,**kwargs)\n _copy_func_details(func,checksig)\n \n name=original.__name__\n context={'_checksig_':checksig,'mock':mock}\n src=\"\"\"async def %s(*args, **kwargs):\n _checksig_(*args, **kwargs)\n return await mock(*args, **kwargs)\"\"\"%name\n exec(src,context)\n funcopy=context[name]\n _setup_func(funcopy,mock,sig)\n _setup_async_mock(funcopy)\n return funcopy\n \n \ndef _setup_func(funcopy,mock,sig):\n funcopy.mock=mock\n \n def assert_called_with(*args,**kwargs):\n return mock.assert_called_with(*args,**kwargs)\n def assert_called(*args,**kwargs):\n return mock.assert_called(*args,**kwargs)\n def assert_not_called(*args,**kwargs):\n return mock.assert_not_called(*args,**kwargs)\n def assert_called_once(*args,**kwargs):\n return mock.assert_called_once(*args,**kwargs)\n def assert_called_once_with(*args,**kwargs):\n return mock.assert_called_once_with(*args,**kwargs)\n def assert_has_calls(*args,**kwargs):\n return mock.assert_has_calls(*args,**kwargs)\n def assert_any_call(*args,**kwargs):\n return mock.assert_any_call(*args,**kwargs)\n def reset_mock():\n funcopy.method_calls=_CallList()\n funcopy.mock_calls=_CallList()\n mock.reset_mock()\n ret=funcopy.return_value\n if _is_instance_mock(ret)and not ret is mock:\n ret.reset_mock()\n \n funcopy.called=False\n funcopy.call_count=0\n funcopy.call_args=None\n funcopy.call_args_list=_CallList()\n funcopy.method_calls=_CallList()\n funcopy.mock_calls=_CallList()\n \n funcopy.return_value=mock.return_value\n funcopy.side_effect=mock.side_effect\n funcopy._mock_children=mock._mock_children\n \n funcopy.assert_called_with=assert_called_with\n funcopy.assert_called_once_with=assert_called_once_with\n funcopy.assert_has_calls=assert_has_calls\n funcopy.assert_any_call=assert_any_call\n funcopy.reset_mock=reset_mock\n funcopy.assert_called=assert_called\n funcopy.assert_not_called=assert_not_called\n funcopy.assert_called_once=assert_called_once\n funcopy.__signature__=sig\n \n mock._mock_delegate=funcopy\n \n \ndef _setup_async_mock(mock):\n mock._is_coroutine=asyncio.coroutines._is_coroutine\n mock.await_count=0\n mock.await_args=None\n mock.await_args_list=_CallList()\n \n \n \n \n def wrapper(attr,/,*args,**kwargs):\n return getattr(mock.mock,attr)(*args,**kwargs)\n \n for attribute in('assert_awaited',\n 'assert_awaited_once',\n 'assert_awaited_with',\n 'assert_awaited_once_with',\n 'assert_any_await',\n 'assert_has_awaits',\n 'assert_not_awaited'):\n \n \n \n \n \n setattr(mock,attribute,partial(wrapper,attribute))\n \n \ndef _is_magic(name):\n return '__%s__'%name[2:-2]==name\n \n \nclass _SentinelObject(object):\n ''\n def __init__(self,name):\n self.name=name\n \n def __repr__(self):\n return 'sentinel.%s'%self.name\n \n def __reduce__(self):\n return 'sentinel.%s'%self.name\n \n \nclass _Sentinel(object):\n ''\n def __init__(self):\n self._sentinels={}\n \n def __getattr__(self,name):\n if name =='__bases__':\n \n raise AttributeError\n return self._sentinels.setdefault(name,_SentinelObject(name))\n \n def __reduce__(self):\n return 'sentinel'\n \n \nsentinel=_Sentinel()\n\nDEFAULT=sentinel.DEFAULT\n_missing=sentinel.MISSING\n_deleted=sentinel.DELETED\n\n\n_allowed_names={\n'return_value','_mock_return_value','side_effect',\n'_mock_side_effect','_mock_parent','_mock_new_parent',\n'_mock_name','_mock_new_name'\n}\n\n\ndef _delegating_property(name):\n _allowed_names.add(name)\n _the_name='_mock_'+name\n def _get(self,name=name,_the_name=_the_name):\n sig=self._mock_delegate\n if sig is None:\n return getattr(self,_the_name)\n return getattr(sig,name)\n def _set(self,value,name=name,_the_name=_the_name):\n sig=self._mock_delegate\n if sig is None:\n self.__dict__[_the_name]=value\n else:\n setattr(sig,name,value)\n \n return property(_get,_set)\n \n \n \nclass _CallList(list):\n\n def __contains__(self,value):\n if not isinstance(value,list):\n return list.__contains__(self,value)\n len_value=len(value)\n len_self=len(self)\n if len_value >len_self:\n return False\n \n for i in range(0,len_self -len_value+1):\n sub_list=self[i:i+len_value]\n if sub_list ==value:\n return True\n return False\n \n def __repr__(self):\n return pprint.pformat(list(self))\n \n \ndef _check_and_set_parent(parent,value,name,new_name):\n value=_extract_mock(value)\n \n if not _is_instance_mock(value):\n return False\n if((value._mock_name or value._mock_new_name)or\n (value._mock_parent is not None)or\n (value._mock_new_parent is not None)):\n return False\n \n _parent=parent\n while _parent is not None:\n \n \n if _parent is value:\n return False\n _parent=_parent._mock_new_parent\n \n if new_name:\n value._mock_new_parent=parent\n value._mock_new_name=new_name\n if name:\n value._mock_parent=parent\n value._mock_name=name\n return True\n \n \nclass _MockIter(object):\n def __init__(self,obj):\n self.obj=iter(obj)\n def __next__(self):\n return next(self.obj)\n \nclass Base(object):\n _mock_return_value=DEFAULT\n _mock_side_effect=None\n def __init__(self,/,*args,**kwargs):\n pass\n \n \n \nclass NonCallableMock(Base):\n ''\n \n \n \n \n \n \n \n _lock=RLock()\n \n def __new__(\n cls,spec=None,wraps=None,name=None,spec_set=None,\n parent=None,_spec_state=None,_new_name='',_new_parent=None,\n _spec_as_instance=False,_eat_self=None,unsafe=False,**kwargs\n ):\n \n \n \n bases=(cls,)\n if not issubclass(cls,AsyncMockMixin):\n \n spec_arg=spec_set or spec\n if spec_arg is not None and _is_async_obj(spec_arg):\n bases=(AsyncMockMixin,cls)\n new=type(cls.__name__,bases,{'__doc__':cls.__doc__})\n instance=_safe_super(NonCallableMock,cls).__new__(new)\n return instance\n \n \n def __init__(\n self,spec=None,wraps=None,name=None,spec_set=None,\n parent=None,_spec_state=None,_new_name='',_new_parent=None,\n _spec_as_instance=False,_eat_self=None,unsafe=False,**kwargs\n ):\n if _new_parent is None:\n _new_parent=parent\n \n __dict__=self.__dict__\n __dict__['_mock_parent']=parent\n __dict__['_mock_name']=name\n __dict__['_mock_new_name']=_new_name\n __dict__['_mock_new_parent']=_new_parent\n __dict__['_mock_sealed']=False\n \n if spec_set is not None:\n spec=spec_set\n spec_set=True\n if _eat_self is None:\n _eat_self=parent is not None\n \n self._mock_add_spec(spec,spec_set,_spec_as_instance,_eat_self)\n \n __dict__['_mock_children']={}\n __dict__['_mock_wraps']=wraps\n __dict__['_mock_delegate']=None\n \n __dict__['_mock_called']=False\n __dict__['_mock_call_args']=None\n __dict__['_mock_call_count']=0\n __dict__['_mock_call_args_list']=_CallList()\n __dict__['_mock_mock_calls']=_CallList()\n \n __dict__['method_calls']=_CallList()\n __dict__['_mock_unsafe']=unsafe\n \n if kwargs:\n self.configure_mock(**kwargs)\n \n _safe_super(NonCallableMock,self).__init__(\n spec,wraps,name,spec_set,parent,\n _spec_state\n )\n \n \n def attach_mock(self,mock,attribute):\n ''\n\n\n \n inner_mock=_extract_mock(mock)\n \n inner_mock._mock_parent=None\n inner_mock._mock_new_parent=None\n inner_mock._mock_name=''\n inner_mock._mock_new_name=None\n \n setattr(self,attribute,mock)\n \n \n def mock_add_spec(self,spec,spec_set=False):\n ''\n\n\n\n \n self._mock_add_spec(spec,spec_set)\n \n \n def _mock_add_spec(self,spec,spec_set,_spec_as_instance=False,\n _eat_self=False):\n if _is_instance_mock(spec):\n raise InvalidSpecError(f'Cannot spec a Mock object. [object={spec !r}]')\n \n _spec_class=None\n _spec_signature=None\n _spec_asyncs=[]\n \n if spec is not None and not _is_list(spec):\n if isinstance(spec,type):\n _spec_class=spec\n else:\n _spec_class=type(spec)\n res=_get_signature_object(spec,\n _spec_as_instance,_eat_self)\n _spec_signature=res and res[1]\n \n spec_list=dir(spec)\n \n for attr in spec_list:\n static_attr=inspect.getattr_static(spec,attr,None)\n unwrapped_attr=static_attr\n try:\n unwrapped_attr=inspect.unwrap(unwrapped_attr)\n except ValueError:\n pass\n if iscoroutinefunction(unwrapped_attr):\n _spec_asyncs.append(attr)\n \n spec=spec_list\n \n __dict__=self.__dict__\n __dict__['_spec_class']=_spec_class\n __dict__['_spec_set']=spec_set\n __dict__['_spec_signature']=_spec_signature\n __dict__['_mock_methods']=spec\n __dict__['_spec_asyncs']=_spec_asyncs\n \n def __get_return_value(self):\n ret=self._mock_return_value\n if self._mock_delegate is not None:\n ret=self._mock_delegate.return_value\n \n if ret is DEFAULT and self._mock_wraps is None:\n ret=self._get_child_mock(\n _new_parent=self,_new_name='()'\n )\n self.return_value=ret\n return ret\n \n \n def __set_return_value(self,value):\n if self._mock_delegate is not None:\n self._mock_delegate.return_value=value\n else:\n self._mock_return_value=value\n _check_and_set_parent(self,value,None,'()')\n \n __return_value_doc=\"The value to be returned when the mock is called.\"\n return_value=property(__get_return_value,__set_return_value,\n __return_value_doc)\n \n \n @property\n def __class__(self):\n if self._spec_class is None:\n return type(self)\n return self._spec_class\n \n called=_delegating_property('called')\n call_count=_delegating_property('call_count')\n call_args=_delegating_property('call_args')\n call_args_list=_delegating_property('call_args_list')\n mock_calls=_delegating_property('mock_calls')\n \n \n def __get_side_effect(self):\n delegated=self._mock_delegate\n if delegated is None:\n return self._mock_side_effect\n sf=delegated.side_effect\n if(sf is not None and not callable(sf)\n and not isinstance(sf,_MockIter)and not _is_exception(sf)):\n sf=_MockIter(sf)\n delegated.side_effect=sf\n return sf\n \n def __set_side_effect(self,value):\n value=_try_iter(value)\n delegated=self._mock_delegate\n if delegated is None:\n self._mock_side_effect=value\n else:\n delegated.side_effect=value\n \n side_effect=property(__get_side_effect,__set_side_effect)\n \n \n def reset_mock(self,visited=None,*,return_value=False,side_effect=False):\n ''\n if visited is None:\n visited=[]\n if id(self)in visited:\n return\n visited.append(id(self))\n \n self.called=False\n self.call_args=None\n self.call_count=0\n self.mock_calls=_CallList()\n self.call_args_list=_CallList()\n self.method_calls=_CallList()\n \n if return_value:\n self._mock_return_value=DEFAULT\n if side_effect:\n self._mock_side_effect=None\n \n for child in self._mock_children.values():\n if isinstance(child,_SpecState)or child is _deleted:\n continue\n child.reset_mock(visited,return_value=return_value,side_effect=side_effect)\n \n ret=self._mock_return_value\n if _is_instance_mock(ret)and ret is not self:\n ret.reset_mock(visited)\n \n \n def configure_mock(self,/,**kwargs):\n ''\n\n\n\n\n\n\n \n for arg,val in sorted(kwargs.items(),\n \n \n \n key=lambda entry:entry[0].count('.')):\n args=arg.split('.')\n final=args.pop()\n obj=self\n for entry in args:\n obj=getattr(obj,entry)\n setattr(obj,final,val)\n \n \n def __getattr__(self,name):\n if name in{'_mock_methods','_mock_unsafe'}:\n raise AttributeError(name)\n elif self._mock_methods is not None:\n if name not in self._mock_methods or name in _all_magics:\n raise AttributeError(\"Mock object has no attribute %r\"%name)\n elif _is_magic(name):\n raise AttributeError(name)\n if not self._mock_unsafe and(not self._mock_methods or name not in self._mock_methods):\n if name.startswith(('assert','assret','asert','aseert','assrt'))or name in _ATTRIB_DENY_LIST:\n raise AttributeError(\n f\"{name !r} is not a valid assertion. Use a spec \"\n f\"for the mock if {name !r} is meant to be an attribute.\")\n \n with NonCallableMock._lock:\n result=self._mock_children.get(name)\n if result is _deleted:\n raise AttributeError(name)\n elif result is None:\n wraps=None\n if self._mock_wraps is not None:\n \n \n wraps=getattr(self._mock_wraps,name)\n \n result=self._get_child_mock(\n parent=self,name=name,wraps=wraps,_new_name=name,\n _new_parent=self\n )\n self._mock_children[name]=result\n \n elif isinstance(result,_SpecState):\n try:\n result=create_autospec(\n result.spec,result.spec_set,result.instance,\n result.parent,result.name\n )\n except InvalidSpecError:\n target_name=self.__dict__['_mock_name']or self\n raise InvalidSpecError(\n f'Cannot autospec attr {name !r} from target '\n f'{target_name !r} as it has already been mocked out. '\n f'[target={self !r}, attr={result.spec !r}]')\n self._mock_children[name]=result\n \n return result\n \n \n def _extract_mock_name(self):\n _name_list=[self._mock_new_name]\n _parent=self._mock_new_parent\n last=self\n \n dot='.'\n if _name_list ==['()']:\n dot=''\n \n while _parent is not None:\n last=_parent\n \n _name_list.append(_parent._mock_new_name+dot)\n dot='.'\n if _parent._mock_new_name =='()':\n dot=''\n \n _parent=_parent._mock_new_parent\n \n _name_list=list(reversed(_name_list))\n _first=last._mock_name or 'mock'\n if len(_name_list)>1:\n if _name_list[1]not in('()','().'):\n _first +='.'\n _name_list[0]=_first\n return ''.join(_name_list)\n \n def __repr__(self):\n name=self._extract_mock_name()\n \n name_string=''\n if name not in('mock','mock.'):\n name_string=' name=%r'%name\n \n spec_string=''\n if self._spec_class is not None:\n spec_string=' spec=%r'\n if self._spec_set:\n spec_string=' spec_set=%r'\n spec_string=spec_string %self._spec_class.__name__\n return \"<%s%s%s id='%s'>\"%(\n type(self).__name__,\n name_string,\n spec_string,\n id(self)\n )\n \n \n def __dir__(self):\n ''\n if not FILTER_DIR:\n return object.__dir__(self)\n \n extras=self._mock_methods or[]\n from_type=dir(type(self))\n from_dict=list(self.__dict__)\n from_child_mocks=[\n m_name for m_name,m_value in self._mock_children.items()\n if m_value is not _deleted]\n \n from_type=[e for e in from_type if not e.startswith('_')]\n from_dict=[e for e in from_dict if not e.startswith('_')or\n _is_magic(e)]\n return sorted(set(extras+from_type+from_dict+from_child_mocks))\n \n \n def __setattr__(self,name,value):\n if name in _allowed_names:\n \n return object.__setattr__(self,name,value)\n elif(self._spec_set and self._mock_methods is not None and\n name not in self._mock_methods and\n name not in self.__dict__):\n raise AttributeError(\"Mock object has no attribute '%s'\"%name)\n elif name in _unsupported_magics:\n msg='Attempting to set unsupported magic method %r.'%name\n raise AttributeError(msg)\n elif name in _all_magics:\n if self._mock_methods is not None and name not in self._mock_methods:\n raise AttributeError(\"Mock object has no attribute '%s'\"%name)\n \n if not _is_instance_mock(value):\n setattr(type(self),name,_get_method(name,value))\n original=value\n value=lambda *args,**kw:original(self,*args,**kw)\n else:\n \n \n _check_and_set_parent(self,value,None,name)\n setattr(type(self),name,value)\n self._mock_children[name]=value\n elif name =='__class__':\n self._spec_class=value\n return\n else:\n if _check_and_set_parent(self,value,name,name):\n self._mock_children[name]=value\n \n if self._mock_sealed and not hasattr(self,name):\n mock_name=f'{self._extract_mock_name()}.{name}'\n raise AttributeError(f'Cannot set {mock_name}')\n \n return object.__setattr__(self,name,value)\n \n \n def __delattr__(self,name):\n if name in _all_magics and name in type(self).__dict__:\n delattr(type(self),name)\n if name not in self.__dict__:\n \n \n return\n \n obj=self._mock_children.get(name,_missing)\n if name in self.__dict__:\n _safe_super(NonCallableMock,self).__delattr__(name)\n elif obj is _deleted:\n raise AttributeError(name)\n if obj is not _missing:\n del self._mock_children[name]\n self._mock_children[name]=_deleted\n \n \n def _format_mock_call_signature(self,args,kwargs):\n name=self._mock_name or 'mock'\n return _format_call_signature(name,args,kwargs)\n \n \n def _format_mock_failure_message(self,args,kwargs,action='call'):\n message='expected %s not found.\\nExpected: %s\\n Actual: %s'\n expected_string=self._format_mock_call_signature(args,kwargs)\n call_args=self.call_args\n actual_string=self._format_mock_call_signature(*call_args)\n return message %(action,expected_string,actual_string)\n \n \n def _get_call_signature_from_name(self,name):\n ''\n\n\n\n\n\n\n\n\n \n if not name:\n return self._spec_signature\n \n sig=None\n names=name.replace('()','').split('.')\n children=self._mock_children\n \n for name in names:\n child=children.get(name)\n if child is None or isinstance(child,_SpecState):\n break\n else:\n \n \n \n child=_extract_mock(child)\n children=child._mock_children\n sig=child._spec_signature\n \n return sig\n \n \n def _call_matcher(self,_call):\n ''\n\n\n\n\n \n \n if isinstance(_call,tuple)and len(_call)>2:\n sig=self._get_call_signature_from_name(_call[0])\n else:\n sig=self._spec_signature\n \n if sig is not None:\n if len(_call)==2:\n name=''\n args,kwargs=_call\n else:\n name,args,kwargs=_call\n try:\n bound_call=sig.bind(*args,**kwargs)\n return call(name,bound_call.args,bound_call.kwargs)\n except TypeError as e:\n return e.with_traceback(None)\n else:\n return _call\n \n def assert_not_called(self):\n ''\n \n if self.call_count !=0:\n msg=(\"Expected '%s' to not have been called. Called %s times.%s\"\n %(self._mock_name or 'mock',\n self.call_count,\n self._calls_repr()))\n raise AssertionError(msg)\n \n def assert_called(self):\n ''\n \n if self.call_count ==0:\n msg=(\"Expected '%s' to have been called.\"%\n (self._mock_name or 'mock'))\n raise AssertionError(msg)\n \n def assert_called_once(self):\n ''\n \n if not self.call_count ==1:\n msg=(\"Expected '%s' to have been called once. Called %s times.%s\"\n %(self._mock_name or 'mock',\n self.call_count,\n self._calls_repr()))\n raise AssertionError(msg)\n \n def assert_called_with(self,/,*args,**kwargs):\n ''\n\n\n \n if self.call_args is None:\n expected=self._format_mock_call_signature(args,kwargs)\n actual='not called.'\n error_message=('expected call not found.\\nExpected: %s\\n Actual: %s'\n %(expected,actual))\n raise AssertionError(error_message)\n \n def _error_message():\n msg=self._format_mock_failure_message(args,kwargs)\n return msg\n expected=self._call_matcher(_Call((args,kwargs),two=True))\n actual=self._call_matcher(self.call_args)\n if actual !=expected:\n cause=expected if isinstance(expected,Exception)else None\n raise AssertionError(_error_message())from cause\n \n \n def assert_called_once_with(self,/,*args,**kwargs):\n ''\n \n if not self.call_count ==1:\n msg=(\"Expected '%s' to be called once. Called %s times.%s\"\n %(self._mock_name or 'mock',\n self.call_count,\n self._calls_repr()))\n raise AssertionError(msg)\n return self.assert_called_with(*args,**kwargs)\n \n \n def assert_has_calls(self,calls,any_order=False):\n ''\n\n\n\n\n\n\n\n \n expected=[self._call_matcher(c)for c in calls]\n cause=next((e for e in expected if isinstance(e,Exception)),None)\n all_calls=_CallList(self._call_matcher(c)for c in self.mock_calls)\n if not any_order:\n if expected not in all_calls:\n if cause is None:\n problem='Calls not found.'\n else:\n problem=('Error processing expected calls.\\n'\n 'Errors: {}').format(\n [e if isinstance(e,Exception)else None\n for e in expected])\n raise AssertionError(\n f'{problem}\\n'\n f'Expected: {_CallList(calls)}\\n'\n f' Actual: {safe_repr(self.mock_calls)}'\n )from cause\n return\n \n all_calls=list(all_calls)\n \n not_found=[]\n for kall in expected:\n try:\n all_calls.remove(kall)\n except ValueError:\n not_found.append(kall)\n if not_found:\n raise AssertionError(\n '%r does not contain all of %r in its call list, '\n 'found %r instead'%(self._mock_name or 'mock',\n tuple(not_found),all_calls)\n )from cause\n \n \n def assert_any_call(self,/,*args,**kwargs):\n ''\n\n\n\n \n expected=self._call_matcher(_Call((args,kwargs),two=True))\n cause=expected if isinstance(expected,Exception)else None\n actual=[self._call_matcher(c)for c in self.call_args_list]\n if cause or expected not in _AnyComparer(actual):\n expected_string=self._format_mock_call_signature(args,kwargs)\n raise AssertionError(\n '%s call not found'%expected_string\n )from cause\n \n \n def _get_child_mock(self,/,**kw):\n ''\n\n\n\n\n\n \n if self._mock_sealed:\n attribute=f\".{kw['name']}\"if \"name\"in kw else \"()\"\n mock_name=self._extract_mock_name()+attribute\n raise AttributeError(mock_name)\n \n _new_name=kw.get(\"_new_name\")\n if _new_name in self.__dict__['_spec_asyncs']:\n return AsyncMock(**kw)\n \n _type=type(self)\n if issubclass(_type,MagicMock)and _new_name in _async_method_magics:\n \n klass=AsyncMock\n elif issubclass(_type,AsyncMockMixin):\n if(_new_name in _all_sync_magics or\n self._mock_methods and _new_name in self._mock_methods):\n \n klass=MagicMock\n else:\n klass=AsyncMock\n elif not issubclass(_type,CallableMixin):\n if issubclass(_type,NonCallableMagicMock):\n klass=MagicMock\n elif issubclass(_type,NonCallableMock):\n klass=Mock\n else:\n klass=_type.__mro__[1]\n return klass(**kw)\n \n \n def _calls_repr(self):\n ''\n\n\n\n\n\n \n if not self.mock_calls:\n return \"\"\n return f\"\\nCalls: {safe_repr(self.mock_calls)}.\"\n \n \n \n_ATTRIB_DENY_LIST=frozenset({\nname.removeprefix(\"assert_\")\nfor name in dir(NonCallableMock)\nif name.startswith(\"assert_\")\n})\n\n\nclass _AnyComparer(list):\n ''\n\n\n \n def __contains__(self,item):\n for _call in self:\n assert len(item)==len(_call)\n if all([\n expected ==actual\n for expected,actual in zip(item,_call)\n ]):\n return True\n return False\n \n \ndef _try_iter(obj):\n if obj is None:\n return obj\n if _is_exception(obj):\n return obj\n if _callable(obj):\n return obj\n try:\n return iter(obj)\n except TypeError:\n \n \n return obj\n \n \nclass CallableMixin(Base):\n\n def __init__(self,spec=None,side_effect=None,return_value=DEFAULT,\n wraps=None,name=None,spec_set=None,parent=None,\n _spec_state=None,_new_name='',_new_parent=None,**kwargs):\n self.__dict__['_mock_return_value']=return_value\n _safe_super(CallableMixin,self).__init__(\n spec,wraps,name,spec_set,parent,\n _spec_state,_new_name,_new_parent,**kwargs\n )\n \n self.side_effect=side_effect\n \n \n def _mock_check_sig(self,/,*args,**kwargs):\n \n pass\n \n \n def __call__(self,/,*args,**kwargs):\n \n \n self._mock_check_sig(*args,**kwargs)\n self._increment_mock_call(*args,**kwargs)\n return self._mock_call(*args,**kwargs)\n \n \n def _mock_call(self,/,*args,**kwargs):\n return self._execute_mock_call(*args,**kwargs)\n \n def _increment_mock_call(self,/,*args,**kwargs):\n self.called=True\n self.call_count +=1\n \n \n \n \n _call=_Call((args,kwargs),two=True)\n self.call_args=_call\n self.call_args_list.append(_call)\n \n \n do_method_calls=self._mock_parent is not None\n method_call_name=self._mock_name\n \n \n mock_call_name=self._mock_new_name\n is_a_call=mock_call_name =='()'\n self.mock_calls.append(_Call(('',args,kwargs)))\n \n \n _new_parent=self._mock_new_parent\n while _new_parent is not None:\n \n \n if do_method_calls:\n _new_parent.method_calls.append(_Call((method_call_name,args,kwargs)))\n do_method_calls=_new_parent._mock_parent is not None\n if do_method_calls:\n method_call_name=_new_parent._mock_name+'.'+method_call_name\n \n \n this_mock_call=_Call((mock_call_name,args,kwargs))\n _new_parent.mock_calls.append(this_mock_call)\n \n if _new_parent._mock_new_name:\n if is_a_call:\n dot=''\n else:\n dot='.'\n is_a_call=_new_parent._mock_new_name =='()'\n mock_call_name=_new_parent._mock_new_name+dot+mock_call_name\n \n \n _new_parent=_new_parent._mock_new_parent\n \n def _execute_mock_call(self,/,*args,**kwargs):\n \n \n \n effect=self.side_effect\n if effect is not None:\n if _is_exception(effect):\n raise effect\n elif not _callable(effect):\n result=next(effect)\n if _is_exception(result):\n raise result\n else:\n result=effect(*args,**kwargs)\n \n if result is not DEFAULT:\n return result\n \n if self._mock_return_value is not DEFAULT:\n return self.return_value\n \n if self._mock_delegate and self._mock_delegate.return_value is not DEFAULT:\n return self.return_value\n \n if self._mock_wraps is not None:\n return self._mock_wraps(*args,**kwargs)\n \n return self.return_value\n \n \n \nclass Mock(CallableMixin,NonCallableMock):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \ndef _check_spec_arg_typos(kwargs_to_check):\n typos=(\"autospect\",\"auto_spec\",\"set_spec\")\n for typo in typos:\n if typo in kwargs_to_check:\n raise RuntimeError(\n f\"{typo !r} might be a typo; use unsafe=True if this is intended\"\n )\n \n \nclass _patch(object):\n\n attribute_name=None\n _active_patches=[]\n \n def __init__(\n self,getter,attribute,new,spec,create,\n spec_set,autospec,new_callable,kwargs,*,unsafe=False\n ):\n if new_callable is not None:\n if new is not DEFAULT:\n raise ValueError(\n \"Cannot use 'new' and 'new_callable' together\"\n )\n if autospec is not None:\n raise ValueError(\n \"Cannot use 'autospec' and 'new_callable' together\"\n )\n if not unsafe:\n _check_spec_arg_typos(kwargs)\n if _is_instance_mock(spec):\n raise InvalidSpecError(\n f'Cannot spec attr {attribute !r} as the spec '\n f'has already been mocked out. [spec={spec !r}]')\n if _is_instance_mock(spec_set):\n raise InvalidSpecError(\n f'Cannot spec attr {attribute !r} as the spec_set '\n f'target has already been mocked out. [spec_set={spec_set !r}]')\n \n self.getter=getter\n self.attribute=attribute\n self.new=new\n self.new_callable=new_callable\n self.spec=spec\n self.create=create\n self.has_local=False\n self.spec_set=spec_set\n self.autospec=autospec\n self.kwargs=kwargs\n self.additional_patchers=[]\n \n \n def copy(self):\n patcher=_patch(\n self.getter,self.attribute,self.new,self.spec,\n self.create,self.spec_set,\n self.autospec,self.new_callable,self.kwargs\n )\n patcher.attribute_name=self.attribute_name\n patcher.additional_patchers=[\n p.copy()for p in self.additional_patchers\n ]\n return patcher\n \n \n def __call__(self,func):\n if isinstance(func,type):\n return self.decorate_class(func)\n if inspect.iscoroutinefunction(func):\n return self.decorate_async_callable(func)\n return self.decorate_callable(func)\n \n \n def decorate_class(self,klass):\n for attr in dir(klass):\n if not attr.startswith(patch.TEST_PREFIX):\n continue\n \n attr_value=getattr(klass,attr)\n if not hasattr(attr_value,\"__call__\"):\n continue\n \n patcher=self.copy()\n setattr(klass,attr,patcher(attr_value))\n return klass\n \n \n @contextlib.contextmanager\n def decoration_helper(self,patched,args,keywargs):\n extra_args=[]\n with contextlib.ExitStack()as exit_stack:\n for patching in patched.patchings:\n arg=exit_stack.enter_context(patching)\n if patching.attribute_name is not None:\n keywargs.update(arg)\n elif patching.new is DEFAULT:\n extra_args.append(arg)\n \n args +=tuple(extra_args)\n yield(args,keywargs)\n \n \n def decorate_callable(self,func):\n \n if hasattr(func,'patchings'):\n func.patchings.append(self)\n return func\n \n @wraps(func)\n def patched(*args,**keywargs):\n with self.decoration_helper(patched,\n args,\n keywargs)as(newargs,newkeywargs):\n return func(*newargs,**newkeywargs)\n \n patched.patchings=[self]\n return patched\n \n \n def decorate_async_callable(self,func):\n \n if hasattr(func,'patchings'):\n func.patchings.append(self)\n return func\n \n @wraps(func)\n async def patched(*args,**keywargs):\n with self.decoration_helper(patched,\n args,\n keywargs)as(newargs,newkeywargs):\n return await func(*newargs,**newkeywargs)\n \n patched.patchings=[self]\n return patched\n \n \n def get_original(self):\n target=self.getter()\n name=self.attribute\n \n original=DEFAULT\n local=False\n \n try:\n original=target.__dict__[name]\n except(AttributeError,KeyError):\n original=getattr(target,name,DEFAULT)\n else:\n local=True\n \n if name in _builtins and isinstance(target,ModuleType):\n self.create=True\n \n if not self.create and original is DEFAULT:\n raise AttributeError(\n \"%s does not have the attribute %r\"%(target,name)\n )\n return original,local\n \n \n def __enter__(self):\n ''\n new,spec,spec_set=self.new,self.spec,self.spec_set\n autospec,kwargs=self.autospec,self.kwargs\n new_callable=self.new_callable\n self.target=self.getter()\n \n \n if spec is False:\n spec=None\n if spec_set is False:\n spec_set=None\n if autospec is False:\n autospec=None\n \n if spec is not None and autospec is not None:\n raise TypeError(\"Can't specify spec and autospec\")\n if((spec is not None or autospec is not None)and\n spec_set not in(True,None)):\n raise TypeError(\"Can't provide explicit spec_set *and* spec or autospec\")\n \n original,local=self.get_original()\n \n if new is DEFAULT and autospec is None:\n inherit=False\n if spec is True:\n \n spec=original\n if spec_set is True:\n spec_set=original\n spec=None\n elif spec is not None:\n if spec_set is True:\n spec_set=spec\n spec=None\n elif spec_set is True:\n spec_set=original\n \n if spec is not None or spec_set is not None:\n if original is DEFAULT:\n raise TypeError(\"Can't use 'spec' with create=True\")\n if isinstance(original,type):\n \n inherit=True\n if spec is None and _is_async_obj(original):\n Klass=AsyncMock\n else:\n Klass=MagicMock\n _kwargs={}\n if new_callable is not None:\n Klass=new_callable\n elif spec is not None or spec_set is not None:\n this_spec=spec\n if spec_set is not None:\n this_spec=spec_set\n if _is_list(this_spec):\n not_callable='__call__'not in this_spec\n else:\n not_callable=not callable(this_spec)\n if _is_async_obj(this_spec):\n Klass=AsyncMock\n elif not_callable:\n Klass=NonCallableMagicMock\n \n if spec is not None:\n _kwargs['spec']=spec\n if spec_set is not None:\n _kwargs['spec_set']=spec_set\n \n \n if(isinstance(Klass,type)and\n issubclass(Klass,NonCallableMock)and self.attribute):\n _kwargs['name']=self.attribute\n \n _kwargs.update(kwargs)\n new=Klass(**_kwargs)\n \n if inherit and _is_instance_mock(new):\n \n \n this_spec=spec\n if spec_set is not None:\n this_spec=spec_set\n if(not _is_list(this_spec)and not\n _instance_callable(this_spec)):\n Klass=NonCallableMagicMock\n \n _kwargs.pop('name')\n new.return_value=Klass(_new_parent=new,_new_name='()',\n **_kwargs)\n elif autospec is not None:\n \n \n \n if new is not DEFAULT:\n raise TypeError(\n \"autospec creates the mock for you. Can't specify \"\n \"autospec and new.\"\n )\n if original is DEFAULT:\n raise TypeError(\"Can't use 'autospec' with create=True\")\n spec_set=bool(spec_set)\n if autospec is True:\n autospec=original\n \n if _is_instance_mock(self.target):\n raise InvalidSpecError(\n f'Cannot autospec attr {self.attribute !r} as the patch '\n f'target has already been mocked out. '\n f'[target={self.target !r}, attr={autospec !r}]')\n if _is_instance_mock(autospec):\n target_name=getattr(self.target,'__name__',self.target)\n raise InvalidSpecError(\n f'Cannot autospec attr {self.attribute !r} from target '\n f'{target_name !r} as it has already been mocked out. '\n f'[target={self.target !r}, attr={autospec !r}]')\n \n new=create_autospec(autospec,spec_set=spec_set,\n _name=self.attribute,**kwargs)\n elif kwargs:\n \n \n raise TypeError(\"Can't pass kwargs to a mock we aren't creating\")\n \n new_attr=new\n \n self.temp_original=original\n self.is_local=local\n self._exit_stack=contextlib.ExitStack()\n try:\n setattr(self.target,self.attribute,new_attr)\n if self.attribute_name is not None:\n extra_args={}\n if self.new is DEFAULT:\n extra_args[self.attribute_name]=new\n for patching in self.additional_patchers:\n arg=self._exit_stack.enter_context(patching)\n if patching.new is DEFAULT:\n extra_args.update(arg)\n return extra_args\n \n return new\n except:\n if not self.__exit__(*sys.exc_info()):\n raise\n \n def __exit__(self,*exc_info):\n ''\n if self.is_local and self.temp_original is not DEFAULT:\n setattr(self.target,self.attribute,self.temp_original)\n else:\n delattr(self.target,self.attribute)\n if not self.create and(not hasattr(self.target,self.attribute)or\n self.attribute in('__doc__','__module__',\n '__defaults__','__annotations__',\n '__kwdefaults__')):\n \n setattr(self.target,self.attribute,self.temp_original)\n \n del self.temp_original\n del self.is_local\n del self.target\n exit_stack=self._exit_stack\n del self._exit_stack\n return exit_stack.__exit__(*exc_info)\n \n \n def start(self):\n ''\n result=self.__enter__()\n self._active_patches.append(self)\n return result\n \n \n def stop(self):\n ''\n try:\n self._active_patches.remove(self)\n except ValueError:\n \n return None\n \n return self.__exit__(None,None,None)\n \n \n \ndef _get_target(target):\n try:\n target,attribute=target.rsplit('.',1)\n except(TypeError,ValueError,AttributeError):\n raise TypeError(\n f\"Need a valid target to patch. You supplied: {target !r}\")\n return partial(pkgutil.resolve_name,target),attribute\n \n \ndef _patch_object(\ntarget,attribute,new=DEFAULT,spec=None,\ncreate=False,spec_set=None,autospec=None,\nnew_callable=None,*,unsafe=False,**kwargs\n):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if type(target)is str:\n raise TypeError(\n f\"{target !r} must be the actual object to be patched, not a str\"\n )\n getter=lambda:target\n return _patch(\n getter,attribute,new,spec,create,\n spec_set,autospec,new_callable,kwargs,unsafe=unsafe\n )\n \n \ndef _patch_multiple(target,spec=None,create=False,spec_set=None,\nautospec=None,new_callable=None,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if type(target)is str:\n getter=partial(pkgutil.resolve_name,target)\n else:\n getter=lambda:target\n \n if not kwargs:\n raise ValueError(\n 'Must supply at least one keyword argument with patch.multiple'\n )\n \n items=list(kwargs.items())\n attribute,new=items[0]\n patcher=_patch(\n getter,attribute,new,spec,create,spec_set,\n autospec,new_callable,{}\n )\n patcher.attribute_name=attribute\n for attribute,new in items[1:]:\n this_patcher=_patch(\n getter,attribute,new,spec,create,spec_set,\n autospec,new_callable,{}\n )\n this_patcher.attribute_name=attribute\n patcher.additional_patchers.append(this_patcher)\n return patcher\n \n \ndef patch(\ntarget,new=DEFAULT,spec=None,create=False,\nspec_set=None,autospec=None,new_callable=None,*,unsafe=False,**kwargs\n):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n getter,attribute=_get_target(target)\n return _patch(\n getter,attribute,new,spec,create,\n spec_set,autospec,new_callable,kwargs,unsafe=unsafe\n )\n \n \nclass _patch_dict(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,in_dict,values=(),clear=False,**kwargs):\n self.in_dict=in_dict\n \n self.values=dict(values)\n self.values.update(kwargs)\n self.clear=clear\n self._original=None\n \n \n def __call__(self,f):\n if isinstance(f,type):\n return self.decorate_class(f)\n if inspect.iscoroutinefunction(f):\n return self.decorate_async_callable(f)\n return self.decorate_callable(f)\n \n \n def decorate_callable(self,f):\n @wraps(f)\n def _inner(*args,**kw):\n self._patch_dict()\n try:\n return f(*args,**kw)\n finally:\n self._unpatch_dict()\n \n return _inner\n \n \n def decorate_async_callable(self,f):\n @wraps(f)\n async def _inner(*args,**kw):\n self._patch_dict()\n try:\n return await f(*args,**kw)\n finally:\n self._unpatch_dict()\n \n return _inner\n \n \n def decorate_class(self,klass):\n for attr in dir(klass):\n attr_value=getattr(klass,attr)\n if(attr.startswith(patch.TEST_PREFIX)and\n hasattr(attr_value,\"__call__\")):\n decorator=_patch_dict(self.in_dict,self.values,self.clear)\n decorated=decorator(attr_value)\n setattr(klass,attr,decorated)\n return klass\n \n \n def __enter__(self):\n ''\n self._patch_dict()\n return self.in_dict\n \n \n def _patch_dict(self):\n values=self.values\n if isinstance(self.in_dict,str):\n self.in_dict=pkgutil.resolve_name(self.in_dict)\n in_dict=self.in_dict\n clear=self.clear\n \n try:\n original=in_dict.copy()\n except AttributeError:\n \n \n original={}\n for key in in_dict:\n original[key]=in_dict[key]\n self._original=original\n \n if clear:\n _clear_dict(in_dict)\n \n try:\n in_dict.update(values)\n except AttributeError:\n \n for key in values:\n in_dict[key]=values[key]\n \n \n def _unpatch_dict(self):\n in_dict=self.in_dict\n original=self._original\n \n _clear_dict(in_dict)\n \n try:\n in_dict.update(original)\n except AttributeError:\n for key in original:\n in_dict[key]=original[key]\n \n \n def __exit__(self,*args):\n ''\n if self._original is not None:\n self._unpatch_dict()\n return False\n \n \n def start(self):\n ''\n result=self.__enter__()\n _patch._active_patches.append(self)\n return result\n \n \n def stop(self):\n ''\n try:\n _patch._active_patches.remove(self)\n except ValueError:\n \n return None\n \n return self.__exit__(None,None,None)\n \n \ndef _clear_dict(in_dict):\n try:\n in_dict.clear()\n except AttributeError:\n keys=list(in_dict)\n for key in keys:\n del in_dict[key]\n \n \ndef _patch_stopall():\n ''\n for patch in reversed(_patch._active_patches):\n patch.stop()\n \n \npatch.object=_patch_object\npatch.dict=_patch_dict\npatch.multiple=_patch_multiple\npatch.stopall=_patch_stopall\npatch.TEST_PREFIX='test'\n\nmagic_methods=(\n\"lt le gt ge eq ne \"\n\"getitem setitem delitem \"\n\"len contains iter \"\n\"hash str sizeof \"\n\"enter exit \"\n\n\n\"divmod rdivmod neg pos abs invert \"\n\"complex int float index \"\n\"round trunc floor ceil \"\n\"bool next \"\n\"fspath \"\n\"aiter \"\n)\n\nnumerics=(\n\"add sub mul matmul truediv floordiv mod lshift rshift and xor or pow\"\n)\ninplace=' '.join('i%s'%n for n in numerics.split())\nright=' '.join('r%s'%n for n in numerics.split())\n\n\n\n\n\n_non_defaults={\n'__get__','__set__','__delete__','__reversed__','__missing__',\n'__reduce__','__reduce_ex__','__getinitargs__','__getnewargs__',\n'__getstate__','__setstate__','__getformat__',\n'__repr__','__dir__','__subclasses__','__format__',\n'__getnewargs_ex__',\n}\n\n\ndef _get_method(name,func):\n ''\n def method(self,/,*args,**kw):\n return func(self,*args,**kw)\n method.__name__=name\n return method\n \n \n_magics={\n'__%s__'%method for method in\n' '.join([magic_methods,numerics,inplace,right]).split()\n}\n\n\n_async_method_magics={\"__aenter__\",\"__aexit__\",\"__anext__\"}\n\n_sync_async_magics={\"__aiter__\"}\n_async_magics=_async_method_magics |_sync_async_magics\n\n_all_sync_magics=_magics |_non_defaults\n_all_magics=_all_sync_magics |_async_magics\n\n_unsupported_magics={\n'__getattr__','__setattr__',\n'__init__','__new__','__prepare__',\n'__instancecheck__','__subclasscheck__',\n'__del__'\n}\n\n_calculate_return_value={\n'__hash__':lambda self:object.__hash__(self),\n'__str__':lambda self:object.__str__(self),\n'__sizeof__':lambda self:object.__sizeof__(self),\n'__fspath__':lambda self:f\"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}\",\n}\n\n_return_values={\n'__lt__':NotImplemented,\n'__gt__':NotImplemented,\n'__le__':NotImplemented,\n'__ge__':NotImplemented,\n'__int__':1,\n'__contains__':False,\n'__len__':0,\n'__exit__':False,\n'__complex__':1j,\n'__float__':1.0,\n'__bool__':True,\n'__index__':1,\n'__aexit__':False,\n}\n\n\ndef _get_eq(self):\n def __eq__(other):\n ret_val=self.__eq__._mock_return_value\n if ret_val is not DEFAULT:\n return ret_val\n if self is other:\n return True\n return NotImplemented\n return __eq__\n \ndef _get_ne(self):\n def __ne__(other):\n if self.__ne__._mock_return_value is not DEFAULT:\n return DEFAULT\n if self is other:\n return False\n return NotImplemented\n return __ne__\n \ndef _get_iter(self):\n def __iter__():\n ret_val=self.__iter__._mock_return_value\n if ret_val is DEFAULT:\n return iter([])\n \n \n return iter(ret_val)\n return __iter__\n \ndef _get_async_iter(self):\n def __aiter__():\n ret_val=self.__aiter__._mock_return_value\n if ret_val is DEFAULT:\n return _AsyncIterator(iter([]))\n return _AsyncIterator(iter(ret_val))\n return __aiter__\n \n_side_effect_methods={\n'__eq__':_get_eq,\n'__ne__':_get_ne,\n'__iter__':_get_iter,\n'__aiter__':_get_async_iter\n}\n\n\n\ndef _set_return_value(mock,method,name):\n fixed=_return_values.get(name,DEFAULT)\n if fixed is not DEFAULT:\n method.return_value=fixed\n return\n \n return_calculator=_calculate_return_value.get(name)\n if return_calculator is not None:\n return_value=return_calculator(mock)\n method.return_value=return_value\n return\n \n side_effector=_side_effect_methods.get(name)\n if side_effector is not None:\n method.side_effect=side_effector(mock)\n \n \n \nclass MagicMixin(Base):\n def __init__(self,/,*args,**kw):\n self._mock_set_magics()\n _safe_super(MagicMixin,self).__init__(*args,**kw)\n self._mock_set_magics()\n \n \n def _mock_set_magics(self):\n orig_magics=_magics |_async_method_magics\n these_magics=orig_magics\n \n if getattr(self,\"_mock_methods\",None)is not None:\n these_magics=orig_magics.intersection(self._mock_methods)\n \n remove_magics=set()\n remove_magics=orig_magics -these_magics\n \n for entry in remove_magics:\n if entry in type(self).__dict__:\n \n delattr(self,entry)\n \n \n these_magics=these_magics -set(type(self).__dict__)\n \n _type=type(self)\n for entry in these_magics:\n setattr(_type,entry,MagicProxy(entry,self))\n \n \n \nclass NonCallableMagicMock(MagicMixin,NonCallableMock):\n ''\n def mock_add_spec(self,spec,spec_set=False):\n ''\n\n\n\n \n self._mock_add_spec(spec,spec_set)\n self._mock_set_magics()\n \n \nclass AsyncMagicMixin(MagicMixin):\n pass\n \n \nclass MagicMock(MagicMixin,Mock):\n ''\n\n\n\n\n\n\n\n\n \n def mock_add_spec(self,spec,spec_set=False):\n ''\n\n\n\n \n self._mock_add_spec(spec,spec_set)\n self._mock_set_magics()\n \n \n \nclass MagicProxy(Base):\n def __init__(self,name,parent):\n self.name=name\n self.parent=parent\n \n def create_mock(self):\n entry=self.name\n parent=self.parent\n m=parent._get_child_mock(name=entry,_new_name=entry,\n _new_parent=parent)\n setattr(parent,entry,m)\n _set_return_value(parent,m,entry)\n return m\n \n def __get__(self,obj,_type=None):\n return self.create_mock()\n \n \ntry:\n _CODE_SIG=inspect.signature(partial(CodeType.__init__,None))\n _CODE_ATTRS=dir(CodeType)\nexcept ValueError:\n _CODE_SIG=None\n \n \nclass AsyncMockMixin(Base):\n await_count=_delegating_property('await_count')\n await_args=_delegating_property('await_args')\n await_args_list=_delegating_property('await_args_list')\n \n def __init__(self,/,*args,**kwargs):\n super().__init__(*args,**kwargs)\n \n \n \n \n \n \n self.__dict__['_is_coroutine']=asyncio.coroutines._is_coroutine\n self.__dict__['_mock_await_count']=0\n self.__dict__['_mock_await_args']=None\n self.__dict__['_mock_await_args_list']=_CallList()\n if _CODE_SIG:\n code_mock=NonCallableMock(spec_set=_CODE_ATTRS)\n code_mock.__dict__[\"_spec_class\"]=CodeType\n code_mock.__dict__[\"_spec_signature\"]=_CODE_SIG\n else:\n code_mock=NonCallableMock(spec_set=CodeType)\n code_mock.co_flags=(\n inspect.CO_COROUTINE\n +inspect.CO_VARARGS\n +inspect.CO_VARKEYWORDS\n )\n code_mock.co_argcount=0\n code_mock.co_varnames=('args','kwargs')\n code_mock.co_posonlyargcount=0\n code_mock.co_kwonlyargcount=0\n self.__dict__['__code__']=code_mock\n self.__dict__['__name__']='AsyncMock'\n self.__dict__['__defaults__']=tuple()\n self.__dict__['__kwdefaults__']={}\n self.__dict__['__annotations__']=None\n \n async def _execute_mock_call(self,/,*args,**kwargs):\n \n \n \n _call=_Call((args,kwargs),two=True)\n self.await_count +=1\n self.await_args=_call\n self.await_args_list.append(_call)\n \n effect=self.side_effect\n if effect is not None:\n if _is_exception(effect):\n raise effect\n elif not _callable(effect):\n try:\n result=next(effect)\n except StopIteration:\n \n \n raise StopAsyncIteration\n if _is_exception(result):\n raise result\n elif iscoroutinefunction(effect):\n result=await effect(*args,**kwargs)\n else:\n result=effect(*args,**kwargs)\n \n if result is not DEFAULT:\n return result\n \n if self._mock_return_value is not DEFAULT:\n return self.return_value\n \n if self._mock_wraps is not None:\n if iscoroutinefunction(self._mock_wraps):\n return await self._mock_wraps(*args,**kwargs)\n return self._mock_wraps(*args,**kwargs)\n \n return self.return_value\n \n def assert_awaited(self):\n ''\n\n \n if self.await_count ==0:\n msg=f\"Expected {self._mock_name or 'mock'} to have been awaited.\"\n raise AssertionError(msg)\n \n def assert_awaited_once(self):\n ''\n\n \n if not self.await_count ==1:\n msg=(f\"Expected {self._mock_name or 'mock'} to have been awaited once.\"\n f\" Awaited {self.await_count} times.\")\n raise AssertionError(msg)\n \n def assert_awaited_with(self,/,*args,**kwargs):\n ''\n\n \n if self.await_args is None:\n expected=self._format_mock_call_signature(args,kwargs)\n raise AssertionError(f'Expected await: {expected}\\nNot awaited')\n \n def _error_message():\n msg=self._format_mock_failure_message(args,kwargs,action='await')\n return msg\n \n expected=self._call_matcher(_Call((args,kwargs),two=True))\n actual=self._call_matcher(self.await_args)\n if actual !=expected:\n cause=expected if isinstance(expected,Exception)else None\n raise AssertionError(_error_message())from cause\n \n def assert_awaited_once_with(self,/,*args,**kwargs):\n ''\n\n\n \n if not self.await_count ==1:\n msg=(f\"Expected {self._mock_name or 'mock'} to have been awaited once.\"\n f\" Awaited {self.await_count} times.\")\n raise AssertionError(msg)\n return self.assert_awaited_with(*args,**kwargs)\n \n def assert_any_await(self,/,*args,**kwargs):\n ''\n\n \n expected=self._call_matcher(_Call((args,kwargs),two=True))\n cause=expected if isinstance(expected,Exception)else None\n actual=[self._call_matcher(c)for c in self.await_args_list]\n if cause or expected not in _AnyComparer(actual):\n expected_string=self._format_mock_call_signature(args,kwargs)\n raise AssertionError(\n '%s await not found'%expected_string\n )from cause\n \n def assert_has_awaits(self,calls,any_order=False):\n ''\n\n\n\n\n\n\n\n\n\n \n expected=[self._call_matcher(c)for c in calls]\n cause=next((e for e in expected if isinstance(e,Exception)),None)\n all_awaits=_CallList(self._call_matcher(c)for c in self.await_args_list)\n if not any_order:\n if expected not in all_awaits:\n if cause is None:\n problem='Awaits not found.'\n else:\n problem=('Error processing expected awaits.\\n'\n 'Errors: {}').format(\n [e if isinstance(e,Exception)else None\n for e in expected])\n raise AssertionError(\n f'{problem}\\n'\n f'Expected: {_CallList(calls)}\\n'\n f'Actual: {self.await_args_list}'\n )from cause\n return\n \n all_awaits=list(all_awaits)\n \n not_found=[]\n for kall in expected:\n try:\n all_awaits.remove(kall)\n except ValueError:\n not_found.append(kall)\n if not_found:\n raise AssertionError(\n '%r not all found in await list'%(tuple(not_found),)\n )from cause\n \n def assert_not_awaited(self):\n ''\n\n \n if self.await_count !=0:\n msg=(f\"Expected {self._mock_name or 'mock'} to not have been awaited.\"\n f\" Awaited {self.await_count} times.\")\n raise AssertionError(msg)\n \n def reset_mock(self,/,*args,**kwargs):\n ''\n\n \n super().reset_mock(*args,**kwargs)\n self.await_count=0\n self.await_args=None\n self.await_args_list=_CallList()\n \n \nclass AsyncMock(AsyncMockMixin,AsyncMagicMixin,Mock):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \nclass _ANY(object):\n ''\n \n def __eq__(self,other):\n return True\n \n def __ne__(self,other):\n return False\n \n def __repr__(self):\n return ''\n \nANY=_ANY()\n\n\n\ndef _format_call_signature(name,args,kwargs):\n message='%s(%%s)'%name\n formatted_args=''\n args_string=', '.join([repr(arg)for arg in args])\n kwargs_string=', '.join([\n '%s=%r'%(key,value)for key,value in kwargs.items()\n ])\n if args_string:\n formatted_args=args_string\n if kwargs_string:\n if formatted_args:\n formatted_args +=', '\n formatted_args +=kwargs_string\n \n return message %formatted_args\n \n \n \nclass _Call(tuple):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __new__(cls,value=(),name='',parent=None,two=False,\n from_kall=True):\n args=()\n kwargs={}\n _len=len(value)\n if _len ==3:\n name,args,kwargs=value\n elif _len ==2:\n first,second=value\n if isinstance(first,str):\n name=first\n if isinstance(second,tuple):\n args=second\n else:\n kwargs=second\n else:\n args,kwargs=first,second\n elif _len ==1:\n value,=value\n if isinstance(value,str):\n name=value\n elif isinstance(value,tuple):\n args=value\n else:\n kwargs=value\n \n if two:\n return tuple.__new__(cls,(args,kwargs))\n \n return tuple.__new__(cls,(name,args,kwargs))\n \n \n def __init__(self,value=(),name=None,parent=None,two=False,\n from_kall=True):\n self._mock_name=name\n self._mock_parent=parent\n self._mock_from_kall=from_kall\n \n \n def __eq__(self,other):\n try:\n len_other=len(other)\n except TypeError:\n return NotImplemented\n \n self_name=''\n if len(self)==2:\n self_args,self_kwargs=self\n else:\n self_name,self_args,self_kwargs=self\n \n if(getattr(self,'_mock_parent',None)and getattr(other,'_mock_parent',None)\n and self._mock_parent !=other._mock_parent):\n return False\n \n other_name=''\n if len_other ==0:\n other_args,other_kwargs=(),{}\n elif len_other ==3:\n other_name,other_args,other_kwargs=other\n elif len_other ==1:\n value,=other\n if isinstance(value,tuple):\n other_args=value\n other_kwargs={}\n elif isinstance(value,str):\n other_name=value\n other_args,other_kwargs=(),{}\n else:\n other_args=()\n other_kwargs=value\n elif len_other ==2:\n \n first,second=other\n if isinstance(first,str):\n other_name=first\n if isinstance(second,tuple):\n other_args,other_kwargs=second,{}\n else:\n other_args,other_kwargs=(),second\n else:\n other_args,other_kwargs=first,second\n else:\n return False\n \n if self_name and other_name !=self_name:\n return False\n \n \n return(other_args,other_kwargs)==(self_args,self_kwargs)\n \n \n __ne__=object.__ne__\n \n \n def __call__(self,/,*args,**kwargs):\n if self._mock_name is None:\n return _Call(('',args,kwargs),name='()')\n \n name=self._mock_name+'()'\n return _Call((self._mock_name,args,kwargs),name=name,parent=self)\n \n \n def __getattr__(self,attr):\n if self._mock_name is None:\n return _Call(name=attr,from_kall=False)\n name='%s.%s'%(self._mock_name,attr)\n return _Call(name=name,parent=self,from_kall=False)\n \n \n def __getattribute__(self,attr):\n if attr in tuple.__dict__:\n raise AttributeError\n return tuple.__getattribute__(self,attr)\n \n \n def _get_call_arguments(self):\n if len(self)==2:\n args,kwargs=self\n else:\n name,args,kwargs=self\n \n return args,kwargs\n \n @property\n def args(self):\n return self._get_call_arguments()[0]\n \n @property\n def kwargs(self):\n return self._get_call_arguments()[1]\n \n def __repr__(self):\n if not self._mock_from_kall:\n name=self._mock_name or 'call'\n if name.startswith('()'):\n name='call%s'%name\n return name\n \n if len(self)==2:\n name='call'\n args,kwargs=self\n else:\n name,args,kwargs=self\n if not name:\n name='call'\n elif not name.startswith('()'):\n name='call.%s'%name\n else:\n name='call%s'%name\n return _format_call_signature(name,args,kwargs)\n \n \n def call_list(self):\n ''\n\n \n vals=[]\n thing=self\n while thing is not None:\n if thing._mock_from_kall:\n vals.append(thing)\n thing=thing._mock_parent\n return _CallList(reversed(vals))\n \n \ncall=_Call(from_kall=False)\n\n\ndef create_autospec(spec,spec_set=False,instance=False,_parent=None,\n_name=None,*,unsafe=False,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if _is_list(spec):\n \n \n spec=type(spec)\n \n is_type=isinstance(spec,type)\n if _is_instance_mock(spec):\n raise InvalidSpecError(f'Cannot autospec a Mock object. '\n f'[object={spec !r}]')\n is_async_func=_is_async_func(spec)\n _kwargs={'spec':spec}\n if spec_set:\n _kwargs={'spec_set':spec}\n elif spec is None:\n \n _kwargs={}\n if _kwargs and instance:\n _kwargs['_spec_as_instance']=True\n if not unsafe:\n _check_spec_arg_typos(kwargs)\n \n _kwargs.update(kwargs)\n \n Klass=MagicMock\n if inspect.isdatadescriptor(spec):\n \n \n _kwargs={}\n elif is_async_func:\n if instance:\n raise RuntimeError(\"Instance can not be True when create_autospec \"\n \"is mocking an async function\")\n Klass=AsyncMock\n elif not _callable(spec):\n Klass=NonCallableMagicMock\n elif is_type and instance and not _instance_callable(spec):\n Klass=NonCallableMagicMock\n \n _name=_kwargs.pop('name',_name)\n \n _new_name=_name\n if _parent is None:\n \n _new_name=''\n \n mock=Klass(parent=_parent,_new_parent=_parent,_new_name=_new_name,\n name=_name,**_kwargs)\n \n if isinstance(spec,FunctionTypes):\n \n \n if is_async_func:\n mock=_set_async_signature(mock,spec)\n else:\n mock=_set_signature(mock,spec)\n else:\n _check_signature(spec,mock,is_type,instance)\n \n if _parent is not None and not instance:\n _parent._mock_children[_name]=mock\n \n \n wrapped=kwargs.pop('wraps',None)\n if is_type and not instance and 'return_value'not in kwargs:\n mock.return_value=create_autospec(spec,spec_set,instance=True,\n _name='()',_parent=mock,\n wraps=wrapped)\n \n for entry in dir(spec):\n if _is_magic(entry):\n \n continue\n \n \n \n \n \n \n \n \n \n \n try:\n original=getattr(spec,entry)\n except AttributeError:\n continue\n \n child_kwargs={'spec':original}\n \n if wrapped and hasattr(wrapped,entry):\n child_kwargs.update(wraps=original)\n if spec_set:\n child_kwargs={'spec_set':original}\n \n if not isinstance(original,FunctionTypes):\n new=_SpecState(original,spec_set,mock,entry,instance)\n mock._mock_children[entry]=new\n else:\n parent=mock\n if isinstance(spec,FunctionTypes):\n parent=mock.mock\n \n skipfirst=_must_skip(spec,entry,is_type)\n child_kwargs['_eat_self']=skipfirst\n if iscoroutinefunction(original):\n child_klass=AsyncMock\n else:\n child_klass=MagicMock\n new=child_klass(parent=parent,name=entry,_new_name=entry,\n _new_parent=parent,**child_kwargs)\n mock._mock_children[entry]=new\n new.return_value=child_klass()\n _check_signature(original,new,skipfirst=skipfirst)\n \n \n \n \n \n if isinstance(new,FunctionTypes):\n setattr(mock,entry,new)\n \n \n \n if _is_instance_mock(mock)and kwargs:\n mock.configure_mock(**kwargs)\n \n return mock\n \n \ndef _must_skip(spec,entry,is_type):\n ''\n\n\n \n if not isinstance(spec,type):\n if entry in getattr(spec,'__dict__',{}):\n \n return False\n spec=spec.__class__\n \n for klass in spec.__mro__:\n result=klass.__dict__.get(entry,DEFAULT)\n if result is DEFAULT:\n continue\n if isinstance(result,(staticmethod,classmethod)):\n return False\n elif isinstance(result,FunctionTypes):\n \n \n return is_type\n else:\n return False\n \n \n return is_type\n \n \nclass _SpecState(object):\n\n def __init__(self,spec,spec_set=False,parent=None,\n name=None,ids=None,instance=False):\n self.spec=spec\n self.ids=ids\n self.spec_set=spec_set\n self.parent=parent\n self.instance=instance\n self.name=name\n \n \nFunctionTypes=(\n\ntype(create_autospec),\n\ntype(ANY.__eq__),\n)\n\n\nfile_spec=None\nopen_spec=None\n\n\ndef _to_stream(read_data):\n if isinstance(read_data,bytes):\n return io.BytesIO(read_data)\n else:\n return io.StringIO(read_data)\n \n \ndef mock_open(mock=None,read_data=''):\n ''\n\n\n\n\n\n\n\n\n\n \n _read_data=_to_stream(read_data)\n _state=[_read_data,None]\n \n def _readlines_side_effect(*args,**kwargs):\n if handle.readlines.return_value is not None:\n return handle.readlines.return_value\n return _state[0].readlines(*args,**kwargs)\n \n def _read_side_effect(*args,**kwargs):\n if handle.read.return_value is not None:\n return handle.read.return_value\n return _state[0].read(*args,**kwargs)\n \n def _readline_side_effect(*args,**kwargs):\n yield from _iter_side_effect()\n while True:\n yield _state[0].readline(*args,**kwargs)\n \n def _iter_side_effect():\n if handle.readline.return_value is not None:\n while True:\n yield handle.readline.return_value\n for line in _state[0]:\n yield line\n \n def _next_side_effect():\n if handle.readline.return_value is not None:\n return handle.readline.return_value\n return next(_state[0])\n \n def _exit_side_effect(exctype,excinst,exctb):\n handle.close()\n \n global file_spec\n if file_spec is None:\n import _io\n file_spec=list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))\n \n global open_spec\n if open_spec is None:\n import _io\n open_spec=list(set(dir(_io.open)))\n if mock is None:\n mock=MagicMock(name='open',spec=open_spec)\n \n handle=MagicMock(spec=file_spec)\n handle.__enter__.return_value=handle\n \n handle.write.return_value=None\n handle.read.return_value=None\n handle.readline.return_value=None\n handle.readlines.return_value=None\n \n handle.read.side_effect=_read_side_effect\n _state[1]=_readline_side_effect()\n handle.readline.side_effect=_state[1]\n handle.readlines.side_effect=_readlines_side_effect\n handle.__iter__.side_effect=_iter_side_effect\n handle.__next__.side_effect=_next_side_effect\n handle.__exit__.side_effect=_exit_side_effect\n \n def reset_data(*args,**kwargs):\n _state[0]=_to_stream(read_data)\n if handle.readline.side_effect ==_state[1]:\n \n _state[1]=_readline_side_effect()\n handle.readline.side_effect=_state[1]\n return DEFAULT\n \n mock.side_effect=reset_data\n mock.return_value=handle\n return mock\n \n \nclass PropertyMock(Mock):\n ''\n\n\n\n\n\n\n \n def _get_child_mock(self,/,**kwargs):\n return MagicMock(**kwargs)\n \n def __get__(self,obj,obj_type=None):\n return self()\n def __set__(self,obj,val):\n self(val)\n \n \n_timeout_unset=sentinel.TIMEOUT_UNSET\n\nclass ThreadingMixin(Base):\n\n DEFAULT_TIMEOUT=None\n \n def _get_child_mock(self,/,**kw):\n if isinstance(kw.get(\"parent\"),ThreadingMixin):\n kw[\"timeout\"]=kw[\"parent\"]._mock_wait_timeout\n elif isinstance(kw.get(\"_new_parent\"),ThreadingMixin):\n kw[\"timeout\"]=kw[\"_new_parent\"]._mock_wait_timeout\n return super()._get_child_mock(**kw)\n \n def __init__(self,*args,timeout=_timeout_unset,**kwargs):\n super().__init__(*args,**kwargs)\n if timeout is _timeout_unset:\n timeout=self.DEFAULT_TIMEOUT\n self.__dict__[\"_mock_event\"]=threading.Event()\n self.__dict__[\"_mock_calls_events\"]=[]\n self.__dict__[\"_mock_calls_events_lock\"]=threading.Lock()\n self.__dict__[\"_mock_wait_timeout\"]=timeout\n \n def reset_mock(self,/,*args,**kwargs):\n ''\n\n \n super().reset_mock(*args,**kwargs)\n self.__dict__[\"_mock_event\"]=threading.Event()\n self.__dict__[\"_mock_calls_events\"]=[]\n \n def __get_event(self,expected_args,expected_kwargs):\n with self._mock_calls_events_lock:\n for args,kwargs,event in self._mock_calls_events:\n if(args,kwargs)==(expected_args,expected_kwargs):\n return event\n new_event=threading.Event()\n self._mock_calls_events.append((expected_args,expected_kwargs,new_event))\n return new_event\n \n def _mock_call(self,*args,**kwargs):\n ret_value=super()._mock_call(*args,**kwargs)\n \n call_event=self.__get_event(args,kwargs)\n call_event.set()\n \n self._mock_event.set()\n \n return ret_value\n \n def wait_until_called(self,*,timeout=_timeout_unset):\n ''\n\n\n\n\n \n if timeout is _timeout_unset:\n timeout=self._mock_wait_timeout\n if not self._mock_event.wait(timeout=timeout):\n msg=(f\"{self._mock_name or 'mock'} was not called before\"\n f\" timeout({timeout}).\")\n raise AssertionError(msg)\n \n def wait_until_any_call_with(self,*args,**kwargs):\n ''\n\n\n \n event=self.__get_event(args,kwargs)\n if not event.wait(timeout=self._mock_wait_timeout):\n expected_string=self._format_mock_call_signature(args,kwargs)\n raise AssertionError(f'{expected_string} call not found')\n \n \nclass ThreadingMock(ThreadingMixin,MagicMixin,Mock):\n ''\n\n\n\n\n\n\n\n\n\n\n \n pass\n \n \ndef seal(mock):\n ''\n\n\n\n\n\n\n\n \n mock._mock_sealed=True\n for attr in dir(mock):\n try:\n m=getattr(mock,attr)\n except AttributeError:\n continue\n if not isinstance(m,NonCallableMock):\n continue\n if isinstance(m._mock_children.get(attr),_SpecState):\n continue\n if m._mock_new_parent is mock:\n seal(m)\n \n \nclass _AsyncIterator:\n ''\n\n \n def __init__(self,iterator):\n self.iterator=iterator\n code_mock=NonCallableMock(spec_set=CodeType)\n code_mock.co_flags=inspect.CO_ITERABLE_COROUTINE\n self.__dict__['__code__']=code_mock\n \n async def __anext__(self):\n try:\n return next(self.iterator)\n except StopIteration:\n pass\n raise StopAsyncIteration\n", ["_io", "asyncio", "builtins", "contextlib", "functools", "inspect", "io", "pkgutil", "pprint", "sys", "threading", "types", "unittest.util"]], "unittest.result": [".py", "''\n\nimport io\nimport sys\nimport traceback\n\nfrom. import util\nfrom functools import wraps\n\n__unittest=True\n\ndef failfast(method):\n @wraps(method)\n def inner(self,*args,**kw):\n if getattr(self,'failfast',False):\n self.stop()\n return method(self,*args,**kw)\n return inner\n \nSTDOUT_LINE='\\nStdout:\\n%s'\nSTDERR_LINE='\\nStderr:\\n%s'\n\n\nclass TestResult(object):\n ''\n\n\n\n\n\n\n\n\n \n _previousTestClass=None\n _testRunEntered=False\n _moduleSetUpFailed=False\n def __init__(self,stream=None,descriptions=None,verbosity=None):\n self.failfast=False\n self.failures=[]\n self.errors=[]\n self.testsRun=0\n self.skipped=[]\n self.expectedFailures=[]\n self.unexpectedSuccesses=[]\n self.collectedDurations=[]\n self.shouldStop=False\n self.buffer=False\n self.tb_locals=False\n self._stdout_buffer=None\n self._stderr_buffer=None\n self._original_stdout=sys.stdout\n self._original_stderr=sys.stderr\n self._mirrorOutput=False\n \n def printErrors(self):\n ''\n \n def startTest(self,test):\n ''\n self.testsRun +=1\n self._mirrorOutput=False\n self._setupStdout()\n \n def _setupStdout(self):\n if self.buffer:\n if self._stderr_buffer is None:\n self._stderr_buffer=io.StringIO()\n self._stdout_buffer=io.StringIO()\n sys.stdout=self._stdout_buffer\n sys.stderr=self._stderr_buffer\n \n def startTestRun(self):\n ''\n\n\n \n \n def stopTest(self,test):\n ''\n self._restoreStdout()\n self._mirrorOutput=False\n \n def _restoreStdout(self):\n if self.buffer:\n if self._mirrorOutput:\n output=sys.stdout.getvalue()\n error=sys.stderr.getvalue()\n if output:\n if not output.endswith('\\n'):\n output +='\\n'\n self._original_stdout.write(STDOUT_LINE %output)\n if error:\n if not error.endswith('\\n'):\n error +='\\n'\n self._original_stderr.write(STDERR_LINE %error)\n \n sys.stdout=self._original_stdout\n sys.stderr=self._original_stderr\n self._stdout_buffer.seek(0)\n self._stdout_buffer.truncate()\n self._stderr_buffer.seek(0)\n self._stderr_buffer.truncate()\n \n def stopTestRun(self):\n ''\n\n\n \n \n @failfast\n def addError(self,test,err):\n ''\n\n \n self.errors.append((test,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n @failfast\n def addFailure(self,test,err):\n ''\n \n self.failures.append((test,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n def addSubTest(self,test,subtest,err):\n ''\n\n\n \n \n \n if err is not None:\n if getattr(self,'failfast',False):\n self.stop()\n if issubclass(err[0],test.failureException):\n errors=self.failures\n else:\n errors=self.errors\n errors.append((subtest,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n def addSuccess(self,test):\n ''\n pass\n \n def addSkip(self,test,reason):\n ''\n self.skipped.append((test,reason))\n \n def addExpectedFailure(self,test,err):\n ''\n self.expectedFailures.append(\n (test,self._exc_info_to_string(err,test)))\n \n @failfast\n def addUnexpectedSuccess(self,test):\n ''\n self.unexpectedSuccesses.append(test)\n \n def addDuration(self,test,elapsed):\n ''\n\n\n\n \n \n if hasattr(self,\"collectedDurations\"):\n \n self.collectedDurations.append((str(test),elapsed))\n \n def wasSuccessful(self):\n ''\n \n \n \n return((len(self.failures)==len(self.errors)==0)and\n (not hasattr(self,'unexpectedSuccesses')or\n len(self.unexpectedSuccesses)==0))\n \n def stop(self):\n ''\n self.shouldStop=True\n \n def _exc_info_to_string(self,err,test):\n ''\n exctype,value,tb=err\n tb=self._clean_tracebacks(exctype,value,tb,test)\n tb_e=traceback.TracebackException(\n exctype,value,tb,\n capture_locals=self.tb_locals,compact=True)\n msgLines=list(tb_e.format())\n \n if self.buffer:\n output=sys.stdout.getvalue()\n error=sys.stderr.getvalue()\n if output:\n if not output.endswith('\\n'):\n output +='\\n'\n msgLines.append(STDOUT_LINE %output)\n if error:\n if not error.endswith('\\n'):\n error +='\\n'\n msgLines.append(STDERR_LINE %error)\n return ''.join(msgLines)\n \n def _clean_tracebacks(self,exctype,value,tb,test):\n ret=None\n first=True\n excs=[(exctype,value,tb)]\n seen={id(value)}\n while excs:\n (exctype,value,tb)=excs.pop()\n \n while tb and self._is_relevant_tb_level(tb):\n tb=tb.tb_next\n \n \n if exctype is test.failureException:\n self._remove_unittest_tb_frames(tb)\n \n if first:\n ret=tb\n first=False\n else:\n value.__traceback__=tb\n \n if value is not None:\n for c in(value.__cause__,value.__context__):\n if c is not None and id(c)not in seen:\n excs.append((type(c),c,c.__traceback__))\n seen.add(id(c))\n return ret\n \n def _is_relevant_tb_level(self,tb):\n return '__unittest'in tb.tb_frame.f_globals\n \n def _remove_unittest_tb_frames(self,tb):\n ''\n\n\n\n\n\n \n prev=None\n while tb and not self._is_relevant_tb_level(tb):\n prev=tb\n tb=tb.tb_next\n if prev is not None:\n prev.tb_next=None\n \n def __repr__(self):\n return(\"<%s run=%i errors=%i failures=%i>\"%\n (util.strclass(self.__class__),self.testsRun,len(self.errors),\n len(self.failures)))\n", ["functools", "io", "sys", "traceback", "unittest", "unittest.util"]], "unittest.runner": [".py", "''\n\nimport sys\nimport time\nimport warnings\n\nfrom. import result\nfrom.case import _SubTest\nfrom.signals import registerResult\n\n__unittest=True\n\n\nclass _WritelnDecorator(object):\n ''\n def __init__(self,stream):\n self.stream=stream\n \n def __getattr__(self,attr):\n if attr in('stream','__getstate__'):\n raise AttributeError(attr)\n return getattr(self.stream,attr)\n \n def writeln(self,arg=None):\n if arg:\n self.write(arg)\n self.write('\\n')\n \n \nclass TextTestResult(result.TestResult):\n ''\n\n\n \n separator1='='*70\n separator2='-'*70\n \n def __init__(self,stream,descriptions,verbosity,*,durations=None):\n ''\n \n super(TextTestResult,self).__init__(stream,descriptions,verbosity)\n self.stream=stream\n self.showAll=verbosity >1\n self.dots=verbosity ==1\n self.descriptions=descriptions\n self._newline=True\n self.durations=durations\n \n def getDescription(self,test):\n doc_first_line=test.shortDescription()\n if self.descriptions and doc_first_line:\n return '\\n'.join((str(test),doc_first_line))\n else:\n return str(test)\n \n def startTest(self,test):\n super(TextTestResult,self).startTest(test)\n if self.showAll:\n self.stream.write(self.getDescription(test))\n self.stream.write(\" ... \")\n self.stream.flush()\n self._newline=False\n \n def _write_status(self,test,status):\n is_subtest=isinstance(test,_SubTest)\n if is_subtest or self._newline:\n if not self._newline:\n self.stream.writeln()\n if is_subtest:\n self.stream.write(\" \")\n self.stream.write(self.getDescription(test))\n self.stream.write(\" ... \")\n self.stream.writeln(status)\n self.stream.flush()\n self._newline=True\n \n def addSubTest(self,test,subtest,err):\n if err is not None:\n if self.showAll:\n if issubclass(err[0],subtest.failureException):\n self._write_status(subtest,\"FAIL\")\n else:\n self._write_status(subtest,\"ERROR\")\n elif self.dots:\n if issubclass(err[0],subtest.failureException):\n self.stream.write('F')\n else:\n self.stream.write('E')\n self.stream.flush()\n super(TextTestResult,self).addSubTest(test,subtest,err)\n \n def addSuccess(self,test):\n super(TextTestResult,self).addSuccess(test)\n if self.showAll:\n self._write_status(test,\"ok\")\n elif self.dots:\n self.stream.write('.')\n self.stream.flush()\n \n def addError(self,test,err):\n super(TextTestResult,self).addError(test,err)\n if self.showAll:\n self._write_status(test,\"ERROR\")\n elif self.dots:\n self.stream.write('E')\n self.stream.flush()\n \n def addFailure(self,test,err):\n super(TextTestResult,self).addFailure(test,err)\n if self.showAll:\n self._write_status(test,\"FAIL\")\n elif self.dots:\n self.stream.write('F')\n self.stream.flush()\n \n def addSkip(self,test,reason):\n super(TextTestResult,self).addSkip(test,reason)\n if self.showAll:\n self._write_status(test,\"skipped {0!r}\".format(reason))\n elif self.dots:\n self.stream.write(\"s\")\n self.stream.flush()\n \n def addExpectedFailure(self,test,err):\n super(TextTestResult,self).addExpectedFailure(test,err)\n if self.showAll:\n self.stream.writeln(\"expected failure\")\n self.stream.flush()\n elif self.dots:\n self.stream.write(\"x\")\n self.stream.flush()\n \n def addUnexpectedSuccess(self,test):\n super(TextTestResult,self).addUnexpectedSuccess(test)\n if self.showAll:\n self.stream.writeln(\"unexpected success\")\n self.stream.flush()\n elif self.dots:\n self.stream.write(\"u\")\n self.stream.flush()\n \n def printErrors(self):\n if self.dots or self.showAll:\n self.stream.writeln()\n self.stream.flush()\n self.printErrorList('ERROR',self.errors)\n self.printErrorList('FAIL',self.failures)\n unexpectedSuccesses=getattr(self,'unexpectedSuccesses',())\n if unexpectedSuccesses:\n self.stream.writeln(self.separator1)\n for test in unexpectedSuccesses:\n self.stream.writeln(f\"UNEXPECTED SUCCESS: {self.getDescription(test)}\")\n self.stream.flush()\n \n def printErrorList(self,flavour,errors):\n for test,err in errors:\n self.stream.writeln(self.separator1)\n self.stream.writeln(\"%s: %s\"%(flavour,self.getDescription(test)))\n self.stream.writeln(self.separator2)\n self.stream.writeln(\"%s\"%err)\n self.stream.flush()\n \n \nclass TextTestRunner(object):\n ''\n\n\n\n \n resultclass=TextTestResult\n \n def __init__(self,stream=None,descriptions=True,verbosity=1,\n failfast=False,buffer=False,resultclass=None,warnings=None,\n *,tb_locals=False,durations=None):\n ''\n\n\n\n \n if stream is None:\n stream=sys.stderr\n self.stream=_WritelnDecorator(stream)\n self.descriptions=descriptions\n self.verbosity=verbosity\n self.failfast=failfast\n self.buffer=buffer\n self.tb_locals=tb_locals\n self.durations=durations\n self.warnings=warnings\n if resultclass is not None:\n self.resultclass=resultclass\n \n def _makeResult(self):\n try:\n return self.resultclass(self.stream,self.descriptions,\n self.verbosity,durations=self.durations)\n except TypeError:\n \n return self.resultclass(self.stream,self.descriptions,\n self.verbosity)\n \n def _printDurations(self,result):\n if not result.collectedDurations:\n return\n ls=sorted(result.collectedDurations,key=lambda x:x[1],\n reverse=True)\n if self.durations >0:\n ls=ls[:self.durations]\n self.stream.writeln(\"Slowest test durations\")\n if hasattr(result,'separator2'):\n self.stream.writeln(result.separator2)\n hidden=False\n for test,elapsed in ls:\n if self.verbosity <2 and elapsed <0.001:\n hidden=True\n continue\n self.stream.writeln(\"%-10s %s\"%(\"%.3fs\"%elapsed,test))\n if hidden:\n self.stream.writeln(\"\\n(durations < 0.001s were hidden; \"\n \"use -v to show these durations)\")\n else:\n self.stream.writeln(\"\")\n \n def run(self,test):\n ''\n result=self._makeResult()\n registerResult(result)\n result.failfast=self.failfast\n result.buffer=self.buffer\n result.tb_locals=self.tb_locals\n with warnings.catch_warnings():\n if self.warnings:\n \n warnings.simplefilter(self.warnings)\n startTime=time.perf_counter()\n startTestRun=getattr(result,'startTestRun',None)\n if startTestRun is not None:\n startTestRun()\n try:\n test(result)\n finally:\n stopTestRun=getattr(result,'stopTestRun',None)\n if stopTestRun is not None:\n stopTestRun()\n stopTime=time.perf_counter()\n timeTaken=stopTime -startTime\n result.printErrors()\n if self.durations is not None:\n self._printDurations(result)\n \n if hasattr(result,'separator2'):\n self.stream.writeln(result.separator2)\n \n run=result.testsRun\n self.stream.writeln(\"Ran %d test%s in %.3fs\"%\n (run,run !=1 and \"s\"or \"\",timeTaken))\n self.stream.writeln()\n \n expectedFails=unexpectedSuccesses=skipped=0\n try:\n results=map(len,(result.expectedFailures,\n result.unexpectedSuccesses,\n result.skipped))\n except AttributeError:\n pass\n else:\n expectedFails,unexpectedSuccesses,skipped=results\n \n infos=[]\n if not result.wasSuccessful():\n self.stream.write(\"FAILED\")\n failed,errored=len(result.failures),len(result.errors)\n if failed:\n infos.append(\"failures=%d\"%failed)\n if errored:\n infos.append(\"errors=%d\"%errored)\n elif run ==0 and not skipped:\n self.stream.write(\"NO TESTS RAN\")\n else:\n self.stream.write(\"OK\")\n if skipped:\n infos.append(\"skipped=%d\"%skipped)\n if expectedFails:\n infos.append(\"expected failures=%d\"%expectedFails)\n if unexpectedSuccesses:\n infos.append(\"unexpected successes=%d\"%unexpectedSuccesses)\n if infos:\n self.stream.writeln(\" (%s)\"%(\", \".join(infos),))\n else:\n self.stream.write(\"\\n\")\n self.stream.flush()\n return result\n", ["sys", "time", "unittest", "unittest.case", "unittest.result", "unittest.signals", "warnings"]], "unittest.signals": [".py", "import signal\nimport weakref\n\nfrom functools import wraps\n\n__unittest=True\n\n\nclass _InterruptHandler(object):\n def __init__(self,default_handler):\n self.called=False\n self.original_handler=default_handler\n if isinstance(default_handler,int):\n if default_handler ==signal.SIG_DFL:\n \n default_handler=signal.default_int_handler\n elif default_handler ==signal.SIG_IGN:\n \n \n def default_handler(unused_signum,unused_frame):\n pass\n else:\n raise TypeError(\"expected SIGINT signal handler to be \"\n \"signal.SIG_IGN, signal.SIG_DFL, or a \"\n \"callable object\")\n self.default_handler=default_handler\n \n def __call__(self,signum,frame):\n installed_handler=signal.getsignal(signal.SIGINT)\n if installed_handler is not self:\n \n \n self.default_handler(signum,frame)\n \n if self.called:\n self.default_handler(signum,frame)\n self.called=True\n for result in _results.keys():\n result.stop()\n \n_results=weakref.WeakKeyDictionary()\ndef registerResult(result):\n _results[result]=1\n \ndef removeResult(result):\n return bool(_results.pop(result,None))\n \n_interrupt_handler=None\ndef installHandler():\n global _interrupt_handler\n if _interrupt_handler is None:\n default_handler=signal.getsignal(signal.SIGINT)\n _interrupt_handler=_InterruptHandler(default_handler)\n signal.signal(signal.SIGINT,_interrupt_handler)\n \n \ndef removeHandler(method=None):\n if method is not None:\n @wraps(method)\n def inner(*args,**kwargs):\n initial=signal.getsignal(signal.SIGINT)\n removeHandler()\n try:\n return method(*args,**kwargs)\n finally:\n signal.signal(signal.SIGINT,initial)\n return inner\n \n global _interrupt_handler\n if _interrupt_handler is not None:\n signal.signal(signal.SIGINT,_interrupt_handler.original_handler)\n", ["functools", "signal", "weakref"]], "unittest.suite": [".py", "''\n\nimport sys\n\nfrom. import case\nfrom. import util\n\n__unittest=True\n\n\ndef _call_if_exists(parent,attr):\n func=getattr(parent,attr,lambda:None)\n func()\n \n \nclass BaseTestSuite(object):\n ''\n \n _cleanup=True\n \n def __init__(self,tests=()):\n self._tests=[]\n self._removed_tests=0\n self.addTests(tests)\n \n def __repr__(self):\n return \"<%s tests=%s>\"%(util.strclass(self.__class__),list(self))\n \n def __eq__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n return list(self)==list(other)\n \n def __iter__(self):\n return iter(self._tests)\n \n def countTestCases(self):\n cases=self._removed_tests\n for test in self:\n if test:\n cases +=test.countTestCases()\n return cases\n \n def addTest(self,test):\n \n if not callable(test):\n raise TypeError(\"{} is not callable\".format(repr(test)))\n if isinstance(test,type)and issubclass(test,\n (case.TestCase,TestSuite)):\n raise TypeError(\"TestCases and TestSuites must be instantiated \"\n \"before passing them to addTest()\")\n self._tests.append(test)\n \n def addTests(self,tests):\n if isinstance(tests,str):\n raise TypeError(\"tests must be an iterable of tests, not a string\")\n for test in tests:\n self.addTest(test)\n \n def run(self,result):\n for index,test in enumerate(self):\n if result.shouldStop:\n break\n test(result)\n if self._cleanup:\n self._removeTestAtIndex(index)\n return result\n \n def _removeTestAtIndex(self,index):\n ''\n try:\n test=self._tests[index]\n except TypeError:\n \n pass\n else:\n \n \n if hasattr(test,'countTestCases'):\n self._removed_tests +=test.countTestCases()\n self._tests[index]=None\n \n def __call__(self,*args,**kwds):\n return self.run(*args,**kwds)\n \n def debug(self):\n ''\n for test in self:\n test.debug()\n \n \nclass TestSuite(BaseTestSuite):\n ''\n\n\n\n\n\n\n \n \n def run(self,result,debug=False):\n topLevel=False\n if getattr(result,'_testRunEntered',False)is False:\n result._testRunEntered=topLevel=True\n \n for index,test in enumerate(self):\n if result.shouldStop:\n break\n \n if _isnotsuite(test):\n self._tearDownPreviousClass(test,result)\n self._handleModuleFixture(test,result)\n self._handleClassSetUp(test,result)\n result._previousTestClass=test.__class__\n \n if(getattr(test.__class__,'_classSetupFailed',False)or\n getattr(result,'_moduleSetUpFailed',False)):\n continue\n \n if not debug:\n test(result)\n else:\n test.debug()\n \n if self._cleanup:\n self._removeTestAtIndex(index)\n \n if topLevel:\n self._tearDownPreviousClass(None,result)\n self._handleModuleTearDown(result)\n result._testRunEntered=False\n return result\n \n def debug(self):\n ''\n debug=_DebugResult()\n self.run(debug,True)\n \n \n \n def _handleClassSetUp(self,test,result):\n previousClass=getattr(result,'_previousTestClass',None)\n currentClass=test.__class__\n if currentClass ==previousClass:\n return\n if result._moduleSetUpFailed:\n return\n if getattr(currentClass,\"__unittest_skip__\",False):\n return\n \n failed=False\n try:\n currentClass._classSetupFailed=False\n except TypeError:\n \n \n pass\n \n setUpClass=getattr(currentClass,'setUpClass',None)\n doClassCleanups=getattr(currentClass,'doClassCleanups',None)\n if setUpClass is not None:\n _call_if_exists(result,'_setupStdout')\n try:\n try:\n setUpClass()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n failed=True\n try:\n currentClass._classSetupFailed=True\n except TypeError:\n pass\n className=util.strclass(currentClass)\n self._createClassOrModuleLevelException(result,e,\n 'setUpClass',\n className)\n if failed and doClassCleanups is not None:\n doClassCleanups()\n for exc_info in currentClass.tearDown_exceptions:\n self._createClassOrModuleLevelException(\n result,exc_info[1],'setUpClass',className,\n info=exc_info)\n finally:\n _call_if_exists(result,'_restoreStdout')\n \n def _get_previous_module(self,result):\n previousModule=None\n previousClass=getattr(result,'_previousTestClass',None)\n if previousClass is not None:\n previousModule=previousClass.__module__\n return previousModule\n \n \n def _handleModuleFixture(self,test,result):\n previousModule=self._get_previous_module(result)\n currentModule=test.__class__.__module__\n if currentModule ==previousModule:\n return\n \n self._handleModuleTearDown(result)\n \n \n result._moduleSetUpFailed=False\n try:\n module=sys.modules[currentModule]\n except KeyError:\n return\n setUpModule=getattr(module,'setUpModule',None)\n if setUpModule is not None:\n _call_if_exists(result,'_setupStdout')\n try:\n try:\n setUpModule()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n result._moduleSetUpFailed=True\n self._createClassOrModuleLevelException(result,e,\n 'setUpModule',\n currentModule)\n if result._moduleSetUpFailed:\n try:\n case.doModuleCleanups()\n except Exception as e:\n self._createClassOrModuleLevelException(result,e,\n 'setUpModule',\n currentModule)\n finally:\n _call_if_exists(result,'_restoreStdout')\n \n def _createClassOrModuleLevelException(self,result,exc,method_name,\n parent,info=None):\n errorName=f'{method_name} ({parent})'\n self._addClassOrModuleLevelException(result,exc,errorName,info)\n \n def _addClassOrModuleLevelException(self,result,exception,errorName,\n info=None):\n error=_ErrorHolder(errorName)\n addSkip=getattr(result,'addSkip',None)\n if addSkip is not None and isinstance(exception,case.SkipTest):\n addSkip(error,str(exception))\n else:\n if not info:\n result.addError(error,sys.exc_info())\n else:\n result.addError(error,info)\n \n def _handleModuleTearDown(self,result):\n previousModule=self._get_previous_module(result)\n if previousModule is None:\n return\n if result._moduleSetUpFailed:\n return\n \n try:\n module=sys.modules[previousModule]\n except KeyError:\n return\n \n _call_if_exists(result,'_setupStdout')\n try:\n tearDownModule=getattr(module,'tearDownModule',None)\n if tearDownModule is not None:\n try:\n tearDownModule()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n self._createClassOrModuleLevelException(result,e,\n 'tearDownModule',\n previousModule)\n try:\n case.doModuleCleanups()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n self._createClassOrModuleLevelException(result,e,\n 'tearDownModule',\n previousModule)\n finally:\n _call_if_exists(result,'_restoreStdout')\n \n def _tearDownPreviousClass(self,test,result):\n previousClass=getattr(result,'_previousTestClass',None)\n currentClass=test.__class__\n if currentClass ==previousClass or previousClass is None:\n return\n if getattr(previousClass,'_classSetupFailed',False):\n return\n if getattr(result,'_moduleSetUpFailed',False):\n return\n if getattr(previousClass,\"__unittest_skip__\",False):\n return\n \n tearDownClass=getattr(previousClass,'tearDownClass',None)\n doClassCleanups=getattr(previousClass,'doClassCleanups',None)\n if tearDownClass is None and doClassCleanups is None:\n return\n \n _call_if_exists(result,'_setupStdout')\n try:\n if tearDownClass is not None:\n try:\n tearDownClass()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n className=util.strclass(previousClass)\n self._createClassOrModuleLevelException(result,e,\n 'tearDownClass',\n className)\n if doClassCleanups is not None:\n doClassCleanups()\n for exc_info in previousClass.tearDown_exceptions:\n if isinstance(result,_DebugResult):\n raise exc_info[1]\n className=util.strclass(previousClass)\n self._createClassOrModuleLevelException(result,exc_info[1],\n 'tearDownClass',\n className,\n info=exc_info)\n finally:\n _call_if_exists(result,'_restoreStdout')\n \n \nclass _ErrorHolder(object):\n ''\n\n\n\n \n \n \n \n \n failureException=None\n \n def __init__(self,description):\n self.description=description\n \n def id(self):\n return self.description\n \n def shortDescription(self):\n return None\n \n def __repr__(self):\n return \"\"%(self.description,)\n \n def __str__(self):\n return self.id()\n \n def run(self,result):\n \n \n pass\n \n def __call__(self,result):\n return self.run(result)\n \n def countTestCases(self):\n return 0\n \ndef _isnotsuite(test):\n ''\n try:\n iter(test)\n except TypeError:\n return True\n return False\n \n \nclass _DebugResult(object):\n ''\n _previousTestClass=None\n _moduleSetUpFailed=False\n shouldStop=False\n", ["sys", "unittest", "unittest.case", "unittest.util"]], "unittest.util": [".py", "''\n\nfrom collections import namedtuple,Counter\nfrom os.path import commonprefix\n\n__unittest=True\n\n_MAX_LENGTH=80\n_PLACEHOLDER_LEN=12\n_MIN_BEGIN_LEN=5\n_MIN_END_LEN=5\n_MIN_COMMON_LEN=5\n_MIN_DIFF_LEN=_MAX_LENGTH -\\\n(_MIN_BEGIN_LEN+_PLACEHOLDER_LEN+_MIN_COMMON_LEN+\n_PLACEHOLDER_LEN+_MIN_END_LEN)\nassert _MIN_DIFF_LEN >=0\n\ndef _shorten(s,prefixlen,suffixlen):\n skip=len(s)-prefixlen -suffixlen\n if skip >_PLACEHOLDER_LEN:\n s='%s[%d chars]%s'%(s[:prefixlen],skip,s[len(s)-suffixlen:])\n return s\n \ndef _common_shorten_repr(*args):\n args=tuple(map(safe_repr,args))\n maxlen=max(map(len,args))\n if maxlen <=_MAX_LENGTH:\n return args\n \n prefix=commonprefix(args)\n prefixlen=len(prefix)\n \n common_len=_MAX_LENGTH -\\\n (maxlen -prefixlen+_MIN_BEGIN_LEN+_PLACEHOLDER_LEN)\n if common_len >_MIN_COMMON_LEN:\n assert _MIN_BEGIN_LEN+_PLACEHOLDER_LEN+_MIN_COMMON_LEN+\\\n (maxlen -prefixlen)<_MAX_LENGTH\n prefix=_shorten(prefix,_MIN_BEGIN_LEN,common_len)\n return tuple(prefix+s[prefixlen:]for s in args)\n \n prefix=_shorten(prefix,_MIN_BEGIN_LEN,_MIN_COMMON_LEN)\n return tuple(prefix+_shorten(s[prefixlen:],_MIN_DIFF_LEN,_MIN_END_LEN)\n for s in args)\n \ndef safe_repr(obj,short=False):\n try:\n result=repr(obj)\n except Exception:\n result=object.__repr__(obj)\n if not short or len(result)<_MAX_LENGTH:\n return result\n return result[:_MAX_LENGTH]+' [truncated]...'\n \ndef strclass(cls):\n return \"%s.%s\"%(cls.__module__,cls.__qualname__)\n \ndef sorted_list_difference(expected,actual):\n ''\n\n\n\n\n\n \n i=j=0\n missing=[]\n unexpected=[]\n while True:\n try:\n e=expected[i]\n a=actual[j]\n if e a:\n unexpected.append(a)\n j +=1\n while actual[j]==a:\n j +=1\n else:\n i +=1\n try:\n while expected[i]==e:\n i +=1\n finally:\n j +=1\n while actual[j]==a:\n j +=1\n except IndexError:\n missing.extend(expected[i:])\n unexpected.extend(actual[j:])\n break\n return missing,unexpected\n \n \ndef unorderable_list_difference(expected,actual):\n ''\n\n\n\n \n missing=[]\n while expected:\n item=expected.pop()\n try:\n actual.remove(item)\n except ValueError:\n missing.append(item)\n \n \n return missing,actual\n \ndef three_way_cmp(x,y):\n ''\n return(x >y)-(x 0:\n self._raiseFailure(\n \"Unexpected logs found: {!r}\".format(\n self.watcher.output\n )\n )\n \n else:\n \n if len(self.watcher.records)==0:\n self._raiseFailure(\n \"no logs of level {} or higher triggered on {}\"\n .format(logging.getLevelName(self.level),self.logger.name))\n", ["collections", "logging", "unittest.case"]], "unittest": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['TestResult','TestCase','IsolatedAsyncioTestCase','TestSuite',\n'TextTestRunner','TestLoader','FunctionTestCase','main',\n'defaultTestLoader','SkipTest','skip','skipIf','skipUnless',\n'expectedFailure','TextTestResult','installHandler',\n'registerResult','removeResult','removeHandler',\n'addModuleCleanup','doModuleCleanups','enterModuleContext']\n\n__unittest=True\n\nfrom.result import TestResult\nfrom.case import(addModuleCleanup,TestCase,FunctionTestCase,SkipTest,skip,\nskipIf,skipUnless,expectedFailure,doModuleCleanups,\nenterModuleContext)\nfrom.suite import BaseTestSuite,TestSuite\nfrom.loader import TestLoader,defaultTestLoader\nfrom.main import TestProgram,main\nfrom.runner import TextTestRunner,TextTestResult\nfrom.signals import installHandler,registerResult,removeResult,removeHandler\n\n\n\n\n\n\n\ndef __dir__():\n return globals().keys()|{'IsolatedAsyncioTestCase'}\n \ndef __getattr__(name):\n if name =='IsolatedAsyncioTestCase':\n global IsolatedAsyncioTestCase\n from.async_case import IsolatedAsyncioTestCase\n return IsolatedAsyncioTestCase\n raise AttributeError(f\"module {__name__ !r} has no attribute {name !r}\")\n", ["unittest.async_case", "unittest.case", "unittest.loader", "unittest.main", "unittest.result", "unittest.runner", "unittest.signals", "unittest.suite"], 1], "unittest.__main__": [".py", "''\n\nimport sys\nif sys.argv[0].endswith(\"__main__.py\"):\n import os.path\n \n \n \n \n executable=os.path.basename(sys.executable)\n sys.argv[0]=executable+\" -m unittest\"\n del os\n \n__unittest=True\n\nfrom.main import main\n\nmain(module=None)\n", ["os.path", "sys", "unittest.main"]], "urllib.error": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\nimport io\nimport urllib.response\n\n__all__=['URLError','HTTPError','ContentTooShortError']\n\n\nclass URLError(OSError):\n\n\n\n\n\n def __init__(self,reason,filename=None):\n self.args=reason,\n self.reason=reason\n if filename is not None:\n self.filename=filename\n \n def __str__(self):\n return ''%self.reason\n \n \nclass HTTPError(URLError,urllib.response.addinfourl):\n ''\n __super_init=urllib.response.addinfourl.__init__\n \n def __init__(self,url,code,msg,hdrs,fp):\n self.code=code\n self.msg=msg\n self.hdrs=hdrs\n self.fp=fp\n self.filename=url\n if fp is None:\n fp=io.BytesIO()\n self.__super_init(fp,hdrs,url,code)\n \n def __str__(self):\n return 'HTTP Error %s: %s'%(self.code,self.msg)\n \n def __repr__(self):\n return ''%(self.code,self.msg)\n \n \n \n @property\n def reason(self):\n return self.msg\n \n @property\n def headers(self):\n return self.hdrs\n \n @headers.setter\n def headers(self,headers):\n self.hdrs=headers\n \n \nclass ContentTooShortError(URLError):\n ''\n def __init__(self,message,content):\n URLError.__init__(self,message)\n self.content=content\n", ["io", "urllib.response"]], "urllib.parse": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom collections import namedtuple\nimport functools\nimport math\nimport re\nimport types\nimport warnings\nimport ipaddress\n\n__all__=[\"urlparse\",\"urlunparse\",\"urljoin\",\"urldefrag\",\n\"urlsplit\",\"urlunsplit\",\"urlencode\",\"parse_qs\",\n\"parse_qsl\",\"quote\",\"quote_plus\",\"quote_from_bytes\",\n\"unquote\",\"unquote_plus\",\"unquote_to_bytes\",\n\"DefragResult\",\"ParseResult\",\"SplitResult\",\n\"DefragResultBytes\",\"ParseResultBytes\",\"SplitResultBytes\"]\n\n\n\n\n\nuses_relative=['','ftp','http','gopher','nntp','imap',\n'wais','file','https','shttp','mms',\n'prospero','rtsp','rtsps','rtspu','sftp',\n'svn','svn+ssh','ws','wss']\n\nuses_netloc=['','ftp','http','gopher','nntp','telnet',\n'imap','wais','file','mms','https','shttp',\n'snews','prospero','rtsp','rtsps','rtspu','rsync',\n'svn','svn+ssh','sftp','nfs','git','git+ssh',\n'ws','wss','itms-services']\n\nuses_params=['','ftp','hdl','prospero','http','imap',\n'https','shttp','rtsp','rtsps','rtspu','sip',\n'sips','mms','sftp','tel']\n\n\n\n\nnon_hierarchical=['gopher','hdl','mailto','news',\n'telnet','wais','imap','snews','sip','sips']\n\nuses_query=['','http','wais','imap','https','shttp','mms',\n'gopher','rtsp','rtsps','rtspu','sip','sips']\n\nuses_fragment=['','ftp','hdl','http','gopher','news',\n'nntp','wais','https','shttp','snews',\n'file','prospero']\n\n\nscheme_chars=('abcdefghijklmnopqrstuvwxyz'\n'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n'0123456789'\n'+-.')\n\n\n\n_WHATWG_C0_CONTROL_OR_SPACE='\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f '\n\n\n_UNSAFE_URL_BYTES_TO_REMOVE=['\\t','\\r','\\n']\n\ndef clear_cache():\n ''\n urlsplit.cache_clear()\n _byte_quoter_factory.cache_clear()\n \n \n \n \n \n \n \n_implicit_encoding='ascii'\n_implicit_errors='strict'\n\ndef _noop(obj):\n return obj\n \ndef _encode_result(obj,encoding=_implicit_encoding,\nerrors=_implicit_errors):\n return obj.encode(encoding,errors)\n \ndef _decode_args(args,encoding=_implicit_encoding,\nerrors=_implicit_errors):\n return tuple(x.decode(encoding,errors)if x else ''for x in args)\n \ndef _coerce_args(*args):\n\n\n\n\n\n str_input=isinstance(args[0],str)\n for arg in args[1:]:\n \n \n if arg and isinstance(arg,str)!=str_input:\n raise TypeError(\"Cannot mix str and non-str arguments\")\n if str_input:\n return args+(_noop,)\n return _decode_args(args)+(_encode_result,)\n \n \nclass _ResultMixinStr(object):\n ''\n __slots__=()\n \n def encode(self,encoding='ascii',errors='strict'):\n return self._encoded_counterpart(*(x.encode(encoding,errors)for x in self))\n \n \nclass _ResultMixinBytes(object):\n ''\n __slots__=()\n \n def decode(self,encoding='ascii',errors='strict'):\n return self._decoded_counterpart(*(x.decode(encoding,errors)for x in self))\n \n \nclass _NetlocResultMixinBase(object):\n ''\n __slots__=()\n \n @property\n def username(self):\n return self._userinfo[0]\n \n @property\n def password(self):\n return self._userinfo[1]\n \n @property\n def hostname(self):\n hostname=self._hostinfo[0]\n if not hostname:\n return None\n \n \n separator='%'if isinstance(hostname,str)else b'%'\n hostname,percent,zone=hostname.partition(separator)\n return hostname.lower()+percent+zone\n \n @property\n def port(self):\n port=self._hostinfo[1]\n if port is not None:\n if port.isdigit()and port.isascii():\n port=int(port)\n else:\n raise ValueError(f\"Port could not be cast to integer value as {port !r}\")\n if not(0 <=port <=65535):\n raise ValueError(\"Port out of range 0-65535\")\n return port\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \nclass _NetlocResultMixinStr(_NetlocResultMixinBase,_ResultMixinStr):\n __slots__=()\n \n @property\n def _userinfo(self):\n netloc=self.netloc\n userinfo,have_info,hostinfo=netloc.rpartition('@')\n if have_info:\n username,have_password,password=userinfo.partition(':')\n if not have_password:\n password=None\n else:\n username=password=None\n return username,password\n \n @property\n def _hostinfo(self):\n netloc=self.netloc\n _,_,hostinfo=netloc.rpartition('@')\n _,have_open_br,bracketed=hostinfo.partition('[')\n if have_open_br:\n hostname,_,port=bracketed.partition(']')\n _,_,port=port.partition(':')\n else:\n hostname,_,port=hostinfo.partition(':')\n if not port:\n port=None\n return hostname,port\n \n \nclass _NetlocResultMixinBytes(_NetlocResultMixinBase,_ResultMixinBytes):\n __slots__=()\n \n @property\n def _userinfo(self):\n netloc=self.netloc\n userinfo,have_info,hostinfo=netloc.rpartition(b'@')\n if have_info:\n username,have_password,password=userinfo.partition(b':')\n if not have_password:\n password=None\n else:\n username=password=None\n return username,password\n \n @property\n def _hostinfo(self):\n netloc=self.netloc\n _,_,hostinfo=netloc.rpartition(b'@')\n _,have_open_br,bracketed=hostinfo.partition(b'[')\n if have_open_br:\n hostname,_,port=bracketed.partition(b']')\n _,_,port=port.partition(b':')\n else:\n hostname,_,port=hostinfo.partition(b':')\n if not port:\n port=None\n return hostname,port\n \n \n_DefragResultBase=namedtuple('DefragResult','url fragment')\n_SplitResultBase=namedtuple(\n'SplitResult','scheme netloc path query fragment')\n_ParseResultBase=namedtuple(\n'ParseResult','scheme netloc path params query fragment')\n\n_DefragResultBase.__doc__=\"\"\"\nDefragResult(url, fragment)\n\nA 2-tuple that contains the url without fragment identifier and the fragment\nidentifier as a separate argument.\n\"\"\"\n\n_DefragResultBase.url.__doc__=\"\"\"The URL with no fragment identifier.\"\"\"\n\n_DefragResultBase.fragment.__doc__=\"\"\"\nFragment identifier separated from URL, that allows indirect identification of a\nsecondary resource by reference to a primary resource and additional identifying\ninformation.\n\"\"\"\n\n_SplitResultBase.__doc__=\"\"\"\nSplitResult(scheme, netloc, path, query, fragment)\n\nA 5-tuple that contains the different components of a URL. Similar to\nParseResult, but does not split params.\n\"\"\"\n\n_SplitResultBase.scheme.__doc__=\"\"\"Specifies URL scheme for the request.\"\"\"\n\n_SplitResultBase.netloc.__doc__=\"\"\"\nNetwork location where the request is made to.\n\"\"\"\n\n_SplitResultBase.path.__doc__=\"\"\"\nThe hierarchical path, such as the path to a file to download.\n\"\"\"\n\n_SplitResultBase.query.__doc__=\"\"\"\nThe query component, that contains non-hierarchical data, that along with data\nin path component, identifies a resource in the scope of URI's scheme and\nnetwork location.\n\"\"\"\n\n_SplitResultBase.fragment.__doc__=\"\"\"\nFragment identifier, that allows indirect identification of a secondary resource\nby reference to a primary resource and additional identifying information.\n\"\"\"\n\n_ParseResultBase.__doc__=\"\"\"\nParseResult(scheme, netloc, path, params, query, fragment)\n\nA 6-tuple that contains components of a parsed URL.\n\"\"\"\n\n_ParseResultBase.scheme.__doc__=_SplitResultBase.scheme.__doc__\n_ParseResultBase.netloc.__doc__=_SplitResultBase.netloc.__doc__\n_ParseResultBase.path.__doc__=_SplitResultBase.path.__doc__\n_ParseResultBase.params.__doc__=\"\"\"\nParameters for last path element used to dereference the URI in order to provide\naccess to perform some operation on the resource.\n\"\"\"\n\n_ParseResultBase.query.__doc__=_SplitResultBase.query.__doc__\n_ParseResultBase.fragment.__doc__=_SplitResultBase.fragment.__doc__\n\n\n\n\n\nResultBase=_NetlocResultMixinStr\n\n\nclass DefragResult(_DefragResultBase,_ResultMixinStr):\n __slots__=()\n def geturl(self):\n if self.fragment:\n return self.url+'#'+self.fragment\n else:\n return self.url\n \nclass SplitResult(_SplitResultBase,_NetlocResultMixinStr):\n __slots__=()\n def geturl(self):\n return urlunsplit(self)\n \nclass ParseResult(_ParseResultBase,_NetlocResultMixinStr):\n __slots__=()\n def geturl(self):\n return urlunparse(self)\n \n \nclass DefragResultBytes(_DefragResultBase,_ResultMixinBytes):\n __slots__=()\n def geturl(self):\n if self.fragment:\n return self.url+b'#'+self.fragment\n else:\n return self.url\n \nclass SplitResultBytes(_SplitResultBase,_NetlocResultMixinBytes):\n __slots__=()\n def geturl(self):\n return urlunsplit(self)\n \nclass ParseResultBytes(_ParseResultBase,_NetlocResultMixinBytes):\n __slots__=()\n def geturl(self):\n return urlunparse(self)\n \n \ndef _fix_result_transcoding():\n _result_pairs=(\n (DefragResult,DefragResultBytes),\n (SplitResult,SplitResultBytes),\n (ParseResult,ParseResultBytes),\n )\n for _decoded,_encoded in _result_pairs:\n _decoded._encoded_counterpart=_encoded\n _encoded._decoded_counterpart=_decoded\n \n_fix_result_transcoding()\ndel _fix_result_transcoding\n\ndef urlparse(url,scheme='',allow_fragments=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n url,scheme,_coerce_result=_coerce_args(url,scheme)\n splitresult=urlsplit(url,scheme,allow_fragments)\n scheme,netloc,url,query,fragment=splitresult\n if scheme in uses_params and ';'in url:\n url,params=_splitparams(url)\n else:\n params=''\n result=ParseResult(scheme,netloc,url,params,query,fragment)\n return _coerce_result(result)\n \ndef _splitparams(url):\n if '/'in url:\n i=url.find(';',url.rfind('/'))\n if i <0:\n return url,''\n else:\n i=url.find(';')\n return url[:i],url[i+1:]\n \ndef _splitnetloc(url,start=0):\n delim=len(url)\n for c in '/?#':\n wdelim=url.find(c,start)\n if wdelim >=0:\n delim=min(delim,wdelim)\n return url[start:delim],url[delim:]\n \ndef _checknetloc(netloc):\n if not netloc or netloc.isascii():\n return\n \n \n import unicodedata\n n=netloc.replace('@','')\n n=n.replace(':','')\n n=n.replace('#','')\n n=n.replace('?','')\n netloc2=unicodedata.normalize('NFKC',n)\n if n ==netloc2:\n return\n for c in '/?#@:':\n if c in netloc2:\n raise ValueError(\"netloc '\"+netloc+\"' contains invalid \"+\n \"characters under NFKC normalization\")\n \n \n \ndef _check_bracketed_host(hostname):\n if hostname.startswith('v'):\n if not re.match(r\"\\Av[a-fA-F0-9]+\\..+\\Z\",hostname):\n raise ValueError(f\"IPvFuture address is invalid\")\n else:\n ip=ipaddress.ip_address(hostname)\n if isinstance(ip,ipaddress.IPv4Address):\n raise ValueError(f\"An IPv4 address cannot be in brackets\")\n \n \n \n@functools.lru_cache(typed=True)\ndef urlsplit(url,scheme='',allow_fragments=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n url,scheme,_coerce_result=_coerce_args(url,scheme)\n \n \n url=url.lstrip(_WHATWG_C0_CONTROL_OR_SPACE)\n scheme=scheme.strip(_WHATWG_C0_CONTROL_OR_SPACE)\n \n for b in _UNSAFE_URL_BYTES_TO_REMOVE:\n url=url.replace(b,\"\")\n scheme=scheme.replace(b,\"\")\n \n allow_fragments=bool(allow_fragments)\n netloc=query=fragment=''\n i=url.find(':')\n if i >0 and url[0].isascii()and url[0].isalpha():\n for c in url[:i]:\n if c not in scheme_chars:\n break\n else:\n scheme,url=url[:i].lower(),url[i+1:]\n if url[:2]=='//':\n netloc,url=_splitnetloc(url,2)\n if(('['in netloc and ']'not in netloc)or\n (']'in netloc and '['not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if '['in netloc and ']'in netloc:\n bracketed_host=netloc.partition('[')[2].partition(']')[0]\n _check_bracketed_host(bracketed_host)\n if allow_fragments and '#'in url:\n url,fragment=url.split('#',1)\n if '?'in url:\n url,query=url.split('?',1)\n _checknetloc(netloc)\n v=SplitResult(scheme,netloc,url,query,fragment)\n return _coerce_result(v)\n \ndef urlunparse(components):\n ''\n\n\n \n scheme,netloc,url,params,query,fragment,_coerce_result=(\n _coerce_args(*components))\n if params:\n url=\"%s;%s\"%(url,params)\n return _coerce_result(urlunsplit((scheme,netloc,url,query,fragment)))\n \ndef urlunsplit(components):\n ''\n\n\n\n \n scheme,netloc,url,query,fragment,_coerce_result=(\n _coerce_args(*components))\n if netloc or(scheme and scheme in uses_netloc and url[:2]!='//'):\n if url and url[:1]!='/':url='/'+url\n url='//'+(netloc or '')+url\n if scheme:\n url=scheme+':'+url\n if query:\n url=url+'?'+query\n if fragment:\n url=url+'#'+fragment\n return _coerce_result(url)\n \ndef urljoin(base,url,allow_fragments=True):\n ''\n \n if not base:\n return url\n if not url:\n return base\n \n base,url,_coerce_result=_coerce_args(base,url)\n bscheme,bnetloc,bpath,bparams,bquery,bfragment=\\\n urlparse(base,'',allow_fragments)\n scheme,netloc,path,params,query,fragment=\\\n urlparse(url,bscheme,allow_fragments)\n \n if scheme !=bscheme or scheme not in uses_relative:\n return _coerce_result(url)\n if scheme in uses_netloc:\n if netloc:\n return _coerce_result(urlunparse((scheme,netloc,path,\n params,query,fragment)))\n netloc=bnetloc\n \n if not path and not params:\n path=bpath\n params=bparams\n if not query:\n query=bquery\n return _coerce_result(urlunparse((scheme,netloc,path,\n params,query,fragment)))\n \n base_parts=bpath.split('/')\n if base_parts[-1]!='':\n \n \n del base_parts[-1]\n \n \n if path[:1]=='/':\n segments=path.split('/')\n else:\n segments=base_parts+path.split('/')\n \n \n segments[1:-1]=filter(None,segments[1:-1])\n \n resolved_path=[]\n \n for seg in segments:\n if seg =='..':\n try:\n resolved_path.pop()\n except IndexError:\n \n \n pass\n elif seg =='.':\n continue\n else:\n resolved_path.append(seg)\n \n if segments[-1]in('.','..'):\n \n \n resolved_path.append('')\n \n return _coerce_result(urlunparse((scheme,netloc,'/'.join(\n resolved_path)or '/',params,query,fragment)))\n \n \ndef urldefrag(url):\n ''\n\n\n\n\n \n url,_coerce_result=_coerce_args(url)\n if '#'in url:\n s,n,p,a,q,frag=urlparse(url)\n defrag=urlunparse((s,n,p,a,q,''))\n else:\n frag=''\n defrag=url\n return _coerce_result(DefragResult(defrag,frag))\n \n_hexdig='0123456789ABCDEFabcdef'\n_hextobyte=None\n\ndef unquote_to_bytes(string):\n ''\n return bytes(_unquote_impl(string))\n \ndef _unquote_impl(string:bytes |bytearray |str)->bytes |bytearray:\n\n\n if not string:\n \n string.split\n return b''\n if isinstance(string,str):\n string=string.encode('utf-8')\n bits=string.split(b'%')\n if len(bits)==1:\n return string\n res=bytearray(bits[0])\n append=res.extend\n \n \n global _hextobyte\n if _hextobyte is None:\n _hextobyte={(a+b).encode():bytes.fromhex(a+b)\n for a in _hexdig for b in _hexdig}\n for item in bits[1:]:\n try:\n append(_hextobyte[item[:2]])\n append(item[2:])\n except KeyError:\n append(b'%')\n append(item)\n return res\n \n_asciire=re.compile('([\\x00-\\x7f]+)')\n\ndef _generate_unquoted_parts(string,encoding,errors):\n previous_match_end=0\n for ascii_match in _asciire.finditer(string):\n start,end=ascii_match.span()\n yield string[previous_match_end:start]\n \n yield _unquote_impl(ascii_match[1]).decode(encoding,errors)\n previous_match_end=end\n yield string[previous_match_end:]\n \ndef unquote(string,encoding='utf-8',errors='replace'):\n ''\n\n\n\n\n\n\n\n \n if isinstance(string,bytes):\n return _unquote_impl(string).decode(encoding,errors)\n if '%'not in string:\n \n string.split\n return string\n if encoding is None:\n encoding='utf-8'\n if errors is None:\n errors='replace'\n return ''.join(_generate_unquoted_parts(string,encoding,errors))\n \n \ndef parse_qs(qs,keep_blank_values=False,strict_parsing=False,\nencoding='utf-8',errors='replace',max_num_fields=None,separator='&'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n parsed_result={}\n pairs=parse_qsl(qs,keep_blank_values,strict_parsing,\n encoding=encoding,errors=errors,\n max_num_fields=max_num_fields,separator=separator)\n for name,value in pairs:\n if name in parsed_result:\n parsed_result[name].append(value)\n else:\n parsed_result[name]=[value]\n return parsed_result\n \n \ndef parse_qsl(qs,keep_blank_values=False,strict_parsing=False,\nencoding='utf-8',errors='replace',max_num_fields=None,separator='&'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not separator or not isinstance(separator,(str,bytes)):\n raise ValueError(\"Separator must be of type string or bytes.\")\n if isinstance(qs,str):\n if not isinstance(separator,str):\n separator=str(separator,'ascii')\n eq='='\n def _unquote(s):\n return unquote_plus(s,encoding=encoding,errors=errors)\n else:\n if not qs:\n return[]\n \n \n qs=bytes(memoryview(qs))\n if isinstance(separator,str):\n separator=bytes(separator,'ascii')\n eq=b'='\n def _unquote(s):\n return unquote_to_bytes(s.replace(b'+',b' '))\n \n if not qs:\n return[]\n \n \n \n \n if max_num_fields is not None:\n num_fields=1+qs.count(separator)\n if max_num_fields \"\n \n def __missing__(self,b):\n \n res=chr(b)if b in self.safe else '%{:02X}'.format(b)\n self[b]=res\n return res\n \ndef quote(string,safe='/',encoding=None,errors=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(string,str):\n if not string:\n return string\n if encoding is None:\n encoding='utf-8'\n if errors is None:\n errors='strict'\n string=string.encode(encoding,errors)\n else:\n if encoding is not None:\n raise TypeError(\"quote() doesn't support 'encoding' for bytes\")\n if errors is not None:\n raise TypeError(\"quote() doesn't support 'errors' for bytes\")\n return quote_from_bytes(string,safe)\n \ndef quote_plus(string,safe='',encoding=None,errors=None):\n ''\n\n\n \n \n \n if((isinstance(string,str)and ' 'not in string)or\n (isinstance(string,bytes)and b' 'not in string)):\n return quote(string,safe,encoding,errors)\n if isinstance(safe,str):\n space=' '\n else:\n space=b' '\n string=quote(string,safe+space,encoding,errors)\n return string.replace(' ','+')\n \n \n@functools.lru_cache\ndef _byte_quoter_factory(safe):\n return _Quoter(safe).__getitem__\n \ndef quote_from_bytes(bs,safe='/'):\n ''\n\n\n \n if not isinstance(bs,(bytes,bytearray)):\n raise TypeError(\"quote_from_bytes() expected bytes\")\n if not bs:\n return ''\n if isinstance(safe,str):\n \n safe=safe.encode('ascii','ignore')\n else:\n \n safe=bytes([c for c in safe if c <128])\n if not bs.rstrip(_ALWAYS_SAFE_BYTES+safe):\n return bs.decode()\n quoter=_byte_quoter_factory(safe)\n if(bs_len :=len(bs))<200_000:\n return ''.join(map(quoter,bs))\n else:\n \n chunk_size=math.isqrt(bs_len)\n chunks=[''.join(map(quoter,bs[i:i+chunk_size]))\n for i in range(0,bs_len,chunk_size)]\n return ''.join(chunks)\n \ndef urlencode(query,doseq=False,safe='',encoding=None,errors=None,\nquote_via=quote_plus):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if hasattr(query,\"items\"):\n query=query.items()\n else:\n \n \n try:\n \n \n if len(query)and not isinstance(query[0],tuple):\n raise TypeError\n \n \n \n \n except TypeError as err:\n raise TypeError(\"not a valid non-string sequence \"\n \"or mapping object\")from err\n \n l=[]\n if not doseq:\n for k,v in query:\n if isinstance(k,bytes):\n k=quote_via(k,safe)\n else:\n k=quote_via(str(k),safe,encoding,errors)\n \n if isinstance(v,bytes):\n v=quote_via(v,safe)\n else:\n v=quote_via(str(v),safe,encoding,errors)\n l.append(k+'='+v)\n else:\n for k,v in query:\n if isinstance(k,bytes):\n k=quote_via(k,safe)\n else:\n k=quote_via(str(k),safe,encoding,errors)\n \n if isinstance(v,bytes):\n v=quote_via(v,safe)\n l.append(k+'='+v)\n elif isinstance(v,str):\n v=quote_via(v,safe,encoding,errors)\n l.append(k+'='+v)\n else:\n try:\n \n x=len(v)\n except TypeError:\n \n v=quote_via(str(v),safe,encoding,errors)\n l.append(k+'='+v)\n else:\n \n for elt in v:\n if isinstance(elt,bytes):\n elt=quote_via(elt,safe)\n else:\n elt=quote_via(str(elt),safe,encoding,errors)\n l.append(k+'='+elt)\n return '&'.join(l)\n \n \ndef to_bytes(url):\n warnings.warn(\"urllib.parse.to_bytes() is deprecated as of 3.8\",\n DeprecationWarning,stacklevel=2)\n return _to_bytes(url)\n \n \ndef _to_bytes(url):\n ''\n \n \n \n if isinstance(url,str):\n try:\n url=url.encode(\"ASCII\").decode()\n except UnicodeError:\n raise UnicodeError(\"URL \"+repr(url)+\n \" contains non-ASCII characters\")\n return url\n \n \ndef unwrap(url):\n ''\n\n\n \n url=str(url).strip()\n if url[:1]=='<'and url[-1:]=='>':\n url=url[1:-1].strip()\n if url[:4]=='URL:':\n url=url[4:].strip()\n return url\n \n \ndef splittype(url):\n warnings.warn(\"urllib.parse.splittype() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splittype(url)\n \n \n_typeprog=None\ndef _splittype(url):\n ''\n global _typeprog\n if _typeprog is None:\n _typeprog=re.compile('([^/:]+):(.*)',re.DOTALL)\n \n match=_typeprog.match(url)\n if match:\n scheme,data=match.groups()\n return scheme.lower(),data\n return None,url\n \n \ndef splithost(url):\n warnings.warn(\"urllib.parse.splithost() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splithost(url)\n \n \n_hostprog=None\ndef _splithost(url):\n ''\n global _hostprog\n if _hostprog is None:\n _hostprog=re.compile('//([^/#?]*)(.*)',re.DOTALL)\n \n match=_hostprog.match(url)\n if match:\n host_port,path=match.groups()\n if path and path[0]!='/':\n path='/'+path\n return host_port,path\n return None,url\n \n \ndef splituser(host):\n warnings.warn(\"urllib.parse.splituser() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splituser(host)\n \n \ndef _splituser(host):\n ''\n user,delim,host=host.rpartition('@')\n return(user if delim else None),host\n \n \ndef splitpasswd(user):\n warnings.warn(\"urllib.parse.splitpasswd() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitpasswd(user)\n \n \ndef _splitpasswd(user):\n ''\n user,delim,passwd=user.partition(':')\n return user,(passwd if delim else None)\n \n \ndef splitport(host):\n warnings.warn(\"urllib.parse.splitport() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitport(host)\n \n \n \n_portprog=None\ndef _splitport(host):\n ''\n global _portprog\n if _portprog is None:\n _portprog=re.compile('(.*):([0-9]*)',re.DOTALL)\n \n match=_portprog.fullmatch(host)\n if match:\n host,port=match.groups()\n if port:\n return host,port\n return host,None\n \n \ndef splitnport(host,defport=-1):\n warnings.warn(\"urllib.parse.splitnport() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitnport(host,defport)\n \n \ndef _splitnport(host,defport=-1):\n ''\n\n\n \n host,delim,port=host.rpartition(':')\n if not delim:\n host=port\n elif port:\n if port.isdigit()and port.isascii():\n nport=int(port)\n else:\n nport=None\n return host,nport\n return host,defport\n \n \ndef splitquery(url):\n warnings.warn(\"urllib.parse.splitquery() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitquery(url)\n \n \ndef _splitquery(url):\n ''\n path,delim,query=url.rpartition('?')\n if delim:\n return path,query\n return url,None\n \n \ndef splittag(url):\n warnings.warn(\"urllib.parse.splittag() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splittag(url)\n \n \ndef _splittag(url):\n ''\n path,delim,tag=url.rpartition('#')\n if delim:\n return path,tag\n return url,None\n \n \ndef splitattr(url):\n warnings.warn(\"urllib.parse.splitattr() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitattr(url)\n \n \ndef _splitattr(url):\n ''\n \n words=url.split(';')\n return words[0],words[1:]\n \n \ndef splitvalue(attr):\n warnings.warn(\"urllib.parse.splitvalue() is deprecated as of 3.8, \"\n \"use urllib.parse.parse_qsl() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitvalue(attr)\n \n \ndef _splitvalue(attr):\n ''\n attr,delim,value=attr.partition('=')\n return attr,(value if delim else None)\n", ["collections", "functools", "ipaddress", "math", "re", "types", "unicodedata", "warnings"]], "urllib.request": [".py", "from browser import ajax\nfrom. import error\n\nclass FileIO:\n\n def __init__(self,data):\n self._data=data\n \n def __enter__(self):\n return self\n \n def __exit__(self,*args):\n pass\n \n def read(self):\n return self._data\n \ndef urlopen(url,data=None,timeout=None):\n global result\n result=None\n \n def on_complete(req):\n global result\n if req.status ==200:\n result=req\n \n _ajax=ajax.ajax()\n _ajax.bind('complete',on_complete)\n if timeout is not None:\n _ajax.set_timeout(timeout)\n \n if data is None:\n _ajax.open('GET',url,False)\n _ajax.send()\n else:\n _ajax.open('POST',url,False)\n _ajax.send(data)\n \n if result is not None:\n if isinstance(result.text,str):\n return FileIO(result.text)\n \n return FileIO(result.text())\n raise error.HTTPError('file not found')\n", ["browser", "browser.ajax", "urllib", "urllib.error"]], "urllib.response": [".py", "''\n\n\n\n\n\n\n\nimport tempfile\n\n__all__=['addbase','addclosehook','addinfo','addinfourl']\n\n\nclass addbase(tempfile._TemporaryFileWrapper):\n ''\n \n \n \n def __init__(self,fp):\n super(addbase,self).__init__(fp,'',delete=False)\n \n self.fp=fp\n \n def __repr__(self):\n return '<%s at %r whose fp = %r>'%(self.__class__.__name__,\n id(self),self.file)\n \n def __enter__(self):\n if self.fp.closed:\n raise ValueError(\"I/O operation on closed file\")\n return self\n \n def __exit__(self,type,value,traceback):\n self.close()\n \n \nclass addclosehook(addbase):\n ''\n \n def __init__(self,fp,closehook,*hookargs):\n super(addclosehook,self).__init__(fp)\n self.closehook=closehook\n self.hookargs=hookargs\n \n def close(self):\n try:\n closehook=self.closehook\n hookargs=self.hookargs\n if closehook:\n self.closehook=None\n self.hookargs=None\n closehook(*hookargs)\n finally:\n super(addclosehook,self).close()\n \n \nclass addinfo(addbase):\n ''\n \n def __init__(self,fp,headers):\n super(addinfo,self).__init__(fp)\n self.headers=headers\n \n def info(self):\n return self.headers\n \n \nclass addinfourl(addinfo):\n ''\n \n def __init__(self,fp,headers,url,code=None):\n super(addinfourl,self).__init__(fp,headers)\n self.url=url\n self.code=code\n \n @property\n def status(self):\n return self.code\n \n def getcode(self):\n return self.code\n \n def geturl(self):\n return self.url\n", ["tempfile"]], "urllib": [".py", "", [], 1]} +var scripts = {"$timestamp": 1728546342437, "array": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nvar typecodes = {\n 'b': Int8Array, // signed char, 1 byte\n 'B': Uint8Array, // unsigned char, 1\n 'u': Uint32Array, // Py_UNICODE Unicode character, 2 (deprecated)\n 'h': Int16Array, // signed short, 2\n 'H': Uint16Array, // unsigned short, 2\n 'i': Int16Array, // signed int, 2\n 'I': Uint16Array, // unsigned int, 2\n 'l': Int32Array, // signed long, 4\n 'L': Uint32Array, // unsigned long, 4\n 'q': null, // signed long, 8 (not implemented)\n 'Q': null, // unsigned long, 8 (not implemented)\n 'f': Float32Array, // float, 4\n 'd': Float64Array // double float, 8\n}\n\nvar array = $B.make_class(\"array\",\n function(){\n var missing = {},\n $ = $B.args(\"array\", 2, {typecode: null, initializer: null},\n [\"typecode\", \"initializer\"], arguments, {initializer: missing},\n null, null),\n typecode = $.typecode,\n initializer = $.initializer\n if(! typecodes.hasOwnProperty(typecode)){\n throw _b_.ValueError.$factory(\"bad typecode (must be b, \" +\n \"B, u, h, H, i, I, l, L, q, Q, f or d)\")\n }\n if(typecodes[typecode] === null){\n console.log(\"array factory, $\", $, typecode)\n throw _b_.NotImplementedError.$factory(\"type code \" +\n typecode + \" is not implemented\")\n }\n var res = {\n __class__: array,\n typecode: typecode,\n obj: null\n }\n if(initializer !== missing){\n if(Array.isArray(initializer)){\n array.fromlist(res, initializer)\n }else if($B.$isinstance(initializer, _b_.bytes)){\n array.frombytes(res, initializer)\n }else{\n array.extend(res, initializer)\n }\n }\n return res\n }\n)\n\narray.$buffer_protocol = true\narray.$match_sequence_pattern = true // for Pattern Matching (PEP 634)\n\narray.__getitem__ = function(self, key){\n if(self.obj && self.obj[key] !== undefined){\n return self.obj[key]\n }\n throw _b_.IndexError.$factory(\"array index out of range\")\n}\n\nvar array_iterator = $B.make_iterator_class(\"array_iterator\")\narray.__iter__ = function(self){\n return array_iterator.$factory(self.obj === null ? [] : self.obj)\n}\n\narray.__len__ = function(self){\n return self.obj === null ? 0 : self.obj.length\n}\n\narray.__mul__ = function(self, nb){\n if(typeof nb == \"number\" || $B.$isinstance(nb, _b_.int)){\n var t = [],\n copy = self.obj.slice()\n for(var i = 0; i < nb; i++){\n t = t.concat(copy)\n }\n return {\n __class__: array,\n typecode: self.typecode,\n obj: t\n }\n }\n throw _b_.ValueError.$factory(\"cannot multiply array by \" +\n $B.class_name(nb))\n}\n\narray.__setitem__ = function(_self, index, value){\n if(_self.obj[index] === undefined){\n throw _b_.IndexError.$factory(\"array index out of range\")\n }\n _self.obj[index] = value\n}\n\narray.__str__ = function(self){\n $B.args(\"__str__\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n var res = \"array('\" + self.typecode + \"'\"\n if(self.obj !== null){\n res += \", [\" + self.obj + \"]\"\n }\n return res + \")\"\n}\n\nfunction normalize_index(self, i){\n // return an index i between 0 and self.obj.length - 1\n if(i < 0){\n i = self.obj.length + i\n }\n if(i < 0){i = 0}\n else if(i > self.obj.length - 1){\n i = self.obj.length\n }\n return i\n}\n\narray.append = function(self, value){\n $B.args(\"append\", 2, {self: null, value: null},\n [\"self\", \"value\"], arguments, {}, null, null)\n var pos = self.obj === null ? 0 : self.obj.length\n return array.insert(self, pos, value)\n}\n\narray.count = function(self, x){\n $B.args(\"count\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n if(self.obj === null){\n return 0\n }\n return self.obj.filter(function(item){return item == x}).length\n}\n\narray.extend = function(self, iterable){\n $B.args(\"extend\", 2, {self: null, iterable: null},\n [\"self\", \"iterable\"], arguments, {}, null, null)\n if(iterable.__class__ === array){\n if(iterable.typecode !== self.typecode){\n throw _b_.TypeError.$factory(\"can only extend with array \" +\n \"of same kind\")\n }\n if(iterable.obj === null){return _b_.None}\n // create new object with length = sum of lengths\n var newobj = new typecodes[self.typecode](self.obj.length +\n iterable.obj.length)\n // copy self.obj\n newobj.set(self.obj)\n // copy iterable.obj\n newobj.set(iterable.obj, self.obj.length)\n self.obj = newobj\n }else{\n var it = _b_.iter(iterable)\n while(true){\n try{\n var item = _b_.next(it)\n array.append(self, item)\n }catch(err){\n if(err.__class__ !== _b_.StopIteration){\n throw err\n }\n break\n }\n }\n }\n return _b_.None\n}\n\narray.frombytes = function(self, s){\n $B.args(\"frombytes\", 2, {self: null, s: null},\n [\"self\", \"s\"], arguments, {}, null, null)\n if(! $B.$isinstance(s, _b_.bytes)){\n throw _b_.TypeError.$factory(\"a bytes-like object is required, \" +\n \"not '\" + $B.class_name(s) + \"'\")\n }\n self.obj = new typecodes[self.typecode](s.source)\n return _b_.None\n}\n\narray.fromlist = function(self, list){\n $B.args(\"fromlist\", 2, {self: null, list: null},\n [\"self\", \"list\"], arguments, {}, null, null)\n var it = _b_.iter(list)\n while(true){\n try{\n var item = _b_.next(it)\n try{\n array.append(self, item)\n }catch(err){\n console.log(err)\n return _b_.None\n }\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n return _b_.None\n }\n throw err\n }\n }\n}\n\narray.fromstring = array.frombytes\n\narray.index = function(self, x){\n $B.args(\"index\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n var res = self.obj.findIndex(function(item){return x == item})\n if(res == -1){\n throw _b_.ValueError.$factory(\"array.index(x): x not in array\")\n }\n return res\n}\n\narray.insert = function(self, i, value){\n $B.args(\"insert\", 3, {self: null, i: null, value: null},\n [\"self\", \"i\", \"value\"], arguments, {}, null, null)\n if(self.obj === null){\n self.obj = [value]\n }else{\n self.obj.splice(i, 0, value)\n }\n return _b_.None\n}\n\narray.itemsize = function(self){\n return typecodes[self.typecode].BYTES_PER_ELEMENT\n}\n\narray.pop = function(self, i){\n var $ = $B.args(\"count\", 2, {self: null, i: null},\n [\"self\", \"i\"], arguments, {i: -1}, null, null)\n i = $.i\n if(self.obj === null){\n throw _b_.IndexError.$factory(\"pop from empty array\")\n }else if(self.obj.length == 1){\n var res = self.obj[0]\n self.obj = null\n return res\n }\n i = normalize_index(self, i)\n // store value to return\n var res = self.obj[i]\n // create new array, size = previous size - 1\n var newobj = new typecodes[self.typecode](self.obj.length - 1)\n // fill new array with values until i excluded\n newobj.set(self.obj.slice(0, i))\n // fill with values after i\n newobj.set(self.obj.slice(i + 1), i)\n // set self.obj to new array\n self.obj = newobj\n // return stored value\n return res\n}\n\narray.remove = function(self, x){\n $B.args(\"remove\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n var res = self.obj.findIndex(function(item){return x == item})\n if(res == -1){\n throw _b_.ValueError.$factory(\"array.remove(x): x not in array\")\n }\n array.pop(self, res)\n return _b_.None\n}\n\narray.reverse = function(self){\n $B.args(\"reverse\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n if(self.obj === null){return _b_.None}\n self.obj.reverse()\n return _b_.None\n}\n\narray.tobytes = function(self){\n $B.args(\"tobytes\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n var items = Array.prototype.slice.call(self.obj),\n res = []\n items.forEach(function(item){\n while(item > 256){\n res.push(item % 256)\n item = Math.floor(item / 256)\n }\n res.push(item)\n })\n return _b_.bytes.$factory(res)\n}\n\narray.tolist = function(self){\n $B.args(\"tolist\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n if(self.obj === null){\n return $B.$list([])\n }\n return $B.$list(Array.prototype.slice.call(self.obj))\n}\n\narray.tostring = array.tobytes\n\narray.typecode = function(self){\n return self.typecode\n}\n\n$B.set_func_names(array, \"array\")\n\nvar module = {\n array: array,\n typecodes: Object.keys(typecodes).join('')\n}\n\n$B.addToImported('array', module)\n\n})(__BRYTHON__)\n"], "builtins": [".js", "(function(){\n var obj = {},\n builtin_names = ['ArithmeticError', 'AssertionError',\n 'AttributeError', 'BaseException', 'BaseExceptionGroup',\n 'BlockingIOError', 'BrokenPipeError', 'BufferError',\n 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError',\n 'ConnectionError', 'ConnectionRefusedError',\n 'ConnectionResetError', 'DeprecationWarning', 'EOFError',\n 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception',\n 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError',\n 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError',\n 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError',\n 'InterruptedError', 'IsADirectoryError', 'KeyError',\n 'KeyboardInterrupt', 'LookupError', 'MemoryError',\n 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError',\n 'NotImplemented', 'NotImplementedError', 'OSError',\n 'OverflowError', 'PendingDeprecationWarning', 'PermissionError',\n 'ProcessLookupError', 'RecursionError', 'ReferenceError',\n 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',\n 'StopAsyncIteration', 'StopIteration', 'SyntaxError',\n 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',\n 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError',\n 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',\n 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',\n 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError',\n '_', '__build_class__', '__debug__', '__import__',\n 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool',\n 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr',\n 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir',\n 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float',\n 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash',\n 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',\n 'iter', 'len', 'list', 'locals', 'map', 'max', 'memoryview',\n 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',\n 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set',\n 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum',\n 'super', 'tuple', 'type', 'vars', 'zip']\n for(var key of builtin_names){\n if(__BRYTHON__.builtins[key] !== undefined){\n obj[key] = __BRYTHON__.builtins[key]\n }\n }\n obj.__doc__ = 'builtins module'\n obj.copyright = 'CPython copyright'\n obj.credits = 'CPython builtins credits'\n obj.license = 'CPython license'\n \n $B.addToImported('builtins', obj)\n})()\n"], "dis": [".js", "(function($B){\n\nvar _b_ = $B.builtins,\n dict = $B.builtins.dict\n\nvar mod = {\n dis:function(src){\n $B.$py_module_path['__main__'] = $B.brython_path\n return __BRYTHON__.py2js(src,'__main__','__main__',\n $B.builtins_scope).to_js()\n },\n COMPILER_FLAG_NAMES: $B.builtins.dict.$factory(),\n Positions: function(){\n return _b_.None\n }\n}\n\n// COMPILER_FLAGS is defined in brython_builtins.js\nfor(var key in $B.COMPILER_FLAGS){\n mod[key] = $B.COMPILER_FLAGS[key]\n _b_.dict.$setitem(mod.COMPILER_FLAG_NAMES, mod[key], key)\n}\n\n$B.addToImported('dis', mod)\n\n})(__BRYTHON__)"], "encoding_cp932": [".js", "const cps = {\"0\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 65377, 65378, 65379, 65380, 65381, 65382, 65383, 65384, 65385, 65386, 65387, 65388, 65389, 65390, 65391, 65392, 65393, 65394, 65395, 65396, 65397, 65398, 65399, 65400, 65401, 65402, 65403, 65404, 65405, 65406, 65407, 65408, 65409, 65410, 65411, 65412, 65413, 65414, 65415, 65416, 65417, 65418, 65419, 65420, 65421, 65422, 65423, 65424, 65425, 65426, 65427, 65428, 65429, 65430, 65431, 65432, 65433, 65434, 65435, 65436, 65437, 65438, 65439, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null], \"33088\": [12288, 12289, 12290, 65292, 65294, 12539, 65306, 65307, 65311, 65281, 12443, 12444, 180, 65344, 168, 65342, 65507, 65343, 12541, 12542, 12445, 12446, 12291, 20189, 12293, 12294, 12295, 12540, 8213, 8208, 65295, 65340, 65374, 8741, 65372, 8230, 8229, 8216, 8217, 8220, 8221, 65288, 65289, 12308, 12309, 65339, 65341, 65371, 65373, 12296, 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 65291, 65293, 177, 215], \"33152\": [247, 65309, 8800, 65308, 65310, 8806, 8807, 8734, 8756, 9794, 9792, 176, 8242, 8243, 8451, 65509, 65284, 65504, 65505, 65285, 65283, 65286, 65290, 65312, 167, 9734, 9733, 9675, 9679, 9678, 9671, 9670, 9633, 9632, 9651, 9650, 9661, 9660, 8251, 12306, 8594, 8592, 8593, 8595, 12307], \"33208\": [8712, 8715, 8838, 8839, 8834, 8835, 8746, 8745], \"33224\": [8743, 8744, 65506, 8658, 8660, 8704, 8707], \"33242\": [8736, 8869, 8978, 8706, 8711, 8801, 8786, 8810, 8811, 8730, 8765, 8733, 8757, 8747, 8748], \"33264\": [8491, 8240, 9839, 9837, 9834, 8224, 8225, 182], \"33276\": [9711], \"33359\": [65296, 65297, 65298, 65299, 65300, 65301, 65302, 65303, 65304, 65305], \"33376\": [65313, 65314, 65315, 65316, 65317, 65318, 65319, 65320, 65321, 65322, 65323, 65324, 65325, 65326, 65327, 65328, 65329, 65330, 65331, 65332, 65333, 65334, 65335, 65336, 65337, 65338], \"33409\": [65345, 65346, 65347, 65348, 65349, 65350, 65351, 65352, 65353, 65354, 65355, 65356, 65357, 65358, 65359, 65360, 65361, 65362, 65363, 65364, 65365, 65366, 65367, 65368, 65369, 65370], \"33439\": [12353, 12354, 12355, 12356, 12357, 12358, 12359, 12360, 12361, 12362, 12363, 12364, 12365, 12366, 12367, 12368, 12369, 12370, 12371, 12372, 12373, 12374, 12375, 12376, 12377, 12378, 12379, 12380, 12381, 12382, 12383, 12384, 12385, 12386, 12387, 12388, 12389, 12390, 12391, 12392, 12393, 12394, 12395, 12396, 12397, 12398, 12399, 12400, 12401, 12402, 12403, 12404, 12405, 12406, 12407, 12408, 12409, 12410, 12411, 12412, 12413, 12414, 12415, 12416, 12417, 12418, 12419, 12420, 12421, 12422, 12423, 12424, 12425, 12426, 12427, 12428, 12429, 12430, 12431, 12432, 12433, 12434, 12435], \"33600\": [12449, 12450, 12451, 12452, 12453, 12454, 12455, 12456, 12457, 12458, 12459, 12460, 12461, 12462, 12463, 12464, 12465, 12466, 12467, 12468, 12469, 12470, 12471, 12472, 12473, 12474, 12475, 12476, 12477, 12478, 12479, 12480, 12481, 12482, 12483, 12484, 12485, 12486, 12487, 12488, 12489, 12490, 12491, 12492, 12493, 12494, 12495, 12496, 12497, 12498, 12499, 12500, 12501, 12502, 12503, 12504, 12505, 12506, 12507, 12508, 12509, 12510, 12511], \"33664\": [12512, 12513, 12514, 12515, 12516, 12517, 12518, 12519, 12520, 12521, 12522, 12523, 12524, 12525, 12526, 12527, 12528, 12529, 12530, 12531, 12532, 12533, 12534], \"33695\": [913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937], \"33727\": [945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 963, 964, 965, 966, 967, 968, 969], \"33856\": [1040, 1041, 1042, 1043, 1044, 1045, 1025, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071], \"33904\": [1072, 1073, 1074, 1075, 1076, 1077, 1105, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085], \"33920\": [1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103], \"33951\": [9472, 9474, 9484, 9488, 9496, 9492, 9500, 9516, 9508, 9524, 9532, 9473, 9475, 9487, 9491, 9499, 9495, 9507, 9523, 9515, 9531, 9547, 9504, 9519, 9512, 9527, 9535, 9501, 9520, 9509, 9528, 9538], \"34624\": [9312, 9313, 9314, 9315, 9316, 9317, 9318, 9319, 9320, 9321, 9322, 9323, 9324, 9325, 9326, 9327, 9328, 9329, 9330, 9331, 8544, 8545, 8546, 8547, 8548, 8549, 8550, 8551, 8552, 8553], \"34655\": [13129, 13076, 13090, 13133, 13080, 13095, 13059, 13110, 13137, 13143, 13069, 13094, 13091, 13099, 13130, 13115, 13212, 13213, 13214, 13198, 13199, 13252, 13217], \"34686\": [13179], \"34688\": [12317, 12319, 8470, 13261, 8481, 12964, 12965, 12966, 12967, 12968, 12849, 12850, 12857, 13182, 13181, 13180, 8786, 8801, 8747, 8750, 8721, 8730, 8869, 8736, 8735, 8895, 8757, 8745, 8746], \"34975\": [20124, 21782, 23043, 38463, 21696, 24859, 25384, 23030, 36898, 33909, 33564, 31312, 24746, 25569, 28197, 26093, 33894, 33446, 39925, 26771, 22311, 26017, 25201, 23451, 22992, 34427, 39156, 32098, 32190, 39822, 25110, 31903, 34999, 23433, 24245, 25353, 26263, 26696, 38343, 38797, 26447, 20197, 20234, 20301, 20381, 20553, 22258, 22839, 22996, 23041, 23561, 24799, 24847, 24944, 26131, 26885, 28858, 30031, 30064, 31227, 32173, 32239, 32963, 33806, 34915, 35586, 36949, 36986, 21307, 20117, 20133, 22495, 32946, 37057, 30959, 19968, 22769, 28322, 36920, 31282, 33576, 33419, 39983, 20801, 21360, 21693, 21729, 22240, 23035, 24341, 39154, 28139, 32996, 34093], \"35136\": [38498, 38512, 38560, 38907, 21515, 21491, 23431, 28879, 32701, 36802, 38632, 21359, 40284, 31418, 19985, 30867, 33276, 28198, 22040, 21764, 27421, 34074, 39995, 23013, 21417, 28006, 29916, 38287, 22082, 20113, 36939, 38642, 33615, 39180, 21473, 21942, 23344, 24433, 26144, 26355, 26628, 27704, 27891, 27945, 29787, 30408, 31310, 38964, 33521, 34907, 35424, 37613, 28082, 30123, 30410, 39365, 24742, 35585, 36234, 38322, 27022, 21421, 20870], \"35200\": [22290, 22576, 22852, 23476, 24310, 24616, 25513, 25588, 27839, 28436, 28814, 28948, 29017, 29141, 29503, 32257, 33398, 33489, 34199, 36960, 37467, 40219, 22633, 26044, 27738, 29989, 20985, 22830, 22885, 24448, 24540, 25276, 26106, 27178, 27431, 27572, 29579, 32705, 35158, 40236, 40206, 40644, 23713, 27798, 33659, 20740, 23627, 25014, 33222, 26742, 29281, 20057, 20474, 21368, 24681, 28201, 31311, 38899, 19979, 21270, 20206, 20309, 20285, 20385, 20339, 21152, 21487, 22025, 22799, 23233, 23478, 23521, 31185, 26247, 26524, 26550, 27468, 27827, 28779, 29634, 31117, 31166, 31292, 31623, 33457, 33499, 33540, 33655, 33775, 33747, 34662, 35506, 22057, 36008, 36838, 36942, 38686, 34442, 20420, 23784, 25105, 29273, 30011, 33253, 33469, 34558, 36032, 38597, 39187, 39381, 20171, 20250, 35299, 22238, 22602, 22730, 24315, 24555, 24618, 24724, 24674, 25040, 25106, 25296, 25913], \"35392\": [39745, 26214, 26800, 28023, 28784, 30028, 30342, 32117, 33445, 34809, 38283, 38542, 35997, 20977, 21182, 22806, 21683, 23475, 23830, 24936, 27010, 28079, 30861, 33995, 34903, 35442, 37799, 39608, 28012, 39336, 34521, 22435, 26623, 34510, 37390, 21123, 22151, 21508, 24275, 25313, 25785, 26684, 26680, 27579, 29554, 30906, 31339, 35226, 35282, 36203, 36611, 37101, 38307, 38548, 38761, 23398, 23731, 27005, 38989, 38990, 25499, 31520, 27179], \"35456\": [27263, 26806, 39949, 28511, 21106, 21917, 24688, 25324, 27963, 28167, 28369, 33883, 35088, 36676, 19988, 39993, 21494, 26907, 27194, 38788, 26666, 20828, 31427, 33970, 37340, 37772, 22107, 40232, 26658, 33541, 33841, 31909, 21000, 33477, 29926, 20094, 20355, 20896, 23506, 21002, 21208, 21223, 24059, 21914, 22570, 23014, 23436, 23448, 23515, 24178, 24185, 24739, 24863, 24931, 25022, 25563, 25954, 26577, 26707, 26874, 27454, 27475, 27735, 28450, 28567, 28485, 29872, 29976, 30435, 30475, 31487, 31649, 31777, 32233, 32566, 32752, 32925, 33382, 33694, 35251, 35532, 36011, 36996, 37969, 38291, 38289, 38306, 38501, 38867, 39208, 33304, 20024, 21547, 23736, 24012, 29609, 30284, 30524, 23721, 32747, 36107, 38593, 38929, 38996, 39000, 20225, 20238, 21361, 21916, 22120, 22522, 22855, 23305, 23492, 23696, 24076, 24190, 24524, 25582, 26426, 26071, 26082, 26399, 26827, 26820], \"35648\": [27231, 24112, 27589, 27671, 27773, 30079, 31048, 23395, 31232, 32000, 24509, 35215, 35352, 36020, 36215, 36556, 36637, 39138, 39438, 39740, 20096, 20605, 20736, 22931, 23452, 25135, 25216, 25836, 27450, 29344, 30097, 31047, 32681, 34811, 35516, 35696, 25516, 33738, 38816, 21513, 21507, 21931, 26708, 27224, 35440, 30759, 26485, 40653, 21364, 23458, 33050, 34384, 36870, 19992, 20037, 20167, 20241, 21450, 21560, 23470, 24339, 24613, 25937], \"35712\": [26429, 27714, 27762, 27875, 28792, 29699, 31350, 31406, 31496, 32026, 31998, 32102, 26087, 29275, 21435, 23621, 24040, 25298, 25312, 25369, 28192, 34394, 35377, 36317, 37624, 28417, 31142, 39770, 20136, 20139, 20140, 20379, 20384, 20689, 20807, 31478, 20849, 20982, 21332, 21281, 21375, 21483, 21932, 22659, 23777, 24375, 24394, 24623, 24656, 24685, 25375, 25945, 27211, 27841, 29378, 29421, 30703, 33016, 33029, 33288, 34126, 37111, 37857, 38911, 39255, 39514, 20208, 20957, 23597, 26241, 26989, 23616, 26354, 26997, 29577, 26704, 31873, 20677, 21220, 22343, 24062, 37670, 26020, 27427, 27453, 29748, 31105, 31165, 31563, 32202, 33465, 33740, 34943, 35167, 35641, 36817, 37329, 21535, 37504, 20061, 20534, 21477, 21306, 29399, 29590, 30697, 33510, 36527, 39366, 39368, 39378, 20855, 24858, 34398, 21936, 31354, 20598, 23507, 36935, 38533, 20018, 27355, 37351, 23633, 23624], \"35904\": [25496, 31391, 27795, 38772, 36705, 31402, 29066, 38536, 31874, 26647, 32368, 26705, 37740, 21234, 21531, 34219, 35347, 32676, 36557, 37089, 21350, 34952, 31041, 20418, 20670, 21009, 20804, 21843, 22317, 29674, 22411, 22865, 24418, 24452, 24693, 24950, 24935, 25001, 25522, 25658, 25964, 26223, 26690, 28179, 30054, 31293, 31995, 32076, 32153, 32331, 32619, 33550, 33610, 34509, 35336, 35427, 35686, 36605, 38938, 40335, 33464, 36814, 39912], \"35968\": [21127, 25119, 25731, 28608, 38553, 26689, 20625, 27424, 27770, 28500, 31348, 32080, 34880, 35363, 26376, 20214, 20537, 20518, 20581, 20860, 21048, 21091, 21927, 22287, 22533, 23244, 24314, 25010, 25080, 25331, 25458, 26908, 27177, 29309, 29356, 29486, 30740, 30831, 32121, 30476, 32937, 35211, 35609, 36066, 36562, 36963, 37749, 38522, 38997, 39443, 40568, 20803, 21407, 21427, 24187, 24358, 28187, 28304, 29572, 29694, 32067, 33335, 35328, 35578, 38480, 20046, 20491, 21476, 21628, 22266, 22993, 23396, 24049, 24235, 24359, 25144, 25925, 26543, 28246, 29392, 31946, 34996, 32929, 32993, 33776, 34382, 35463, 36328, 37431, 38599, 39015, 40723, 20116, 20114, 20237, 21320, 21577, 21566, 23087, 24460, 24481, 24735, 26791, 27278, 29786, 30849, 35486, 35492, 35703, 37264, 20062, 39881, 20132, 20348, 20399, 20505, 20502, 20809, 20844, 21151, 21177, 21246, 21402, 21475, 21521], \"36160\": [21518, 21897, 22353, 22434, 22909, 23380, 23389, 23439, 24037, 24039, 24055, 24184, 24195, 24218, 24247, 24344, 24658, 24908, 25239, 25304, 25511, 25915, 26114, 26179, 26356, 26477, 26657, 26775, 27083, 27743, 27946, 28009, 28207, 28317, 30002, 30343, 30828, 31295, 31968, 32005, 32024, 32094, 32177, 32789, 32771, 32943, 32945, 33108, 33167, 33322, 33618, 34892, 34913, 35611, 36002, 36092, 37066, 37237, 37489, 30783, 37628, 38308, 38477], \"36224\": [38917, 39321, 39640, 40251, 21083, 21163, 21495, 21512, 22741, 25335, 28640, 35946, 36703, 40633, 20811, 21051, 21578, 22269, 31296, 37239, 40288, 40658, 29508, 28425, 33136, 29969, 24573, 24794, 39592, 29403, 36796, 27492, 38915, 20170, 22256, 22372, 22718, 23130, 24680, 25031, 26127, 26118, 26681, 26801, 28151, 30165, 32058, 33390, 39746, 20123, 20304, 21449, 21766, 23919, 24038, 24046, 26619, 27801, 29811, 30722, 35408, 37782, 35039, 22352, 24231, 25387, 20661, 20652, 20877, 26368, 21705, 22622, 22971, 23472, 24425, 25165, 25505, 26685, 27507, 28168, 28797, 37319, 29312, 30741, 30758, 31085, 25998, 32048, 33756, 35009, 36617, 38555, 21092, 22312, 26448, 32618, 36001, 20916, 22338, 38442, 22586, 27018, 32948, 21682, 23822, 22524, 30869, 40442, 20316, 21066, 21643, 25662, 26152, 26388, 26613, 31364, 31574, 32034, 37679, 26716, 39853, 31545, 21273, 20874, 21047], \"36416\": [23519, 25334, 25774, 25830, 26413, 27578, 34217, 38609, 30352, 39894, 25420, 37638, 39851, 30399, 26194, 19977, 20632, 21442, 23665, 24808, 25746, 25955, 26719, 29158, 29642, 29987, 31639, 32386, 34453, 35715, 36059, 37240, 39184, 26028, 26283, 27531, 20181, 20180, 20282, 20351, 21050, 21496, 21490, 21987, 22235, 22763, 22987, 22985, 23039, 23376, 23629, 24066, 24107, 24535, 24605, 25351, 25903, 23388, 26031, 26045, 26088, 26525, 27490], \"36480\": [27515, 27663, 29509, 31049, 31169, 31992, 32025, 32043, 32930, 33026, 33267, 35222, 35422, 35433, 35430, 35468, 35566, 36039, 36060, 38604, 39164, 27503, 20107, 20284, 20365, 20816, 23383, 23546, 24904, 25345, 26178, 27425, 28363, 27835, 29246, 29885, 30164, 30913, 31034, 32780, 32819, 33258, 33940, 36766, 27728, 40575, 24335, 35672, 40235, 31482, 36600, 23437, 38635, 19971, 21489, 22519, 22833, 23241, 23460, 24713, 28287, 28422, 30142, 36074, 23455, 34048, 31712, 20594, 26612, 33437, 23649, 34122, 32286, 33294, 20889, 23556, 25448, 36198, 26012, 29038, 31038, 32023, 32773, 35613, 36554, 36974, 34503, 37034, 20511, 21242, 23610, 26451, 28796, 29237, 37196, 37320, 37675, 33509, 23490, 24369, 24825, 20027, 21462, 23432, 25163, 26417, 27530, 29417, 29664, 31278, 33131, 36259, 37202, 39318, 20754, 21463, 21610, 23551, 25480, 27193, 32172, 38656, 22234, 21454, 21608], \"36672\": [23447, 23601, 24030, 20462, 24833, 25342, 27954, 31168, 31179, 32066, 32333, 32722, 33261, 33311, 33936, 34886, 35186, 35728, 36468, 36655, 36913, 37195, 37228, 38598, 37276, 20160, 20303, 20805, 21313, 24467, 25102, 26580, 27713, 28171, 29539, 32294, 37325, 37507, 21460, 22809, 23487, 28113, 31069, 32302, 31899, 22654, 29087, 20986, 34899, 36848, 20426, 23803, 26149, 30636, 31459, 33308, 39423, 20934, 24490, 26092, 26991, 27529, 28147], \"36736\": [28310, 28516, 30462, 32020, 24033, 36981, 37255, 38918, 20966, 21021, 25152, 26257, 26329, 28186, 24246, 32210, 32626, 26360, 34223, 34295, 35576, 21161, 21465, 22899, 24207, 24464, 24661, 37604, 38500, 20663, 20767, 21213, 21280, 21319, 21484, 21736, 21830, 21809, 22039, 22888, 22974, 23100, 23477, 23558, 23567, 23569, 23578, 24196, 24202, 24288, 24432, 25215, 25220, 25307, 25484, 25463, 26119, 26124, 26157, 26230, 26494, 26786, 27167, 27189, 27836, 28040, 28169, 28248, 28988, 28966, 29031, 30151, 30465, 30813, 30977, 31077, 31216, 31456, 31505, 31911, 32057, 32918, 33750, 33931, 34121, 34909, 35059, 35359, 35388, 35412, 35443, 35937, 36062, 37284, 37478, 37758, 37912, 38556, 38808, 19978, 19976, 19998, 20055, 20887, 21104, 22478, 22580, 22732, 23330, 24120, 24773, 25854, 26465, 26454, 27972, 29366, 30067, 31331, 33976, 35698, 37304, 37664, 22065, 22516, 39166], \"36928\": [25325, 26893, 27542, 29165, 32340, 32887, 33394, 35302, 39135, 34645, 36785, 23611, 20280, 20449, 20405, 21767, 23072, 23517, 23529, 24515, 24910, 25391, 26032, 26187, 26862, 27035, 28024, 28145, 30003, 30137, 30495, 31070, 31206, 32051, 33251, 33455, 34218, 35242, 35386, 36523, 36763, 36914, 37341, 38663, 20154, 20161, 20995, 22645, 22764, 23563, 29978, 23613, 33102, 35338, 36805, 38499, 38765, 31525, 35535, 38920, 37218, 22259, 21416], \"36992\": [36887, 21561, 22402, 24101, 25512, 27700, 28810, 30561, 31883, 32736, 34928, 36930, 37204, 37648, 37656, 38543, 29790, 39620, 23815, 23913, 25968, 26530, 36264, 38619, 25454, 26441, 26905, 33733, 38935, 38592, 35070, 28548, 25722, 23544, 19990, 28716, 30045, 26159, 20932, 21046, 21218, 22995, 24449, 24615, 25104, 25919, 25972, 26143, 26228, 26866, 26646, 27491, 28165, 29298, 29983, 30427, 31934, 32854, 22768, 35069, 35199, 35488, 35475, 35531, 36893, 37266, 38738, 38745, 25993, 31246, 33030, 38587, 24109, 24796, 25114, 26021, 26132, 26512, 30707, 31309, 31821, 32318, 33034, 36012, 36196, 36321, 36447, 30889, 20999, 25305, 25509, 25666, 25240, 35373, 31363, 31680, 35500, 38634, 32118, 33292, 34633, 20185, 20808, 21315, 21344, 23459, 23554, 23574, 24029, 25126, 25159, 25776, 26643, 26676, 27849, 27973, 27927, 26579, 28508, 29006, 29053, 26059, 31359, 31661, 32218], \"37184\": [32330, 32680, 33146, 33307, 33337, 34214, 35438, 36046, 36341, 36984, 36983, 37549, 37521, 38275, 39854, 21069, 21892, 28472, 28982, 20840, 31109, 32341, 33203, 31950, 22092, 22609, 23720, 25514, 26366, 26365, 26970, 29401, 30095, 30094, 30990, 31062, 31199, 31895, 32032, 32068, 34311, 35380, 38459, 36961, 40736, 20711, 21109, 21452, 21474, 20489, 21930, 22766, 22863, 29245, 23435, 23652, 21277, 24803, 24819, 25436, 25475, 25407, 25531], \"37248\": [25805, 26089, 26361, 24035, 27085, 27133, 28437, 29157, 20105, 30185, 30456, 31379, 31967, 32207, 32156, 32865, 33609, 33624, 33900, 33980, 34299, 35013, 36208, 36865, 36973, 37783, 38684, 39442, 20687, 22679, 24974, 33235, 34101, 36104, 36896, 20419, 20596, 21063, 21363, 24687, 25417, 26463, 28204, 36275, 36895, 20439, 23646, 36042, 26063, 32154, 21330, 34966, 20854, 25539, 23384, 23403, 23562, 25613, 26449, 36956, 20182, 22810, 22826, 27760, 35409, 21822, 22549, 22949, 24816, 25171, 26561, 33333, 26965, 38464, 39364, 39464, 20307, 22534, 23550, 32784, 23729, 24111, 24453, 24608, 24907, 25140, 26367, 27888, 28382, 32974, 33151, 33492, 34955, 36024, 36864, 36910, 38538, 40667, 39899, 20195, 21488, 22823, 31532, 37261, 38988, 40441, 28381, 28711, 21331, 21828, 23429, 25176, 25246, 25299, 27810, 28655, 29730, 35351, 37944, 28609, 35582, 33592, 20967, 34552, 21482], \"37440\": [21481, 20294, 36948, 36784, 22890, 33073, 24061, 31466, 36799, 26842, 35895, 29432, 40008, 27197, 35504, 20025, 21336, 22022, 22374, 25285, 25506, 26086, 27470, 28129, 28251, 28845, 30701, 31471, 31658, 32187, 32829, 32966, 34507, 35477, 37723, 22243, 22727, 24382, 26029, 26262, 27264, 27573, 30007, 35527, 20516, 30693, 22320, 24347, 24677, 26234, 27744, 30196, 31258, 32622, 33268, 34584, 36933, 39347, 31689, 30044, 31481, 31569, 33988], \"37504\": [36880, 31209, 31378, 33590, 23265, 30528, 20013, 20210, 23449, 24544, 25277, 26172, 26609, 27880, 34411, 34935, 35387, 37198, 37619, 39376, 27159, 28710, 29482, 33511, 33879, 36015, 19969, 20806, 20939, 21899, 23541, 24086, 24115, 24193, 24340, 24373, 24427, 24500, 25074, 25361, 26274, 26397, 28526, 29266, 30010, 30522, 32884, 33081, 33144, 34678, 35519, 35548, 36229, 36339, 37530, 38263, 38914, 40165, 21189, 25431, 30452, 26389, 27784, 29645, 36035, 37806, 38515, 27941, 22684, 26894, 27084, 36861, 37786, 30171, 36890, 22618, 26626, 25524, 27131, 20291, 28460, 26584, 36795, 34086, 32180, 37716, 26943, 28528, 22378, 22775, 23340, 32044, 29226, 21514, 37347, 40372, 20141, 20302, 20572, 20597, 21059, 35998, 21576, 22564, 23450, 24093, 24213, 24237, 24311, 24351, 24716, 25269, 25402, 25552, 26799, 27712, 30855, 31118, 31243, 32224, 33351, 35330, 35558, 36420, 36883], \"37696\": [37048, 37165, 37336, 40718, 27877, 25688, 25826, 25973, 28404, 30340, 31515, 36969, 37841, 28346, 21746, 24505, 25764, 36685, 36845, 37444, 20856, 22635, 22825, 23637, 24215, 28155, 32399, 29980, 36028, 36578, 39003, 28857, 20253, 27583, 28593, 30000, 38651, 20814, 21520, 22581, 22615, 22956, 23648, 24466, 26007, 26460, 28193, 30331, 33759, 36077, 36884, 37117, 37709, 30757, 30778, 21162, 24230, 22303, 22900, 24594, 20498, 20826, 20908], \"37760\": [20941, 20992, 21776, 22612, 22616, 22871, 23445, 23798, 23947, 24764, 25237, 25645, 26481, 26691, 26812, 26847, 30423, 28120, 28271, 28059, 28783, 29128, 24403, 30168, 31095, 31561, 31572, 31570, 31958, 32113, 21040, 33891, 34153, 34276, 35342, 35588, 35910, 36367, 36867, 36879, 37913, 38518, 38957, 39472, 38360, 20685, 21205, 21516, 22530, 23566, 24999, 25758, 27934, 30643, 31461, 33012, 33796, 36947, 37509, 23776, 40199, 21311, 24471, 24499, 28060, 29305, 30563, 31167, 31716, 27602, 29420, 35501, 26627, 27233, 20984, 31361, 26932, 23626, 40182, 33515, 23493, 37193, 28702, 22136, 23663, 24775, 25958, 27788, 35930, 36929, 38931, 21585, 26311, 37389, 22856, 37027, 20869, 20045, 20970, 34201, 35598, 28760, 25466, 37707, 26978, 39348, 32260, 30071, 21335, 26976, 36575, 38627, 27741, 20108, 23612, 24336, 36841, 21250, 36049, 32905, 34425, 24319, 26085, 20083, 20837], \"37952\": [22914, 23615, 38894, 20219, 22922, 24525, 35469, 28641, 31152, 31074, 23527, 33905, 29483, 29105, 24180, 24565, 25467, 25754, 29123, 31896, 20035, 24316, 20043, 22492, 22178, 24745, 28611, 32013, 33021, 33075, 33215, 36786, 35223, 34468, 24052, 25226, 25773, 35207, 26487, 27874, 27966, 29750, 30772, 23110, 32629, 33453, 39340, 20467, 24259, 25309, 25490, 25943, 26479, 30403, 29260, 32972, 32954, 36649, 37197, 20493, 22521, 23186, 26757], \"38016\": [26995, 29028, 29437, 36023, 22770, 36064, 38506, 36889, 34687, 31204, 30695, 33833, 20271, 21093, 21338, 25293, 26575, 27850, 30333, 31636, 31893, 33334, 34180, 36843, 26333, 28448, 29190, 32283, 33707, 39361, 40614, 20989, 31665, 30834, 31672, 32903, 31560, 27368, 24161, 32908, 30033, 30048, 20843, 37474, 28300, 30330, 37271, 39658, 20240, 32624, 25244, 31567, 38309, 40169, 22138, 22617, 34532, 38588, 20276, 21028, 21322, 21453, 21467, 24070, 25644, 26001, 26495, 27710, 27726, 29256, 29359, 29677, 30036, 32321, 33324, 34281, 36009, 31684, 37318, 29033, 38930, 39151, 25405, 26217, 30058, 30436, 30928, 34115, 34542, 21290, 21329, 21542, 22915, 24199, 24444, 24754, 25161, 25209, 25259, 26000, 27604, 27852, 30130, 30382, 30865, 31192, 32203, 32631, 32933, 34987, 35513, 36027, 36991, 38750, 39131, 27147, 31800, 20633, 23614, 24494, 26503, 27608, 29749, 30473, 32654], \"38208\": [40763, 26570, 31255, 21305, 30091, 39661, 24422, 33181, 33777, 32920, 24380, 24517, 30050, 31558, 36924, 26727, 23019, 23195, 32016, 30334, 35628, 20469, 24426, 27161, 27703, 28418, 29922, 31080, 34920, 35413, 35961, 24287, 25551, 30149, 31186, 33495, 37672, 37618, 33948, 34541, 39981, 21697, 24428, 25996, 27996, 28693, 36007, 36051, 38971, 25935, 29942, 19981, 20184, 22496, 22827, 23142, 23500, 20904, 24067, 24220, 24598, 25206, 25975], \"38272\": [26023, 26222, 28014, 29238, 31526, 33104, 33178, 33433, 35676, 36000, 36070, 36212, 38428, 38468, 20398, 25771, 27494, 33310, 33889, 34154, 37096, 23553, 26963, 39080, 33914, 34135, 20239, 21103, 24489, 24133, 26381, 31119, 33145, 35079, 35206, 28149, 24343, 25173, 27832, 20175, 29289, 39826, 20998, 21563, 22132, 22707, 24996, 25198, 28954, 22894, 31881, 31966, 32027, 38640, 25991, 32862, 19993, 20341, 20853, 22592, 24163, 24179, 24330, 26564, 20006, 34109, 38281, 38491, 31859, 38913, 20731, 22721, 30294, 30887, 21029, 30629, 34065, 31622, 20559, 22793, 29255, 31687, 32232, 36794, 36820, 36941, 20415, 21193, 23081, 24321, 38829, 20445, 33303, 37610, 22275, 25429, 27497, 29995, 35036, 36628, 31298, 21215, 22675, 24917, 25098, 26286, 27597, 31807, 33769, 20515, 20472, 21253, 21574, 22577, 22857, 23453, 23792, 23791, 23849, 24214, 25265, 25447, 25918, 26041, 26379], \"38464\": [27861, 27873, 28921, 30770, 32299, 32990, 33459, 33804, 34028, 34562, 35090, 35370, 35914, 37030, 37586, 39165, 40179, 40300, 20047, 20129, 20621, 21078, 22346, 22952, 24125, 24536, 24537, 25151, 26292, 26395, 26576, 26834, 20882, 32033, 32938, 33192, 35584, 35980, 36031, 37502, 38450, 21536, 38956, 21271, 20693, 21340, 22696, 25778, 26420, 29287, 30566, 31302, 37350, 21187, 27809, 27526, 22528, 24140, 22868, 26412, 32763, 20961, 30406], \"38528\": [25705, 30952, 39764, 40635, 22475, 22969, 26151, 26522, 27598, 21737, 27097, 24149, 33180, 26517, 39850, 26622, 40018, 26717, 20134, 20451, 21448, 25273, 26411, 27819, 36804, 20397, 32365, 40639, 19975, 24930, 28288, 28459, 34067, 21619, 26410, 39749, 24051, 31637, 23724, 23494, 34588, 28234, 34001, 31252, 33032, 22937, 31885, 27665, 30496, 21209, 22818, 28961, 29279, 30683, 38695, 40289, 26891, 23167, 23064, 20901, 21517, 21629, 26126, 30431, 36855, 37528, 40180, 23018, 29277, 28357, 20813, 26825, 32191, 32236, 38754, 40634, 25720, 27169, 33538, 22916, 23391, 27611, 29467, 30450, 32178, 32791, 33945, 20786, 26408, 40665, 30446, 26466, 21247, 39173, 23588, 25147, 31870, 36016, 21839, 24758, 32011, 38272, 21249, 20063, 20918, 22812, 29242, 32822, 37326, 24357, 30690, 21380, 24441, 32004, 34220, 35379, 36493, 38742, 26611, 34222, 37971, 24841, 24840, 27833, 30290], \"38720\": [35565, 36664, 21807, 20305, 20778, 21191, 21451, 23461, 24189, 24736, 24962, 25558, 26377, 26586, 28263, 28044, 29494, 29495, 30001, 31056, 35029, 35480, 36938, 37009, 37109, 38596, 34701, 22805, 20104, 20313, 19982, 35465, 36671, 38928, 20653, 24188, 22934, 23481, 24248, 25562, 25594, 25793, 26332, 26954, 27096, 27915, 28342, 29076, 29992, 31407, 32650, 32768, 33865, 33993, 35201, 35617, 36362, 36965, 38525, 39178, 24958, 25233, 27442], \"38784\": [27779, 28020, 32716, 32764, 28096, 32645, 34746, 35064, 26469, 33713, 38972, 38647, 27931, 32097, 33853, 37226, 20081, 21365, 23888, 27396, 28651, 34253, 34349, 35239, 21033, 21519, 23653, 26446, 26792, 29702, 29827, 30178, 35023, 35041, 37324, 38626, 38520, 24459, 29575, 31435, 33870, 25504, 30053, 21129, 27969, 28316, 29705, 30041, 30827, 31890, 38534, 31452, 40845, 20406, 24942, 26053, 34396, 20102, 20142, 20698, 20001, 20940, 23534, 26009, 26753, 28092, 29471, 30274, 30637, 31260, 31975, 33391, 35538, 36988, 37327, 38517, 38936, 21147, 32209, 20523, 21400, 26519, 28107, 29136, 29747, 33256, 36650, 38563, 40023, 40607, 29792, 22593, 28057, 32047, 39006, 20196, 20278, 20363, 20919, 21169, 23994, 24604, 29618, 31036, 33491, 37428, 38583, 38646, 38666, 40599, 40802, 26278, 27508, 21015, 21155, 28872, 35010, 24265, 24651, 24976, 28451, 29001, 31806, 32244, 32879], \"38976\": [34030, 36899, 37676, 21570, 39791, 27347, 28809, 36034, 36335, 38706, 21172, 23105, 24266, 24324, 26391, 27004, 27028, 28010, 28431, 29282, 29436, 31725, 32769, 32894, 34635, 37070, 20845, 40595, 31108, 32907, 37682, 35542, 20525, 21644, 35441, 27498, 36036, 33031, 24785, 26528, 40434, 20121, 20120, 39952, 35435, 34241, 34152, 26880, 28286, 30871, 33109], \"39071\": [24332, 19984, 19989, 20010, 20017, 20022, 20028, 20031, 20034, 20054, 20056, 20098, 20101, 35947, 20106, 33298, 24333, 20110, 20126, 20127, 20128, 20130, 20144, 20147, 20150, 20174, 20173, 20164, 20166, 20162, 20183, 20190, 20205, 20191, 20215, 20233, 20314, 20272, 20315, 20317, 20311, 20295, 20342, 20360, 20367, 20376, 20347, 20329, 20336, 20369, 20335, 20358, 20374, 20760, 20436, 20447, 20430, 20440, 20443, 20433, 20442, 20432, 20452, 20453, 20506, 20520, 20500, 20522, 20517, 20485, 20252, 20470, 20513, 20521, 20524, 20478, 20463, 20497, 20486, 20547, 20551, 26371, 20565, 20560, 20552, 20570, 20566, 20588, 20600, 20608, 20634, 20613, 20660, 20658], \"39232\": [20681, 20682, 20659, 20674, 20694, 20702, 20709, 20717, 20707, 20718, 20729, 20725, 20745, 20737, 20738, 20758, 20757, 20756, 20762, 20769, 20794, 20791, 20796, 20795, 20799, 20800, 20818, 20812, 20820, 20834, 31480, 20841, 20842, 20846, 20864, 20866, 22232, 20876, 20873, 20879, 20881, 20883, 20885, 20886, 20900, 20902, 20898, 20905, 20906, 20907, 20915, 20913, 20914, 20912, 20917, 20925, 20933, 20937, 20955, 20960, 34389, 20969, 20973], \"39296\": [20976, 20981, 20990, 20996, 21003, 21012, 21006, 21031, 21034, 21038, 21043, 21049, 21071, 21060, 21067, 21068, 21086, 21076, 21098, 21108, 21097, 21107, 21119, 21117, 21133, 21140, 21138, 21105, 21128, 21137, 36776, 36775, 21164, 21165, 21180, 21173, 21185, 21197, 21207, 21214, 21219, 21222, 39149, 21216, 21235, 21237, 21240, 21241, 21254, 21256, 30008, 21261, 21264, 21263, 21269, 21274, 21283, 21295, 21297, 21299, 21304, 21312, 21318, 21317, 19991, 21321, 21325, 20950, 21342, 21353, 21358, 22808, 21371, 21367, 21378, 21398, 21408, 21414, 21413, 21422, 21424, 21430, 21443, 31762, 38617, 21471, 26364, 29166, 21486, 21480, 21485, 21498, 21505, 21565, 21568, 21548, 21549, 21564, 21550, 21558, 21545, 21533, 21582, 21647, 21621, 21646, 21599, 21617, 21623, 21616, 21650, 21627, 21632, 21622, 21636, 21648, 21638, 21703, 21666, 21688, 21669, 21676, 21700, 21704, 21672], \"39488\": [21675, 21698, 21668, 21694, 21692, 21720, 21733, 21734, 21775, 21780, 21757, 21742, 21741, 21754, 21730, 21817, 21824, 21859, 21836, 21806, 21852, 21829, 21846, 21847, 21816, 21811, 21853, 21913, 21888, 21679, 21898, 21919, 21883, 21886, 21912, 21918, 21934, 21884, 21891, 21929, 21895, 21928, 21978, 21957, 21983, 21956, 21980, 21988, 21972, 22036, 22007, 22038, 22014, 22013, 22043, 22009, 22094, 22096, 29151, 22068, 22070, 22066, 22072], \"39552\": [22123, 22116, 22063, 22124, 22122, 22150, 22144, 22154, 22176, 22164, 22159, 22181, 22190, 22198, 22196, 22210, 22204, 22209, 22211, 22208, 22216, 22222, 22225, 22227, 22231, 22254, 22265, 22272, 22271, 22276, 22281, 22280, 22283, 22285, 22291, 22296, 22294, 21959, 22300, 22310, 22327, 22328, 22350, 22331, 22336, 22351, 22377, 22464, 22408, 22369, 22399, 22409, 22419, 22432, 22451, 22436, 22442, 22448, 22467, 22470, 22484, 22482, 22483, 22538, 22486, 22499, 22539, 22553, 22557, 22642, 22561, 22626, 22603, 22640, 27584, 22610, 22589, 22649, 22661, 22713, 22687, 22699, 22714, 22750, 22715, 22712, 22702, 22725, 22739, 22737, 22743, 22745, 22744, 22757, 22748, 22756, 22751, 22767, 22778, 22777, 22779, 22780, 22781, 22786, 22794, 22800, 22811, 26790, 22821, 22828, 22829, 22834, 22840, 22846, 31442, 22869, 22864, 22862, 22874, 22872, 22882, 22880, 22887, 22892, 22889], \"39744\": [22904, 22913, 22941, 20318, 20395, 22947, 22962, 22982, 23016, 23004, 22925, 23001, 23002, 23077, 23071, 23057, 23068, 23049, 23066, 23104, 23148, 23113, 23093, 23094, 23138, 23146, 23194, 23228, 23230, 23243, 23234, 23229, 23267, 23255, 23270, 23273, 23254, 23290, 23291, 23308, 23307, 23318, 23346, 23248, 23338, 23350, 23358, 23363, 23365, 23360, 23377, 23381, 23386, 23387, 23397, 23401, 23408, 23411, 23413, 23416, 25992, 23418, 23424], \"39808\": [23427, 23462, 23480, 23491, 23495, 23497, 23508, 23504, 23524, 23526, 23522, 23518, 23525, 23531, 23536, 23542, 23539, 23557, 23559, 23560, 23565, 23571, 23584, 23586, 23592, 23608, 23609, 23617, 23622, 23630, 23635, 23632, 23631, 23409, 23660, 23662, 20066, 23670, 23673, 23692, 23697, 23700, 22939, 23723, 23739, 23734, 23740, 23735, 23749, 23742, 23751, 23769, 23785, 23805, 23802, 23789, 23948, 23786, 23819, 23829, 23831, 23900, 23839, 23835, 23825, 23828, 23842, 23834, 23833, 23832, 23884, 23890, 23886, 23883, 23916, 23923, 23926, 23943, 23940, 23938, 23970, 23965, 23980, 23982, 23997, 23952, 23991, 23996, 24009, 24013, 24019, 24018, 24022, 24027, 24043, 24050, 24053, 24075, 24090, 24089, 24081, 24091, 24118, 24119, 24132, 24131, 24128, 24142, 24151, 24148, 24159, 24162, 24164, 24135, 24181, 24182, 24186, 40636, 24191, 24224, 24257, 24258, 24264, 24272, 24271], \"40000\": [24278, 24291, 24285, 24282, 24283, 24290, 24289, 24296, 24297, 24300, 24305, 24307, 24304, 24308, 24312, 24318, 24323, 24329, 24413, 24412, 24331, 24337, 24342, 24361, 24365, 24376, 24385, 24392, 24396, 24398, 24367, 24401, 24406, 24407, 24409, 24417, 24429, 24435, 24439, 24451, 24450, 24447, 24458, 24456, 24465, 24455, 24478, 24473, 24472, 24480, 24488, 24493, 24508, 24534, 24571, 24548, 24568, 24561, 24541, 24755, 24575, 24609, 24672], \"40064\": [24601, 24592, 24617, 24590, 24625, 24603, 24597, 24619, 24614, 24591, 24634, 24666, 24641, 24682, 24695, 24671, 24650, 24646, 24653, 24675, 24643, 24676, 24642, 24684, 24683, 24665, 24705, 24717, 24807, 24707, 24730, 24708, 24731, 24726, 24727, 24722, 24743, 24715, 24801, 24760, 24800, 24787, 24756, 24560, 24765, 24774, 24757, 24792, 24909, 24853, 24838, 24822, 24823, 24832, 24820, 24826, 24835, 24865, 24827, 24817, 24845, 24846, 24903, 24894, 24872, 24871, 24906, 24895, 24892, 24876, 24884, 24893, 24898, 24900, 24947, 24951, 24920, 24921, 24922, 24939, 24948, 24943, 24933, 24945, 24927, 24925, 24915, 24949, 24985, 24982, 24967, 25004, 24980, 24986, 24970, 24977, 25003, 25006, 25036, 25034, 25033, 25079, 25032, 25027, 25030, 25018, 25035, 32633, 25037, 25062, 25059, 25078, 25082, 25076, 25087, 25085, 25084, 25086, 25088, 25096, 25097, 25101, 25100, 25108, 25115], \"40256\": [25118, 25121, 25130, 25134, 25136, 25138, 25139, 25153, 25166, 25182, 25187, 25179, 25184, 25192, 25212, 25218, 25225, 25214, 25234, 25235, 25238, 25300, 25219, 25236, 25303, 25297, 25275, 25295, 25343, 25286, 25812, 25288, 25308, 25292, 25290, 25282, 25287, 25243, 25289, 25356, 25326, 25329, 25383, 25346, 25352, 25327, 25333, 25424, 25406, 25421, 25628, 25423, 25494, 25486, 25472, 25515, 25462, 25507, 25487, 25481, 25503, 25525, 25451], \"40320\": [25449, 25534, 25577, 25536, 25542, 25571, 25545, 25554, 25590, 25540, 25622, 25652, 25606, 25619, 25638, 25654, 25885, 25623, 25640, 25615, 25703, 25711, 25718, 25678, 25898, 25749, 25747, 25765, 25769, 25736, 25788, 25818, 25810, 25797, 25799, 25787, 25816, 25794, 25841, 25831, 33289, 25824, 25825, 25260, 25827, 25839, 25900, 25846, 25844, 25842, 25850, 25856, 25853, 25880, 25884, 25861, 25892, 25891, 25899, 25908, 25909, 25911, 25910, 25912, 30027, 25928, 25942, 25941, 25933, 25944, 25950, 25949, 25970, 25976, 25986, 25987, 35722, 26011, 26015, 26027, 26039, 26051, 26054, 26049, 26052, 26060, 26066, 26075, 26073, 26080, 26081, 26097, 26482, 26122, 26115, 26107, 26483, 26165, 26166, 26164, 26140, 26191, 26180, 26185, 26177, 26206, 26205, 26212, 26215, 26216, 26207, 26210, 26224, 26243, 26248, 26254, 26249, 26244, 26264, 26269, 26305, 26297, 26313, 26302, 26300], \"40512\": [26308, 26296, 26326, 26330, 26336, 26175, 26342, 26345, 26352, 26357, 26359, 26383, 26390, 26398, 26406, 26407, 38712, 26414, 26431, 26422, 26433, 26424, 26423, 26438, 26462, 26464, 26457, 26467, 26468, 26505, 26480, 26537, 26492, 26474, 26508, 26507, 26534, 26529, 26501, 26551, 26607, 26548, 26604, 26547, 26601, 26552, 26596, 26590, 26589, 26594, 26606, 26553, 26574, 26566, 26599, 27292, 26654, 26694, 26665, 26688, 26701, 26674, 26702], \"40576\": [26803, 26667, 26713, 26723, 26743, 26751, 26783, 26767, 26797, 26772, 26781, 26779, 26755, 27310, 26809, 26740, 26805, 26784, 26810, 26895, 26765, 26750, 26881, 26826, 26888, 26840, 26914, 26918, 26849, 26892, 26829, 26836, 26855, 26837, 26934, 26898, 26884, 26839, 26851, 26917, 26873, 26848, 26863, 26920, 26922, 26906, 26915, 26913, 26822, 27001, 26999, 26972, 27000, 26987, 26964, 27006, 26990, 26937, 26996, 26941, 26969, 26928, 26977, 26974, 26973, 27009, 26986, 27058, 27054, 27088, 27071, 27073, 27091, 27070, 27086, 23528, 27082, 27101, 27067, 27075, 27047, 27182, 27025, 27040, 27036, 27029, 27060, 27102, 27112, 27138, 27163, 27135, 27402, 27129, 27122, 27111, 27141, 27057, 27166, 27117, 27156, 27115, 27146, 27154, 27329, 27171, 27155, 27204, 27148, 27250, 27190, 27256, 27207, 27234, 27225, 27238, 27208, 27192, 27170, 27280, 27277, 27296, 27268, 27298, 27299], \"40768\": [27287, 34327, 27323, 27331, 27330, 27320, 27315, 27308, 27358, 27345, 27359, 27306, 27354, 27370, 27387, 27397, 34326, 27386, 27410, 27414, 39729, 27423, 27448, 27447, 30428, 27449, 39150, 27463, 27459, 27465, 27472, 27481, 27476, 27483, 27487, 27489, 27512, 27513, 27519, 27520, 27524, 27523, 27533, 27544, 27541, 27550, 27556, 27562, 27563, 27567, 27570, 27569, 27571, 27575, 27580, 27590, 27595, 27603, 27615, 27628, 27627, 27635, 27631], \"40832\": [40638, 27656, 27667, 27668, 27675, 27684, 27683, 27742, 27733, 27746, 27754, 27778, 27789, 27802, 27777, 27803, 27774, 27752, 27763, 27794, 27792, 27844, 27889, 27859, 27837, 27863, 27845, 27869, 27822, 27825, 27838, 27834, 27867, 27887, 27865, 27882, 27935, 34893, 27958, 27947, 27965, 27960, 27929, 27957, 27955, 27922, 27916, 28003, 28051, 28004, 27994, 28025, 27993, 28046, 28053, 28644, 28037, 28153, 28181, 28170, 28085, 28103, 28134, 28088, 28102, 28140, 28126, 28108, 28136, 28114, 28101, 28154, 28121, 28132, 28117, 28138, 28142, 28205, 28270, 28206, 28185, 28274, 28255, 28222, 28195, 28267, 28203, 28278, 28237, 28191, 28227, 28218, 28238, 28196, 28415, 28189, 28216, 28290, 28330, 28312, 28361, 28343, 28371, 28349, 28335, 28356, 28338, 28372, 28373, 28303, 28325, 28354, 28319, 28481, 28433, 28748, 28396, 28408, 28414, 28479, 28402, 28465, 28399, 28466, 28364], \"57408\": [28478, 28435, 28407, 28550, 28538, 28536, 28545, 28544, 28527, 28507, 28659, 28525, 28546, 28540, 28504, 28558, 28561, 28610, 28518, 28595, 28579, 28577, 28580, 28601, 28614, 28586, 28639, 28629, 28652, 28628, 28632, 28657, 28654, 28635, 28681, 28683, 28666, 28689, 28673, 28687, 28670, 28699, 28698, 28532, 28701, 28696, 28703, 28720, 28734, 28722, 28753, 28771, 28825, 28818, 28847, 28913, 28844, 28856, 28851, 28846, 28895, 28875, 28893], \"57472\": [28889, 28937, 28925, 28956, 28953, 29029, 29013, 29064, 29030, 29026, 29004, 29014, 29036, 29071, 29179, 29060, 29077, 29096, 29100, 29143, 29113, 29118, 29138, 29129, 29140, 29134, 29152, 29164, 29159, 29173, 29180, 29177, 29183, 29197, 29200, 29211, 29224, 29229, 29228, 29232, 29234, 29243, 29244, 29247, 29248, 29254, 29259, 29272, 29300, 29310, 29314, 29313, 29319, 29330, 29334, 29346, 29351, 29369, 29362, 29379, 29382, 29380, 29390, 29394, 29410, 29408, 29409, 29433, 29431, 20495, 29463, 29450, 29468, 29462, 29469, 29492, 29487, 29481, 29477, 29502, 29518, 29519, 40664, 29527, 29546, 29544, 29552, 29560, 29557, 29563, 29562, 29640, 29619, 29646, 29627, 29632, 29669, 29678, 29662, 29858, 29701, 29807, 29733, 29688, 29746, 29754, 29781, 29759, 29791, 29785, 29761, 29788, 29801, 29808, 29795, 29802, 29814, 29822, 29835, 29854, 29863, 29898, 29903, 29908, 29681], \"57664\": [29920, 29923, 29927, 29929, 29934, 29938, 29936, 29937, 29944, 29943, 29956, 29955, 29957, 29964, 29966, 29965, 29973, 29971, 29982, 29990, 29996, 30012, 30020, 30029, 30026, 30025, 30043, 30022, 30042, 30057, 30052, 30055, 30059, 30061, 30072, 30070, 30086, 30087, 30068, 30090, 30089, 30082, 30100, 30106, 30109, 30117, 30115, 30146, 30131, 30147, 30133, 30141, 30136, 30140, 30129, 30157, 30154, 30162, 30169, 30179, 30174, 30206, 30207], \"57728\": [30204, 30209, 30192, 30202, 30194, 30195, 30219, 30221, 30217, 30239, 30247, 30240, 30241, 30242, 30244, 30260, 30256, 30267, 30279, 30280, 30278, 30300, 30296, 30305, 30306, 30312, 30313, 30314, 30311, 30316, 30320, 30322, 30326, 30328, 30332, 30336, 30339, 30344, 30347, 30350, 30358, 30355, 30361, 30362, 30384, 30388, 30392, 30393, 30394, 30402, 30413, 30422, 30418, 30430, 30433, 30437, 30439, 30442, 34351, 30459, 30472, 30471, 30468, 30505, 30500, 30494, 30501, 30502, 30491, 30519, 30520, 30535, 30554, 30568, 30571, 30555, 30565, 30591, 30590, 30585, 30606, 30603, 30609, 30624, 30622, 30640, 30646, 30649, 30655, 30652, 30653, 30651, 30663, 30669, 30679, 30682, 30684, 30691, 30702, 30716, 30732, 30738, 31014, 30752, 31018, 30789, 30862, 30836, 30854, 30844, 30874, 30860, 30883, 30901, 30890, 30895, 30929, 30918, 30923, 30932, 30910, 30908, 30917, 30922, 30956], \"57920\": [30951, 30938, 30973, 30964, 30983, 30994, 30993, 31001, 31020, 31019, 31040, 31072, 31063, 31071, 31066, 31061, 31059, 31098, 31103, 31114, 31133, 31143, 40779, 31146, 31150, 31155, 31161, 31162, 31177, 31189, 31207, 31212, 31201, 31203, 31240, 31245, 31256, 31257, 31264, 31263, 31104, 31281, 31291, 31294, 31287, 31299, 31319, 31305, 31329, 31330, 31337, 40861, 31344, 31353, 31357, 31368, 31383, 31381, 31384, 31382, 31401, 31432, 31408], \"57984\": [31414, 31429, 31428, 31423, 36995, 31431, 31434, 31437, 31439, 31445, 31443, 31449, 31450, 31453, 31457, 31458, 31462, 31469, 31472, 31490, 31503, 31498, 31494, 31539, 31512, 31513, 31518, 31541, 31528, 31542, 31568, 31610, 31492, 31565, 31499, 31564, 31557, 31605, 31589, 31604, 31591, 31600, 31601, 31596, 31598, 31645, 31640, 31647, 31629, 31644, 31642, 31627, 31634, 31631, 31581, 31641, 31691, 31681, 31692, 31695, 31668, 31686, 31709, 31721, 31761, 31764, 31718, 31717, 31840, 31744, 31751, 31763, 31731, 31735, 31767, 31757, 31734, 31779, 31783, 31786, 31775, 31799, 31787, 31805, 31820, 31811, 31828, 31823, 31808, 31824, 31832, 31839, 31844, 31830, 31845, 31852, 31861, 31875, 31888, 31908, 31917, 31906, 31915, 31905, 31912, 31923, 31922, 31921, 31918, 31929, 31933, 31936, 31941, 31938, 31960, 31954, 31964, 31970, 39739, 31983, 31986, 31988, 31990, 31994, 32006], \"58176\": [32002, 32028, 32021, 32010, 32069, 32075, 32046, 32050, 32063, 32053, 32070, 32115, 32086, 32078, 32114, 32104, 32110, 32079, 32099, 32147, 32137, 32091, 32143, 32125, 32155, 32186, 32174, 32163, 32181, 32199, 32189, 32171, 32317, 32162, 32175, 32220, 32184, 32159, 32176, 32216, 32221, 32228, 32222, 32251, 32242, 32225, 32261, 32266, 32291, 32289, 32274, 32305, 32287, 32265, 32267, 32290, 32326, 32358, 32315, 32309, 32313, 32323, 32311], \"58240\": [32306, 32314, 32359, 32349, 32342, 32350, 32345, 32346, 32377, 32362, 32361, 32380, 32379, 32387, 32213, 32381, 36782, 32383, 32392, 32393, 32396, 32402, 32400, 32403, 32404, 32406, 32398, 32411, 32412, 32568, 32570, 32581, 32588, 32589, 32590, 32592, 32593, 32597, 32596, 32600, 32607, 32608, 32616, 32617, 32615, 32632, 32642, 32646, 32643, 32648, 32647, 32652, 32660, 32670, 32669, 32666, 32675, 32687, 32690, 32697, 32686, 32694, 32696, 35697, 32709, 32710, 32714, 32725, 32724, 32737, 32742, 32745, 32755, 32761, 39132, 32774, 32772, 32779, 32786, 32792, 32793, 32796, 32801, 32808, 32831, 32827, 32842, 32838, 32850, 32856, 32858, 32863, 32866, 32872, 32883, 32882, 32880, 32886, 32889, 32893, 32895, 32900, 32902, 32901, 32923, 32915, 32922, 32941, 20880, 32940, 32987, 32997, 32985, 32989, 32964, 32986, 32982, 33033, 33007, 33009, 33051, 33065, 33059, 33071, 33099], \"58432\": [38539, 33094, 33086, 33107, 33105, 33020, 33137, 33134, 33125, 33126, 33140, 33155, 33160, 33162, 33152, 33154, 33184, 33173, 33188, 33187, 33119, 33171, 33193, 33200, 33205, 33214, 33208, 33213, 33216, 33218, 33210, 33225, 33229, 33233, 33241, 33240, 33224, 33242, 33247, 33248, 33255, 33274, 33275, 33278, 33281, 33282, 33285, 33287, 33290, 33293, 33296, 33302, 33321, 33323, 33336, 33331, 33344, 33369, 33368, 33373, 33370, 33375, 33380], \"58496\": [33378, 33384, 33386, 33387, 33326, 33393, 33399, 33400, 33406, 33421, 33426, 33451, 33439, 33467, 33452, 33505, 33507, 33503, 33490, 33524, 33523, 33530, 33683, 33539, 33531, 33529, 33502, 33542, 33500, 33545, 33497, 33589, 33588, 33558, 33586, 33585, 33600, 33593, 33616, 33605, 33583, 33579, 33559, 33560, 33669, 33690, 33706, 33695, 33698, 33686, 33571, 33678, 33671, 33674, 33660, 33717, 33651, 33653, 33696, 33673, 33704, 33780, 33811, 33771, 33742, 33789, 33795, 33752, 33803, 33729, 33783, 33799, 33760, 33778, 33805, 33826, 33824, 33725, 33848, 34054, 33787, 33901, 33834, 33852, 34138, 33924, 33911, 33899, 33965, 33902, 33922, 33897, 33862, 33836, 33903, 33913, 33845, 33994, 33890, 33977, 33983, 33951, 34009, 33997, 33979, 34010, 34000, 33985, 33990, 34006, 33953, 34081, 34047, 34036, 34071, 34072, 34092, 34079, 34069, 34068, 34044, 34112, 34147, 34136, 34120], \"58688\": [34113, 34306, 34123, 34133, 34176, 34212, 34184, 34193, 34186, 34216, 34157, 34196, 34203, 34282, 34183, 34204, 34167, 34174, 34192, 34249, 34234, 34255, 34233, 34256, 34261, 34269, 34277, 34268, 34297, 34314, 34323, 34315, 34302, 34298, 34310, 34338, 34330, 34352, 34367, 34381, 20053, 34388, 34399, 34407, 34417, 34451, 34467, 34473, 34474, 34443, 34444, 34486, 34479, 34500, 34502, 34480, 34505, 34851, 34475, 34516, 34526, 34537, 34540], \"58752\": [34527, 34523, 34543, 34578, 34566, 34568, 34560, 34563, 34555, 34577, 34569, 34573, 34553, 34570, 34612, 34623, 34615, 34619, 34597, 34601, 34586, 34656, 34655, 34680, 34636, 34638, 34676, 34647, 34664, 34670, 34649, 34643, 34659, 34666, 34821, 34722, 34719, 34690, 34735, 34763, 34749, 34752, 34768, 38614, 34731, 34756, 34739, 34759, 34758, 34747, 34799, 34802, 34784, 34831, 34829, 34814, 34806, 34807, 34830, 34770, 34833, 34838, 34837, 34850, 34849, 34865, 34870, 34873, 34855, 34875, 34884, 34882, 34898, 34905, 34910, 34914, 34923, 34945, 34942, 34974, 34933, 34941, 34997, 34930, 34946, 34967, 34962, 34990, 34969, 34978, 34957, 34980, 34992, 35007, 34993, 35011, 35012, 35028, 35032, 35033, 35037, 35065, 35074, 35068, 35060, 35048, 35058, 35076, 35084, 35082, 35091, 35139, 35102, 35109, 35114, 35115, 35137, 35140, 35131, 35126, 35128, 35148, 35101, 35168, 35166], \"58944\": [35174, 35172, 35181, 35178, 35183, 35188, 35191, 35198, 35203, 35208, 35210, 35219, 35224, 35233, 35241, 35238, 35244, 35247, 35250, 35258, 35261, 35263, 35264, 35290, 35292, 35293, 35303, 35316, 35320, 35331, 35350, 35344, 35340, 35355, 35357, 35365, 35382, 35393, 35419, 35410, 35398, 35400, 35452, 35437, 35436, 35426, 35461, 35458, 35460, 35496, 35489, 35473, 35493, 35494, 35482, 35491, 35524, 35533, 35522, 35546, 35563, 35571, 35559], \"59008\": [35556, 35569, 35604, 35552, 35554, 35575, 35550, 35547, 35596, 35591, 35610, 35553, 35606, 35600, 35607, 35616, 35635, 38827, 35622, 35627, 35646, 35624, 35649, 35660, 35663, 35662, 35657, 35670, 35675, 35674, 35691, 35679, 35692, 35695, 35700, 35709, 35712, 35724, 35726, 35730, 35731, 35734, 35737, 35738, 35898, 35905, 35903, 35912, 35916, 35918, 35920, 35925, 35938, 35948, 35960, 35962, 35970, 35977, 35973, 35978, 35981, 35982, 35988, 35964, 35992, 25117, 36013, 36010, 36029, 36018, 36019, 36014, 36022, 36040, 36033, 36068, 36067, 36058, 36093, 36090, 36091, 36100, 36101, 36106, 36103, 36111, 36109, 36112, 40782, 36115, 36045, 36116, 36118, 36199, 36205, 36209, 36211, 36225, 36249, 36290, 36286, 36282, 36303, 36314, 36310, 36300, 36315, 36299, 36330, 36331, 36319, 36323, 36348, 36360, 36361, 36351, 36381, 36382, 36368, 36383, 36418, 36405, 36400, 36404, 36426], \"59200\": [36423, 36425, 36428, 36432, 36424, 36441, 36452, 36448, 36394, 36451, 36437, 36470, 36466, 36476, 36481, 36487, 36485, 36484, 36491, 36490, 36499, 36497, 36500, 36505, 36522, 36513, 36524, 36528, 36550, 36529, 36542, 36549, 36552, 36555, 36571, 36579, 36604, 36603, 36587, 36606, 36618, 36613, 36629, 36626, 36633, 36627, 36636, 36639, 36635, 36620, 36646, 36659, 36667, 36665, 36677, 36674, 36670, 36684, 36681, 36678, 36686, 36695, 36700], \"59264\": [36706, 36707, 36708, 36764, 36767, 36771, 36781, 36783, 36791, 36826, 36837, 36834, 36842, 36847, 36999, 36852, 36869, 36857, 36858, 36881, 36885, 36897, 36877, 36894, 36886, 36875, 36903, 36918, 36917, 36921, 36856, 36943, 36944, 36945, 36946, 36878, 36937, 36926, 36950, 36952, 36958, 36968, 36975, 36982, 38568, 36978, 36994, 36989, 36993, 36992, 37002, 37001, 37007, 37032, 37039, 37041, 37045, 37090, 37092, 25160, 37083, 37122, 37138, 37145, 37170, 37168, 37194, 37206, 37208, 37219, 37221, 37225, 37235, 37234, 37259, 37257, 37250, 37282, 37291, 37295, 37290, 37301, 37300, 37306, 37312, 37313, 37321, 37323, 37328, 37334, 37343, 37345, 37339, 37372, 37365, 37366, 37406, 37375, 37396, 37420, 37397, 37393, 37470, 37463, 37445, 37449, 37476, 37448, 37525, 37439, 37451, 37456, 37532, 37526, 37523, 37531, 37466, 37583, 37561, 37559, 37609, 37647, 37626, 37700, 37678], \"59456\": [37657, 37666, 37658, 37667, 37690, 37685, 37691, 37724, 37728, 37756, 37742, 37718, 37808, 37804, 37805, 37780, 37817, 37846, 37847, 37864, 37861, 37848, 37827, 37853, 37840, 37832, 37860, 37914, 37908, 37907, 37891, 37895, 37904, 37942, 37931, 37941, 37921, 37946, 37953, 37970, 37956, 37979, 37984, 37986, 37982, 37994, 37417, 38000, 38005, 38007, 38013, 37978, 38012, 38014, 38017, 38015, 38274, 38279, 38282, 38292, 38294, 38296, 38297], \"59520\": [38304, 38312, 38311, 38317, 38332, 38331, 38329, 38334, 38346, 28662, 38339, 38349, 38348, 38357, 38356, 38358, 38364, 38369, 38373, 38370, 38433, 38440, 38446, 38447, 38466, 38476, 38479, 38475, 38519, 38492, 38494, 38493, 38495, 38502, 38514, 38508, 38541, 38552, 38549, 38551, 38570, 38567, 38577, 38578, 38576, 38580, 38582, 38584, 38585, 38606, 38603, 38601, 38605, 35149, 38620, 38669, 38613, 38649, 38660, 38662, 38664, 38675, 38670, 38673, 38671, 38678, 38681, 38692, 38698, 38704, 38713, 38717, 38718, 38724, 38726, 38728, 38722, 38729, 38748, 38752, 38756, 38758, 38760, 21202, 38763, 38769, 38777, 38789, 38780, 38785, 38778, 38790, 38795, 38799, 38800, 38812, 38824, 38822, 38819, 38835, 38836, 38851, 38854, 38856, 38859, 38876, 38893, 40783, 38898, 31455, 38902, 38901, 38927, 38924, 38968, 38948, 38945, 38967, 38973, 38982, 38991, 38987, 39019, 39023, 39024], \"59712\": [39025, 39028, 39027, 39082, 39087, 39089, 39094, 39108, 39107, 39110, 39145, 39147, 39171, 39177, 39186, 39188, 39192, 39201, 39197, 39198, 39204, 39200, 39212, 39214, 39229, 39230, 39234, 39241, 39237, 39248, 39243, 39249, 39250, 39244, 39253, 39319, 39320, 39333, 39341, 39342, 39356, 39391, 39387, 39389, 39384, 39377, 39405, 39406, 39409, 39410, 39419, 39416, 39425, 39439, 39429, 39394, 39449, 39467, 39479, 39493, 39490, 39488, 39491], \"59776\": [39486, 39509, 39501, 39515, 39511, 39519, 39522, 39525, 39524, 39529, 39531, 39530, 39597, 39600, 39612, 39616, 39631, 39633, 39635, 39636, 39646, 39647, 39650, 39651, 39654, 39663, 39659, 39662, 39668, 39665, 39671, 39675, 39686, 39704, 39706, 39711, 39714, 39715, 39717, 39719, 39720, 39721, 39722, 39726, 39727, 39730, 39748, 39747, 39759, 39757, 39758, 39761, 39768, 39796, 39827, 39811, 39825, 39830, 39831, 39839, 39840, 39848, 39860, 39872, 39882, 39865, 39878, 39887, 39889, 39890, 39907, 39906, 39908, 39892, 39905, 39994, 39922, 39921, 39920, 39957, 39956, 39945, 39955, 39948, 39942, 39944, 39954, 39946, 39940, 39982, 39963, 39973, 39972, 39969, 39984, 40007, 39986, 40006, 39998, 40026, 40032, 40039, 40054, 40056, 40167, 40172, 40176, 40201, 40200, 40171, 40195, 40198, 40234, 40230, 40367, 40227, 40223, 40260, 40213, 40210, 40257, 40255, 40254, 40262, 40264], \"59968\": [40285, 40286, 40292, 40273, 40272, 40281, 40306, 40329, 40327, 40363, 40303, 40314, 40346, 40356, 40361, 40370, 40388, 40385, 40379, 40376, 40378, 40390, 40399, 40386, 40409, 40403, 40440, 40422, 40429, 40431, 40445, 40474, 40475, 40478, 40565, 40569, 40573, 40577, 40584, 40587, 40588, 40594, 40597, 40593, 40605, 40613, 40617, 40632, 40618, 40621, 38753, 40652, 40654, 40655, 40656, 40660, 40668, 40670, 40669, 40672, 40677, 40680, 40687], \"60032\": [40692, 40694, 40695, 40697, 40699, 40700, 40701, 40711, 40712, 30391, 40725, 40737, 40748, 40766, 40778, 40786, 40788, 40803, 40799, 40800, 40801, 40806, 40807, 40812, 40810, 40823, 40818, 40822, 40853, 40860, 40864, 22575, 27079, 36953, 29796, 20956, 29081], \"60736\": [32394, 35100, 37704, 37512, 34012, 20425, 28859, 26161, 26824, 37625, 26363, 24389, 20008, 20193, 20220, 20224, 20227, 20281, 20310, 20370, 20362, 20378, 20372, 20429, 20544, 20514, 20479, 20510, 20550, 20592, 20546, 20628, 20724, 20696, 20810, 20836, 20893, 20926, 20972, 21013, 21148, 21158, 21184, 21211, 21248, 21255, 21284, 21362, 21395, 21426, 21469, 64014, 21660, 21642, 21673, 21759, 21894, 22361, 22373, 22444, 22472, 22471, 64015], \"60800\": [64016, 22686, 22706, 22795, 22867, 22875, 22877, 22883, 22948, 22970, 23382, 23488, 29999, 23512, 23532, 23582, 23718, 23738, 23797, 23847, 23891, 64017, 23874, 23917, 23992, 23993, 24016, 24353, 24372, 24423, 24503, 24542, 24669, 24709, 24714, 24798, 24789, 24864, 24818, 24849, 24887, 24880, 24984, 25107, 25254, 25589, 25696, 25757, 25806, 25934, 26112, 26133, 26171, 26121, 26158, 26142, 26148, 26213, 26199, 26201, 64018, 26227, 26265, 26272, 26290, 26303, 26362, 26382, 63785, 26470, 26555, 26706, 26560, 26625, 26692, 26831, 64019, 26984, 64020, 27032, 27106, 27184, 27243, 27206, 27251, 27262, 27362, 27364, 27606, 27711, 27740, 27782, 27759, 27866, 27908, 28039, 28015, 28054, 28076, 28111, 28152, 28146, 28156, 28217, 28252, 28199, 28220, 28351, 28552, 28597, 28661, 28677, 28679, 28712, 28805, 28843, 28943, 28932, 29020, 28998, 28999, 64021, 29121, 29182, 29361], \"60992\": [29374, 29476, 64022, 29559, 29629, 29641, 29654, 29667, 29650, 29703, 29685, 29734, 29738, 29737, 29742, 29794, 29833, 29855, 29953, 30063, 30338, 30364, 30366, 30363, 30374, 64023, 30534, 21167, 30753, 30798, 30820, 30842, 31024, 64024, 64025, 64026, 31124, 64027, 31131, 31441, 31463, 64028, 31467, 31646, 64029, 32072, 32092, 32183, 32160, 32214, 32338, 32583, 32673, 64030, 33537, 33634, 33663, 33735, 33782, 33864, 33972, 34131, 34137], \"61056\": [34155, 64031, 34224, 64032, 64033, 34823, 35061, 35346, 35383, 35449, 35495, 35518, 35551, 64034, 35574, 35667, 35711, 36080, 36084, 36114, 36214, 64035, 36559, 64036, 64037, 36967, 37086, 64038, 37141, 37159, 37338, 37335, 37342, 37357, 37358, 37348, 37349, 37382, 37392, 37386, 37434, 37440, 37436, 37454, 37465, 37457, 37433, 37479, 37543, 37495, 37496, 37607, 37591, 37593, 37584, 64039, 37589, 37600, 37587, 37669, 37665, 37627, 64040, 37662, 37631, 37661, 37634, 37744, 37719, 37796, 37830, 37854, 37880, 37937, 37957, 37960, 38290, 63964, 64041, 38557, 38575, 38707, 38715, 38723, 38733, 38735, 38737, 38741, 38999, 39013, 64042, 64043, 39207, 64044, 39326, 39502, 39641, 39644, 39797, 39794, 39823, 39857, 39867, 39936, 40304, 40299, 64045, 40473, 40657], \"61167\": [8560, 8561, 8562, 8563, 8564, 8565, 8566, 8567, 8568, 8569, 65506, 65508, 65287, 65282], \"64064\": [8560, 8561, 8562, 8563, 8564, 8565, 8566, 8567, 8568, 8569, 8544, 8545, 8546, 8547, 8548, 8549, 8550, 8551, 8552, 8553, 65506, 65508, 65287, 65282, 12849, 8470, 8481, 8757, 32394, 35100, 37704, 37512, 34012, 20425, 28859, 26161, 26824, 37625, 26363, 24389, 20008, 20193, 20220, 20224, 20227, 20281, 20310, 20370, 20362, 20378, 20372, 20429, 20544, 20514, 20479, 20510, 20550, 20592, 20546, 20628, 20724, 20696, 20810], \"64128\": [20836, 20893, 20926, 20972, 21013, 21148, 21158, 21184, 21211, 21248, 21255, 21284, 21362, 21395, 21426, 21469, 64014, 21660, 21642, 21673, 21759, 21894, 22361, 22373, 22444, 22472, 22471, 64015, 64016, 22686, 22706, 22795, 22867, 22875, 22877, 22883, 22948, 22970, 23382, 23488, 29999, 23512, 23532, 23582, 23718, 23738, 23797, 23847, 23891, 64017, 23874, 23917, 23992, 23993, 24016, 24353, 24372, 24423, 24503, 24542, 24669, 24709, 24714, 24798, 24789, 24864, 24818, 24849, 24887, 24880, 24984, 25107, 25254, 25589, 25696, 25757, 25806, 25934, 26112, 26133, 26171, 26121, 26158, 26142, 26148, 26213, 26199, 26201, 64018, 26227, 26265, 26272, 26290, 26303, 26362, 26382, 63785, 26470, 26555, 26706, 26560, 26625, 26692, 26831, 64019, 26984, 64020, 27032, 27106, 27184, 27243, 27206, 27251, 27262, 27362, 27364, 27606, 27711, 27740, 27782, 27759, 27866, 27908, 28039, 28015], \"64320\": [28054, 28076, 28111, 28152, 28146, 28156, 28217, 28252, 28199, 28220, 28351, 28552, 28597, 28661, 28677, 28679, 28712, 28805, 28843, 28943, 28932, 29020, 28998, 28999, 64021, 29121, 29182, 29361, 29374, 29476, 64022, 29559, 29629, 29641, 29654, 29667, 29650, 29703, 29685, 29734, 29738, 29737, 29742, 29794, 29833, 29855, 29953, 30063, 30338, 30364, 30366, 30363, 30374, 64023, 30534, 21167, 30753, 30798, 30820, 30842, 31024, 64024, 64025], \"64384\": [64026, 31124, 64027, 31131, 31441, 31463, 64028, 31467, 31646, 64029, 32072, 32092, 32183, 32160, 32214, 32338, 32583, 32673, 64030, 33537, 33634, 33663, 33735, 33782, 33864, 33972, 34131, 34137, 34155, 64031, 34224, 64032, 64033, 34823, 35061, 35346, 35383, 35449, 35495, 35518, 35551, 64034, 35574, 35667, 35711, 36080, 36084, 36114, 36214, 64035, 36559, 64036, 64037, 36967, 37086, 64038, 37141, 37159, 37338, 37335, 37342, 37357, 37358, 37348, 37349, 37382, 37392, 37386, 37434, 37440, 37436, 37454, 37465, 37457, 37433, 37479, 37543, 37495, 37496, 37607, 37591, 37593, 37584, 64039, 37589, 37600, 37587, 37669, 37665, 37627, 64040, 37662, 37631, 37661, 37634, 37744, 37719, 37796, 37830, 37854, 37880, 37937, 37957, 37960, 38290, 63964, 64041, 38557, 38575, 38707, 38715, 38723, 38733, 38735, 38737, 38741, 38999, 39013, 64042, 64043, 39207, 64044, 39326, 39502, 39641], \"64576\": [39644, 39797, 39794, 39823, 39857, 39867, 39936, 40304, 40299, 64045, 40473, 40657]}\nvar decoding_table = [],\n encoding_table = []\nfor(let cp in cps){\n cp = parseInt(cp)\n for(let i = 0, len = cps[cp].length; i < len; i++){\n let key = cp + i,\n value = cps[cp][i]\n decoding_table[key] = value\n encoding_table[value] = key\n }\n}\nvar module = {encoding_table, decoding_table}\n__BRYTHON__.addToImported(\"encoding_cp932\", module)\n"], "hashlib": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nvar block_size = {\n md5: 64,\n sha1: 64,\n sha224: 64,\n sha256: 64,\n sha384: 128,\n sha512: 128\n}\n\nvar $mod = {\n\n __getattr__ : function(attr){\n if(attr == 'new'){\n return hash.$factory\n }\n throw $B.attr_error(attr, $mod)\n },\n md5: function(obj){return hash.$factory('md5', obj)},\n sha1: function(obj){return hash.$factory('sha1', obj)},\n sha224: function(obj){return hash.$factory('sha224', obj)},\n sha256: function(obj){return hash.$factory('sha256', obj)},\n sha384: function(obj){return hash.$factory('sha384', obj)},\n sha512: function(obj){return hash.$factory('sha512', obj)},\n\n algorithms_guaranteed: ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],\n algorithms_available: ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']\n}\n\n//todo: eventually move this function to a \"utility\" file or use ajax module?\nfunction $get_CryptoJS_lib(alg){\n if($B.VFS !== undefined && $B.VFS.hashlib){\n // use file in brython_stdlib.js\n var lib = $B.VFS[\"crypto_js.rollups.\" + alg]\n if (lib === undefined){\n throw _b_.ImportError.$factory(\"can't import hashlib.\" + alg)\n }\n var res = lib[1]\n try{\n eval(res + \"; $B.CryptoJS = CryptoJS;\")\n return\n }catch(err){\n throw Error(\"JS Eval Error\",\n \"Cannot eval CryptoJS algorithm '\" + alg + \"' : error:\" + err)\n }\n }\n\n var module = {__name__: 'CryptoJS', $is_package: false}\n var res = $B.$download_module(module, $B.brython_path + 'libs/crypto_js/rollups/' + alg + '.js');\n\n try{\n eval(res + \"; $B.CryptoJS = CryptoJS;\")\n }catch(err){\n throw Error(\"JS Eval Error\",\n \"Cannot eval CryptoJS algorithm '\" + alg + \"' : error:\" + err)\n }\n}\n\nfunction bytes2WordArray(obj){\n // Transform a bytes object into an instance of class WordArray\n // defined in CryptoJS\n if(!$B.$isinstance(obj, _b_.bytes)){\n throw _b_.TypeError(\"expected bytes, got \" + $B.class_name(obj))\n }\n\n var words = []\n for(var i = 0; i < obj.source.length; i += 4){\n var word = obj.source.slice(i, i + 4)\n while(word.length < 4){word.push(0)}\n var w = word[3] + (word[2] << 8) + (word[1] << 16) + (word[0] << 24)\n words.push(w)\n }\n return {words: words, sigBytes: obj.source.length}\n}\n\nvar hash = {\n __class__: _b_.type,\n __mro__: [_b_.object],\n __qualname__: 'hash',\n __name__: 'hash'\n}\n\nhash.update = function(self, msg){\n self.hash.update(bytes2WordArray(msg))\n}\n\nhash.copy = function(self){\n return self.hash.clone()\n}\n\nhash.digest = function(self){\n var obj = self.hash.clone().finalize().toString(),\n res = []\n for(var i = 0; i < obj.length; i += 2){\n res.push(parseInt(obj.substr(i, 2), 16))\n }\n return _b_.bytes.$factory(res)\n}\n\nhash.hexdigest = function(self) {\n return self.hash.clone().finalize().toString()\n}\n\nhash.$factory = function(alg, obj) {\n var res = {\n __class__: hash\n }\n\n switch(alg) {\n case 'md5':\n case 'sha1':\n case 'sha224':\n case 'sha256':\n case 'sha384':\n case 'sha512':\n var ALG = alg.toUpperCase()\n if($B.Crypto === undefined ||\n $B.CryptoJS.algo[ALG] === undefined){$get_CryptoJS_lib(alg)}\n\n res.hash = $B.CryptoJS.algo[ALG].create()\n if(obj !== undefined){\n res.hash.update(bytes2WordArray(obj))\n }\n break\n default:\n throw $B.builtins.AttributeError.$factory('Invalid hash algorithm: ' + alg)\n }\n res.digest_size = res.hash._hash.sigBytes\n res.block_size = block_size[alg]\n return res\n}\n\n$B.addToImported('hashlib', $mod)\n\n})(__BRYTHON__)\n"], "html_parser": [".js", "(function($B){\n\n_b_ = $B.builtins\n\nvar ELEMENT_NODE = 1,\n TEXT_NODE = 3,\n COMMENT_NODE = 8,\n DOCUMENT_TYPE_NODE = 10\n\nvar HTMLNode = $B.make_class(\"HTMLNode\",\n function(){\n return {\n __class__: HTMLNode,\n nodeType: TEXT_NODE,\n text: \"\"\n }\n }\n)\n\nHTMLNode.__str__ = function(self){\n return self.text\n}\n\n$B.set_func_names(HTMLNode, \"_html_parser\")\n\nfunction* tokenize(src){\n var node = HTMLNode.$factory(),\n pos = 0,\n tag = \"\",\n type = \"text\"\n while(pos < src.length){\n var char = src[pos]\n switch(type){\n case \"text\":\n if(char == \"<\"){\n // starts a tag if immediately followed by a letter or by /\n var tag_mo = /^(\\/?)[a-zA-Z]+/.exec(src.substr(pos + 1))\n if(tag_mo){\n yield node\n node = HTMLNode.$factory()\n type = \"tag\"\n node.tagName = \"\"\n node.nodeType = ELEMENT_NODE\n node.closing = tag_mo[1] != \"\"\n node.attrs = []\n }else{\n // doctype declaration\n var decl_mo = /^/i.exec(src.substr(pos))\n if(decl_mo){\n yield node\n node = HTMLNode.$factory()\n node.text = decl_mo[0]\n node.doctype = decl_mo[1]\n node.nodeType = DOCUMENT_TYPE_NODE\n yield node\n node = HTMLNode.$factory()\n type = \"text\"\n pos += decl_mo[0].length\n break\n }else{\n // comment\n var comment_mo = /^\\/.exec(src.substr(pos))\n if(comment_mo){\n yield node\n node = HTMLNode.$factory()\n node.text = comment_mo[0]\n node.comment = comment_mo[1]\n node.nodeType = COMMENT_NODE\n yield node\n node = HTMLNode.$factory()\n type = \"text\"\n pos += comment_mo[0].length\n break\n }\n }\n }\n }\n pos++\n node.text += char\n break\n case \"tag\":\n if(char.search(/[_a-zA-Z]/) > -1){\n var mo = /\\w+/.exec(src.substr(pos))\n if(mo !== null){\n pos += mo[0].length\n if(node.tagName == \"\"){\n node.tagName = mo[0].toUpperCase()\n }\n node.text += mo[0]\n }else{\n pos++\n }\n }else if(char == \">\"){\n node.text += char\n yield node\n node = HTMLNode.$factory()\n type = \"text\"\n pos++\n }else if(char == \"=\"){\n node.text += char\n pos++\n }else if(char == \"'\" || char == '\"'){\n var i = pos + 1,\n found_string_end = false\n while(i < src.length){\n if(src[i] == char){\n var nb_escape = 0\n while(src[i - 1 - nb_escape] == '/'){\n nb_escape++\n }\n if(nb_escape % 2 == 0){\n node.text += src.substr(pos, i + 1 - pos)\n pos = i + 1\n found_string_end = true\n break\n }else{\n i++\n }\n }else if(src[i] == '>'){\n break\n }else{\n i++\n }\n }\n if(! found_string_end){\n // unterminated string: ignore\n pos++\n }\n }else{\n node.text += char\n pos++\n }\n break\n default:\n pos++\n }\n }\n yield node\n}\nvar module = {\n ELEMENT_NODE: 1,\n TEXT_NODE: 3,\n COMMENT_NODE: 8,\n DOCUMENT_TYPE_NODE: 10,\n tokenize: tokenize\n}\n\n$B.addToImported('html_parser', module)\n\n})(__BRYTHON__)\n"], "marshal": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nvar module = {\n loads: function(){\n var $ = $B.args('loads', 1, {obj:null}, ['obj'], arguments, {},\n null, null)\n return $B.structuredclone2pyobj(JSON.parse($.obj))\n },\n load: function(){\n var $ = $B.args('load', 1, {file:null}, ['file'], arguments, {},\n null, null)\n var content = $B.$call($B.$getattr($.file, \"read\"))()\n return $module.loads(_b_.bytes.decode(content, \"latin-1\"));\n },\n dump: function(){\n var $ = $B.args('dump', 2, {value:null, file: null},\n ['value', 'file'], arguments, {}, null, null)\n var s = JSON.stringify($B.pyobj2structuredclone($.value))\n $B.$getattr($.file, \"write\")(_b_.str.encode(s, 'latin-1'))\n var flush = $B.$getattr($.file, \"flush\", null)\n if(flush !== null){\n $B.$call(flush)()\n }\n return _b_.None\n },\n dumps: function(){\n var $ = $B.args('dumps', 1, {obj:null}, ['obj'], arguments, {},\n null, null)\n return JSON.stringify($B.pyobj2structuredclone($.obj))\n }\n}\n\n$B.addToImported('marshal', module)\n\n})(__BRYTHON__)\n"], "math": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nconst INF = $B.fast_float(Number.POSITIVE_INFINITY),\n NINF = $B.fast_float(Number.NEGATIVE_INFINITY),\n ZERO = $B.fast_float(0),\n NAN = $B.fast_float(Number.NaN)\n\nvar float_check = function(x) {\n // Returns a Javascript number\n if(x.__class__ === $B.long_int){\n var res = parseInt(x.value)\n if(! isFinite(res)){\n throw _b_.OverflowError.$factory('int too big for float')\n }\n return res\n }else if(x.__class__ === _b_.float){\n return x.value\n }\n try{\n return _b_.float.$factory(x).value\n }catch(err){\n throw _b_.TypeError.$factory('must be real number, not ' +\n $B.class_name(x))\n }\n}\n\nfunction check_int(x){\n if(! $B.$isinstance(x, _b_.int)){\n throw _b_.TypeError.$factory(\"'\" + $B.class_name(x) +\n \"' object cannot be interpreted as an integer\")\n }\n}\n\nfunction check_int_or_round_float(x){\n return ($B.$isinstance(x, _b_.float) && Number.isInteger(x.value)) ||\n $B.$isinstance(x, _b_.int)\n}\n\nvar isWholeNumber = function(x){return (x * 10) % 10 == 0}\n\nvar isOdd = function(x) {return isWholeNumber(x) && 2 * Math.floor(x / 2) != x}\n\nvar isNegZero = function(x) {return x === 0 && Math.atan2(x,x) < 0}\n\nfunction overflow(){\n throw _b_.OverflowError.$factory(\"math range error\")\n}\n\nfunction value_error(){\n throw _b_.ValueError.$factory(\"math range error\")\n}\n\nvar EPSILON = Math.pow(2, -52),\n MAX_VALUE = (2 - EPSILON) * Math.pow(2, 1023),\n MIN_VALUE = Math.pow(2, -1022),\n Py_HUGE_VAL = Number.POSITIVE_INFINITY,\n logpi = 1.144729885849400174143427351353058711647,\n sqrtpi = 1.772453850905516027298167483341145182798\n\nfunction nextUp(x){\n if(x !== x){ // NaN\n return x\n }\n if(_b_.float.$funcs.isinf(x)){\n if(_b_.float.$funcs.isninf(x)){\n return -MAX_VALUE\n }\n return _mod.inf\n }\n if($B.$isinstance(x, $B.long_int)){\n x = Number(x.value)\n }else if($B.$isinstance(x, _b_.float)){\n x = x.value\n }\n\n if(x == +MAX_VALUE){\n return +1 / 0\n }\n if(typeof x == \"number\"){\n var y = x * (x < 0 ? 1 - EPSILON / 2 : 1 + EPSILON)\n if(y == x){\n y = MIN_VALUE * EPSILON > 0 ? x + MIN_VALUE * EPSILON : x + MIN_VALUE\n }\n if(y === +1 / 0){\n y = +MAX_VALUE\n }\n var b = x + (y - x) / 2\n if(x < b && b < y){\n y = b;\n }\n var c = (y + x) / 2\n if(x < c && c < y){\n y = c;\n }\n return y === 0 ? -0 : y\n }else{\n var factor = $B.rich_comp('__lt__', x, 0) ? 1 - EPSILON / 2 :\n 1 + EPSILON\n var y = $B.rich_op(\"__mul__\", x , factor)\n if(y == x){\n y = MIN_VALUE * EPSILON > 0 ?\n $B.rich_op('__add__', x, MIN_VALUE * EPSILON) :\n $B.rich_op('__add__', x, MIN_VALUE)\n }\n if(y === +1 / 0){\n y = +MAX_VALUE\n }\n var y_minus_x = $B.rich_op('__sub__', y, x)\n var z = $B.rich_op('__truediv__', y_minus_x, 2) // (y - x) / 2\n\n var b = $B.rich_op('__add__', x, z)\n if($B.rich_comp('__lt__', x, b) && $B.rich_comp('__lt__', b, y)){\n y = b;\n }\n var c = $B.rich_op('__truediv__', $B.rich_op('__add__', y, x), 2)\n if($B.rich_comp('__lt__', x, c) && $B.rich_comp('__lt__', c, y)){\n y = c;\n }\n return y === 0 ? -0 : y\n }\n}\n\nfunction gcd2(a, b){\n // GCD of 2 factors\n if($B.rich_comp(\"__gt__\", b, a)){\n var temp = a\n a = b\n b = temp\n }\n while(true){\n if(b == 0){\n return a\n }\n a = $B.rich_op(\"__mod__\", a, b)\n if(a == 0){\n return b\n }\n b = $B.rich_op(\"__mod__\", b, a)\n }\n}\n\nconst LANCZOS_N = 13,\n lanczos_g = 6.024680040776729583740234375,\n lanczos_g_minus_half = 5.524680040776729583740234375,\n lanczos_num_coeffs = [\n 23531376880.410759688572007674451636754734846804940,\n 42919803642.649098768957899047001988850926355848959,\n 35711959237.355668049440185451547166705960488635843,\n 17921034426.037209699919755754458931112671403265390,\n 6039542586.3520280050642916443072979210699388420708,\n 1439720407.3117216736632230727949123939715485786772,\n 248874557.86205415651146038641322942321632125127801,\n 31426415.585400194380614231628318205362874684987640,\n 2876370.6289353724412254090516208496135991145378768,\n 186056.26539522349504029498971604569928220784236328,\n 8071.6720023658162106380029022722506138218516325024,\n 210.82427775157934587250973392071336271166969580291,\n 2.5066282746310002701649081771338373386264310793408\n ],\n /* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */\n lanczos_den_coeffs = [\n 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,\n 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0],\n /* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */\n NGAMMA_INTEGRAL = 23,\n gamma_integral = [\n 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,\n 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,\n 1307674368000.0, 20922789888000.0, 355687428096000.0,\n 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,\n 51090942171709440000.0, 1124000727777607680000.0]\n\n/* Lanczos' sum L_g(x), for positive x */\nfunction lanczos_sum(x){\n var num = 0.0,\n den = 0.0,\n i\n /* evaluate the rational function lanczos_sum(x). For large\n x, the obvious algorithm risks overflow, so we instead\n rescale the denominator and numerator of the rational\n function by x**(1-LANCZOS_N) and treat this as a\n rational function in 1/x. This also reduces the error for\n larger x values. The choice of cutoff point (5.0 below) is\n somewhat arbitrary; in tests, smaller cutoff values than\n this resulted in lower accuracy. */\n if (x < 5.0) {\n for (i = LANCZOS_N; --i >= 0; ) {\n num = num * x + lanczos_num_coeffs[i];\n den = den * x + lanczos_den_coeffs[i];\n }\n }else{\n for (i = 0; i < LANCZOS_N; i++) {\n num = num / x + lanczos_num_coeffs[i];\n den = den / x + lanczos_den_coeffs[i];\n }\n }\n return num/den;\n}\n\nfunction m_sinpi(x){\n // x is float\n // returns a float\n var r,\n y = fmod(fabs(x), 2.0), // float\n n = _b_.round($B.fast_float(2.0 * y.value)) // int\n switch(n){\n case 0:\n r = sin(pi.value * y.value);\n break;\n case 1:\n r = cos(pi.value * (y.value - 0.5));\n break;\n case 2:\n /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give\n -0.0 instead of 0.0 when y == 1.0. */\n r = sin(pi.value * (1.0 - y.value));\n break;\n case 3:\n r = _b_.float.__neg__(cos(pi.value *(y.value - 1.5)))\n break;\n case 4:\n r = sin(pi.value * (y.value - 2.0));\n break;\n }\n return $B.fast_float(copysign(1.0, x).value * r.value);\n}\n\n/*\n lgamma: natural log of the absolute value of the Gamma function.\n For large arguments, Lanczos' formula works extremely well here.\n*/\nfunction m_lgamma(x){\n var r,\n absx\n\n /* special cases */\n if(! isfinite(x)){\n if(isnan(x)){\n return x; /* lgamma(nan) = nan */\n }else{\n return $B.fast_float(Number.POSITIVE_INFINITY); /* lgamma(+-inf) = +inf */\n }\n }\n\n /* integer arguments */\n var x1 = float_check(x)\n if(Number.isInteger(x1) && x1 <= 2.0){\n if(x1 <= 0.0){\n value_error()\n }else{\n return $B.fast_float(0.0); /* lgamma(1) = lgamma(2) = 0.0 */\n }\n }\n\n absx = fabs(x)\n /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */\n if (absx.value < 1e-20){\n return $B.fast_float(-log(absx).value);\n }\n /* Lanczos' formula. We could save a fraction of a ulp in accuracy by\n having a second set of numerator coefficients for lanczos_sum that\n absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g\n subtraction below; it's probably not worth it. */\n var lsum = $B.fast_float(lanczos_sum(absx.value))\n r = log(lsum).value - lanczos_g;\n r += (absx.value - 0.5) *\n (log($B.fast_float(absx.value + lanczos_g - 0.5)).value - 1)\n if (x1 < 0.0){\n /* Use reflection formula to get value for negative x. */\n r = logpi - log(fabs(m_sinpi(absx))).value - log(absx).value - r\n }\n r = $B.fast_float(r)\n if(isinf(r)){\n overflow()\n }\n return r;\n}\n\nfunction acos(x){\n $B.check_nb_args('acos', 1, arguments)\n $B.check_no_kw('acos', x)\n if(_mod.isinf(x)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }else if(_mod.isnan(x)){\n return _mod.nan\n }else{\n x = float_check(x)\n if(x > 1 || x < -1){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return _b_.float.$factory(Math.acos(x))\n }\n}\n\nfunction acosh(x){\n $B.check_nb_args('acosh', 1, arguments)\n $B.check_no_kw('acosh', x)\n\n if(_b_.float.$funcs.isinf(x)){\n if(_b_.float.$funcs.isninf(x)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return _mod.inf\n }else if(_mod.isnan(x)){\n return _mod.nan\n }\n var y = float_check(x)\n if(y <= 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if(y > Math.pow(2, 28)){ // issue 1590\n return _b_.float.$factory(_mod.log(y).value + _mod.log(2).value)\n }\n return _b_.float.$factory(Math.log(y + Math.sqrt(y * y - 1)))\n}\n\nfunction asin(x){\n $B.check_nb_args('asin', 1, arguments)\n $B.check_no_kw('asin', x)\n if(_mod.isinf(x)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }else if(_mod.isnan(x)){\n return _mod.nan\n }else{\n x = float_check(x)\n if(x > 1 || x < -1){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return _b_.float.$factory(Math.asin(x))\n }\n}\n\nfunction asinh(x){\n $B.check_nb_args('asinh', 1, arguments)\n $B.check_no_kw('asinh', x)\n\n var y = float_check(x)\n if(_b_.float.$funcs.isninf(x)){\n return NINF\n }else if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n if(y == 0 && 1 / y === -Infinity){\n return $B.fast_float(-0.0)\n }\n return _b_.float.$factory(Math.asinh(y))\n}\n\nfunction atan(x){\n $B.check_nb_args('atan', 1, arguments)\n $B.check_no_kw('atan', x)\n\n if(_b_.float.$funcs.isninf(x)){return _b_.float.$factory(-Math.PI / 2)}\n if(_b_.float.$funcs.isinf(x)){return _b_.float.$factory(Math.PI / 2)}\n return _b_.float.$factory(Math.atan(float_check(x)))\n}\n\nfunction atan2(x, y){\n $B.check_nb_args('atan2', 2, arguments)\n $B.check_no_kw('atan2', x, y)\n\n return _b_.float.$factory(Math.atan2(float_check(x), float_check(y)))\n}\n\nfunction atanh(x){\n $B.check_nb_args('atanh', 1, arguments)\n $B.check_no_kw('atanh', x)\n if(_b_.float.$funcs.isinf(x)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n var y = float_check(x)\n if(y == 0){\n return 0\n }else if(y <= -1 || y >= 1){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return _b_.float.$factory(0.5 * Math.log((1 / y + 1)/(1 / y - 1)));\n}\n\nfunction cbrt(x){\n // Cubic root\n $B.check_nb_args('cbrt ', 1, arguments)\n $B.check_no_kw('cbrt ', x)\n\n var y = float_check(x)\n if(_b_.float.$funcs.isninf(x)){\n return NINF\n }else if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n var _r = $B.fast_float(Math.cbrt(y))\n if(_b_.float.$funcs.isinf(_r)){\n throw _b_.OverflowError.$factory(\"math range error\")\n }\n return _r\n}\n\nfunction ceil(x){\n $B.check_nb_args('ceil', 1, arguments)\n $B.check_no_kw('ceil', x)\n\n var res\n\n if($B.$isinstance(x, _b_.float)){\n if(_b_.float.$funcs.isinf(x)){\n throw _b_.OverflowError.$factory(\n \"cannot convert float infinity to integer\")\n }else if(_mod.isnan(x)){\n throw _b_.OverflowError.$factory(\n \"cannot convert float NaN to integer\")\n }\n }\n\n var klass = x.__class__ || $B.get_class(x)\n\n try{\n // Use attribute of the object's class, not of the object\n // itself (special method)\n return $B.$call($B.$getattr(klass, '__ceil__'))(x)\n }catch(err){\n if(! $B.is_exc(err, [_b_.AttributeError])){\n throw err\n }\n }\n\n try{\n x = $B.$call($B.$getattr(klass, '__float__'))(x)\n }catch(err){\n if(! $B.is_exc(err, [_b_.AttributeError])){\n throw err\n }else{\n throw _b_.TypeError.$factory(\"must be real number, not \" +\n $B.class_name(x))\n }\n }\n return _mod.ceil(x)\n}\n\nconst ULLONG_MAX = 2n ** 64n - 1n,\n LONG_MAX = 2147483647,\n LONG_MIN = -2147483647,\n LLONG_MAX = 9223372036854775807n,\n LLONG_MIN = -9223372036854775807n,\n p2_64 = 2n ** 64n\n\nconst reduced_factorial_odd_part = [\n 0x0000000000000001n, 0x0000000000000001n, 0x0000000000000001n, 0x0000000000000003n,\n 0x0000000000000003n, 0x000000000000000fn, 0x000000000000002dn, 0x000000000000013bn,\n 0x000000000000013bn, 0x0000000000000b13n, 0x000000000000375fn, 0x0000000000026115n,\n 0x000000000007233fn, 0x00000000005cca33n, 0x0000000002898765n, 0x00000000260eeeebn,\n 0x00000000260eeeebn, 0x0000000286fddd9bn, 0x00000016beecca73n, 0x000001b02b930689n,\n 0x00000870d9df20adn, 0x0000b141df4dae31n, 0x00079dd498567c1bn, 0x00af2e19afc5266dn,\n 0x020d8a4d0f4f7347n, 0x335281867ec241efn, 0x9b3093d46fdd5923n, 0x5e1f9767cc5866b1n,\n 0x92dd23d6966aced7n, 0xa30d0f4f0a196e5bn, 0x8dc3e5a1977d7755n, 0x2ab8ce915831734bn,\n 0x2ab8ce915831734bn, 0x81d2a0bc5e5fdcabn, 0x9efcac82445da75bn, 0xbc8b95cf58cde171n,\n 0xa0e8444a1f3cecf9n, 0x4191deb683ce3ffdn, 0xddd3878bc84ebfc7n, 0xcb39a64b83ff3751n,\n 0xf8203f7993fc1495n, 0xbd2a2a78b35f4bddn, 0x84757be6b6d13921n, 0x3fbbcfc0b524988bn,\n 0xbd11ed47c8928df9n, 0x3c26b59e41c2f4c5n, 0x677a5137e883fdb3n, 0xff74e943b03b93ddn,\n 0xfe5ebbcb10b2bb97n, 0xb021f1de3235e7e7n, 0x33509eb2e743a58fn, 0x390f9da41279fb7dn,\n 0xe5cb0154f031c559n, 0x93074695ba4ddb6dn, 0x81c471caa636247fn, 0xe1347289b5a1d749n,\n 0x286f21c3f76ce2ffn, 0x00be84a2173e8ac7n, 0x1595065ca215b88bn, 0xf95877595b018809n,\n 0x9c2efe3c5516f887n, 0x373294604679382bn, 0xaf1ff7a888adcd35n, 0x18ddf279a2c5800bn,\n 0x18ddf279a2c5800bn, 0x505a90e2542582cbn, 0x5bacad2cd8d5dc2bn, 0xfe3152bcbff89f41n,\n 0xe1467e88bf829351n, 0xb8001adb9e31b4d5n, 0x2803ac06a0cbb91fn, 0x1904b5d698805799n,\n 0xe12a648b5c831461n, 0x3516abbd6160cfa9n, 0xac46d25f12fe036dn, 0x78bfa1da906b00efn,\n 0xf6390338b7f111bdn, 0x0f25f80f538255d9n, 0x4ec8ca55b8db140fn, 0x4ff670740b9b30a1n,\n 0x8fd032443a07f325n, 0x80dfe7965c83eeb5n, 0xa3dc1714d1213afdn, 0x205b7bbfcdc62007n,\n 0xa78126bbe140a093n, 0x9de1dc61ca7550cfn, 0x84f0046d01b492c5n, 0x2d91810b945de0f3n,\n 0xf5408b7f6008aa71n, 0x43707f4863034149n, 0xdac65fb9679279d5n, 0xc48406e7d1114eb7n,\n 0xa7dc9ed3c88e1271n, 0xfb25b2efdb9cb30dn, 0x1bebda0951c4df63n, 0x5c85e975580ee5bdn,\n 0x1591bc60082cb137n, 0x2c38606318ef25d7n, 0x76ca72f7c5c63e27n, 0xf04a75d17baa0915n,\n 0x77458175139ae30dn, 0x0e6c1330bc1b9421n, 0xdf87d2b5797e8293n, 0xefa5c703e1e68925n,\n 0x2b6b1b3278b4f6e1n, 0xceee27b382394249n, 0xd74e3829f5dab91dn, 0xfdb17989c26b5f1fn,\n 0xc1b7d18781530845n, 0x7b4436b2105a8561n, 0x7ba7c0418372a7d7n, 0x9dbc5c67feb6c639n,\n 0x502686d7f6ff6b8fn, 0x6101855406be7a1fn, 0x9956afb5806930e7n, 0xe1f0ee88af40f7c5n,\n 0x984b057bda5c1151n, 0x9a49819acc13ea05n, 0x8ef0dead0896ef27n, 0x71f7826efe292b21n,\n 0xad80a480e46986efn, 0x01cdc0ebf5e0c6f7n, 0x6e06f839968f68dbn, 0xdd5943ab56e76139n,\n 0xcdcf31bf8604c5e7n, 0x7e2b4a847054a1cbn, 0x0ca75697a4d3d0f5n, 0x4703f53ac514a98bn,\n];\n\nconst inverted_factorial_odd_part = [\n 0x0000000000000001n, 0x0000000000000001n, 0x0000000000000001n, 0xaaaaaaaaaaaaaaabn,\n 0xaaaaaaaaaaaaaaabn, 0xeeeeeeeeeeeeeeefn, 0x4fa4fa4fa4fa4fa5n, 0x2ff2ff2ff2ff2ff3n,\n 0x2ff2ff2ff2ff2ff3n, 0x938cc70553e3771bn, 0xb71c27cddd93e49fn, 0xb38e3229fcdee63dn,\n 0xe684bb63544a4cbfn, 0xc2f684917ca340fbn, 0xf747c9cba417526dn, 0xbb26eb51d7bd49c3n,\n 0xbb26eb51d7bd49c3n, 0xb0a7efb985294093n, 0xbe4b8c69f259eabbn, 0x6854d17ed6dc4fb9n,\n 0xe1aa904c915f4325n, 0x3b8206df131cead1n, 0x79c6009fea76fe13n, 0xd8c5d381633cd365n,\n 0x4841f12b21144677n, 0x4a91ff68200b0d0fn, 0x8f9513a58c4f9e8bn, 0x2b3e690621a42251n,\n 0x4f520f00e03c04e7n, 0x2edf84ee600211d3n, 0xadcaa2764aaacdfdn, 0x161f4f9033f4fe63n,\n 0x161f4f9033f4fe63n, 0xbada2932ea4d3e03n, 0xcec189f3efaa30d3n, 0xf7475bb68330bf91n,\n 0x37eb7bf7d5b01549n, 0x46b35660a4e91555n, 0xa567c12d81f151f7n, 0x4c724007bb2071b1n,\n 0x0f4a0cce58a016bdn, 0xfa21068e66106475n, 0x244ab72b5a318ae1n, 0x366ce67e080d0f23n,\n 0xd666fdae5dd2a449n, 0xd740ddd0acc06a0dn, 0xb050bbbb28e6f97bn, 0x70b003fe890a5c75n,\n 0xd03aabff83037427n, 0x13ec4ca72c783bd7n, 0x90282c06afdbd96fn, 0x4414ddb9db4a95d5n,\n 0xa2c68735ae6832e9n, 0xbf72d71455676665n, 0xa8469fab6b759b7fn, 0xc1e55b56e606caf9n,\n 0x40455630fc4a1cffn, 0x0120a7b0046d16f7n, 0xa7c3553b08faef23n, 0x9f0bfd1b08d48639n,\n 0xa433ffce9a304d37n, 0xa22ad1d53915c683n, 0xcb6cbc723ba5dd1dn, 0x547fb1b8ab9d0ba3n,\n 0x547fb1b8ab9d0ba3n, 0x8f15a826498852e3n, 0x32e1a03f38880283n, 0x3de4cce63283f0c1n,\n 0x5dfe6667e4da95b1n, 0xfda6eeeef479e47dn, 0xf14de991cc7882dfn, 0xe68db79247630ca9n,\n 0xa7d6db8207ee8fa1n, 0x255e1f0fcf034499n, 0xc9a8990e43dd7e65n, 0x3279b6f289702e0fn,\n 0xe7b5905d9b71b195n, 0x03025ba41ff0da69n, 0xb7df3d6d3be55aefn, 0xf89b212ebff2b361n,\n 0xfe856d095996f0adn, 0xd6e533e9fdf20f9dn, 0xf8c0e84a63da3255n, 0xa677876cd91b4db7n,\n 0x07ed4f97780d7d9bn, 0x90a8705f258db62fn, 0xa41bbb2be31b1c0dn, 0x6ec28690b038383bn,\n 0xdb860c3bb2edd691n, 0x0838286838a980f9n, 0x558417a74b36f77dn, 0x71779afc3646ef07n,\n 0x743cda377ccb6e91n, 0x7fdf9f3fe89153c5n, 0xdc97d25df49b9a4bn, 0x76321a778eb37d95n,\n 0x7cbb5e27da3bd487n, 0x9cff4ade1a009de7n, 0x70eb166d05c15197n, 0xdcf0460b71d5fe3dn,\n 0x5ac1ee5260b6a3c5n, 0xc922dedfdd78efe1n, 0xe5d381dc3b8eeb9bn, 0xd57e5347bafc6aadn,\n 0x86939040983acd21n, 0x395b9d69740a4ff9n, 0x1467299c8e43d135n, 0x5fe440fcad975cdfn,\n 0xcaa9a39794a6ca8dn, 0xf61dbd640868dea1n, 0xac09d98d74843be7n, 0x2b103b9e1a6b4809n,\n 0x2ab92d16960f536fn, 0x6653323d5e3681dfn, 0xefd48c1c0624e2d7n, 0xa496fefe04816f0dn,\n 0x1754a7b07bbdd7b1n, 0x23353c829a3852cdn, 0xbf831261abd59097n, 0x57a8e656df0618e1n,\n 0x16e9206c3100680fn, 0xadad4c6ee921dac7n, 0x635f2b3860265353n, 0xdd6d0059f44b3d09n,\n 0xac4dd6b894447dd7n, 0x42ea183eeaa87be3n, 0x15612d1550ee5b5dn, 0x226fa19d656cb623n,\n]\n\nconst factorial_trailing_zeros = [\n 0, 0, 1, 1, 3, 3, 4, 4, 7, 7, 8, 8, 10, 10, 11, 11, // 0-15\n 15, 15, 16, 16, 18, 18, 19, 19, 22, 22, 23, 23, 25, 25, 26, 26, // 16-31\n 31, 31, 32, 32, 34, 34, 35, 35, 38, 38, 39, 39, 41, 41, 42, 42, // 32-47\n 46, 46, 47, 47, 49, 49, 50, 50, 53, 53, 54, 54, 56, 56, 57, 57, // 48-63\n 63, 63, 64, 64, 66, 66, 67, 67, 70, 70, 71, 71, 73, 73, 74, 74, // 64-79\n 78, 78, 79, 79, 81, 81, 82, 82, 85, 85, 86, 86, 88, 88, 89, 89, // 80-95\n 94, 94, 95, 95, 97, 97, 98, 98, 101, 101, 102, 102, 104, 104, 105, 105, // 96-111\n 109, 109, 110, 110, 112, 112, 113, 113, 116, 116, 117, 117, 119, 119, 120, 120, // 112-127\n].map(BigInt)\n\nconst NULL = undefined\n\n/* Calculate C(n, k) for n in the 63-bit range. */\n\nfunction perm_comb_small(n, k, iscomb){\n if(k == 0){\n return 1n\n }\n\n /* For small enough n and k the result fits in the 64-bit range and can\n * be calculated without allocating intermediate PyLong objects. */\n if(iscomb){\n /* Maps k to the maximal n so that 2*k-1 <= n <= 127 and C(n, k)\n * fits into a uint64_t. Exclude k = 1, because the second fast\n * path is faster for this case.*/\n var fast_comb_limits1 = [\n 0, 0, 127, 127, 127, 127, 127, 127, // 0-7\n 127, 127, 127, 127, 127, 127, 127, 127, // 8-15\n 116, 105, 97, 91, 86, 82, 78, 76, // 16-23\n 74, 72, 71, 70, 69, 68, 68, 67, // 24-31\n 67, 67, 67 // 32-34\n ];\n if(k < fast_comb_limits1.length && n <= fast_comb_limits1[k]){\n /*\n comb(n, k) fits into a uint64_t. We compute it as\n comb_odd_part << shift\n where 2**shift is the largest power of two dividing comb(n, k)\n and comb_odd_part is comb(n, k) >> shift. comb_odd_part can be\n calculated efficiently via arithmetic modulo 2**64, using three\n lookups and two uint64_t multiplications.\n */\n var comb_odd_part = reduced_factorial_odd_part[n]\n * inverted_factorial_odd_part[k]\n * inverted_factorial_odd_part[n - k];\n comb_odd_part %= p2_64\n var shift = factorial_trailing_zeros[n]\n - factorial_trailing_zeros[k]\n - factorial_trailing_zeros[n - k];\n return comb_odd_part << shift;\n }\n\n /* Maps k to the maximal n so that 2*k-1 <= n <= 127 and C(n, k)*k\n * fits into a long long (which is at least 64 bit). Only contains\n * items larger than in fast_comb_limits1. */\n var fast_comb_limits2 = [\n 0, ULLONG_MAX, 4294967296, 3329022, 102570, 13467, 3612, 1449, // 0-7\n 746, 453, 308, 227, 178, 147 // 8-13\n ];\n if (k < fast_comb_limits2.length && n <= fast_comb_limits2[k]) {\n /* C(n, k) = C(n, k-1) * (n-k+1) / k */\n var result = n,\n i = 1n;\n while(i < k){\n result *= --n;\n result /= ++i;\n }\n return result;\n }\n }else{\n /* Maps k to the maximal n so that k <= n and P(n, k)\n * fits into a long long (which is at least 64 bit). */\n var fast_perm_limits = [\n 0, ULLONG_MAX, 4294967296, 2642246, 65537, 7133, 1627, 568, // 0-7\n 259, 142, 88, 61, 45, 36, 30, 26, // 8-15\n 24, 22, 21, 20, 20 // 16-20\n ];\n if (k < fast_perm_limits.length && n <= fast_perm_limits[k]) {\n if(n <= 127){\n /* P(n, k) fits into a uint64_t. */\n var perm_odd_part = reduced_factorial_odd_part[n]\n * inverted_factorial_odd_part[n - k];\n perm_odd_part %= p2_64\n var shift = factorial_trailing_zeros[n]\n - factorial_trailing_zeros[n - k];\n var res = perm_odd_part << shift\n\n return res;\n }\n\n /* P(n, k) = P(n, k-1) * (n-k+1) */\n var result = n;\n for (var i = 1; i < k; i++) {\n result *= --n;\n }\n return result\n }\n }\n\n /* For larger n use recursive formulas:\n *\n * P(n, k) = P(n, j) * P(n-j, k-j)\n * C(n, k) = C(n, j) * C(n-j, k-j) // C(k, j)\n */\n var j = k / 2n;\n var a = perm_comb_small(n, j, iscomb);\n var b = perm_comb_small(n - j, k - j, iscomb);\n a = a * b;\n if(iscomb){\n b = perm_comb_small(k, j, 1);\n a = a / b;\n }\n return a;\n}\n\n/* Calculate P(n, k) or C(n, k) using recursive formulas.\n * It is more efficient than sequential multiplication thanks to\n * Karatsuba multiplication.\n */\nfunction perm_comb(n, k, iscomb){\n if(k == 0){\n return 1;\n }\n if(k == 1){\n return n;\n }\n\n /* P(n, k) = P(n, j) * P(n-j, k-j) */\n /* C(n, k) = C(n, j) * C(n-j, k-j) // C(k, j) */\n var j = k / 2n\n var a = perm_comb(n, j, iscomb);\n //var t = j\n //n = n - t;\n var b = perm_comb(n - j, k - j, iscomb);\n a = a * b;\n if(iscomb){\n b = perm_comb_small(k, j, 1);\n a = a / b;\n }\n return a;\n}\n\nfunction comb(n, k){\n var $ = $B.args('comb', 2, {n: null, k: null}, ['n', 'k'],\n arguments, {}, null, null),\n n = $.n,\n k = $.k\n\n var result = NULL,\n temp,\n overflow, cmp;\n\n // accept integers or objects with __index__\n n = $B.PyNumber_Index(n)\n k = $B.PyNumber_Index(k)\n\n n = _b_.int.$to_bigint(n);\n k = _b_.int.$to_bigint(k);\n\n if(n < 0){\n throw _b_.ValueError.$factory(\n \"n must be a non-negative integer\");\n }\n if(k < 0){\n throw _b_.ValueError.$factory(\n \"k must be a non-negative integer\");\n }\n\n overflow = n > LLONG_MAX || n < LLONG_MIN\n if(! overflow){\n overflow = k > LLONG_MAX || k < LLONG_MIN\n if (overflow || k > n) {\n result = 0n;\n }else{\n if(n - k < k){\n k = n - k\n }\n if (k > 1) {\n result = perm_comb_small(n, k, 1);\n }\n }\n /* For k == 1 just return the original n in perm_comb(). */\n }else{\n /* k = min(k, n - k) */\n temp = n - k\n if(temp < 0) {\n result = 0n;\n }\n if (temp < k) {\n k = temp\n }\n\n overflow = k > LLONG_MAX || k < LLONG_MIN\n if (overflow) {\n throw _b_.OverflowError.$factory(\n \"min(n - k, k) must not exceed \" +\n LLONG_MAX);\n }\n }\n if(result === undefined){\n result = perm_comb(n, k, 1);\n }\n\n return _b_.int.$int_or_long(result)\n}\n\n\nfunction copysign(x, y){\n $B.check_nb_args_no_kw('copysign', 2, arguments)\n\n var x1 = Math.abs(float_check(x))\n var y1 = float_check(y)\n var sign = Math.sign(y1)\n sign = (sign == 1 || Object.is(sign, +0)) ? 1 : - 1\n return _b_.float.$factory(x1 * sign)\n}\n\nfunction cos(x){\n $B.check_nb_args('cos ', 1, arguments)\n $B.check_no_kw('cos ', x)\n return _b_.float.$factory(Math.cos(float_check(x)))\n}\n\nfunction cosh(x){\n $B.check_nb_args('cosh', 1, arguments)\n $B.check_no_kw('cosh', x)\n\n if(_b_.float.$funcs.isinf(x)){return INF}\n var y = float_check(x)\n if(Math.cosh !== undefined){return _b_.float.$factory(Math.cosh(y))}\n return _b_.float.$factory((Math.pow(Math.E, y) +\n Math.pow(Math.E, -y)) / 2)\n}\n\nfunction degrees(x){\n $B.check_nb_args('degrees', 1, arguments)\n $B.check_no_kw('degrees', x)\n return _b_.float.$factory(float_check(x) * 180 / Math.PI)\n}\n\nfunction dist(p, q){\n $B.check_nb_args_no_kw('dist', 2, arguments)\n\n function test(x){\n if(typeof x === \"number\"){\n return x\n }else if(x.__class__ === _b_.float){\n return x.value\n }\n var y = $B.$getattr(x, '__float__', null)\n if(y === null){\n throw _b_.TypeError.$factory('not a float')\n }\n return $B.$call(y)().value\n }\n\n // build list of differences (as floats) between coordinates of p and q\n var diffs = [],\n diff\n\n if(Array.isArray(p) && Array.isArray(q)){\n // simple case : p and q are lists of tuples\n if(p.length != q.length){\n throw _b_.ValueError.$factory(\"both points must have \" +\n \"the same number of dimensions\")\n }\n p = p.map(test)\n q = q.map(test)\n for(var i = 0, len = p.length; i < len; i++){\n var next_p = p[i],\n next_q = q[i]\n var diff = Math.abs(next_p - next_q)\n diffs.push(diff)\n }\n }else{\n var itp = _b_.iter(p),\n itq = _b_.iter(q),\n res = 0\n\n while(true){\n try{\n var next_p = _b_.next(itp)\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n // check that the other iterator is also exhausted\n try{\n var next_q = _b_.next(itq)\n throw _b_.ValueError.$factory(\"both points must have \" +\n \"the same number of dimensions\")\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n break\n }\n throw err\n }\n }\n throw err\n }\n next_p = test(next_p)\n try{\n var next_q = _b_.next(itq)\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n throw _b_.ValueError.$factory(\"both points must have \" +\n \"the same number of dimensions\")\n }\n throw err\n }\n next_q = test(next_q)\n diff = Math.abs(next_p - next_q)\n diffs.push(diff)\n }\n }\n for(var diff of diffs){\n if(! isFinite(diff) && ! isNaN(diff)){\n return _mod.inf\n }\n }\n for(var diff of diffs){\n if(isNaN(diff)){\n return _mod.nan\n }\n }\n\n var res = 0,\n scale = 1,\n max_diff = Math.max(...diffs),\n min_diff = Math.min(...diffs)\n max_value = Math.sqrt(Number.MAX_VALUE) / p.length,\n min_value = Math.sqrt(Number.MIN_VALUE) * p.length\n if(max_diff > max_value){\n var nb = 0\n while(max_diff > max_value){\n scale *= 2\n max_diff /= 2\n nb++\n }\n for(var diff of diffs){\n diff = diff / scale\n res += diff * diff\n }\n return $B.fast_float(scale * Math.sqrt(res))\n }else if(min_diff !== 0 && min_diff < min_value){\n while(min_diff < min_value){\n scale *= 2\n min_diff *= 2\n }\n for(var diff of diffs){\n diff = diff * scale\n res += diff * diff\n }\n return $B.fast_float(Math.sqrt(res) / scale)\n }else{\n for(var diff of diffs){\n res += Math.pow(diff, 2)\n }\n return $B.fast_float(Math.sqrt(res))\n }\n}\n\nconst e = _b_.float.$factory(Math.E)\n\nconst ERF_SERIES_CUTOFF = 1.5,\n ERF_SERIES_TERMS = 25,\n ERFC_CONTFRAC_CUTOFF = 30.0,\n ERFC_CONTFRAC_TERMS = 50\n\n/*\n Error function, via power series.\n Given a finite float x, return an approximation to erf(x).\n Converges reasonably fast for small x.\n*/\n\nfunction m_erf_series(x){\n var x2, acc, fk, result\n var i\n\n x2 = x * x\n acc = 0.0\n fk = ERF_SERIES_TERMS + 0.5\n for(i = 0; i < ERF_SERIES_TERMS; i++){\n acc = 2.0 + x2 * acc / fk\n fk -= 1.0\n }\n result = acc * x * exp(-x2).value / sqrtpi\n return result\n}\n\nfunction m_erfc_contfrac(x){\n var x2, a, da, p, p_last, q, q_last, b, result;\n var i\n\n if(x >= ERFC_CONTFRAC_CUTOFF){\n return 0.0\n }\n\n x2 = x * x\n a = 0.0\n da = 0.5\n p = 1.0\n p_last = 0.0\n q = da + x2\n q_last = 1.0\n for(i = 0; i < ERFC_CONTFRAC_TERMS; i++){\n var temp\n a += da\n da += 2.0\n b = da + x2\n temp = p; p = b * p - a * p_last; p_last = temp\n temp = q; q = b * q - a * q_last; q_last = temp\n }\n result = p / q * x * exp(-x2).value / sqrtpi\n return result\n}\n\n\nfunction erf(x){\n var absx,\n cf\n var x1 = float_check(x)\n if(isNaN(x1)){\n return x\n }\n absx = fabs(x)\n if(absx.value < ERF_SERIES_CUTOFF){\n return $B.fast_float(m_erf_series(x1))\n }else{\n cf = m_erfc_contfrac(absx.value)\n return $B.fast_float(x1 > 0.0 ? 1.0 - cf : cf - 1.0)\n }\n}\n\nfunction erfc(x){\n\n // inspired from\n // http://stackoverflow.com/questions/457408/is-there-an-easily-available-implementation-of-erf-for-python\n var y = float_check(x)\n var t = 1.0 / (1.0 + 0.5 * Math.abs(y))\n var ans = 1 - t * Math.exp( -y * y - 1.26551223 +\n t * ( 1.00002368 +\n t * ( 0.37409196 +\n t * ( 0.09678418 +\n t * (-0.18628806 +\n t * ( 0.27886807 +\n t * (-1.13520398 +\n t * ( 1.48851587 +\n t * (-0.82215223 +\n t * 0.17087277)))))))))\n if(y >= 0.0){return 1 - ans}\n return 1 + ans\n}\n\nfunction erfc(x){\n $B.check_nb_args_no_kw('erfc', 1, arguments)\n var absx, cf;\n\n var x1 = float_check(x)\n if(isNaN(x1)){\n return x\n }\n absx = fabs(x);\n if(absx.value < ERF_SERIES_CUTOFF){\n return $B.fast_float(1.0 - m_erf_series(x1))\n }else{\n cf = m_erfc_contfrac(absx.value)\n return $B.fast_float(x1 > 0.0 ? cf : 2.0 - cf)\n }\n}\n\nfunction exp(x){\n $B.check_nb_args('exp', 1, arguments)\n $B.check_no_kw('exp', x)\n\n if(_b_.float.$funcs.isninf(x)){\n return _b_.float.$factory(0)\n }\n if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n var _r = Math.exp(float_check(x))\n if(! isNaN(_r) && ! isFinite(_r)){\n throw _b_.OverflowError.$factory(\"math range error\")\n }\n return _b_.float.$factory(_r)\n}\n\nfunction exp2(x){\n return pow(2, x)\n}\n\nfunction expm1(x){\n $B.check_nb_args('expm1', 1, arguments)\n $B.check_no_kw('expm1', x)\n\n if(_b_.float.$funcs.isninf(x)){\n return $B.fast_float(-1)\n }else if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n var _r = Math.expm1(float_check(x))\n if((! isNaN(_r)) && ! isFinite(_r)){\n overflow()\n }\n return $B.fast_float(_r)\n}\n\nfunction fabs(x){\n $B.check_nb_args_no_kw('fabs', 1, arguments)\n return _b_.float.$funcs.fabs(float_check(x)) // located in py_float.js\n}\n\n// factorial implementation, adapted from CPython's mathmodule.c\n\nconst SmallFactorials = [\n 1n, 1n, 2n, 6n, 24n, 120n, 720n, 5040n, 40320n,\n 362880n, 3628800n, 39916800n, 479001600n,\n 6227020800n, 87178291200n, 1307674368000n,\n 20922789888000n, 355687428096000n, 6402373705728000n,\n 121645100408832000n, 2432902008176640000n\n ]\n\nconst SIZEOF_LONG = 4\n\nfunction _Py_bit_length(x){\n const BIT_LENGTH_TABLE = [\n 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5\n ]\n var msb = 0;\n while(x >= 32n){\n msb += 6;\n x >>= 6n;\n }\n msb += BIT_LENGTH_TABLE[parseInt(x)];\n return msb\n}\nfunction count_set_bits(n){\n var count = 0n;\n while(n != 0){\n ++count;\n n &= n - 1n; /* clear least significant bit */\n }\n return count;\n}\n\nfunction factorial_partial_product(start, stop, max_bits){\n var midpoint,\n num_operands,\n left,\n right,\n result\n\n /* If the return value will fit an unsigned long, then we can\n * multiply in a tight, fast loop where each multiply is O(1).\n * Compute an upper bound on the number of bits required to store\n * the answer.\n *\n * Storing some integer z requires floor(lg(z))+1 bits, which is\n * conveniently the value returned by bit_length(z). The\n * product x*y will require at most\n * bit_length(x) + bit_length(y) bits to store, based\n * on the idea that lg product = lg x + lg y.\n *\n * We know that stop - 2 is the largest number to be multiplied. From\n * there, we have: bit_length(answer) <= num_operands *\n * bit_length(stop - 2)\n */\n\n num_operands = (stop - start) / 2n;\n max_bits = BigInt(max_bits)\n /* The \"num_operands <= 8 * SIZEOF_LONG\" check guards against the\n * unlikely case of an overflow in num_operands * max_bits. */\n if(num_operands <= 8 * SIZEOF_LONG &&\n num_operands * max_bits <= 8 * SIZEOF_LONG) {\n var j,\n total;\n for (total = start, j = start + 2n; j < stop; j += 2n){\n total *= j;\n }\n return total\n }\n\n /* find midpoint of range(start, stop), rounded up to next odd number. */\n midpoint = (start + num_operands) | 1n;\n left = factorial_partial_product(start, midpoint,\n _Py_bit_length(midpoint - 2n));\n right = factorial_partial_product(midpoint, stop, max_bits);\n result = left * right\n return result;\n}\n\n\nfunction factorial_odd_part(n){\n var i,\n v, lower, upper,\n partial, tmp, inner, outer;\n\n inner = 1n\n outer = inner;\n upper = 3n;\n for (i = BigInt(_Py_bit_length(n)) - 2n; i >= 0; i--) {\n v = n >> i;\n if (v <= 2){\n continue\n }\n lower = upper;\n /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */\n upper = (v + 1n) | 1n;\n /* Here inner is the product of all odd integers j in the range (0,\n n/2**(i+1)]. The factorial_partial_product call below gives the\n product of all odd integers j in the range (n/2**(i+1), n/2**i]. */\n partial = factorial_partial_product(lower, upper,\n _Py_bit_length(upper-2n));\n /* inner *= partial */\n tmp = inner * partial\n inner = tmp;\n /* Now inner is the product of all odd integers j in the range (0,\n n/2**i], giving the inner product in the formula above. */\n\n /* outer *= inner; */\n tmp = outer * inner\n outer = tmp;\n }\n return outer;\n}\n\nfunction factorial(arg){\n var x,\n two_valuation,\n overflow,\n result,\n odd_part;\n // Check that arg can be converted to an integer, and transform it to\n // a bigint\n x = _b_.int.$to_bigint($B.PyNumber_Index(arg))\n overflow = x > LONG_MAX || x < LONG_MIN\n if(x > LONG_MAX) {\n throw _b_.OverflowError.$factory(\n \"factorial() argument should not exceed \" +\n LONG_MAX)\n }else if(x < 0) {\n throw _b_.ValueError.$factory(\n \"factorial() not defined for negative values\");\n }\n\n /* use lookup table if x is small */\n if (x < SmallFactorials.length){\n return _b_.int.$int_or_long(SmallFactorials[x]);\n }\n /* else express in the form odd_part * 2**two_valuation, and compute as\n odd_part << two_valuation. */\n odd_part = factorial_odd_part(x);\n two_valuation = x - count_set_bits(x);\n return _b_.int.$int_or_long(odd_part << two_valuation);\n}\n\nfunction floor(x){\n $B.check_nb_args_no_kw('floor', 1, arguments)\n\n if(typeof x == \"number\" || x.__class__ === _b_.float){\n return Math.floor(float_check(x))\n }\n var klass = $B.get_class(x)\n try{\n return $B.$call($B.$getattr(klass, \"__floor__\"))(x)\n }catch(err){\n if($B.is_exc(err, [_b_.AttributeError])){\n try{\n var float = $B.$call($B.$getattr(klass, \"__float__\"))(x)\n return floor(float)\n }catch(err){\n if($B.is_exc(err, [_b_.AttributeError])){\n throw _b_.TypeError.$factory(\"no __float__\")\n }\n throw err\n }\n }\n }\n}\n\nvar _fma = (function () {\n // copied from \n // https://gist.github.com/Yaffle/fb47de4c18b63147699e0b621f1031f7\n\n \n var SPLIT = Math.pow(2, 27) + 1;\n var MIN_VALUE = Math.pow(2, -1022);\n var EPSILON = Math.pow(2, -52);\n // (1022 + 52) / 3 < C <= (1022 - 53 - 53 + 4) / 2 - ?\n var C = 416;\n var A = Math.pow(2, +C);\n var B = Math.pow(2, -C);\n\n var multiply = function (a, b) {\n var at = SPLIT * a;\n var ahi = at - (at - a);\n var alo = a - ahi;\n var bt = SPLIT * b;\n var bhi = bt - (bt - b);\n var blo = b - bhi;\n var p = a * b;\n var e = ((ahi * bhi - p) + ahi * blo + alo * bhi) + alo * blo;\n return {\n p: p,\n e: e\n };\n };\n\n var add = function (a, b) {\n var s = a + b;\n var v = s - a;\n var e = (a - (s - v)) + (b - v);\n return {\n s: s,\n e: e\n };\n };\n\n var adjust = function (x, y) {\n return x !== 0 && y !== 0 && SPLIT * x - (SPLIT * x - x) === x ? x * (1 + (x < 0 ? -1 : +1) * (y < 0 ? -1 : +1) * EPSILON) : x;\n };\n\n var fma = function (x, y, z) {\n x = Number(x);\n y = Number(y);\n z = Number(z);\n\n if (x === 0 || x !== x || x === +1 / 0 || x === -1 / 0 ||\n y === 0 || y !== y || y === +1 / 0 || y === -1 / 0) {\n return x * y + z;\n }\n if (z === 0) {\n return x * y;\n }\n if (z !== z || z === +1 / 0 || z === -1 / 0) {\n return z;\n }\n\n var scale = 1;\n while (Math.abs(x) > A) {\n scale *= A;\n x *= B;\n }\n while (Math.abs(y) > A) {\n scale *= A;\n y *= B;\n }\n if (scale === 1 / 0) {\n return x * y * scale;\n }\n while (Math.abs(x) < B) {\n scale *= B;\n x *= A;\n }\n while (Math.abs(y) < B) {\n scale *= B;\n y *= A;\n }\n if (scale === 0) {\n return z;\n }\n\n var xs = x;\n var ys = y;\n var zs = z / scale;\n\n if (Math.abs(zs) > Math.abs(xs * ys) * 4 / EPSILON) {\n return z;\n }\n if (Math.abs(zs) < Math.abs(xs * ys) * EPSILON / 4 * EPSILON / 4) {\n zs = (z < 0 ? -1 : +1) * MIN_VALUE;\n }\n\n var xy = multiply(xs, ys);\n var s = add(xy.p, zs);\n var u = add(xy.e, s.e);\n var i = add(s.s, u.s);\n\n var f = i.s + adjust(i.e, u.e);\n if (f === 0) {\n return f;\n }\n\n var fs = f * scale;\n if (Math.abs(fs) > MIN_VALUE) {\n return fs;\n }\n\n // It is possible that there was extra rounding for a denormalized value.\n return fs + adjust(f - fs / scale, i.e) * scale;\n };\n\n return fma\n\n}());\n\nfunction fma(x, y, z){\n var $ = $B.args('fma', 3, {x: null, y: null, z: null}, ['x', 'y', 'z'],\n arguments, {}, null, null),\n x = float_check($.x),\n y = float_check($.y),\n z = float_check($.z)\n\n var res =_fma(x, y, z)\n if(isFinite(res)){\n return $B.fast_float(res)\n }\n if(isNaN(res)){\n if (!isNaN(x) && !isNaN(y) && !isNaN(z)) {\n /* NaN result from non-NaN inputs. */\n throw _b_.ValueError.$factory(\"invalid operation in fma\");\n }\n }else if(isFinite(x) && isFinite(y) && isFinite(z)) {\n /* Infinite result from finite inputs. */\n throw _b_.OverflowError.$factory(\"overflow in fma\");\n }\n\n return $B.fast_float(res)\n}\n\nfunction fmod(x, y){\n $B.check_nb_args_no_kw('fmod', 2, arguments)\n if($B.$isinstance(x, _b_.float)){\n if(_b_.float.$funcs.isinf(x)){\n throw _b_.ValueError.$factory('math domain error')\n }\n }\n y = float_check(y)\n if(y == 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n return _b_.float.$factory(float_check(x) % float_check(y))\n}\n\nfunction frexp(x){\n $B.check_nb_args_no_kw('frexp', 1, arguments)\n\n var _l = _b_.float.$funcs.frexp(x)\n return _b_.tuple.$factory([_b_.float.$factory(_l[0]), _l[1]])\n}\n\nfunction fsum(x){\n $B.check_nb_args_no_kw('fsum', 1, arguments)\n\n /* Translation into Javascript of the function msum in an Active\n State Cookbook recipe : https://code.activestate.com/recipes/393090/\n by Raymond Hettinger\n */\n var partials = [],\n res = new Number(),\n _it = _b_.iter(x)\n while(true){\n try{\n var x = _b_.next(_it),\n i = 0\n x = float_check(x)\n for(var j = 0, len = partials.length; j < len; j++){\n var y = float_check(partials[j])\n if(Math.abs(x) < Math.abs(y)){\n var z = x\n x = y\n y = z\n }\n var hi = x + y,\n lo = y - (hi - x)\n if(lo){\n partials[i] = lo\n i++\n }\n x = hi\n }\n partials = partials.slice(0, i).concat([x])\n }catch(err){\n if($B.$isinstance(err, _b_.StopIteration)){break}\n throw err\n }\n }\n var res = 0\n for(var i = 0; i < partials.length; i++){\n res += partials[i]\n }\n return $B.fast_float(res)\n}\n\nfunction gamma(x){\n $B.check_nb_args('gamma', 1, arguments)\n $B.check_no_kw('gamma', x)\n var x_as_number = x,\n r,\n y,\n z,\n sqrtpow\n\n /* special cases */\n if($B.$isinstance(x, _b_.float)){\n x_as_number = x.value\n }else if(! $B.$isinstance(x, _b_.int)){\n throw _b_.TypeError.$factory(\"must be real number, not \" +\n $B.class_name(x))\n }\n if(x_as_number === Number.POSITIVE_INFINITY || isNaN(x_as_number)){\n return x\n }else if(x_as_number === Number.NEGATIVE_INFINITY || x_as_number == 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n\n /* integer arguments */\n if(Number.isInteger(x_as_number)){\n if($B.rich_comp('__lt__', x, 0.0)){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if($B.rich_comp('__le__', x, NGAMMA_INTEGRAL)){\n return $B.fast_float(gamma_integral[x_as_number - 1])\n }\n }\n var absx = fabs(x)\n\n /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */\n if(absx.value < 1e-20){\n r = 1.0 / x_as_number\n if(r === Infinity || r === -Infinity){\n overflow()\n }\n return $B.fast_float(r)\n }\n\n /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for\n x > 200, and underflows to +-0.0 for x < -200, not a negative\n integer. */\n if(absx.value > 200.0){\n if(x_as_number < 0.0){\n return $B.fast_float(0.0 / m_sinpi(x).value);\n }else{\n overflow()\n }\n }\n\n y = absx.value + lanczos_g_minus_half;\n /* compute error in sum */\n if (absx.value > lanczos_g_minus_half) {\n /* note: the correction can be foiled by an optimizing\n compiler that (incorrectly) thinks that an expression like\n a + b - a - b can be optimized to 0.0. This shouldn't\n happen in a standards-conforming compiler. */\n var q = y - absx.value;\n z = q - lanczos_g_minus_half;\n }else{\n var q = y - lanczos_g_minus_half;\n z = q - absx.value;\n }\n z = z * lanczos_g / y;\n if (x_as_number < 0.0) {\n r = -pi.value / m_sinpi(absx).value /\n absx.value * _mod.exp(y).value /\n lanczos_sum(absx.value);\n r -= z * r;\n if(absx.value < 140.0){\n r /= pow(y, absx.value - 0.5).value;\n }else{\n sqrtpow = pow(y, absx.value / 2.0 - 0.25);\n r /= sqrtpow.value;\n r /= sqrtpow.value;\n }\n }else{\n r = lanczos_sum(absx.value) / exp(y).value;\n r += z * r;\n if(absx.value < 140.0){\n r *= pow(y, absx.value - 0.5).value;\n }else{\n sqrtpow = pow(y, absx.value / 2.0 - 0.25);\n r *= sqrtpow.value;\n r *= sqrtpow.value;\n }\n }\n if(r === Number.POSITIVE_INFINITY){\n overflow()\n }\n return $B.fast_float(r);\n}\n\n\n// GCD algorithm. Javascript adaptation of Python script at\n// https://gist.github.com/cmpute/baa545f0c2b6be8b628e9ded3c19f6c1\n// by Jacob Zhong\nfunction bit_length(x){\n return x.toString(2).length\n}\n\n$B.nb_simple_gcd = 0\n\nfunction simple_gcd(a, b){\n /* a fits into a long, so b must too */\n $B.nb_simple_gcd++\n var x = a >= 0 ? a : -a,\n y = b >= 0 ? b : -b\n\n /* usual Euclidean algorithm for longs */\n while (y != 0) {\n t = y;\n y = x % y;\n x = t;\n }\n return x\n}\n\nfunction lgcd(x, y){\n var a, b, c, d\n if(x < y){\n return lgcd(y, x)\n }\n var shift = BigInt(Math.max(Math.floor(bit_length(x) / 64),\n Math.floor(bit_length(y) / 64))),\n xbar = x >> (shift * 64n),\n ybar = y >> (shift * 64n)\n while(y > p2_64){\n [a, b, c, d] = [1n, 0n, 0n, 1n]\n while(ybar + c != 0 && ybar + d != 0){\n q = (xbar + a) / (ybar + c)\n p = (xbar + b) / (ybar + d)\n if(q != p){\n break\n }\n [a, c] = [c, a - q * c]\n [b, d] = [d, b - q * d]\n [xbar, ybar] = [ybar, xbar - q * ybar]\n }\n if(b == 0){\n [x, y] = [y, x % y]\n }else{\n [x, y] = [a * x + b * y, c * x + d * y]\n }\n }\n return simple_gcd(x, y)\n}\n\nfunction xgcd(x, y){\n var xneg = x < 0 ? -1n : 1n,\n yneg = y < 0 ? -1n : 1n,\n last_r,\n last_s,\n last_t,\n q, r, s, t;\n\n [x, y] = [x >= 0 ? x : -x, y >= 0 ? y : -y];\n\n // it's maintained that r = s * x + t * y, last_r = last_s * x + last_t * y\n [last_r, r] = [x, y];\n [last_s, s] = [1n, 0n];\n [last_t, t] = [0n, 1n];\n\n while(r > 0){\n q = last_r / r;\n [last_r, r] = [r, last_r - q * r];\n [last_s, s] = [s, last_s - q * s];\n [last_t, t] = [t, last_t - q * t];\n }\n return [last_r, last_s * xneg, last_t * yneg]\n}\n\nfunction lxgcd(x, y){\n var g, cy, cx,\n s, last_s,\n t, last_t,\n a, b, c, d\n x = x >= 0 ? x : -x\n y = y >= 0 ? y : -y\n\n if(x < y){\n [g, cy, cx] = xgcd(y, x)\n return [g, cx, cy]\n }\n\n var shift = BigInt(Math.max(Math.floor(bit_length(x) / 64),\n Math.floor(bit_length(y) / 64))),\n xbar = x >> (shift * 64n),\n ybar = y >> (shift * 64n);\n\n [last_s, s] = [1n, 0n];\n [last_t, t] = [0n, 1n];\n\n while(y > p2_64){\n [a, b, c, d] = [1n, 0n, 0n, 1n]\n while(ybar + c != 0 && ybar + d != 0){\n q = (xbar + a) / (ybar + c)\n p = (xbar + b) / (ybar + d)\n if(q != p){\n break\n };\n [a, c = c], [a - q * c];\n [b, d = d], [b - q * d];\n [xbar, ybar] = [ybar, xbar - q * ybar];\n }\n if(b == 0){\n q = x / y;\n [x, y] = [y, x % y];\n [last_s, s] = [s, last_s - q * s];\n [last_t, t] = [t, last_t - q * t];\n }else{\n [x, y] = [a * x + b * y, c * x + d * y];\n [last_s, s] = [a * last_s + b * s, c * last_s + d * s];\n [last_t, t] = [a * last_t + b * t, c * last_t + d * t];\n }\n }\n // notice that here x, y could be negative\n [g, cx, cy] = xgcd(x, y)\n\n return [g, cx * last_s + cy * s, cx * last_t + cy * t]\n}\n\nfunction gcd(x, y){\n var $ = $B.args(\"gcd\", 0, {}, [], arguments, {}, 'args', null)\n var args = $.args.map($B.PyNumber_Index)\n if(args.length == 0){\n return 0\n }else if(args.length == 1){\n return _b_.abs(args[0])\n }\n x = _b_.int.$to_bigint(args[0])\n y = _b_.int.$to_bigint(args[1])\n var res = lxgcd(x, y)[0],\n i = 2\n while(i < args.length){\n res = lxgcd(res, _b_.int.$to_bigint(args[i]))[0]\n i++\n }\n return _b_.int.$int_or_long(res)\n}\n\n\nfunction hypot(x, y){\n var $ = $B.args(\"hypot\", 0, {}, [],\n arguments, {}, \"args\", null)\n var args = []\n for(var arg of $.args){\n try{\n args.push(float_check(arg))\n }catch(err){\n if($B.is_exc(err, [_b_.ValueError])){\n throw _b_.TypeError.$factory('must be real number, not ' +\n $B.class_name(arg))\n }\n throw err\n }\n }\n return $B.fast_float(Math.hypot(...args))\n}\n\nvar inf = INF\n\nfunction isclose(){\n var $ = $B.args(\"isclose\",\n 4,\n {a: null, b: null, rel_tol: null, abs_tol: null},\n ['a', 'b', 'rel_tol', 'abs_tol'],\n arguments,\n {rel_tol: $B.fast_float(1e-09),\n abs_tol: $B.fast_float(0.0)},\n '*',\n null)\n var a = float_check($.a),\n b = float_check($.b),\n rel_tol = float_check($.rel_tol),\n abs_tol = float_check($.abs_tol)\n\n if(rel_tol < 0.0 || abs_tol < 0.0){\n throw _b_.ValueError.$factory('tolerances must be non-negative')\n }\n\n if(a == b){\n return _b_.True\n }\n if(_b_.float.$funcs.isinf(a) || _b_.float.$funcs.isinf(b)){\n return a === b\n }\n // isclose(a, b, rel_tol, abs_tol) is the same as\n // abs_diff = abs(a - b)\n // max_ab = max(abs(a), abs(b))\n // abs_diff <= abs_tol or abs_diff / max_ab <= rel_tol\n // This is more correct than in Python docs:\n // \"abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)\"\n // because this fails for Decimal instances, which do not support\n // multiplication by floats\n\n var diff = b - a,\n abs_diff = Math.abs(diff)\n if(abs_diff <= abs_tol){\n return true\n }\n var abs_a = Math.abs(a),\n abs_b = Math.abs(b),\n max_ab = Math.max(abs_a, abs_b)\n return abs_diff / max_ab <= rel_tol\n}\n\nfunction isfinite(x){\n $B.check_nb_args('isfinite', 1, arguments)\n $B.check_no_kw('isfinite', x)\n return isFinite(float_check(x))\n}\n\nfunction isinf(x){\n $B.check_nb_args('isinf', 1, arguments)\n $B.check_no_kw('isinf', x)\n return _b_.float.$funcs.isinf(x)\n}\n\nfunction isnan(x){\n $B.check_nb_args('isnan', 1, arguments)\n $B.check_no_kw('isnan', x)\n return isNaN(float_check(x))\n}\n\nfunction isqrt(x){\n $B.check_nb_args_no_kw('isqrt', 1, arguments)\n\n x = $B.PyNumber_Index(x)\n if($B.rich_comp(\"__lt__\", x, 0)){\n throw _b_.ValueError.$factory(\n \"isqrt() argument must be nonnegative\")\n }\n if(typeof x == \"number\"){\n return Math.floor(Math.sqrt(x))\n }else{ // big integer\n // adapted from code in mathmodule.c\n var n = x.value,\n bit_length = n.toString(2).length,\n c = BigInt(Math.floor((bit_length - 1) / 2)),\n c_bit_length = c.toString(2).length,\n a = 1n,\n d = 0n,\n e\n\n for(var s = BigInt(c_bit_length - 1); s >= 0; s--){\n // Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2\n e = d\n d = c >> s\n a = (a << d - e - 1n) + (n >> 2n*c - e - d + 1n) / a\n }\n return _b_.int.$int_or_long(a - (a * a > n ? 1n : 0n))\n }\n}\n\nfunction lcm(){\n var $ = $B.args(\"lcm\", 0, {}, [], arguments, {}, 'args', null),\n product = 1\n\n var args = $.args.map($B.PyNumber_Index)\n if(args.length == 0){\n return 1\n }else if(args.length == 1){\n return _b_.abs(args[0])\n }\n var a = _b_.abs(args[0]),\n b,\n product, gcd\n for(var i = 0, len = args.length; i < len; i++){\n b = _b_.abs(args[i])\n if(b == 0){\n return 0\n }\n gcd = gcd2(a, b)\n product = $B.rich_op('__mul__', a, b)\n a = $B.$getattr(product, \"__floordiv__\")(gcd)\n }\n return a\n}\n\nfunction ldexp(x, i){\n $B.check_nb_args('ldexp', 2, arguments)\n $B.check_no_kw('ldexp', x, i)\n return _b_.float.$funcs.ldexp(x, i) // in py_float.js\n}\n\nfunction lgamma(x){\n $B.check_nb_args('lgamma', 1, arguments)\n $B.check_no_kw('lgamma', x)\n\n return m_lgamma(x)\n}\n\nfunction longint_mant_exp(long_int){\n // Returns mantissa and exponent of a long integer\n var value = long_int.value,\n exp = value.toString(2).length,\n exp1 = exp,\n nb = 0n\n // 2 ** exp is infinite if n > 1023\n var nb = Math.floor(exp / 1023),\n exp1 = BigInt(exp - 1023 * nb)\n nb = BigInt(nb)\n var reduced_value = long_int.value / 2n ** (nb * 1023n)\n var mant = Number(reduced_value) / Number(2n ** exp1)\n return [mant, exp]\n}\n\nvar log10_func = Math.log10 || (x => Math.log(x) / Math.log(10)),\n log2_func = Math.log2 || (x => Math.log(x) / Math.log(2))\n\nfunction log(x, base){\n var $ = $B.args(\"log\", 2, {x: null, base: null}, ['x', 'base'],\n arguments, {base: _b_.None}, null, null),\n x = $.x,\n base = $.base\n if(base == 10){\n return log10(x)\n }else if(base == 2){\n return log2(x)\n }\n var log\n if($B.$isinstance(x, $B.long_int)){\n if(x.value <= 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n var mant_exp = longint_mant_exp(x)\n log = Math.log(mant_exp[0]) + Math.log(2) * mant_exp[1]\n }else if($B.$isinstance(x, _b_.int)){\n x = _b_.int.$int_value(x)\n if(x <= 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n log = Math.log(x)\n }else{\n var x1 = float_check(x)\n if(x1 <= 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n log = Math.log(x1)\n }\n if(x1 <= 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if(base === _b_.None){\n return $B.fast_float(log)\n }\n var denom = _mod.log(base).value\n if(denom == 0){\n throw _b_.ZeroDivisionError.$factory('float division by zero')\n }\n return $B.fast_float(log / denom)\n}\n\nfunction log1p(x){\n $B.check_nb_args('log1p', 1, arguments)\n $B.check_no_kw('log1p', x)\n if($B.$isinstance(x, $B.long_int)){\n if($B.long_int.bit_length(x) > 1024){\n throw _b_.OverflowError.$factory(\n \"int too large to convert to float\")\n }\n x = $B.long_int.$log2($B.fast_long_int(x.value + 1n))\n return $B.fast_float(Number(x.value) * Math.LN2)\n }\n x = float_check(x)\n if(x + 1 <= 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return $B.fast_float(Math.log1p(x))\n}\n\nfunction log2(x){\n $B.check_nb_args('log2', 1, arguments)\n $B.check_no_kw('log2', x)\n var log2_func = Math.log2 || (x => Math.log(x) / Math.LN2)\n if($B.$isinstance(x, $B.long_int)){\n if(x.value <= 0){\n throw _b_.ValueError.$factory('math domain error')\n }\n var mant_exp = longint_mant_exp(x)\n return $B.fast_float(log2_func(mant_exp[0]) + mant_exp[1])\n }\n if(_b_.float.$funcs.isninf(x)){\n throw _b_.ValueError.$factory('')\n }\n x = float_check(x)\n if(x == 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if(isNaN(x)){\n return _b_.float.$factory('nan')\n }\n if(x < 0.0){\n throw _b_.ValueError.$factory('math domain error')\n }\n return $B.fast_float(log2_func(x))\n}\n\nfunction log10(x){\n $B.check_nb_args('log10', 1, arguments)\n $B.check_no_kw('log10', x)\n if($B.$isinstance(x, $B.long_int)){\n return $B.fast_float($B.long_int.$log10(x).value)\n }\n x = float_check(x)\n if(x <= 0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n return $B.fast_float(Math.log10(x))\n}\n\nfunction modf(x){\n $B.check_nb_args('modf', 1, arguments)\n $B.check_no_kw('modf', x)\n\n if(_b_.float.$funcs.isninf(x)){\n return _b_.tuple.$factory([0.0, NINF])\n }\n if(_b_.float.$funcs.isinf(x)){\n return _b_.tuple.$factory([0.0, INF])\n }\n var x1 = float_check(x)\n\n if(isNaN(x1)){\n return _b_.tuple.$factory([_b_.float.$factory('nan'),\n _b_.float.$factory('nan')])\n }\n\n if(x1 > 0){\n var i = _b_.float.$factory(x1 - Math.floor(x1))\n return _b_.tuple.$factory([i, _b_.float.$factory(x1 - i.value)])\n }\n\n var x2 = Math.ceil(x1)\n var i = _b_.float.$factory(x1 - x2)\n return _b_.tuple.$factory([i, _b_.float.$factory(x2)])\n}\n\nvar nan = _b_.float.$factory('nan')\n\nfunction _nextafter(x, y){\n // always returns a Javascript number\n if($B.rich_comp('__lt__', y, x)){\n var nu = nextUp($B.rich_op('__mul__', -1, x))\n return -nu\n }else if($B.rich_comp('__gt__', y, x)){\n return nextUp(x)\n }else{\n var res = x !== x ? x : y\n res = typeof res == 'number' ? res : res.value\n return res\n }\n}\n\nfunction make_float(x){\n return typeof x == 'number' ? $B.fast_float(x) : x\n}\n\nfunction make_number(x){\n return typeof x == 'number' ? x : x.value\n}\n\nfunction doubleToByteArray(number) {\n // adapted from https://stackoverflow.com/questions/\n // 25942516/double-to-byte-array-conversion-in-javascript\n var buffer = new ArrayBuffer(8); // JS numbers are 8 bytes long, or 64 bits\n var longNum = new Float64Array(buffer); // so equivalent to Float64\n\n longNum[0] = number;\n\n return Array.from(new Uint8Array(buffer)).reverse(); // reverse to get little endian\n}\n\nfunction byteArrayToDouble(bytearray) {\n // adapted from https://stackoverflow.com/questions/\n // 42699162/javascript-convert-array-of-4-bytes-into-a-float-value-from-modbustcp-read\n // Create a buffer\n var buf = new ArrayBuffer(8);\n // Create a data view of it\n var view = new DataView(buf);\n\n // set bytes\n bytearray.forEach(function (b, i) {\n view.setUint8(i, b);\n });\n\n // Read the bits as a float\n var num = view.getFloat64(0);\n // Done\n return num\n}\n\nfunction addSteps(array, steps){\n // convert to BigInt, avoids issue when steps >= 2 ** 32\n if(steps.__class__ == $B.long_int){\n steps = steps.value\n }else{\n steps = BigInt(steps)\n }\n var positive = steps > 0n\n if(steps < 0n){\n steps = -steps\n }\n var x1 = steps >> 32n,\n x2 = steps - x1 * 2n ** 32n\n var buffer = new ArrayBuffer(8)\n var longStep = new BigInt64Array(buffer)\n longStep[0] = steps\n var stepArray = Array.from(new Uint8Array(buffer)).reverse()\n if(positive){\n var carry = 0\n for(var i = 7; i >= 0; i--){\n array[i] += stepArray[i] + carry\n if(array[i] > 255){\n carry = 1\n array[i] -= 256\n }else{\n carry = 0\n }\n }\n }else{\n var carry = 0\n for(var i = 7; i >= 0; i--){\n array[i] -= stepArray[i] - carry\n if(array[i] < 0){\n carry = -1\n array[i] += 256\n }else{\n carry = 0\n }\n }\n }\n}\n\nfunction nextafter(){\n var $ = $B.args(\"nextafter\", 3, {x: null, y: null, steps: null},\n ['x', 'y', 'steps'], arguments, {steps: _b_.None}, null, null),\n x = $.x,\n y = $.y,\n steps = $.steps\n if(! $B.$isinstance(x, [_b_.int, _b_.float])){\n throw _b_.TypeError.$factory('must be a real number, not ' +\n $B.class_name(x))\n }\n if(! $B.$isinstance(y, [_b_.int, _b_.float])){\n throw _b_.TypeError.$factory('must be a real number, not ' +\n $B.class_name(y))\n }\n if(isnan(x)){\n return make_float(x)\n }\n if(isnan(y)){\n return make_float(y)\n }\n if(steps === _b_.None){\n return $B.fast_float(_nextafter(x, y))\n }\n steps = $B.PyNumber_Index(steps);\n if(steps < 0) {\n throw _b_.ValueError.$factory(\n \"steps must be a non-negative integer\");\n }\n if(steps == 0){\n return make_float(x)\n }\n if(isnan(x)){\n return make_float(x)\n }\n if(isnan(y)){\n return make_float(y)\n }\n var x1 = make_number(x),\n y1 = make_number(y)\n\n if(y1 == x1){\n return make_float(y)\n }else if(y1 > x1){\n var x_uint64 = doubleToByteArray(x1)\n addSteps(x_uint64, steps)\n var res = byteArrayToDouble(x_uint64)\n return res >= y1 ? y : make_float(res)\n }else{\n var x_uint64 = doubleToByteArray(x1)\n addSteps(x_uint64, -steps)\n var res = byteArrayToDouble(x_uint64)\n return res <= y1 ? y : make_float(res)\n }\n}\n\nfunction perm(n, k){\n var $ = $B.args(\"perm\", 2, {n: null, k: null}, ['n', 'k'],\n arguments, {k: _b_.None}, null, null),\n n = $.n,\n k = $.k\n\n if(k === _b_.None){\n check_int(n)\n return _mod.factorial(n)\n }\n // raise TypeError if n or k is not an integer\n n = $B.PyNumber_Index(n)\n k = $B.PyNumber_Index(k)\n\n // transform to Javascript BigInt\n var n1 = _b_.int.$to_bigint(n),\n k1 = _b_.int.$to_bigint(k);\n\n if(k1 < 0){\n throw _b_.ValueError.$factory(\"k must be a non-negative integer\")\n }\n if(n1 < 0){\n throw _b_.ValueError.$factory(\"n must be a non-negative integer\")\n }\n if(k1 == 0){\n return 1\n }\n if(k1 == 1){\n return n\n }\n if(k1 == 2){\n return _b_.int.$int_or_long(n1 * (n1 - 1n))\n }\n if(k1 > n1){\n return 0\n }\n // Evaluates to n! / (n - k)!\n var fn = _mod.factorial(n),\n fn_k = _mod.factorial(n - k)\n return $B.rich_op('__floordiv__', fn, fn_k)\n}\n\nconst pi = $B.fast_float(Math.PI)\n\nfunction pow(){\n var $ = $B.args(\"pow\", 2, {base: null, exp: null}, ['base', 'exp'],\n arguments, {}, null, null),\n x = $.base,\n y = $.exp\n\n var x1 = float_check(x)\n var y1 = float_check(y)\n\n if(y1 == 0){\n return _b_.float.$factory(1)\n }\n if(x1 == 0 && y1 < 0){\n if(y1 === -Infinity){\n return INF\n }\n throw _b_.ValueError.$factory('math domain error')\n }\n if(isFinite(x1) && x1 < 0 && isFinite(y1) && ! Number.isInteger(y1)){\n throw _b_.ValueError.$factory('math domain error')\n }\n\n if(isNaN(y1)){\n if(x1 == 1){return _b_.float.$factory(1)}\n return NAN\n }\n if(x1 == 0){\n return ZERO\n }\n\n if(_b_.float.$funcs.isninf(y)){\n if(_b_.float.$funcs.isinf(x)){ // pow(INF, NINF) = 0.0\n return ZERO\n }else if(_b_.float.$funcs.isninf(x)){ // pow(NINF, NINF) = 0.0\n return ZERO\n }\n if(x1 == 1 || x1 == -1){return _b_.float.$factory(1)}\n if(x1 < 1 && x1 > -1){return INF}\n return ZERO\n }\n if(_b_.float.$funcs.isinf(y)){\n if(_b_.float.$funcs.isinf(x)){ // pow(INF, INF)\n return INF\n }\n if(_b_.float.$funcs.isninf(x)){\n return INF\n }\n if(x1 == 1 || x1 == -1){return _b_.float.$factory(1)}\n if(x1 < 1 && x1 > -1){return ZERO}\n return INF\n }\n\n if(isNaN(x1)){return _b_.float.$factory('nan')}\n if(_b_.float.$funcs.isninf(x)){\n if(y1 > 0 && isOdd(y1)){return NINF}\n if(y1 > 0){return INF} // this is even or a float\n if(y1 < 0){return ZERO}\n if(_b_.float.$float.isinf(y)){return INF}\n return _b_.float.$factory(1)\n }\n\n if(_b_.float.$funcs.isinf(x)){\n if(y1 > 0){return INF}\n if(y1 < 0){return ZERO}\n return _b_.float.$factory(1)\n }\n\n var r = Math.pow(x1, y1)\n if(isNaN(r)){\n return NAN\n }\n if(! isFinite(r)){\n overflow()\n }\n return _b_.float.$factory(r)\n}\n\nfunction prod(){\n var $ = $B.args(\"prod\", 1, {iterable:null, start:null},\n [\"iterable\", \"start\"], arguments, {start: 1}, \"*\",\n null),\n iterable = $.iterable,\n start = $.start\n var res = start,\n it = _b_.iter(iterable),\n x\n while(true){\n try{\n x = _b_.next(it)\n if(x == 0){\n return 0\n }\n res = $B.rich_op('__mul__', res, x)\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n return res\n }\n throw err\n }\n }\n}\n\nfunction radians(x){\n $B.check_nb_args('radians', 1, arguments)\n $B.check_no_kw('radians', x)\n\n return _b_.float.$factory(float_check(x) * Math.PI / 180)\n}\n\nfunction is_finite(x){\n return typeof x == \"number\" ||\n (x.__class__ === _b_.floar && isFinite(x.value)) ||\n $B.$isinstance(x, _b_.int) ||\n ($B.$isinstance(x, _b_.float) && isFinite(x.value))\n}\n\nfunction remainder(x, y){\n $B.check_nb_args_no_kw('remainder', 2, arguments)\n float_check(x) // might raise TypeError\n /* Deal with most common case first. */\n if(is_finite(x) && is_finite(y)){\n var absx,\n absy,\n c,\n m,\n r;\n\n if(float_check(y) == 0.0){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n\n absx = fabs(x);\n absy = fabs(y);\n m = fmod(absx, absy);\n\n c = absy.value - m.value\n if(m.value < c){\n r = m.value\n }else if(m.value > c){\n r = -c\n }else{\n r = m.value -\n 2.0 * fmod($B.fast_float(0.5 * (absx.value - m.value)), absy).value;\n }\n return $B.fast_float(copysign(1.0, x).value * r);\n }\n\n /* Special values. */\n if(float_check(y) == 0){\n if(isnan(x)){\n return x\n }\n }\n if(isinf(x)){\n if(isnan(y)){\n return y\n }\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n if(isnan(y)){\n return y;\n }\n return x;\n}\n\nfunction sin(x){\n $B.check_nb_args('sin ', 1, arguments)\n $B.check_no_kw('sin ', x)\n return _b_.float.$factory(Math.sin(float_check(x)))\n}\n\nfunction sinh(x) {\n $B.check_nb_args('sinh', 1, arguments)\n $B.check_no_kw('sinh', x)\n\n var y = float_check(x)\n if(Math.sinh !== undefined){\n return _b_.float.$factory(Math.sinh(y))\n }\n return _b_.float.$factory(\n (Math.pow(Math.E, y) - Math.pow(Math.E, -y)) / 2)\n}\n\nfunction sqrt(x){\n $B.check_nb_args('sqrt ', 1, arguments)\n $B.check_no_kw('sqrt ', x)\n\n if(_b_.float.$funcs.isninf(x)){\n value_error()\n }else if(_b_.float.$funcs.isinf(x)){\n return INF\n }\n var y = float_check(x)\n if(y < 0){\n value_error()\n }\n var _r = $B.fast_float(Math.sqrt(y))\n if(_b_.float.$funcs.isinf(_r)){\n overflow()\n }\n return _r\n}\n\n/*[clinic input]\nmath.sumprod\n\n p: object\n q: object\n /\n\nReturn the sum of products of values from two iterables p and q.\n\nRoughly equivalent to:\n\n sum(itertools.starmap(operator.mul, zip(p, q, strict=True)))\n\nFor float and mixed int/float inputs, the intermediate products\nand sums are computed with extended precision.\n[clinic start generated code]*/\n\nconst tl_zero = {hi: 0, lo: 0, tiny: 0}\n\nfunction _check_long_mult_overflow(a, b) {\n\n /* From Python2's int_mul code:\n\n Integer overflow checking for * is painful: Python tried a couple ways, but\n they didn't work on all platforms, or failed in endcases (a product of\n -sys.maxint-1 has been a particular pain).\n\n Here's another way:\n\n The native long product x*y is either exactly right or *way* off, being\n just the last n bits of the true product, where n is the number of bits\n in a long (the delivered product is the true product plus i*2**n for\n some integer i).\n\n The native double product (double)x * (double)y is subject to three\n rounding errors: on a sizeof(long)==8 box, each cast to double can lose\n info, and even on a sizeof(long)==4 box, the multiplication can lose info.\n But, unlike the native long product, it's not in *range* trouble: even\n if sizeof(long)==32 (256-bit longs), the product easily fits in the\n dynamic range of a double. So the leading 50 (or so) bits of the double\n product are correct.\n\n We check these two ways against each other, and declare victory if they're\n approximately the same. Else, because the native long product is the only\n one that can lose catastrophic amounts of information, it's the native long\n product that must have overflowed.\n\n */\n\n /*\n\n var longprod = (long)((unsigned long)a * b);\n double doubleprod = (double)a * (double)b;\n double doubled_longprod = (double)longprod;\n\n if (doubled_longprod == doubleprod) {\n return 0;\n }\n\n const double diff = doubled_longprod - doubleprod;\n const double absdiff = diff >= 0.0 ? diff : -diff;\n const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;\n\n if (32.0 * absdiff <= absprod) {\n return 0;\n }\n\n return 1;\n */\n return 0\n}\n\nfunction long_add_would_overflow(a, b){\n return (a > 0n) ? (b > BigInt(LONG_MAX) - a) : (b < BigInt(LONG_MIN) - a);\n}\n\nfunction PyLong_CheckExact(n){\n return typeof n == 'number' || n.__class__ === $B.long_int\n}\n\n/*\n The default implementation of dl_mul() depends on the C math library\n having an accurate fma() function as required by \u00a7 7.12.13.1 of the\n C99 standard.\n\n The UNRELIABLE_FMA option is provided as a slower but accurate\n alternative for builds where the fma() function is found wanting.\n The speed penalty may be modest (17% slower on an Apple M1 Max),\n so don't hesitate to enable this build option.\n\n The algorithms are from the T. J. Dekker paper:\n A Floating-Point Technique for Extending the Available Precision\n https://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf\n*/\n\nfunction dl_split(x) {\n // Dekker (5.5) and (5.6).\n var t = x * 134217729.0; // Veltkamp constant = 2.0 ** 27 + 1\n var hi = t - (t - x);\n var lo = x - hi;\n return {hi, lo};\n}\n\nfunction dl_mul(x, y){\n // Dekker (5.12) and mul12()\n var xx = dl_split(x);\n var yy = dl_split(y);\n var p = xx.hi * yy.hi;\n var q = xx.hi * yy.lo + xx.lo * yy.hi;\n var z = p + q;\n var zz = p - z + q + xx.lo * yy.lo;\n return {hi: z, lo: zz};\n}\n\nfunction dl_sum(a, b){\n /* Algorithm 3.1 Error-free transformation of the sum */\n var x = a + b;\n var z = x - a;\n var y = (a - (x - z)) + (b - z);\n return {hi: x, lo: y};\n}\n\nfunction tl_fma(x, y, total){\n /* Algorithm 5.10 with SumKVert for K=3 */\n var pr = dl_mul(x, y);\n var sm = dl_sum(total.hi, pr.hi);\n var r1 = dl_sum(total.lo, pr.lo);\n var r2 = dl_sum(r1.hi, sm.lo);\n return {hi: sm.hi, lo: r2.hi, tiny: total.tiny + r1.lo + r2.lo}\n}\n\nfunction tl_to_d(total){\n var last = dl_sum(total.lo, total.hi);\n return total.tiny + last.lo + last.hi;\n}\n\nfunction sumprod(p, q){\n var $ = $B.args('sumprod', 2, {p: null, q: null}, ['p', 'q'],\n arguments, {}, null, null)\n var p_i = NULL,\n q_i = NULL,\n term_i = NULL,\n new_total = NULL;\n var p_it, q_it, total;\n var p_next, q_next;\n var p_stopped = false, q_stopped = false;\n var int_path_enabled = true,\n int_total_in_use = false;\n var flt_path_enabled = true,\n flt_total_in_use = false;\n var int_total = 0n;\n var flt_total = tl_zero;\n\n p_it = $B.make_js_iterator(p);\n q_it = $B.make_js_iterator(q);\n total = 0\n p_next = p_it.next\n q_next = q_it.next\n while (1) {\n var finished;\n p_i = p_it.next()\n if (p_i.done) {\n p_stopped = true;\n }else{\n p_i = p_i.value\n }\n q_i = q_it.next()\n if (q_i.done) {\n q_stopped = true;\n }else{\n q_i = q_i.value\n }\n if (p_stopped != q_stopped) {\n throw _b_.ValueError.$factory(\"Inputs are not the same length\");\n }\n\n finished = p_stopped & q_stopped;\n\n if (int_path_enabled) {\n\n if (! finished && PyLong_CheckExact(p_i) & PyLong_CheckExact(q_i)) {\n var overflow;\n var int_p, int_q, int_prod;\n\n int_p = _b_.int.$to_bigint($B.PyNumber_Index(p_i))\n overflow = int_p > LONG_MAX || int_p < LONG_MIN\n\n if (overflow) {\n finalize_int_path()\n }\n int_q = _b_.int.$to_bigint($B.PyNumber_Index(q_i));\n overflow = int_q > LONG_MAX || int_q < LONG_MIN\n if (overflow) {\n finalize_int_path()\n }\n if (_check_long_mult_overflow(int_p, int_q)) {\n finalize_int_path()\n }\n int_prod = int_p * int_q;\n if (long_add_would_overflow(int_total, int_prod)) {\n finalize_int_path()\n }\n if(int_path_enabled){\n int_total = int_total + int_prod;\n int_total_in_use = true;\n continue;\n }\n }\n\n if(finished){\n finalize_int_path()\n }\n\n function finalize_int_path(){\n // We're finished, overflowed, or have a non-int\n int_path_enabled = false;\n if (int_total_in_use) {\n term_i = _b_.int.$int_or_long(int_total);\n new_total = $B.rich_op('__add__', total, term_i);\n total = new_total\n new_total = NULL;\n int_total = 0; // An ounce of prevention, ...\n int_total_in_use = false;\n }\n }\n }\n\n if (flt_path_enabled) {\n\n if (!finished) {\n var flt_p, flt_q;\n var p_type_float = p_i.__class__ === _b_.float;\n var q_type_float = q_i.__class__ === _b_.float\n if(p_type_float && q_type_float) {\n flt_p = p_i;\n flt_q = q_i;\n }else if (p_type_float && (PyLong_CheckExact(q_i) ||\n typeof q_i == 'boolean')){\n /* We care about float/int pairs and int/float pairs because\n they arise naturally in several use cases such as price\n times quantity, measurements with integer weights, or\n data selected by a vector of bools. */\n flt_p = p_i\n flt_q = _b_.int.$int_value(q_i)\n }else if(q_type_float && (PyLong_CheckExact(p_i) ||\n typeof p_i == 'boolean')) {\n flt_q = q_i\n flt_p = _b_.int.$int_value(p_i)\n }else{\n finalize_flt_path()\n }\n if(flt_path_enabled){\n var new_flt_total = tl_fma(flt_p.value, flt_q.value, flt_total);\n if (isfinite(new_flt_total.hi)) {\n flt_total = new_flt_total;\n flt_total_in_use = true;\n continue;\n }\n }\n }\n if(finished){\n finalize_flt_path()\n }\n\n function finalize_flt_path(){\n // We're finished, overflowed, have a non-float, or got a non-finite value\n flt_path_enabled = false;\n if(flt_total_in_use){\n term_i = $B.fast_float(tl_to_d(flt_total));\n if (term_i == NULL) {\n err_exit()\n }\n new_total = $B.rich_op('__add__', total, term_i);\n total = new_total\n new_total = NULL\n flt_total = tl_zero;\n flt_total_in_use = false;\n }\n }\n }\n\n if (finished) {\n return total\n }\n term_i = $B.rich_op('__mul__', p_i, q_i);\n new_total = $B.rich_op('__add__', total, term_i);\n total = new_total\n new_total = NULL;\n }\n\n}\n\n\n\nfunction tan(x) {\n $B.check_nb_args('tan', 1, arguments)\n $B.check_no_kw('tan', x)\n\n var y = float_check(x)\n return _b_.float.$factory(Math.tan(y))\n}\n\nfunction tanh(x) {\n $B.check_nb_args('tanh', 1, arguments)\n $B.check_no_kw('tanh', x)\n\n var y = float_check(x)\n if(Math.tanh !== undefined){return _b_.float.$factory(Math.tanh(y))}\n return _b_.float.$factory((Math.pow(Math.E, y) - Math.pow(Math.E, -y))/\n (Math.pow(Math.E, y) + Math.pow(Math.E, -y)))\n}\n\nconst tau = $B.fast_float(2 * Math.PI)\n\nfunction trunc(x) {\n $B.check_nb_args('trunc', 1, arguments)\n $B.check_no_kw('trunc', x)\n\n try{\n return $B.$getattr(x, '__trunc__')()\n }catch(err){\n }\n var x1 = float_check(x)\n if(!isNaN(parseFloat(x1)) && isFinite(x1)){\n if(Math.trunc !== undefined){\n return _b_.int.$factory(Math.trunc(x1))\n }\n if(x1 > 0){\n return _b_.int.$factory(Math.floor(x1))\n }\n return _b_.int.$factory(Math.ceil(x1)) // x1 < 0\n }\n throw _b_.ValueError.$factory(\n 'object is not a number and does not contain __trunc__')\n}\n\nfunction ulp(){\n var $ = $B.args(\"ulp\", 1, {x: null}, ['x'], arguments, {}, null, null),\n x = $.x\n if($B.$isinstance(x, _b_.float)){\n if(_b_.float.$funcs.isinf(x)){\n return _mod.inf\n }else if(_b_.float.$funcs.isnan(x)){\n return _mod.nan\n }\n }\n if(typeof x == \"number\"){\n return x >= 0 ? $B.fast_float(nextUp(x) - x) :\n $B.fast_float(x - (-nextUp(-x)))\n }else if($B.$isinstance(x, $B.long_int)){\n x = Number(_b_.int.$to_bigint(x))\n return x > 0 ? $B.fast_float(nextUp(x) - x) :\n $B.fast_float(x - (-nextUp(-x)))\n }else{\n if($B.rich_comp('__ge__', x, 0)){\n return $B.rich_op('__sub__', $B.fast_float(nextUp(x.value)), x)\n }else{\n var neg_x = $B.$call($B.$getattr(x, \"__neg__\"))()\n return $B.rich_op('__sub__', x,\n $B.$call($B.$getattr($B.fast_float(nextUp(neg_x.value)), '__neg__'))())\n }\n }\n}\n\nvar _mod = {\n acos,\n acosh,\n asin,\n asinh,\n atan,\n atan2,\n atanh,\n cbrt,\n ceil,\n comb,\n copysign,\n cos,\n cosh,\n degrees,\n dist,\n e,\n erf,\n erfc,\n exp,\n exp2,\n expm1,\n fabs,\n factorial,\n floor,\n fma,\n fmod,\n frexp,\n fsum,\n gamma,\n gcd,\n hypot,\n inf,\n isclose,\n isfinite,\n isinf,\n isnan,\n isqrt,\n lcm,\n ldexp,\n lgamma,\n log,\n log1p,\n log2,\n log10,\n modf,\n nan,\n nextafter,\n perm,\n pi,\n pow,\n prod,\n radians,\n remainder,\n sin,\n sinh,\n sqrt,\n sumprod,\n tan,\n tanh,\n tau,\n trunc,\n ulp\n}\n\nfor(var $attr in _mod){\n if(typeof _mod[$attr] === 'function'){\n _mod[$attr].__class__ = $B.builtin_function_or_method\n }\n}\n\n$B.addToImported('math', _mod)\n\n})(__BRYTHON__)\n"], "modulefinder": [".js", "(function($B){\n\nvar _b_=$B.builtins\nvar _mod = {}\n\n$ModuleFinderDict = {__class__:_b_.type,__name__:'ModuleFinder'}\n$ModuleFinderDict.__mro__ = [_b_.object]\n\n$ModuleFinderDict.run_script = function(self, pathname){\n // pathname is the url of a Python script\n var py_src = _b_.$open(pathname).read()\n // transform into internal Brython tree structure\n var root = $B.py2js(py_src)\n // walk the tree to find occurences of imports\n function walk(node){\n var modules = []\n var ctx = node.context\n if(ctx && ctx.type=='node'){ctx = ctx.tree[0]}\n\n if(ctx && ctx.type==\"import\"){\n for(var i=0, _len_i = ctx.tree.length; i < _len_i;i++){\n if(modules.indexOf(ctx.tree[i].name)==-1){\n modules.push(ctx.tree[i].name)\n }\n }\n }else if(ctx && ctx.type==\"from\"){\n if(modules.indexOf(ctx.module)==-1){\n modules.push(ctx.module)\n }\n }\n\n for(var i=0, _len_i = node.children.length; i < _len_i;i++){\n mods = walk(node.children[i])\n for(var j=0, _len_j = mods.length; j < _len_j;j++){\n if(modules.indexOf(mods[j])==-1){modules.push(mods[j])}\n }\n }\n return modules\n }\n self.modules = walk(root)\n}\n\n_mod.ModuleFinder = function(){return {__class__:$ModuleFinderDict}\n}\n_mod.ModuleFinder.$dict = $ModuleFinderDict\n_mod.ModuleFinder.__class__ = $B.$factory\n$ModuleFinderDict.$factory = _mod.ModuleFinder\n\n$B.addToImported('modulefinder', _mod)\n\n})(__BRYTHON__)\n"], "posix": [".js", "/*\nThis module provides access to operating system functionality that is\nstandardized by the C Standard and the POSIX standard (a thinly\ndisguised Unix interface). Refer to the library manual and\ncorresponding Unix manual entries for more information on calls.\n*/\nvar $B = __BRYTHON__,\n _b_ = $B.builtins\n\nfunction _randint(a, b){\n return parseInt(Math.random() * (b - a + 1) + a)\n}\n\nvar stat_result = $B.make_class(\"stat_result\",\n function(filename){\n filename = _b_.str.$factory(filename)\n if($B.file_cache && $B.file_cache.hasOwnProperty(filename)){\n var f = $B.file_cache[filename],\n res = {\n __class__: stat_result,\n st_atime: __BRYTHON__.timestamp,\n st_ctime: f.ctime,\n st_mtime: f.mtime,\n st_uid: -1,\n st_gid: -1,\n st_ino: -1,\n st_mode: 0,\n st_size: f.length\n };\n [\"mtime\", \"ctime\", \"atime_ns\", \"mtime_ns\", \"ctime_ns\"].\n forEach(function(item){\n res[\"st_\" + item] = res.st_atime\n });\n return res\n }else if($B.files && $B.files.hasOwnProperty(filename)){\n var f = $B.files[filename],\n res = {\n __class__: stat_result,\n st_atime: __BRYTHON__.timestamp,\n st_ctime: f.ctime,\n st_mtime: f.mtime,\n st_uid: -1,\n st_gid: -1,\n st_ino: -1,\n st_mode: 0,\n st_size: f.content.length\n };\n for(var item of [\"mtime\", \"ctime\", \"atime_ns\", \"mtime_ns\", \"ctime_ns\"]){\n res[\"st_\" + item] = res.st_atime\n }\n return res\n\n }else{\n var res = {\n __class__: stat_result,\n st_atime: __BRYTHON__.timestamp,\n st_uid: -1,\n st_gid: -1,\n st_ino: -1,\n st_mode: filename.endsWith('/') ? 16895 : 33206,\n st_size: 1 // fake\n };\n [\"mtime\", \"ctime\", \"atime_ns\", \"mtime_ns\", \"ctime_ns\"].\n forEach(function(item){\n res[\"st_\" + item] = res.st_atime\n });\n return res\n }\n }\n)\n$B.set_func_names(stat_result, \"posix\")\n\nvar module = {\n F_OK: 0,\n O_APPEND: 8,\n O_BINARY: 32768,\n O_CREAT: 256,\n O_EXCL: 1024,\n O_NOINHERIT: 128,\n O_RANDOM: 16,\n O_RDONLY: 0,\n O_RDWR: 2,\n O_SEQUENTIAL: 32,\n O_SHORT_LIVED: 4096,\n O_TEMPORARY: 64,\n O_TEXT: 16384,\n O_TRUNC: 512,\n O_WRONLY: 1,\n P_DETACH: 4,\n P_NOWAIT: 1,\n P_NOWAITO: 3,\n P_OVERLAY: 2,\n P_WAIT: 0,\n R_OK: 4,\n TMP_MAX: 32767,\n W_OK: 2,\n X_OK: 1,\n _have_functions: $B.$list(['MS_WINDOWS']),\n environ: _b_.dict.$from_array(\n [['PYTHONPATH', $B.brython_path],\n ['PYTHONUSERBASE', ' ']]),\n error: _b_.OSError,\n fspath: function(path){\n return path\n },\n getcwd: function(){\n return $B.brython_path\n },\n getpid: function(){\n return 0\n },\n lstat: function(filename){\n return stat_result.$factory(filename)\n },\n open: function(path, flags){\n return _b_.open(path, flags)\n },\n remove: function(path) {\n var $ = $B.args(\"remove\", 1, { path: null }, [\"path\"], arguments, {}, null, null)\n console.log($)\n\n var path = $.path\n var found_file = false\n\n if ($B.file_cache && $B.file_cache.hasOwnProperty(path)){\n delete $B.file_cache[path]\n found_file = true\n }\n if ($B.files && $B.files.hasOwnProperty(path)){\n delete $B.files[path]\n found_file = true\n }\n\n if(!found_file) {\n throw _b_.FileNotFoundError.$factory(`No such file or directory: '${path}'`)\n }\n\n return _b_.None\n },\n stat: function(filename){\n return stat_result.$factory(filename)\n },\n stat_result: function(filename){\n return stat_result.$factory(filename)\n },\n urandom: function(n){\n const randbytes = new Uint8Array(n);\n crypto.getRandomValues(randbytes);\n return _b_.bytes.$factory(Array.from(randbytes));\n },\n WTERMSIG: function(){\n return 0\n },\n WNOHANG: function(){\n return _b_.tuple.$factory([0, 0])\n }\n};\n\n[\"WCOREDUMP\", \"WIFCONTINUED\", \"WIFSTOPPED\", \"WIFSIGNALED\", \"WIFEXITED\"].forEach(function(funcname){\n module[funcname] = function(){return false}\n });\n\n[\"WEXITSTATUS\", \"WSTOPSIG\", \"WTERMSIG\"].\n forEach(function(funcname){\n module[funcname] = function(){return _b_.None}\n });\n\n[\"_exit\", \"_getdiskusage\", \"_getfileinformation\", \"_getfinalpathname\",\n \"_getfullpathname\", \"_isdir\", \"abort\", \"access\", \"chdir\", \"chmod\",\n \"close\", \"closerange\", \"device_encoding\", \"dup\", \"dup2\",\n \"execv\", \"execve\", \"fsat\", \"fsync\", \"get_terminal_size\", \"getcwdb\",\n \"getlogin\", \"getppid\", \"isatty\", \"kill\", \"link\", \"listdir\", \"lseek\",\n \"mkdir\", \"pipe\", \"putenv\", \"read\", \"readlink\", \"rename\",\n \"replace\", \"rmdir\", \"spawnv\", \"spawnve\", \"startfile\", \"stat_float_times\",\n \"statvfs_result\", \"strerror\", \"symlink\", \"system\", \"terminal_size\",\n \"times\", \"times_result\", \"umask\", \"uname_result\", \"unlink\", \"utime\",\n \"waitpid\", \"write\"].forEach(function(funcname){\n module[funcname] = function(){\n throw _b_.NotImplementedError.$factory(\"posix.\" + funcname +\n \" is not implemented\")\n }\n });\n\n$B.addToImported('posix', module)"], "pyexpat": [".js", "(function($B){\n\n$B.$import('xml_parser')\n\nvar model = $B.imported.xml_parser.models\nconsole.log('model', model)\n\nvar _b_ = $B.builtins\n\nconst XML_PARAM_ENTITY_PARSING_NEVER = 0,\n XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE = 1,\n XML_PARAM_ENTITY_PARSING_ALWAYS = 2\n\nconst FAIL = {}\n\nconst xml_entities = {\n '>': '>',\n '<': '<',\n '"': '\"',\n ''': \"'\",\n '&': '&'\n }\n\nvar xmlparser = $B.make_class('xmlparser',\n function(encoding, namespace_separator, intern){\n return {\n __class__: xmlparser,\n __dict__: $B.empty_dict(),\n encoding,\n namespace_separator,\n intern,\n buffer_text: false,\n _buffer: '',\n _state: 'data',\n _data_buffer: '',\n _initialized: false,\n _maybe_entity: null,\n _element_stack: [],\n _chunk_size: 2 << 14\n }\n }\n)\n\nxmlparser._handle_stack = function(self){\n if(! (self._element instanceof ELEMENT)){\n return\n }\n if(self._element.name === undefined){\n console.log('name undefined', self._element)\n alert()\n }\n if(self._element.is_end){\n if(self._element_stack.length == 0){\n raise_error(self, 'no opening tag for closing ' + self._element.name)\n }else{\n var expected = $B.last(self._element_stack)\n if(expected !== self._element.name){\n console.log('error handle stack, stack', self._element_stack, self._element)\n raise_error(self, `tag mismatch, ` +\n `expected closing tag ${expected}, ` +\n `got: ${self._element.name}`)\n }\n self._element_stack.pop()\n if(self._element_stack.length == 0){\n flush_char_data(self)\n }\n }\n }else if(! self._element.self_closing){\n self._element_stack.push(self._element.name)\n }\n}\n\nxmlparser.CharacterDataHandler = _b_.None\n\nxmlparser.CommentHandler = _b_.None\n\nxmlparser.EndElementHandler = _b_.None\n\nfunction check_entity(parser, pos){\n var entity = parser._maybe_entity\n var decimal = /&#(\\d+);$/.exec(entity)\n if(decimal){\n return _b_.chr(parseInt(decimal[1]))\n }\n var hexa = /&#x(\\d+);$/.exec(entity)\n if(hexa){\n return _b_.chr(parseInt(hexa[1], 16))\n }\n var xml_entity = xml_entities[entity]\n if(xml_entity){\n return xml_entity\n }\n raise_error_known_position(parser, `unknown entity: \"${entity}\"`, pos)\n}\n\nfunction flush_char_data(parser){\n var buf = parser._data_buffer\n if(buf.length > 0){\n let handler = parser._handlers.CharacterDataHandler\n if(handler !== _b_.None){\n handler(buf)\n }\n }\n parser._data_buffer = ''\n}\n\nfunction flush_final_char_data(parser){\n var buf = parser._data_buffer\n for(var i = 0; i < buf.length; i++){\n if(! buf[i].match(/\\s/)){\n var pos = parser._pos - buf.length + i - 1\n console.log('rest', buf)\n var msg = `junk after document element: line 1, column ${pos}`\n raise_error(parser, msg)\n }\n }\n}\n\nconst encoding_re = /<\\?xml .*encoding\\s*=\\s*\"(.*?)\"/\n\nconst handler_names = [\n 'CharacterDataHandler',\n 'CommentHandler',\n 'StartElementHandler',\n 'EndElementHandler',\n 'XmlDeclHandler'\n ]\n\nxmlparser.Parse = function(){\n var $ = $B.args('Parse', 3,\n {self: null, data: null, isfinal: null},\n ['self', 'data', 'isfinal'], arguments,\n {}, null, null),\n self = $.self,\n data = $.data,\n isfinal = $.isfinal,\n decoder,\n array\n if(self.finished){\n throw Error('parsing finished')\n }\n if(_b_.isinstance(data, _b_.bytes)){\n if(self.encoding === _b_.None){\n // try getting encoding from prolog\n decoder = new TextDecoder('iso-8859-1')\n array = new Uint8Array(data.source.slice(0, 200))\n var head = decoder.decode(array)\n var mo = encoding_re.exec(head)\n if(mo){\n self.encoding = mo[1]\n }else{\n self.encoding = 'utf-8' // default\n }\n }\n // decode bytes\n decoder = new TextDecoder(self.encoding)\n array = new Uint8Array(data.source)\n data = decoder.decode(array)\n }\n if(! self._initialized){\n if(data[0] != '<'){\n throw Error(\"XML or text declaration not at start of entity\")\n }\n self._initialized = true\n }\n self._buffer = data\n self._buffer_length = _b_.len(data)\n self._pos = 0\n\n var handlers = self._handlers = {}\n for(var handler_name of handler_names){\n let handler = $B.$getattr(self, handler_name)\n if(handler !== _b_.None){\n handlers[handler_name] = $B.$call(handler)\n }else{\n handlers[handler_name] = _b_.None\n }\n }\n\n for(var token of xmlparser.xml_tokenizer(self)){\n if(token instanceof ELEMENT){\n if(! token.is_declaration && ! token.is_end){\n if(handlers.StartElementHandler !== _b_.None){\n flush_char_data(self)\n handlers.StartElementHandler(token.name, token.attrs)\n }\n if(token.self_closing &&\n handlers.EndElementHandler !== _b_.None){\n handlers.EndElementHandler(token.name)\n }\n }else if(token.is_end &&\n handlers.EndElementHandler !== _b_.None){\n flush_char_data(self)\n handlers.EndElementHandler(token.name)\n }\n }else if(token instanceof DATA &&\n handlers.CharacterDataHandler !== _b_.None){\n handlers.CharacterDataHandler(token.value)\n }else if(token instanceof COMMENT &&\n handlers.CommentHandler !== _b_.None){\n flush_char_data(self)\n handlers.CommentHandler(token.value)\n }\n }\n flush_final_char_data(self)\n if(isfinal){\n self.finished = true\n }\n}\n\nxmlparser.ParseFile = function(){\n var $ = $B.args('ParseFile', 2,\n {self: null, file: null},\n ['self', 'file'], arguments,\n {}, null, null),\n self = $.self,\n file = $.file\n var reader = $B.$call($B.$getattr(file, 'read'))\n while(true){\n var data = reader(self._chunk_size)\n console.log('ParseFile, data', data)\n if(_b_.len(data) == 0){\n return xmlparser.Parse(self, data, true)\n }else{\n xmlparser.Parse(self, data, false)\n }\n }\n}\n\nxmlparser.SetBase = function(self, base){\n self._base = base\n return _b_.None\n}\n\nxmlparser.SetParamEntityParsing = function(self, peParsing){\n self._peParsing = peParsing\n return peParsing\n}\n\nxmlparser.StartElementHandler = _b_.None\n\nxmlparser.xml_tokenizer = function*(self){\n // convert bytes to string\n self._element = new $B.imported.xml_parser.DOCUMENT(self)\n while(self._pos < self._buffer_length){\n var char = self._buffer[self._pos]\n self._element = self._element.feed(char)\n if(self._element.closed){\n yield self._element\n }\n self._pos++\n }\n console.log('element', self._element)\n console.log('fini')\n alert()\n}\n\n$B.set_func_names(xmlparser, 'expat')\n\nfunction raise_error_known_position(parser, message, pos){\n message += ' at position ' + pos\n var ix = pos\n while(ix >= 0 && parser._buffer[ix] !== '\\n'){\n ix--\n }\n message += '\\n' + parser._buffer.substring(ix, pos + 1)\n message += '\\n' + ' '.repeat(pos - ix - 1) + '^'\n throw error.$factory(message)\n}\n\nfunction raise_error(parser, message){\n throw error.$factory(message)\n}\n\nfunction raise_error1(element, char){\n var head = element\n while(head.origin){\n head = head.origin\n }\n console.log(head)\n var cls = element.constructor.name,\n message = cls + ' expected ' + element.expect +\n ', got: ' + char\n var pos = head.parser._pos\n raise_error_known_position(head.parser, message, pos)\n}\n\nvar error = $B.make_class(\"error\",\n function(message){\n return {\n __class__: error,\n msg: message,\n args: $B.fast_tuple([message]),\n __cause__: _b_.None,\n __context__: _b_.None,\n __suppress_context__: false\n }\n })\nerror.__bases__ = [_b_.Exception, _b_.object]\nerror.__mro__ = [_b_.Exception, _b_.BaseException, _b_.object]\n\n$B.set_func_names(error, \"expat\")\n\nfunction expect_chars(element, char, stop){\n var res\n if(! element.hasOwnProperty('expected_chars')){\n element.expected_chars = ''\n }\n if(is_char(char)){\n element.expected_chars += char\n if(stop){\n var end_pos = element.expected_chars.length - stop.length\n var tail = element.expected_chars.substr(end_pos)\n if(tail == stop){\n res = {value: element.expected_chars.substr(0, end_pos)}\n delete element.expected_chars\n return res\n }\n }\n }else{\n res = {value: element.expected_chars}\n if(element.expected_pos == literal.length){\n delete element.expected_pos\n return {value: literal}\n }\n }\n return {value: null}\n}\n\n\nfunction expect_name(element, char){\n if(! element.hasOwnProperty('expected_name')){\n if(is_id_start(char)){\n element.expected_name = char\n }else if(! is_whitespace(char)){\n raise_error(element.parser, 'expected name start, got: ' + char)\n }\n }else if(is_id_continue(char)){\n element.expected_name += char\n }else if(is_whitespace(char)){\n var res = {value: element.expected_name}\n delete element.expected_name\n return res\n }else{\n raise_error(element.parser, 'name expected id, got: ' + char)\n }\n return {}\n}\n\nfunction expect_literal(element, literal, char){\n if(! element.hasOwnProperty('expected_pos')){\n element.expected_pos = 0\n }\n if(literal[element.expected_pos] == char){\n element.expected_pos++\n if(element.expected_pos == literal.length){\n delete element.expected_pos\n return {value: literal}\n }else{\n return {value: null}\n }\n }\n return FAIL\n}\n\nfunction get_parser(element){\n while(element.origin){\n element = element.origin\n }\n return element.parser\n}\n\nfunction get_pos(element){\n while(element.origin){\n element = element.origin\n }\n return element.parser._pos\n}\n\n/*\ndocument ::= prolog element Misc*\n\nprolog ::= XMLDecl? Misc* (doctypedecl Misc*)?\nXMLDecl ::= ''\nMisc ::= Comment | PI | S\nComment ::= ''\nPI ::= '' Char*)))? '?>'\ndoctypedecl ::= ''\n*/\nfunction DOCUMENT(parser){\n this.parser = parser\n this.expect = 'prolog'\n this.names = []\n}\n\nDOCUMENT.prototype.feed = function(char){\n if(this.expect == 'prolog'){\n this.expect = 'element'\n return (new prolog(this)).feed(char)\n if(char !== '<'){\n raise_error(this.parser, 'expected <')\n }\n this.expect = 'name_start_or_special'\n }else if(this.expect == 'name_start_or_special'){\n if(char == '!'){\n this.expect = 'comment_or_doctype'\n }else if(char == '?'){\n this.expect = 'xmldecl_or_pi'\n }else if(is_id_start(char)){\n this.expect = 'prolog'\n return new ELEMENT(this).feed(char)\n }else{\n raise_error1(this, char)\n }\n }else if(this.expect == 'comment_or_doctype'){\n if(char == '-'){\n this.expect = 'comment'\n }else if(char == 'D'){\n this.expect = 'DOCTYPE'\n return this.feed(char)\n }else{\n raise_error('expected comment or DOCTYPE, got: ' + char)\n }\n }else if(this.expect == 'DOCTYPE'){\n var res = expect_literal(this, 'DOCTYPE', char)\n if(res.value){\n return new DOCTYPE(this.parser, this)\n }\n }else if(this.expect == 'xmldecl_or_pi'){\n var res = expect_name(this, char)\n if(res.value){\n if(res.value == 'xml'){\n this.expect = 'prolog'\n return new XMLDECL(this.parser, this)\n }else{\n this.expect = 'prolog'\n var pi = new PI(this.parser, this)\n pi.name = res.value\n pi.expect = 'content'\n return pi\n }\n }\n return this\n }else if(this.expect == 'comment'){\n if(char == '-'){\n this.expect = 'prolog'\n return new COMMENT(this.parser, this)\n }else{\n raise_error(this.parser, 'DOCUMENT, expected -, got: ' + char)\n }\n }else{\n raise_error(this.parser, 'DOCUMENT, unhandled expect: ' + this.expect)\n }\n return this\n}\n\n/*\nprolog ::= XMLDecl? Misc* (doctypedecl Misc*)?\n*/\nfunction prolog(origin){\n this.origin = origin\n this.expect = 'XMLDecl?'\n}\n\nprolog.prototype.feed = function(char){\n if(this.expect == 'XMLDecl?'){\n return (new XMLDecl(this)).feed(char)\n }\n return this\n}\n\n/*\nXMLDecl ::= ''\n*/\nfunction XMLDecl(origin){\n this.origin = origin\n this.expect = ''\nintSubset ::= (markupdecl | DeclSep)*\nmarkupdecl ::= elementdecl | AttlistDecl | EntityDecl | NotationDecl\n | PI | Comment\nDeclSep ::= PEReference | S\n*/\n\nfunction DOCTYPE(parser, origin){\n this.parser = parser\n this.origin = origin\n this.expect = 'element_start'\n}\n\nDOCTYPE.prototype.feed = function(char){\n console.log('DOCTYPE feed', this.expect, 'char', char)\n if(this.expect == 'element_start'){\n var res = expect_name(this, char)\n if(res.value){\n this.name = res.value\n this.expect = 'external_id_or_[_or_>'\n }\n }else if(this.expect == 'external_id_or_[_or_>'){\n if(char == '['){\n this.expect = '>'\n return new intSubset(this)\n }else if(char == '>'){\n this.expect == 'no_whitespace'\n }else if(char == 'S' || char == 'P'){\n this.expect = '[_or_>'\n var res = new ExternalID(this)\n return res.feed(char)\n }else{\n raise_error(this.parser, 'DOCTYPE expected SYSTEM, PUBLIC, [ or >, got: ' + char)\n }\n }else if(this.expect == '[_or_>'){\n if(char == '['){\n this.expect = '>'\n return new intSubset(this)\n }else if(char == '>'){\n this.expect = 'no_whitespace'\n }else if(! is_whitespace(char)){\n raise_error(this.parser, 'DOCTYPE expected [ or >, got: ' + char)\n }\n }else if(this.expect == '>'){\n if(! is_whitespace(char)){\n if(char == '>'){\n this.expect = 'no_whitespace'\n }else{\n raise_error(this.parser, 'DOCTYPE expected >, got: ' + char)\n }\n }\n }else if(this.expect = 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }\n return this\n}\n\n/*\nXMLDecl ::= ''\nVersionInfo ::= S 'version' Eq (\"'\" VersionNum \"'\" | '\"' VersionNum '\"')\nEq ::= S? '=' S?\nVersionNum ::= '1.0'\nEncodingDecl ::= S 'encoding' Eq ('\"' EncName '\"' | \"'\" EncName \"'\" )\nEncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*\nSDDecl ::= S 'standalone' Eq\n ((\"'\" ('yes' | 'no') \"'\") | ('\"' ('yes' | 'no') '\"'))\n*/\nfunction XMLDECL(parser, origin){\n this.parser = parser\n this.expect = 'version_info'\n this.origin = origin\n}\n\nXMLDECL.prototype.feed = function(char){\n switch(this.expect){\n case 'version_info':\n var res = expect_literal(this, 'version', char)\n if(res.value){\n this.expect = 'eq'\n this.attr_name = 'version'\n }\n break\n case 'eq':\n if(char == '='){\n this.expect = 'quote'\n }else if(! is_whitespace(char)){\n raise_error(this.parser, 'expect =, got: ' + char)\n }\n break\n case 'quote':\n if(is_quote(char)){\n this.expect = char\n this.quoted = ''\n }else if(! is_whitespace(char)){\n raise_error(this.parser, 'expected quote, got: ' + char)\n }\n break\n case '\"':\n case \"'\":\n var res = expect_literal(this, this.expect, char)\n if(res.value){\n this[this.attr_name] = this.quoted\n this.expect = 'encoding_or_sd_or_close'\n }else{\n this.quoted += char\n }\n break\n case 'encoding_or_sd_or_close':\n switch(char){\n case 'e':\n if(! this.hasOwnProperty('encoding')){\n this.expect = 'encoding'\n return this.feed(char)\n }\n break\n case 's':\n if(! this.hasOwnProperty('standalone')){\n this.expect = 'standalone'\n return this.feed(char)\n }\n break\n case '?':\n this.expect = '>'\n break\n default:\n if(! is_whitespace(char)){\n raise_error(this.parser,\n 'expected encoding, standalone or ?, got: ' + char)\n }\n }\n break\n case 'encoding':\n case 'standalone':\n var res = expect_literal(this, this.expect, char)\n if(res.value){\n this.attr_name = this.expect\n this.expect = 'eq'\n }\n break\n case '>':\n if(char == '>'){\n this.closed = true\n }else if(! is_whitespace(char)){\n if(this.closed){\n return this.origin.feed(char)\n }\n raise_error(this.parser, 'expected >, got: ' + char)\n }\n break\n default:\n raise_error(this.parser, 'unhandled case: ' + this.expect)\n }\n return this\n}\n\n/*\nPI ::= '' Char*)))? '?>'\nPITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))\n*/\nfunction PI(parser, origin){\n this.parser = parser\n this.origin = origin\n this.expect = 'pi_target'\n}\n\nPI.prototype.feed = function(char){\n if(this.expect == 'pi_target'){\n var res = expect_name(this, char)\n if(res.value){\n this.pi_target = res.value\n this.expect = 'content'\n }\n }else if(this.expect == 'content'){\n var res = expect_chars(this, char, '?>')\n if(res.value){\n this.content = res.value\n this.closed = true\n this.expect = 'no_whitespace'\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }\n return this\n}\n\nfunction CDATA(){\n this.content = ''\n this.expect = ']'\n this.level = 1\n}\n\nCDATA.prototype.feed = function(char){\n switch(this.expect){\n case ']':\n if(char == '>'){\n throw Error('closed without closing ]')\n }else if(char == '['){\n this.level++\n }else if(char == ']'){\n if(this.level == 1){\n this.expect = '>'\n }else{\n this.level--\n }\n }else{\n this.content += char\n }\n break\n case '>':\n if(char != '>'){\n console.log('-- error', this, 'char', char)\n throw Error('expected \">\", got: ' + char)\n }\n this.closed = true\n break\n }\n return this\n}\n\nfunction DTD(parser){\n this.parser = parser\n this.expect = 'name_start'\n this.items = []\n}\n\nDTD.prototype.feed = function(char){\n if(this.expect == 'name_start'){\n if(is_id_start(char)){\n this.name = char\n this.expect = 'name_continue'\n }else if(char == '-'){\n this.expect = '-' // maybe comment start\n }else if(char == '['){\n return new CDATA()\n }else{\n throw Error('expected name, got ' + char)\n }\n }else if(this.expect == 'name_continue'){\n if(is_id_continue(char)){\n this.name += char\n }else{\n console.log('DD, name', this.name)\n if(this.name == 'DOCTYPE'){\n return new DOCTYPE(this.parser)\n }else if(this.name == 'ENTITY'){\n return new ENTITY(this.parser)\n }\n if(char == '>'){\n this.closed = true\n }else{\n this.expect == 'any'\n }\n }\n }else if(this.expect == '-'){\n if(char == '-'){\n // comment\n this.is_comment = true\n }else{\n throw Error('expected -, got: ' + char)\n }\n }else{\n if(char == '>'){\n this.closed = true\n }else{\n this.items.push(char)\n }\n }\n return this\n}\n\nDTD.prototype.toString = function(){\n var res = ` 0){\n res += ' '\n var items = this.items.map(x => x.toString())\n res += items.join(' ')\n }\n return res + '>'\n}\n\nfunction COMMENT(parser, origin){\n this.parser = parser\n this.origin = origin\n this.value = ''\n this.expect = '-->'\n}\n\nCOMMENT.prototype.feed = function(char){\n if(this.expect == '-->'){\n var res = expect_chars(this, char, '-->')\n if(res.value){\n this.content = res.value\n this.expect = 'no_whitespace'\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }\n return this\n}\n\n/*\nelement ::= EmptyElemTag | STag content ETag\nSTag ::= '<' Name (S Attribute)* S? '>'\nAttribute ::= Name Eq AttValue\nETag ::= ''\ncontent ::= CharData?\n ((element | Reference | CDSect | PI | Comment) CharData?)*\nEmptyElemTag ::= '<' Name (S Attribute)* S? '/>'\n*/\n\nfunction ELEMENT(origin) {\n this.origin = origin\n this.expect = '?_/_or_name_start'\n this.attrs = $B.empty_dict()\n}\n\nELEMENT.prototype.add_attribute_name = function(attr_name){\n if(_b_.dict.$contains(this.attrs, attr_name)){\n throw Error(`duplicate attribute name: ${attr_name}`)\n }\n _b_.dict.$setitem(this.attrs, attr_name, _b_.None)\n}\n\nELEMENT.prototype.set_attribute_value = function(value){\n _b_.dict.$setitem(this.attrs, this.attr_name, value)\n}\n\nELEMENT.prototype.feed = function(char){\n console.log('ELEMENT feed, expects', this.expect, 'char', char)\n if(this.expect == 'name_start'){\n if(char == '?'){\n if(this.is_declaration){\n throw Error('already got ?')\n }\n this.is_declaration = true\n }else if(char == '/'){\n if(this.is_end){\n throw Error('already got /')\n }\n this.is_end = true\n }else if(is_id_start(char)){\n this.name = char\n this.expect = 'name_continue'\n }\n }else if(this.expect == 'name_continue'){\n if(is_id_continue(char)){\n this.name += char\n }else{\n // end of element name\n if(this.is_declaration){\n if(this.name == 'xml'){\n this.is_xml_header = true\n }else{\n return new PROCESSING_INSTRUCTION(this.parser, this.name)\n }\n }\n if(is_whitespace(char)){\n this.expect = 'attr_name_start'\n }else if(char == '>'){\n this.closed = true\n }else if(char == '/'){\n this.self_closing = true\n this.expect = '>'\n }else{\n throw Error('unexpected at end of element name: ' + char)\n }\n }\n }else if(this.expect == 'attr_name_start'){\n if(char == '/'){\n this.self_closing = true\n }else if(char == '>'){\n this.expect = 'no_whitespace'\n }else if(is_id_start(char)){\n this.attr_name = char\n this.expect = 'attr_name_continue'\n }else if(char == '?' && this.is_declaration){\n this.expect = '>'\n }else if(! is_whitespace(char)){\n throw Error('expected attribute name, got: ' + char)\n }\n }else if(this.expect == 'attr_name_continue'){\n if(is_id_continue(char)){\n this.attr_name += char\n }else if(char == '='){\n this.add_attribute_name(this.attr_name)\n this.expect = 'attr_value_start'\n this.attr_value = ''\n }else if(is_whitespace(char)){\n this.add_attribute_name(this.attr_name)\n this.expect = '='\n }else if(char == '>'){\n this.add_attribute_name(this.attr_name)\n this.closed = true\n }else{\n throw Error('unexpected character in attribute name: ' + char)\n }\n }else if(this.expect == '='){\n if(char == '='){\n this.expect = 'attr_value_start'\n }else if(! is_whitespace(char)){\n raise_error1(this, char)\n }\n }else if(this.expect == 'attr_value'){\n if(char == '='){\n this.expect = 'attr_value_start'\n this.attr_value = ''\n }else if(char == '>'){\n this.closed = true\n }else if(is_id_start(char)){\n this.attr_name = char\n this.expect = 'attr_name_continue'\n }else if(! is_whitespace(char)){\n throw Error('expected attribute value or name, got: ' + char)\n }\n }else if(this.expect == 'attr_value_start'){\n if(char == '\"' || char == \"'\"){\n this.expect = 'quote'\n this.quote = char\n this.attr_value = ''\n }else if(! is_whitespace(char)){\n throw Error('unexpect attribute value start: ' + char)\n }\n }else if(this.expect == \"quote\"){\n if(char == this.quote){\n this.set_attribute_value(this.attr_value)\n this.expect = 'attr_name_start'\n }else{\n this.attr_value += char\n }\n }else if(this.expect == '>'){\n if(char == '>'){\n this.closed = true\n }else{\n throw Error('expected >, got: ' + char)\n }\n }else if(this.expect == 'attr_name'){\n if(char instanceof Name){\n if(_b_.dict.__contains__(this.attrs, char.value)){\n throw Error('duplicate value ' + char.value)\n }\n _b_.dict.$setitem(this.attrs, char.value, _b_.None)\n this.last_attr = char.value\n }else if(char.value == '?' && this.is_declaration){\n if(this.question_mark){\n throw Error('already ?')\n }\n this.question_mark = true\n }else if(char == END){\n if(this.is_declaration && ! this.question_mark){\n throw Error('missing ')\n }\n }else if(char instanceof Punctuation && char.value == '/'){\n this.no_end = true\n this.expect = END\n }else{\n throw Error('expected attribute name, got ' + char)\n }\n }else if(this.expect == 'attr_value'){\n _b_.dict.$setitem(this.attrs, this.last_attr, char)\n this.expect = 'attr_name'\n }else if(this.expect == END){\n // after \"/\"\n if(char != END){\n throw Error('nothing after /')\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }else{\n raise_error1(this, char)\n }\n return this\n}\n\nELEMENT.prototype.toString = function() {\n var res = `<`\n res += this.is_end ? '/' : ''\n res += this.name\n if(this.attrs.length > 0){\n res += ' '\n }\n var attrs = []\n for(var item of _b_.dict.$iter_items(this.attrs)){\n console.log('item', item)\n attrs.push(`${item.key}: ${item.value.toString()}`)\n }\n res += attrs.join(' ')\n if(this.no_end){\n res += '/'\n }\n return res + '>'\n}\n\n/*\nEntityDecl ::= GEDecl | PEDecl\nPEDecl ::= ''\nPEDef ::= EntityValue | ExternalID\n*/\nfunction ENTITY(parser){\n this.parser = parser\n}\n\nENTITY.prototype.feed = function(char){\n if(! is_whitespace(char)){\n if(is_id_start(char)){\n return new GEDecl(this.parser, char)\n }else if(char == \"%\"){\n return new PEDecl(this.parser)\n }\n throw Error('unexpected after ENTITY: ' + char)\n }\n}\n\n/*\nGEDecl ::= ''\nEntityDef ::= EntityValue | (ExternalID NDataDecl?)\nExternalID ::= 'SYSTEM' S SystemLiteral\n | 'PUBLIC' S PubidLiteral S SystemLiteral\nNDataDecl ::= S 'NDATA' S Name\nEntityValue ::= '\"' ([^%&\"] | PEReference | Reference)* '\"'\n | \"'\" ([^%&'] | PEReference | Reference)* \"'\"\n\n*/\nfunction GEDecl(parser, char){\n this.parser = parser\n this.expect = 'name_continue'\n this.name = char\n this.state = 'name'\n}\n\nGEDecl.prototype.feed = function(char){\n switch(this.expect){\n case 'name_start':\n if(is_id_start(char)){\n if(this.state == 'NDATA'){\n this.ndata_name = char\n }\n this.expect = 'name_continue'\n }else if(! is_whitespace(char)){\n throw Error('GEDecl expected name start, got: ' + char)\n }\n break\n case 'name_continue':\n if(is_id_continue(char)){\n if(this.state == 'name'){\n this.name += char\n }else if(this.state == 'NDATA'){\n this.ndata_name += char\n }\n }else if(is_whitespace(char)){\n if(this.state == 'NDATA'){\n this.expect = '>'\n }else{\n this.expect = 'entity_def'\n }\n }else if(char == '>' && this.state == 'NDATA'){\n this.closed = true\n }else{\n throw Error('GEDecl expected name, got: ' + char)\n }\n break\n case 'entity_def':\n if(is_quote(char)){\n this.quoted = ''\n this.state = this.expect\n this.expect = char\n }else if(char == 'S' || char == 'P'){\n this.expect = char == 'S' ? 'SYSTEM' : 'PUBLIC'\n this.expect_pos = 1\n this.external_id = this.expect\n }else if(! is_whitespace(char)){\n throw Error('GEDCL expect quote, SYSTEM or PUBLIC, got: ' + char)\n }\n break\n case 'SYSTEM':\n case 'PUBLIC':\n if(char == this.expect[this.expect_pos]){\n this.expect_pos++\n if(this.expect_pos == this.expect.length){\n this.expect = this.expect == 'SYSTEM' ? 'system_literal' :\n 'pubid_literal'\n }\n }else{\n throw Error(`GEDecl expected ${this.expect}, got: ${char}`)\n }\n break\n case 'NDATA':\n if(char == this.expect[this.expect_pos]){\n this.expect_pos++\n if(this.expect_pos == this.expect.length){\n this.expect = 'name_start'\n this.ndata_name = ''\n this.state = 'NDATA'\n }\n }else{\n throw Error(`GEDecl expected ${this.expect}, got: ${char}`)\n }\n break\n case '\"':\n case \"'\":\n if(this.state == 'entity_def'){\n if(char == this.expect){\n this.entity_def = this.quoted\n this.expect = '>'\n }else{\n this.quoted += char\n }\n }else if(this.state == 'system_literal'){\n if(char == this.expect){\n this.system_literal = this.quoted\n this.expect = 'n_data_decl_or_close'\n }else{\n this.quoted += char\n }\n }\n break\n case 'system_literal':\n if(is_quote(char)){\n this.expect = char\n this.state = 'system_literal'\n this.quoted = ''\n }else if(! is_whitespace(char)){\n throw Error('GEDecl expected SystemLiteral, got: ' + char)\n }\n break\n case '>':\n if(! is_whitespace(char)){\n if(char == '>'){\n this.closed = true\n }else{\n throw Error('GEDecl expected >, got: ' + char)\n }\n }\n break\n case 'n_data_decl_or_close':\n if(char == '>'){\n this.closed = true\n }else if(char == 'N'){\n this.expect = 'NDATA'\n this.expect_pos = 1\n }else if(! is_whitespace(char)){\n throw Error('GEDecl expected NDATA or >, got: ' + char)\n }\n break\n default:\n console.log(this.parser._buffer.substr(0, this.parser._pos))\n throw Error('pas fini...')\n }\n return this\n}\n\n/*\nExternalID ::= 'SYSTEM' S SystemLiteral\n | 'PUBLIC' S PubidLiteral S SystemLiteral\n*/\nfunction ExternalID(origin){\n this.origin = origin\n this.expect = 'first'\n}\n\nExternalID.prototype.feed = function(char){\n if(this.expect == 'first'){\n if(! is_whitespace(char)){\n if(char == 'S'){\n this.expect = 'SYSTEM'\n return this.feed(char)\n }else if(char == 'P'){\n this.expect = 'PUBLIC'\n return this.feed(char)\n }else{\n raise_error(this, 'ExternalID expected SYSTME or PUBLIC, got: ' + char)\n }\n }\n }else if(this.expect == 'SYSTEM' || this.expect == 'PUBLIC'){\n var res = expect_literal(this, this.expect, char)\n if(res.value){\n this.type = this.expect\n if(this.type == 'SYSTEM'){\n this.expect = '[_or_>'\n return new SystemLiteral(this)\n }else{\n this.expect = 'system_after_pubid'\n return new PubidLiteral(this)\n }\n }\n }else if(this.expect == 'system_after_pubid'){\n if(! is_whitespace(char)){\n this.expect = '[_or_>'\n return (new SystemLiteral(this)).feed(char)\n }\n }else if(this.expect == '[_or_>'){\n if(char == '['){\n this.expect = '>'\n return new intSubset(this)\n }else if(char == '>'){\n return this.origin.feed(char)\n }else{\n raise_error1(this, char)\n }\n }else if(this.expect == '>'){\n if(char == '>'){\n this.expect = 'no_whitespace'\n }else if(! is_whitespace(char)){\n raise_error1(this, char)\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n console.log('return to origin', this.origin, 'char', char)\n return this.origin.feed(char)\n }\n }\n return this\n}\n\n/*\nPubidLiteral ::= '\"' PubidChar* '\"' | \"'\" (PubidChar - \"'\")* \"'\"\nPubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9]\n | [-'()+,./:=?;!*#@$_%]\n*/\nfunction PubidLiteral(origin){\n this.origin = origin\n this.expect = 'quote'\n}\n\n\nfunction is_pubid_char(char){\n /*\n#x20 | #xD | #xA | [a-zA-Z0-9]\n | [-'()+,./:=?;!*#@$_%]\n*/\n return char.match(new RegExp(\"[a-zA-Z0-9-'()+,./:=?;!*#@$_%]\")) ||\n ' \\n\\r'.includes(char)\n}\n\nPubidLiteral.prototype.feed = function(char){\n if(this.expect == 'quote'){\n if(is_quote(char)){\n this.expect = char\n this.content = ''\n }else if(! is_whitespace(char)){\n raise_error1(this, char)\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }else{\n if(char == this.expect){\n this.expect = 'no_whitespace'\n }else if(is_pubid_char(char)){\n this.content += char\n }else{\n console.log('PubidLiteral expects', this.expect, 'char', char)\n console.log(is_pubid_char(char))\n raise_error1(this, char)\n }\n }\n return this\n}\n\nfunction SystemLiteral(origin){\n this.origin = origin\n this.expect = 'quote'\n}\n\nSystemLiteral.prototype.feed = function(char){\n console.log('SystemLiteral expects', this.expect, 'char', char)\n if(this.expect == 'quote'){\n if(is_quote(char)){\n this.expect = char\n this.content = ''\n }else if(! is_whitespace(char)){\n raise_error1(this, char)\n }\n }else if(this.expect == 'no_whitespace'){\n if(! is_whitespace(char)){\n return this.origin.feed(char)\n }\n }else{\n if(char == this.expect){\n this.expect = 'no_whitespace'\n }else{\n this.content += char\n }\n }\n return this\n}\n\nfunction PROCESSING_INSTRUCTION(parser, name){\n this.parser = parser\n this.name = name\n this.expect = '?'\n this.content = ''\n}\n\nPROCESSING_INSTRUCTION.prototype.feed = function(char){\n // capture everything until the sequence ?>\n if(this.expect == '?'){\n if(char == '?'){\n this.expect = '>'\n }else{\n this.content += char\n }\n }else if(this.expect == '>'){\n if(char == '>'){\n this.closed = true\n }else{\n this.content += '?' + char\n this.expect = '-'\n }\n }\n return this\n}\n\nfunction ATTR(name){\n this.name = name\n}\n\nATTR.prototype.toString = function(){\n var res = this.name\n if(this.hasOwnProperty('value')){\n res += '=' + this.value\n }\n return res\n}\n\nfunction DATA(value) {\n this.value = value\n}\n\nDATA.prototype.toString = function() {\n return `${this.value}`\n}\n\nvar START = 'START'\nvar END = 'END'\n\n\nfunction Name(value){\n this.value = value\n}\n\nName.prototype.toString = function(){\n return this.value\n}\n\nfunction Punctuation(value){\n this.value = value\n}\n\nfunction String(quote, value){\n this.quote = quote\n this.value = value\n}\n\nString.prototype.toString = function(){\n return this.quote + this.value + this.quote\n}\n\nconst punctuations = '!?/'\n\nfunction open(url){\n var xhr = new XMLHttpRequest()\n xhr.open('GET', url, false)\n xhr.onreadystatechange = function(ev){\n if(this.readyState == 4){\n process(this.responseText)\n }\n }\n xhr.send()\n}\n\nfunction create_parser(){\n var $ = $B.args('ParserCreate', 3,\n {encoding: null, namespace_separator: null, intern: null},\n ['encoding', 'namespace_separator', 'intern'], arguments,\n {encoding: _b_.None, namespace_separator: _b_.None, intern: _b_.None},\n null, null),\n encoding = $.encoding,\n ns_sep = $.namespace_separator,\n intern = $.intern\n if(encoding !== _b_.None && ! _b_.isinstance(encoding, _b_.str)){\n throw _b_.TypeError.$factory(\n `ParserCreate() argument 'encoding' must be ` +\n `str or None, not ${$B.class_name(encoding)}`)\n }\n if(ns_sep !== _b_.None){\n if(! _b_.isinstance(ns_sep, _b_.str)){\n throw _b_.TypeError.$factory(\n `ParserCreate() argument 'namespace_separator' must be ` +\n `str or None, not ${$B.class_name(ns_sep)}`)\n }\n if(ns_sep.length != 1){\n throw _b_.ValueError.$factory(\"namespace_separator must be at \" +\n \"most one character, omitted, or None\")\n }\n }\n if(intern === _b_.None){\n intern = $B.empty_dict()\n }else if(! _b_.isinstance(intern, _b_.dict)){\n throw _b_.TypeError.$factory('intern must be a dictionary')\n }\n return xmlparser.$factory(encoding, ns_sep, intern)\n}\n\nfunction display(text){\n report.value += text + '\\n'\n}\n\nfunction process(src){\n var indent = 0\n for(var token of xml_tokenizer(src)){\n if(indent > 50){\n break\n }\n var head = ' '.repeat(indent)\n if(token instanceof DATA){\n display(head + ' ' + token.toString())\n }else if(token instanceof ELEMENT){\n if(token.is_end){\n indent--\n }\n head = ' '.repeat(indent)\n display(head + token.toString())\n if(token.is_end || token.self_closing || token.is_declaration){\n //\n }else{\n indent++\n }\n }else if(token instanceof DECLARATION){\n display(head + token.toString())\n }else{\n console.log(head + 'token', token, token.toString())\n }\n }\n}\n\nfunction is_id_start(char){\n return char.match(/\\p{L}/u) || char == \"_\"\n}\n\nfunction is_id_continue(char){\n return char.match(/\\p{L}/u) || \"-_:\".includes(char) || char.match(/\\d/)\n}\n\nfunction is_whitespace(s){\n for(let char of s){\n if(! ' \\n\\r\\t'.includes(char)){\n return false\n }\n }\n return s.length > 0\n}\n\nfunction is_quote(char){\n return char == '\"' || char == \"'\"\n}\n\nfunction is_char(char){\n // #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n var cp = char.codePointAt(0)\n return ([0x9, 0xa, 0xd].includes(cp)) ||\n (0x20 <= cp && cp <= 0xd7ff) ||\n (0xe000 <= cp && cp <= 0xfffd) ||\n (0x10000 <= cp && cp <= 0x10ffff)\n}\n\nvar errors = 'errors'\n\n$B.addToImported('pyexpat',\n {\n create_parser,\n ParserCreate: create_parser,\n model,\n error,\n errors,\n XML_PARAM_ENTITY_PARSING_NEVER,\n XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE,\n XML_PARAM_ENTITY_PARSING_ALWAYS\n }\n)\n\n})(__BRYTHON__)"], "python_re": [".js", "// Regular expression\n(function($B){\n\nvar _debug = {value: 0}\n\nvar _b_ = $B.builtins\n\nvar MAXGROUPS = 2147483647,\n MAXREPEAT = 2147483648\n\nvar word_gcs = ['Ll', 'Lu', 'Lm', 'Lt', 'Lo',\n 'Nd',\n 'Mc', 'Me', 'Mn',\n 'Pc']\n\nfunction is_word(cp){\n if((cp >= 97 && cp <= 122) // a-z\n || (cp >= 65 && cp <= 90) // A-Z\n ){\n return true\n }\n for(var word_gc of word_gcs){\n if($B.in_unicode_category(word_gc, cp)){\n return true\n }\n }\n return false\n}\n\nvar ascii_word = {}\n\nfor(var cp = 0; cp <= 127; cp++){\n if(is_word(cp)){\n ascii_word[cp] = true\n }\n}\n\nfunction is_ascii_word(cp){\n return ascii_word[cp] !== undefined\n}\n\nfunction is_digit(cp){\n if(cp >= 48 && cp <= 57){\n return true\n }\n return $B.in_unicode_category('Nd', cp)\n}\n\nfunction is_ascii_digit(cp){\n return cp <= 127 && is_digit(cp)\n}\n\nvar $error_2 = {\n $name: \"error\",\n $qualname: \"error\",\n $is_class: true,\n __module__: \"re\"\n}\n\nvar error = $B.make_class(\"error\",\n function(message){\n return {\n __class__: error,\n msg: message,\n args: $B.fast_tuple([]),\n __cause__: _b_.None,\n __context__: _b_.None,\n __suppress_context__: false\n }\n })\nerror.__bases__ = [_b_.Exception, _b_.object]\nerror.__mro__ = [_b_.Exception, _b_.BaseException, _b_.object]\n\nerror.__str__ = function(self){\n var s = self.msg + ' at position ' + self.pos\n if(self.lineno > 1){\n s += ` (line ${self.lineno}, column ${self.colno})`\n }\n return s\n}\n\n$B.set_func_names(error, \"re\")\n\nfunction $last(t){\n return t[t.length - 1]\n}\n\nfunction fail(message, pos, pattern){\n var err = error.$factory(message)\n err.msg = message\n err.pos = pos\n if(pattern){\n err.pattern = pattern.py_obj // Python object passed to compile()\n err.lineno = 1\n var linestart = 0\n for(var i = 0, len = pattern.string.length; i < pos; i++){\n if(pattern.string[i] == '\\n'){\n err.lineno++\n linestart = i + 1\n }\n }\n err.colno = pos - linestart + 1\n }\n throw err\n}\n\nfunction warn(klass, message, pos, text){\n var frame = $B.frame_obj.frame,\n file = frame[3].__file__,\n src = $B.file_cache[file]\n if(text === undefined){\n var lineno = frame[1].$lineno\n var lines = src.split('\\n'),\n line = lines[lineno - 1]\n }else{\n if(Array.isArray(text)){\n text = from_codepoint_list(text)\n }\n var lineno = 1,\n line_start = 0\n for(var i = 0; i < pos; i++){\n if(text[i] == '\\n'){\n lineno++\n line_start = i + 1\n }\n }\n var line_end = text.substr(line_start).search('\\n'),\n line\n if(line_end == -1){\n line = text.substr(line_start)\n }else{\n line = text.substr(line_start, line_end)\n }\n var col_offset = pos - line_start\n }\n var warning = klass.$factory(message)\n warning.pos = pos\n warning.args[1] = [file, lineno, col_offset, lineno, col_offset,\n line]\n warning.filename = file\n warning.lineno = warning.end_lineno = lineno\n warning.offset = warning.end_offset = col_offset\n warning.line = line\n // module _warning is in builtin_modules.js\n $B.imported._warnings.warn(warning)\n}\n\nfunction chr(i){\n if(i < 0 || i > 1114111){\n throw _b_.ValueError.$factory('Outside valid range')\n }else if(i >= 0x10000 && i <= 0x10FFFF){\n var code = (i - 0x10000)\n return String.fromCodePoint(0xD800 | (code >> 10)) +\n String.fromCodePoint(0xDC00 | (code & 0x3FF))\n }else{\n return String.fromCodePoint(i)\n }\n}\n\nfunction ord(char){\n return char.charCodeAt(0)\n}\n\nconst LETTERS = {\n b: ord('b'),\n N: ord('N'),\n P: ord('P'),\n u: ord('u'),\n U: ord('U'),\n x: ord('x')\n}\n\nconst PARENTH_OPEN = ord('('),\n PARENTH_CLOSE = ord(')'),\n BRACKET_OPEN = ord('['),\n BRACKET_CLOSE = ord(']'),\n BRACE_OPEN = ord('{'),\n BRACE_CLOSE = ord('}'),\n EQUAL = ord('='),\n SUP = ord('>'),\n INF = ord('<'),\n MINUS = ord('-'),\n PLUS = ord('+'),\n OR = ord('|'),\n DOT = ord('.'),\n QUESTION_MARK = ord('?'),\n EXCLAMATION_MARK = ord('!'),\n COLON = ord(':'),\n BACKSLASH = ord('\\\\'),\n DOLLAR = ord('$'),\n CARET = ord('^'),\n LINEFEED = ord('\\n')\n\n// pattern tokenizer\n\nfunction is_ascii(name){\n return /^[\\x00-\\x7F]*$/.test(name)\n}\n\nfunction open_unicode_db(){\n if($B.unicodedb === undefined){\n var xhr = new XMLHttpRequest\n xhr.open(\"GET\",\n $B.brython_path + \"unicode.txt?\" + (new Date()).getTime(), false)\n xhr.onreadystatechange = function(){\n if(this.readyState == 4){\n if(this.status == 200){\n $B.unicodedb = this.responseText\n }else{\n console.log(\n \"Warning - could not load unicode.txt\")\n }\n }\n }\n xhr.send()\n }\n}\n\nfunction validate_named_char(description, pos){\n // validate that \\N{} is in the Unicode db\n // Load unicode table if not already loaded\n if(description.length == 0){\n fail(\"missing character name\", pos)\n }\n open_unicode_db()\n if($B.unicodedb !== undefined){\n var re = new RegExp(\"^([0-9A-F]+);\" +\n description.toUpperCase() + \";.*$\", \"m\")\n search = re.exec($B.unicodedb)\n if(search === null){\n fail(`undefined character name '${description}'`, pos)\n }\n return parseInt(search[1], 16)\n }else{\n fail(\"could not load unicode.txt\", pos)\n }\n}\n\nfunction validate_group_name(sname, pos, is_bytes){\n // sname is an instance of StringObj\n if(! _b_.str.isidentifier(sname.string)){\n fail(`bad character in group name '${sname.string}'`, pos + 4)\n }\n if(is_bytes && ! is_ascii(sname.string)){\n var s = _b_.bytes.decode(_b_.bytes.$factory(sname.codepoints),\n 'ascii', 'backslashreplace')\n warn(_b_.DeprecationWarning,\n `bad character in group name '${s}' at position ${pos + 4}`)\n }\n return true\n}\n\nfunction validate_group_num(so, pos){\n var s = so.string\n if(s.match(/^\\d+$/)){\n return true\n }\n try{\n var num = _b_.int.$factory(s)\n warn(_b_.DeprecationWarning,\n `bad character in group name '${s}' at position ${pos + 3}`,\n pos + 3, s)\n so.string = num + ''\n return true\n }catch(err){\n return false\n }\n}\n\nfunction validate_num_or_name(so, pos, is_bytes){\n return validate_group_num(so, pos, is_bytes) ||\n validate_group_name(so, pos - 1, is_bytes)\n}\n\nvar character_classes = {\n in_charset: to_codepoint_list('dDsSwW'),\n in_re: to_codepoint_list('AbBdDsSwWZ')\n}\n\nfunction escaped_char(args){\n var cps = args.codepoints,\n pos = args.pos,\n in_charset = args.in_charset,\n is_bytes = args.is_bytes // if pattern is bytes\n var special = cps[pos + 1]\n if(special === undefined){\n fail('bad escape (end of pattern)', pos)\n }\n var key = in_charset ? 'in_charset' : 'in_re'\n if(in_charset && special == LETTERS.b){\n // Inside a character range, \\b represents the backspace character,\n // for compatibility with Python\u2019s string literals.\n return '\\b'\n }\n if(character_classes[key].indexOf(special) > -1){\n return new CharacterClass(pos, special, 2)\n }else if(special == LETTERS.N && ! is_bytes){\n if(cps[pos + 2] != BRACE_OPEN){\n fail('missing {', pos)\n }\n var i = pos + 3,\n description = []\n while(i < cps.length){\n if(cps[i] == BRACE_CLOSE){\n break\n }\n description.push(cps[i])\n i++\n }\n if(description.length == 0){\n fail(\"missing character name\", pos)\n }\n if(i == cps.length){\n fail(\"missing }, unterminated name\", pos)\n }\n var cp = validate_named_char(from_codepoint_list(description), pos)\n return {\n type: 'N',\n ord: cp,\n char: chr(cp),\n length: i - pos + 1\n }\n }else if(special == LETTERS.x){\n // \\xhh = character with hex value hh\n var rest = from_codepoint_list(cps.slice(pos + 2)),\n mo = /^[0-9a-fA-F]{0,2}/.exec(rest),\n hh = mo ? mo[0] : ''\n if(mo && mo[0].length == 2){\n var cp = parseInt(mo[0], 16)\n return {\n type: 'x',\n ord: cp,\n char: chr(cp),\n length: 2 + mo[0].length\n }\n }\n fail('incomplete escape \\\\x' + hh, pos)\n }else if(special == LETTERS.u){\n // \\uxxxx = character with 16-bit hex value xxxx\n var rest = from_codepoint_list(cps.slice(pos + 2)),\n mo = /^[0-9a-fA-F]{0,4}/.exec(rest),\n xx = mo ? mo[0] : ''\n if(mo && mo[0].length == 4){\n var cp = parseInt(mo[0], 16)\n return {\n type: 'u',\n ord: cp,\n char: chr(cp),\n length: 2 + mo[0].length\n }\n }\n fail('incomplete escape \\\\u' + xx, pos)\n }else if(special == LETTERS.U){\n // \\Uxxxxxxxx = character with 32-bit hex value xxxxxxxx\n var rest = from_codepoint_list(cps.slice(pos + 2)),\n mo = /^[0-9a-fA-F]{0,8}/.exec(rest),\n xx = mo ? mo[0] : ''\n if(mo && mo[0].length == 8){\n var cp = parseInt(mo[0], 16)\n if(cp > 0x10FFFF){\n fail(`bad escape \\\\U${mo[0]}`, pos)\n }\n return {\n type: 'U',\n ord: cp,\n char: chr(cp),\n length: 2 + mo[0].length\n }\n }\n fail('incomplete escape \\\\U' + xx, pos)\n }else{\n // octal ?\n // If the first digit of number is 0, or number is 3 octal digits\n // long, it will not be interpreted as a group match, but as the\n // character with octal value number\n var rest = from_codepoint_list(cps.slice(pos + 1)),\n mo = /^[0-7]{3}/.exec(rest)\n if(in_charset){\n try{\n var res = $B.test_escape(rest, -1)\n if(res){\n return {\n type: 'u',\n ord: res[0].codePointAt(0),\n char: res[0],\n length: res[1]\n }\n }\n }catch(err){\n // ignore\n }\n }\n if(mo == null){\n mo = /^0[0-7]*/.exec(rest)\n }\n if(mo){\n var octal_value = parseInt(mo[0], 8)\n if(octal_value > 0o377){\n fail(`octal escape value \\\\` +\n `${mo[0]} outside of range 0-0o377`, pos)\n }\n return {\n type: 'o',\n ord: octal_value,\n char: chr(octal_value),\n length: 1 + mo[0].length\n }\n }\n var mo = /^\\d{1,2}/.exec(rest) // backref is at most 99\n if(mo){\n return {\n type: 'backref',\n value: parseInt(mo[0]),\n length: 1 + mo[0].length\n }\n }\n var trans = {a: chr(7), f: '\\f', n: '\\n', r: '\\r', t: '\\t', v: '\\v'},\n res = trans[chr(special)]\n if(res){\n return ord(res)\n }\n if(chr(special).match(/[a-zA-Z]/)){\n fail(\"bad escape \\\\\" + chr(special), pos)\n }else{\n return special\n }\n }\n}\n\nfunction check_character_range(t, positions){\n // Check if last 2 items in t are a valid character range\n var start = t[t.length - 2],\n end = t[t.length - 1]\n if(start instanceof CharacterClass || end instanceof CharacterClass){\n fail(`bad character range ${start}-${end}`,\n positions[positions.length - 2])\n }else if(end < start){\n fail(`bad character range ${start}-${end}`,\n positions[positions.length - 2])\n }\n t.splice(t.length - 2, 2, {\n type: 'character_range',\n start: start,\n end: end,\n ord: [start.ord, end.ord]\n })\n}\n\nfunction parse_character_set(text, pos, is_bytes){\n // Parse character set starting at position \"pos\" in \"text\"\n // pos is the position of the leading \"[\"\n var start = pos,\n result = {items: []},\n positions = []\n pos++\n if(text[pos] == CARET){\n result.neg = true\n pos++\n }else if(text[pos] == BRACKET_CLOSE){\n // a leading ] is the character \"]\", not the set end\n result.items.push(']')\n positions.push(pos)\n pos++\n }else if(text[pos] == BRACKET_OPEN){\n // send FutureWarning\n warn(_b_.FutureWarning, \"Possible nested set\", pos, text)\n }\n var range = false\n while(pos < text.length){\n var cp = text[pos],\n char = chr(cp)\n if(char == ']'){\n if(pos == start + 2 && result.neg){\n // in \"[^]]\", the first ] is the character \"]\"\n result.items.push(']')\n }else{\n return [result, pos]\n }\n }\n if(char == '\\\\'){\n var escape = escaped_char({\n codepoints: text,\n pos,\n in_charset: true,\n is_bytes\n })\n if(typeof escape == \"number\"){\n var s = chr(escape)\n escape = {\n ord: escape,\n length: 2,\n toString: function(){\n return s\n }\n }\n }\n if(escape.type == \"num\"){\n // [\\9] is invalid\n fail(\"bad escape 1 \\\\\" +\n escape.value.toString()[0], pos)\n }\n result.items.push(escape)\n positions.push(pos)\n if(range){\n check_character_range(result.items, positions)\n }\n range = false\n pos += escape.length\n }else if(char == '-'){\n // Character range, or character \"-\"\n if(pos == start + 1 ||\n (result.neg && pos == start + 2) ||\n pos == text.length - 2 || // [a-]\n range ||\n (result.items.length > 0 &&\n result.items[result.items.length - 1].type ==\n \"character_range\")){\n result.items.push({\n ord: cp,\n char,\n toString: function(){\n return this.char\n }\n })\n if(text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set difference\", pos, text)\n }\n pos++\n if(range){\n check_character_range(result.items, positions)\n }\n range = false\n }else{\n range = true\n if(text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set difference\", pos, text)\n }\n pos++\n }\n }else{\n positions.push(pos)\n result.items.push({\n ord: cp,\n char,\n toString: function(){\n return this.char\n }\n })\n if(range){\n check_character_range(result.items, positions)\n }\n range = false\n // FutureWarning for consecutive \"&\", \"|\" or \"~\"\n if(char == \"&\" && text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set intersection\", pos, text)\n }else if(char == \"|\" && text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set union\", pos, text)\n }else if(char == \"~\" && text[pos + 1] == cp){\n warn(_b_.FutureWarning, \"Possible set symmetric difference\",\n pos, text)\n }\n pos++\n }\n }\n fail(\"unterminated character set\", start)\n}\n\nfunction* tokenize(pattern, type, _verbose){\n // pattern is a list of codepoints\n var is_bytes = type == \"bytes\"\n // verbose_stack is the stack of verbose state for each group in the regex\n var verbose_stack = [_verbose],\n verbose = _verbose,\n parenth_pos\n var pos = 0\n while(pos < pattern.length){\n var cp = pattern[pos],\n char = String.fromCharCode(cp)\n if(verbose){\n // current group is in verbose mode\n if(char == \"#\"){\n // skip until next line feed\n while(pos < pattern.length && pattern[pos] != 10){\n pos++\n }\n pos++\n continue\n }else{\n while(pos < pattern.length &&\n [9, 10, 11, 12, 13, 32].indexOf(pattern[pos]) > -1){\n pos++\n }\n }\n cp = pattern[pos]\n if(cp === undefined){\n break\n }\n char = String.fromCharCode(cp)\n if(char == '#'){\n continue\n }\n }\n if(char == '('){\n parenth_pos = pos\n if(pattern[pos + 1] == QUESTION_MARK){\n if(pattern[pos + 2] == LETTERS.P){\n if(pattern[pos + 3] == INF){\n var name = [],\n i = pos + 4\n while(i < pattern.length){\n if(pattern[i] == SUP){\n break\n }else if(pattern[i] == PARENTH_CLOSE){\n fail(\"missing >, unterminated name\", pos)\n }\n name.push(pattern[i])\n i++\n }\n var sname = StringObj.from_codepoints(name)\n validate_group_name(sname, pos, is_bytes)\n name = sname\n if(i == pattern.length){\n fail(\"missing >, unterminated name\", pos)\n }\n yield new Group(pos, {type: 'name_def', value: name})\n verbose_stack.push(verbose)\n pos = i + 1\n continue\n }else if(pattern[pos + 3] == EQUAL){\n var name = [],\n i = pos + 4\n while(i < pattern.length){\n if(pattern[i] == PARENTH_CLOSE){\n break\n }\n name.push(pattern[i])\n i++\n }\n name = StringObj.from_codepoints(name)\n validate_group_name(name, pos, is_bytes)\n if(i == pattern.length){\n fail(\"missing ), unterminated name\", pos)\n }\n yield new BackReference(pos, 'name', name.string)\n pos = i + 1\n continue\n }else if(pattern[pos + 3] === undefined){\n fail(\"unexpected end of pattern\", pos)\n }else{\n fail(\"unknown extension ?P\" + chr(pattern[pos + 3]), pos)\n }\n }else if(pattern[pos + 2] == PARENTH_OPEN){\n var ref = [],\n i = pos + 3\n while(i < pattern.length){\n if(pattern[i] == PARENTH_CLOSE){\n break\n }\n ref.push(pattern[i])\n i++\n }\n var sref = StringObj.from_codepoints(ref)\n if(sref.string.match(/^\\d+$/)){\n ref = parseInt(sref.string)\n }else{\n validate_num_or_name(sref, pos, is_bytes)\n ref = sref.string\n }\n if(i == pattern.length){\n fail(\"missing ), unterminated name\", pos)\n }\n yield new ConditionalBackref(pos, ref)\n pos = i + 1\n continue\n }else if(pattern[pos + 2] == EQUAL){\n // (?=...) : lookahead assertion\n yield new Group(pos, {type: 'lookahead_assertion'})\n verbose_stack.push(verbose)\n pos += 3\n continue\n }else if(pattern[pos + 2] == EXCLAMATION_MARK){\n // (?!...) : negative lookahead assertion\n yield new Group(pos, {type: 'negative_lookahead_assertion'})\n verbose_stack.push(verbose)\n pos += 3\n continue\n }else if(from_codepoint_list(pattern.slice(pos + 2, pos + 4)) == ' -1){\n if(pattern[pos + 2] == MINUS){\n var on_flags = [],\n has_off = true,\n off_flags = []\n pos += 3\n }else{\n var on_flags = [chr(pattern[pos + 2])],\n has_off = false,\n off_flags = [],\n auL = auL_flags.indexOf(pattern[pos + 2]) > -1 ?\n 1 : 0,\n closed = false\n pos += 3\n while(pos < pattern.length){\n if(flags.indexOf(pattern[pos]) > -1){\n if(auL_flags.indexOf(pattern[pos]) > -1){\n auL++\n if(auL > 1){\n fail(\"bad inline flags: flags 'a', 'u'\" +\n \" and 'L' are incompatible\", pos)\n }\n }\n on_flags.push(chr(pattern[pos]))\n pos++\n }else if(pattern[pos] == MINUS){\n has_off = true\n closed = true\n pos++\n break\n }else if(String.fromCharCode(pattern[pos]).\n match(/[a-zA-Z]/)){\n fail(\"unknown flag\", pos)\n }else if(pattern[pos] == PARENTH_CLOSE){\n closed = true\n break\n }else if(pattern[pos] == COLON){\n yield new Group(pos, {name: \"Group\", type: \"flags\"})\n verbose_stack.push(verbose)\n closed = true\n break\n }else{\n fail(\"missing -, : or )\", pos)\n }\n }\n if(! closed){\n fail(\"missing -, : or )\", pos)\n }\n }\n if(has_off){\n while(pos < pattern.length){\n if(flags.indexOf(pattern[pos]) > -1){\n if(auL_flags.indexOf(pattern[pos]) > -1){\n fail(\"bad inline flags: cannot turn off \" +\n \"flags 'a', 'u' and 'L'\", pos)\n }\n if(on_flags.indexOf(chr(pattern[pos])) > -1){\n fail(\"bad inline flags: flag turned on and off\", pos)\n }\n off_flags.push(chr(pattern[pos]))\n pos++\n }else if(pattern[pos] == COLON){\n yield new Group(pos, {name: \"Group\", type: \"flags\"})\n verbose_stack.push(verbose)\n break\n }else if(String.fromCharCode(pattern[pos]).\n match(/[a-zA-Z]/)){\n fail(\"unknown flag\", pos)\n }else if(off_flags.length == 0){\n fail(\"missing flag\", pos)\n }else{\n fail(\"missing :\", pos)\n }\n }\n if(off_flags.length == 0){\n fail(\"missing flag\", pos)\n }\n }\n if(has_off && pattern[pos] != COLON){\n fail(\"missing :\", pos)\n }\n if(on_flags.length == 0 && off_flags.length == 0){\n fail(\"missing flag\", pos)\n }\n var set_flags = new SetFlags(flags_start,\n {on_flags, off_flags})\n\n yield set_flags\n // reset verbose\n if(on_flags.indexOf('x') > -1){\n verbose = true\n verbose_stack.push(verbose)\n }\n if(off_flags.indexOf('x') > -1){\n verbose = false\n }\n if(! closed){\n node = set_flags\n }\n pos++\n }else if(pattern[pos + 2] == ord('#')){\n pos += 3\n while(pos < pattern.length){\n if(pattern[pos] == PARENTH_CLOSE){\n break\n }\n pos++\n }\n if(pos == pattern.length){\n fail(\"missing ), unterminated comment\", pos)\n }\n pos++\n continue\n }else{\n fail(\"unknown extension ?\" + _b_.chr(pattern[pos + 2]),\n pos)\n }\n }else{\n yield new Group(pos)\n verbose_stack.push(verbose)\n pos++\n }\n }else if(cp == PARENTH_CLOSE){\n yield new GroupEnd(pos)\n verbose_stack.pop()\n verbose = $last(verbose_stack)\n pos++\n }else if(cp == BACKSLASH){\n var escape = escaped_char({codepoints: pattern, pos, is_bytes})\n if(escape instanceof CharacterClass){\n yield escape\n pos += escape.length\n }else if(escape.char !== undefined){\n yield new Char(pos, escape.ord)\n pos += escape.length\n }else if(escape.type == \"backref\"){\n var len = escape.length\n if(escape.value.length > 2){\n escape.value = escape.value.substr(0, 2)\n len = 2\n }\n yield new BackReference(pos, \"num\", escape.value)\n pos += len\n }else if(typeof escape == \"number\"){\n // eg \"\\.\"\n var esc = new Char(pos, escape)\n esc.escaped = true\n yield esc\n pos += 2\n }else{\n yield new Char(pos, escape)\n pos += escape.length\n }\n }else if(cp == BRACKET_OPEN){\n // Set of characters\n var set,\n end_pos\n [set, end_pos] = parse_character_set(pattern, pos, is_bytes)\n yield new CharacterSet(pos, set)\n pos = end_pos + 1\n }else if('+?*'.indexOf(char) > -1){\n yield new Repeater(pos, char)\n pos++\n }else if(cp == BRACE_OPEN){\n var reps = /\\{(\\d*)((,)(\\d*))?\\}/.exec(\n from_codepoint_list(pattern.slice(pos)))\n if(reps && reps[0] != '{}'){\n if(reps[1] == \"\"){\n var limits = [0]\n }else{\n var limits = [parseInt(reps[1])]\n }\n if(reps[4] !== undefined){\n if(reps[4] == \"\"){\n var max = Number.POSITIVE_INFINITY\n }else{\n var max = parseInt(reps[4])\n }\n limits.push(max)\n }\n yield new Repeater(pos, limits)\n pos += reps[0].length\n }else if(pattern[pos + 1] == BRACE_CLOSE){\n // {} is the characters \"{\" and \"}\"\n yield new Char(pos, BRACE_OPEN)\n pos++\n }else{\n yield new Char(pos, BRACE_OPEN)\n pos++\n }\n }else if(cp == OR){\n yield new Or(pos)\n pos++\n }else if(cp == DOT){\n yield new CharacterClass(pos, cp, 1)\n pos++\n }else if(cp == CARET){\n yield new StringStart(pos)\n pos++\n }else if(cp == DOLLAR){\n yield new StringEnd(pos)\n pos++\n }else{\n yield new Char(pos, cp)\n pos++\n }\n }\n}\n\nfunction transform_repl(data, pattern){\n // data.repl is a StringObj instance\n var repl = data.repl.string\n repl = repl.replace(/\\\\n/g, '\\n')\n repl = repl.replace(/\\\\r/g, '\\r')\n repl = repl.replace(/\\\\t/g, '\\t')\n repl = repl.replace(/\\\\b/g, '\\b')\n repl = repl.replace(/\\\\v/g, '\\v')\n repl = repl.replace(/\\\\f/g, '\\f')\n repl = repl.replace(/\\\\a/g, '\\x07')\n // detect backreferences\n var pos = 0,\n escaped = false,\n br = false,\n repl1 = \"\",\n has_backref = false\n while(pos < repl.length){\n br = false\n if(repl[pos] == \"\\\\\"){\n escaped = ! escaped\n if(escaped){\n pos++\n continue\n }\n }else if(escaped){\n escaped = false\n var mo = /^\\d+/.exec(repl.substr(pos))\n if(mo){\n var cps = to_codepoint_list(repl)\n var escape = escaped_char({\n codepoints: cps,\n pos: pos - 1,\n is_bytes: cps.type == \"bytes\"\n })\n if(escape.type == \"o\"){\n if(escape.ord > 0o377){\n fail(`octal escape value \\\\${mo[0]} ` +\n \" outside of range 0-0o377\", pos)\n }\n repl1 += escape.char\n pos += escape.length - 1\n continue\n }else if(escape.type != \"backref\"){\n var group_num = mo[0].substr(0,\n Math.min(2, mo[0].length))\n fail(`invalid group reference ${group_num}`, pos)\n }else{\n // only keep first 2 digits\n var group_num = mo[0].substr(0,\n Math.min(2, mo[0].length))\n // check that pattern has the specified group num\n if(pattern.groups === undefined){\n throw _b_.AttributeError.$factory(\"$groups\")\n }\n if(pattern.groups[group_num] === undefined){\n fail(`invalid group reference ${group_num}`,\n pos)\n }else{\n mo[0] = group_num\n }\n }\n if(! has_backref){\n var parts = [repl.substr(0, pos - 1),\n parseInt(mo[0])]\n }else{\n parts.push(repl.substring(next_pos, pos - 1))\n parts.push(parseInt(mo[0]))\n }\n has_backref = true\n var next_pos = pos + mo[0].length\n br = true\n pos += mo[0].length\n }else if(repl[pos] == \"g\"){\n pos++\n if(repl[pos] != '<'){\n fail(\"missing <\", pos)\n }\n pos++\n mo = /(.*?)>/.exec(repl.substr(pos))\n if(mo){\n if(mo[1] == \"\"){\n pos += mo[0].length\n fail(\"missing group name\", pos - 1)\n }\n var group_name = mo[1]\n if(group_name == '0'){\n // The backreference \\g<0> substitutes in the entire\n // substring matched by the RE.\n }else if(/^\\d+$/.exec(group_name)){\n if(pattern.groups[group_name] === undefined){\n fail(`invalid group reference ${group_name}`,\n pos)\n }\n }else{\n try{\n var group_num = _b_.int.$factory(group_name)\n if(group_num < 0){\n fail(`bad character in group name ` +\n `'${group_name}' at position ${pos}`, pos)\n }\n warn(_b_.DeprecationWarning,\n `bad character in group name '${group_name}' ` +\n `at position ${pos}`)\n mo[1] = group_name = group_num + ''\n }catch(err){\n if(! _b_.str.isidentifier(group_name)){\n var cps = to_codepoint_list(group_name)\n if(! $B.is_XID_Start(cps[0])){\n fail(\"bad character in group name '\" +\n group_name + \"'\", pos)\n }else{\n for(cp of cps.slice(1)){\n if(! $B.is_XID_Continue(cp)){\n fail(\"bad character in group name '\" +\n group_name + \"'\", pos)\n }\n }\n }\n }else if(data.type == \"bytes\" && ! is_ascii(group_name)){\n var b = _b_.bytes.$factory(group_name, 'latin-1'),\n s = _b_.bytes.decode(b, 'ascii', 'backslashreplace')\n warn(_b_.DeprecationWarning,\n `bad character in group name '${s}'` +\n ` at position ${pos}`)\n }\n }\n if(pattern.groups[group_name] === undefined){\n throw _b_.IndexError.$factory(\n `unknown group name '${group_name}'`,\n pos)\n }\n }\n if(! has_backref){\n var parts = [repl.substr(0, pos - 3),\n mo[1]]\n }else{\n parts.push(repl.substring(next_pos, pos - 3))\n parts.push(mo[1])\n }\n has_backref = true\n var next_pos = pos + mo[0].length\n br = true\n pos = next_pos\n }else{\n if(repl.substr(pos).length > 0){\n fail(\"missing >, unterminated name\", pos)\n }else{\n fail(\"missing group name\", pos)\n }\n }\n }else{\n if(/[a-zA-Z]/.exec(repl[pos])){\n fail(\"unknown escape\", pos)\n }\n pos += repl[pos]\n }\n }\n if(! br){\n repl1 += repl[pos]\n pos ++\n }\n }\n data.repl1 = repl1\n if(has_backref){\n parts.push(repl.substr(next_pos))\n data.repl = function(bmo){\n var mo = bmo.mo,\n res = parts[0],\n groups = mo.$groups,\n s = mo.string,\n group,\n is_bytes = s.type == 'bytes'\n for(var i = 1, len = parts.length; i < len; i += 2){\n if(parts[i] == 0){\n var x = s.substring(mo.start, mo.end)\n if(is_bytes){\n x = _b_.bytes.decode(x, 'latin-1')\n }\n res += x\n }else if(groups[parts[i]] === undefined){\n if(mo.node.$groups[parts[i]] !== undefined){\n // group is defined in the RE, but didn't contribute\n // to the match\n // groups[parts[i]] = ''\n }else{\n // group is not defined in the RE\n pos++\n group_num = parts[i].toString().substr(0, 2)\n fail(`invalid group reference ${group_num}`, pos)\n }\n }else{\n group = groups[parts[i]]\n var x = s.substring(group.start, group.end)\n if(is_bytes){\n x = _b_.bytes.decode(x, 'latin-1')\n }\n res += x\n }\n res += parts[i + 1]\n }\n return res\n }\n }else{\n data.repl = new StringObj(repl)\n }\n return data\n}\n\n\n\nvar Flag = $B.make_class(\"Flag\",\n function(value){\n return {\n __class__: Flag,\n value\n }\n }\n)\n\nFlag.__and__ = function(self, other){\n if(other.__class__ === Flag){\n return Flag.$factory(self.value & other.value)\n }else if(typeof other == \"number\" || typeof other == \"boolean\"){\n return Flag.$factory(self.value & other)\n }\n return _b_.NotImplemented\n}\n\nFlag.__index__ = function(self){\n return self.value\n}\n\nFlag.__invert__ = function(self){\n return Flag.$factory(~self.value)\n}\n\nFlag.__eq__ = function(self, other){\n return self.value == other.value\n}\n\nFlag.__or__ = function(self, other){\n if(other.__class__ === Flag){\n return Flag.$factory(self.value | other.value)\n }else if(typeof other == \"number\" || typeof other == \"boolean\"){\n return Flag.$factory(self.value | other)\n }\n return _b_.NotImplemented\n}\n\nFlag.__rand__ = function(self, other){\n if(typeof other == \"number\" || $B.$isinstance(other, _b_.int)){\n if(other == 0){\n return false // Flag.$factory(self.value)\n }\n return self.value & other\n }\n return _b_.NotImplemented\n}\n\nFlag.__ror__ = function(self, other){\n if(typeof other == \"number\" || $B.$isinstance(other, _b_.int)){\n if(other == 0){\n return self.value\n }\n return self.value | other\n }\n return _b_.NotImplemented\n}\n\nFlag.__repr__ = Flag.__str__ = function(self){\n if(self.value == 0){\n return \"re.none\"\n }\n var inverted = self.value < 0\n\n var t = [],\n value = inverted ? ~self.value : self.value\n for(var flag in inline_flags){\n if(value & inline_flags[flag].value){\n t.push('re.' + flag_names[flag])\n value &= ~inline_flags[flag].value\n }\n }\n if(value > 0){\n t.push('0x' + value.toString(16))\n }\n var res = t.join('|')\n if(inverted){\n if(t.length > 1){\n return '~(' + res + ')'\n }else{\n return '~' + res\n }\n }\n return res\n}\n\nFlag.__xor__ = function(self, other){\n return Flag.$factory(self.value ^ other.value)\n}\n\n$B.set_func_names(Flag, \"re\")\n\nvar no_flag = {}\n\nvar Scanner = $B.make_class(\"Scanner\",\n function(pattern, string, pos, endpos){\n var $ = $B.args('__init__', 4,\n {pattern: null, string: null, pos: null, endpos:null},\n ['pattern', 'string', 'pos', 'endpos'],\n arguments, {pos: 0, endpos: _b_.None}, null, null),\n endpos = endpos === _b_.None ? $.string.length : endpos\n return {\n __class__: Scanner,\n $string: $.string,\n pattern: $.pattern,\n pos: $.pos,\n endpos\n }\n }\n)\n\nScanner.match = function(self){\n return Pattern.match(self.pattern, self.$string)\n}\n\nScanner.search = function(self){\n if(! self.$iterator){\n self.$iterator = module.finditer(self.pattern, self.$string)\n }\n // return last match\n var mo = _b_.None\n for(mo of self.$iterator.js_gen){\n // set mo\n }\n return mo\n}\n\nvar GroupIndex = $B.make_class(\"GroupIndex\",\n function(self, _default){\n var res = $B.empty_dict()\n res.__class__ = GroupIndex\n for(var key in self.$groups){\n if(isNaN(parseInt(key))){\n _b_.dict.$setitem(res, key, self.$groups[key].num)\n }\n }\n return res\n }\n)\nGroupIndex.__mro__ = [_b_.dict, _b_.object]\nGroupIndex.__setitem__ = function(){\n throw _b_.TypeError.$factory(\"read only\")\n}\n\n$B.set_func_names(GroupIndex, \"re\")\n\nvar Pattern = $B.make_class(\"Pattern\",\n function(pattern){\n var nb_groups = 0\n for(var key in pattern.groups){\n if(isFinite(key)){\n nb_groups++\n }\n }\n return {\n __class__: Pattern,\n pattern: pattern.text,\n groups: nb_groups,\n flags: pattern.flags,\n $groups: pattern.groups,\n $pattern: pattern\n }\n }\n)\n\nPattern.__copy__ = function(self){\n return self\n}\n\nPattern.__deepcopy__ = function(self){\n return self\n}\n\nPattern.__eq__ = function(self, other){\n if(other.$pattern && self.$pattern.type != other.$pattern.$type){\n // warn(_b_.BytesWarning, \"cannot compare str and bytes pattern\", 1)\n }\n return self.pattern == other.pattern &&\n self.flags.value == other.flags.value\n}\n\nPattern.__hash__ = function(self){\n // best effort ;-)\n return _b_.hash(self.pattern) + self.flags.value\n}\n\nPattern.__new__ = Pattern.$factory\n\nPattern.__reduce__ = function(self){\n return Pattern.__reduce_ex__(self, 4)\n}\n\nPattern.__reduce_ex__ = function(self, protocol){\n var res = _reconstructor,\n state = [self.__class__].concat(self.__class__.__mro__)\n var d = $B.empty_dict()\n _b_.dict.$setitem(d, 'pattern', self.pattern)\n _b_.dict.$setitem(d, 'flags', self.flags.value)\n state.push(d)\n return $B.fast_tuple([res, $B.fast_tuple(state)])\n}\n\nfunction _reconstructor(cls, base, state){\n var pattern = _b_.dict.$getitem(state, 'pattern'),\n flags = Flag.$factory(_b_.dict.$getitem(state, 'flags'))\n return module.compile(pattern, flags)\n}\n\nPattern.__repr__ = Pattern.__str__ = function(self){\n var text = self.$pattern.text,\n s = text\n if(self.$pattern.type == \"bytes\"){\n s = _b_.str.$factory(_b_.str.encode(s, 'latin-1'))\n }else{\n s = _b_.repr(s)\n }\n s = s.substr(0, 200)\n var res = `re.compile(${s}`,\n flags = self.$pattern.flags\n if(flags === no_flag){\n return res + ')'\n }\n // mask UNICODE flag\n if(flags.__class__ === Flag){\n // copy flag, otherwise U.value would become 0\n flags = Flag.$factory(flags.value)\n flags.value &= ~U.value\n }else if(typeof flags == \"number\"){\n flags &= ~U.value\n }\n if(flags != 0 && flags.value != 0){\n res += `, ${_b_.str.$factory(flags)}`\n }\n return res + ')'\n}\n\nPattern.findall = function(self){\n var iter = Pattern.finditer.apply(null, arguments).js_gen,\n res = []\n\n while(true){\n var next = iter.next()\n if(next.done){\n return $B.$list(res)\n }\n var bmo = next.value,\n mo = bmo.mo,\n groups = MatchObject.groups(bmo)\n\n // replace None by the empty string\n for(var i = 0, len = groups.length; i < len; i++){\n groups[i] = groups[i] === _b_.None ? \"\" : groups[i]\n }\n if(groups.length > 0){\n if(groups.length == 1){\n res.push(groups[0])\n }else{\n res.push($B.fast_tuple(groups))\n }\n }else{\n res.push(mo.string.substring(mo.start, mo.end))\n }\n }\n}\n\nPattern.finditer = function(self){\n var $ = $B.args(\"finditer\", 4,\n {self: null, string: null, pos: null, endpos: null},\n 'self string pos endpos'.split(' '), arguments,\n {pos: 0, endpos: _b_.None}, null, null)\n var data = prepare({string: $.string})\n var endpos = $.endpos === _b_.None ? data.string.length : $.endpos\n return $B.generator.$factory(iterator)(self.$pattern, data.string,\n self.flags, $.string, $.pos, endpos)\n}\n\nPattern.fullmatch = function(self, string){\n var $ = $B.args(\"match\", 4,\n {self: null, string: null, pos: null, endpos: null},\n [\"self\", \"string\", \"pos\", \"endpos\"], arguments,\n {pos: 0, endpos: _b_.None}, null, null)\n if($.endpos === _b_.None){\n $.endpos = $.string.length\n }\n var data = prepare({string: $.string})\n if(self.$pattern.type != data.string.type){\n throw _b_.TypeError.$factory(\"not the same type for pattern \" +\n \"and string\")\n }\n var fullmatch_pattern = create_fullmatch_pattern($.self.$pattern)\n var mo = match(fullmatch_pattern, data.string, $.pos, $.endpos)\n if(mo && mo.end - mo.start == $.endpos - $.pos){\n return MatchObject.$factory(mo)\n }else{\n return _b_.None\n }\n}\n\nPattern.groupindex = {\n __get__: function(self){\n return GroupIndex.$factory(self)\n }\n}\n\nPattern.match = function(self, string){\n var $ = $B.args(\"match\", 4,\n {self: null, string: null, pos: null, endpos: null},\n [\"self\", \"string\", \"pos\", \"endpos\"], arguments,\n {pos: 0, endpos: _b_.None}, null, null)\n if($.endpos === _b_.None){\n $.endpos = $.string.length\n }\n var data = prepare({string: $.string})\n if(self.$pattern.type != data.string.type){\n throw _b_.TypeError.$factory(\"not the same type for pattern \" +\n \"and string\")\n }\n var mo = match($.self.$pattern, data.string, $.pos,\n $.endpos)\n return mo ? MatchObject.$factory(mo) : _b_.None\n}\n\nPattern.scanner = function(self, string, pos, endpos){\n return Scanner.$factory.apply(null, arguments) // self, string, pos, endpos)\n}\n\nPattern.search = function(self, string){\n var $ = $B.args(\"match\", 4,\n {self: null, string: null, pos: null, endpos: null},\n [\"self\", \"string\", \"pos\", \"endpos\"], arguments,\n {pos: 0, endpos: _b_.None}, null, null)\n var data = prepare({string: $.string})\n if(self.$pattern.type != data.string.type){\n throw _b_.TypeError.$factory(\"not the same type for pattern \" +\n \"and string\")\n }\n if($.endpos === _b_.None){\n $.endpos = data.string.length\n }\n var pos = $.pos\n while(pos <= $.endpos){\n var mo = match(self.$pattern, data.string, pos)\n if(mo){\n return MatchObject.$factory(mo)\n }else{\n pos++\n }\n }\n return _b_.None\n}\n\nPattern.split = function(){\n return module.split.apply(null, arguments)\n}\n\nPattern.sub = function(){\n var $ = $B.args(\"match\", 4,\n {self: null, repl: null, string: null, count: null},\n \"self repl string count\".split(' '), arguments,\n {count: 0}, null, null)\n var data = prepare({string: $.string})\n if($.self.$pattern.type != data.string.type){\n throw _b_.TypeError.$factory(\"not the same type for pattern \" +\n \"and string\")\n }\n\n return module.sub($.self, $.repl, $.string, $.count)\n}\n\n$B.set_func_names(Pattern, \"re\")\n\nfunction Node(parent){\n this.parent = parent\n this.items = []\n}\n\nNode.prototype.add = function(item){\n this.items.push(item)\n item.parent = this\n}\n\nNode.prototype.fixed_length = function(){\n // Return the sum of items lengths if fixed, else undefined\n if(this.repeat){\n return false\n }\n var len = 0\n for(var item of this.items){\n if(item.fixed_length === undefined){\n console.log(\"pas de fixed length\", item)\n alert()\n }\n var sublen = item.fixed_length()\n if(sublen === false){\n return false\n }\n len += sublen\n }\n return len\n}\n\nfunction get_top(node){\n var top = node.parent\n while(top.parent){\n top = top.parent\n }\n return top\n}\n\nvar BackReference = function(pos, type, value){\n // for \"\\number\"\n this.name = \"BackReference\"\n this.pos = pos\n this.type = type // \"name\" or \"num\"\n this.value = value\n this.groups = []\n}\n\nBackReference.prototype.fixed_length = function(){\n // Return length of referenced group if it is fixed, else undefined\n if(this.repeat){\n return undefined\n }\n var group = this.get_group()\n if(group.fixed_length === undefined){\n console.log(\"group\", group, \"no fixed length\")\n }\n return group === undefined ? false : group.fixed_length()\n}\n\nBackReference.prototype.get_group = function(){\n var top = get_top(this)\n return top.$groups[this.value]\n}\n\nBackReference.prototype.match = function(string, pos, endpos, groups){\n this.repeat = this.repeat || {min: 1, max: 1}\n\n var group = groups[this.value]\n if(group === undefined){\n if(this.repeat.min == 0){\n return {\n nb_min: 0,\n nb_max: 0\n }\n }\n return false\n }\n\n // Get the codepoints matched by the referenced group\n group_cps = string.codepoints.slice(group.start, group.end)\n\n // search (repetitions of) the matched group codepoints\n var _pos = pos,\n nb = 0,\n group_len = group_cps.length,\n flag,\n cp\n while(string.cp_at(_pos) !== undefined && nb < this.repeat.max){\n flag = true\n for(var i = 0; i < group_len; i++){\n cp = string.cp_at(_pos + i)\n if(cp != group_cps[i]){\n flag = false\n break\n }\n }\n if(flag){\n nb++\n _pos += group_len\n }else{\n break\n }\n }\n if(nb >= this.repeat.min){\n // Returns the accepted minimum and maximum number of repeats\n // and the length of each repeat\n return {\n nb_min: this.repeat.min,\n nb_max: nb,\n group_len\n }\n }\n return false\n}\n\nBackReference.prototype.toString = function(){\n return \"BackRef to group\" + this.value\n}\n\nvar Case = function(){\n this.name = \"Case\"\n this.items = []\n this.groups = []\n this.text = 'Case '\n}\n\nCase.prototype.add = function(item){\n this.items.push(item)\n item.parent = this\n}\n\nCase.prototype.fixed_length = function(){\n var len\n for(var item of this.items){\n var fl = item.fixed_length()\n if(fl === false){\n return false\n }else if(len === undefined){\n len = fl\n }else{\n len += fl\n }\n }\n return len\n}\n\nCase.prototype.toString = function(){\n var res = 'Case '\n res += this.items.map(x => x + '').join(' ')\n return this.text = res\n}\n\nvar Choice = function(){\n this.type = \"choice\"\n this.items = []\n this.groups = []\n}\n\nChoice.prototype.add = Node.prototype.add\n\nChoice.prototype.fixed_length = function(){\n var len\n for(var item of this.items){\n var fl = item.fixed_length()\n if(fl === false){\n return false\n }else if(len === undefined){\n len = fl\n }else if(len != fl){\n return false\n }\n }\n return len\n}\n\nChoice.prototype.toString = function(){\n return 'Choice'\n}\n\nvar EmptyString = {\n toString: function(){\n return ''\n },\n match: function(string, pos, endpos){\n return {nb_min: 0, nb_max: 0}\n },\n fixed_length: function(){\n return 1\n },\n length: 0\n },\n Flags = function(flags){\n this.flags = flags\n },\n GroupEnd = function(pos){\n this.name = \"GroupEnd\"\n this.pos = pos\n this.text = ')'\n this.toString = function(){\n return '[end of group #' + this.group.num + ']'\n }\n },\n Or = function(pos){\n this.name = \"Or\"\n this.pos = pos\n this.text = '|'\n this.toString = function(){\n return '|'\n }\n },\n Repeater = function(pos, op){\n this.name = \"Repeater\"\n this.pos = pos\n this.op = op\n }\n\nfunction cased_cps(cp, ignore_case, ascii){\n // If cp is the codepoint of a cased Unicode character, return the list\n // of the codepoints that match the character in a case-insensitive way\n\n // ignore_case = this.flags && this.flags.value & IGNORECASE.value\n // ascii = this.flags.value & ASCII.value\n var cps,\n char = $B.codepoint2jsstring(cp)\n if(! ignore_case){\n return [cp]\n }\n if(ascii){\n // only test ASCII letters\n ignore_case = ignore_case && (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z'))\n }\n if(ignore_case){\n var char_up = char.toUpperCase(),\n char_low = char.toLowerCase(),\n cps = new Set([cp, $B.jsstring2codepoint(char_low),\n $B.jsstring2codepoint(char_up)])\n // special cases\n if(char.toLowerCase() == \"k\"){\n cps.add(0x212a) // Kelvin sign\n }\n if(cp == 0x212a){\n cps.add(ord('k'))\n cps.add(ord('K'))\n }\n if(char.toLowerCase() == \"s\"){\n cps.add(0x017f) // (Latin small letter long s)\n }\n if(cp == 0x017f){\n cps.add(ord('s'))\n cps.add(ord('S'))\n }\n if(char.toLowerCase() == 'i'){\n cps.add(0x0130) // (Latin capital letter I with dot above)\n cps.add(0x0131) // (Latin small letter dotless i)\n }\n if(cp == 0x0130 || cp == 0x0131){\n cps.add(ord('i'))\n cps.add(ord('I'))\n }\n return Array.from(cps)\n }else{\n cps = [cp]\n }\n return cps\n}\n\nvar Char = function(pos, cp, groups){\n // character in a regular expression or in a character set\n // pos : position of the character in the pattern string\n // cp : the character's codepoint\n // groups (optional) : the groups that contain the character\n this.pos = pos\n this.cp = cp\n this.char = chr(this.cp)\n this.text = this.char\n}\n\nChar.prototype.fixed_length = function(){\n if(this.repeat){\n return this.repeat.min\n }\n return this.char === EmptyString ? 0 : 1\n}\n\nChar.prototype.match = function(string, pos, endpos){\n // Returns {pos1, pos2} such that \"this\" matches all the substrings\n // string[pos:i] with pos1 <= i < pos2, or false if no match\n this.repeat = this.repeat || {min: 1, max: 1}\n\n var i = 0\n\n // browse string codepoints until they don't match, or the number of\n // matches is above the maximum allowed\n if(this.flags){\n if(this.flags.value & ASCII.value){\n if(this.cp > 127){\n return false\n }\n }\n if(this.flags.value & IGNORECASE.value &&\n (! this.is_bytes || this.cp <= 127)){\n // Flag IGNORECASE set\n // For bytes pattern, case insensitive matching only works\n // for ASCII characters\n var char_upper = this.char.toUpperCase(),\n char_lower = this.char.toLowerCase(),\n cp\n while(i < this.repeat.max && pos + i < endpos){\n cp = string.cp_at(pos + i)\n var char = chr(cp)\n if(char.toUpperCase() != char_upper &&\n char.toLowerCase() != char_lower){\n break\n }\n i++\n }\n }else{\n while(pos + i < endpos &&\n string.cp_at(pos + i) == this.cp &&\n i < this.repeat.max){\n i++\n }\n }\n }else{\n while(pos + i < endpos &&\n string.cp_at(pos + i) == this.cp &&\n i < this.repeat.max){\n i++\n }\n }\n var nb = i\n if(nb >= this.repeat.min){\n // Number of repeats ok\n return {\n nb_min: this.repeat.min,\n nb_max: nb\n }\n }else{\n return false\n }\n}\n\nChar.prototype.toString = function(){\n var res = 'Char ' + this.text\n if(this.repeat !== undefined){\n res += ' repeat {' + this.repeat.min + ',' + this.repeat.max + '}'\n if(this.non_greedy){\n res += '?'\n }\n }\n return res\n}\n\nfunction CharSeq(chars, flags){\n // sequence of consecutive characters\n this.chars = chars\n this.flags = flags\n this.merge_same_chars()\n}\n\nCharSeq.prototype.add_char = function(char){\n this.chars.push(char)\n this.merge_same_chars()\n}\n\nCharSeq.prototype.fixed_length = function(){\n var len = 0,\n cps = [],\n char_len\n for(var char of this.chars){\n if(! char.repeat){\n char_len = 1\n }else if(char.repeat.min == char.repeat.max){\n char_len = char.repeat.min\n }else{\n len = false\n break\n }\n for(var i = 0; i < char_len; i++){\n cps.push(char.cp)\n }\n len += char_len\n }\n this.cps = cps\n return this.len = len\n}\n\nCharSeq.prototype.match = function(string, pos, endpos){\n var mos = [],\n i = 0,\n backtrack,\n nb\n this.len = this.len === undefined ? this.fixed_length() : this.len\n // optimization if character sequence has a fixed length\n if(this.len !== false && ! (this.flags.value & IGNORECASE.value)){\n for(var i = 0; i < this.len; i++){\n if(string.cp_at(pos + i) !== this.cps[i]){\n return false\n }\n }\n return {nb_min: this.len, nb_max: this.len}\n }\n for(var i = 0, len = this.chars.length; i < len; i++){\n var char = this.chars[i],\n mo = char.match(string, pos, endpos) // form {nb_min, nb_max}\n if(_debug.value){\n console.log('CharSeq match, pos', pos, 'char', char, 'mo', mo)\n alert()\n }\n if(mo){\n nb = char.non_greedy ? mo.nb_min : mo.nb_max\n mos.push({nb,\n nb_min: mo.nb_min,\n nb_max: mo.nb_max,\n non_greedy: !!char.non_greedy\n })\n pos += nb\n }else{\n // backtrack\n backtrack = false\n while(mos.length > 0){\n i--\n mo = mos.pop()\n pos -= mo.nb\n nb = mo.nb\n if(mo.non_greedy && nb < mo.nb_max){\n nb += 1\n backtrack = true\n }else if(! mo.non_greedy && nb - 1 >= mo.nb_min){\n nb -= 1\n backtrack = true\n }\n if(backtrack){\n pos += nb\n mo.nb = nb\n mos.push(mo)\n break\n }\n }\n if(mos.length == 0){\n return false\n }\n }\n }\n var nb = 0,\n last_mo = $B.last(mos)\n for(var mo of mos.slice(0, mos.length - 1)){\n nb += mo.nb\n }\n var res = {\n nb_min: nb + last_mo.nb_min,\n nb_max: nb + last_mo.nb_max\n }\n return res\n}\n\nCharSeq.prototype.merge_same_chars = function(){\n // b?b merged into b+ etc.\n var current,\n chars = [],\n merged\n for(var item of this.chars){\n if(current && current.char == item.char &&\n current.non_greedy === item.non_greedy){\n if(! current.repeat){\n current.repeat = {min: 1, max: 1}\n }\n if(item.repeat){\n current.repeat.min += item.repeat.min\n current.repeat.max += item.repeat.max\n }else{\n current.repeat.min += 1\n current.repeat.max += 1\n }\n merged = true\n }else{\n chars.push(item)\n }\n current = item\n }\n if(merged){\n this.chars = chars\n }\n}\n\nCharSeq.prototype.toString = function(){\n var res = ''\n for(var char of this.chars){\n res += char.text\n }\n return 'CharSeq ' + res\n}\n\nfunction CharacterClass(pos, cp, length, groups){\n this.cp = cp\n this.value = chr(cp)\n this.length = length\n this.pos = pos\n\n var flags = this.flags\n\n // Test function : test(string, pos) returns:\n // - true if \"this\" matches 1 character string[pos]\n // - [true, 0] if \"this\" matches the empty string at pos\n // - false or undefined if \"this\" doesn't match\n switch(this.value){\n case 'A':\n this.test_func = function(string, pos){\n if(pos == 0){\n return [true, 0]\n }\n }\n break\n case 's':\n this.test_func = function(string, pos){\n var cp = string.cp_at(pos)\n return $B.in_unicode_category('Zs', cp) ||\n $B.unicode_bidi_whitespace.indexOf(cp) > -1\n }\n break\n case 'S':\n this.test_func = function(string, pos){\n var cp = string.cp_at(pos)\n return cp !== undefined &&\n ! $B.in_unicode_category('Zs', cp) &&\n $B.unicode_bidi_whitespace.indexOf(cp) == -1\n }\n break\n case '.':\n this.test_func = function(string, pos){\n if(string.cp_at(pos) === undefined){\n return false\n }\n if(this.flags.value & DOTALL.value){\n return true\n }else{\n return string.cp_at(pos) != 10\n }\n }\n break\n case 'd':\n this.test_func = function(string, pos){\n if(this.flags === undefined){\n console.log(\"\\\\d, no flags\", this)\n }\n var cp = string.cp_at(pos),\n tester = (this.flags.value & ASCII.value) ?\n is_ascii_digit : is_digit\n return tester(cp)\n }\n break\n case 'D':\n this.test_func = function(string, pos){\n var cp = string.cp_at(pos),\n tester = (this.flags.value & ASCII.value) ?\n is_ascii_digit : is_digit\n return ! tester(cp)\n }\n break\n case 'b':\n this.test_func = function(string, pos){\n var tester = is_word\n if(this.is_bytes || (this.flags.value & ASCII.value)){\n tester = is_ascii_word\n }\n var cp = string.cp_at(pos),\n ok = {nb_min: 0, nb_max: 0}\n\n // return true if char at pos is at the beginning or start\n // of a word\n if(pos == 0 && tester(cp)){\n return ok\n }\n if(string.cp_at(pos) === undefined && tester(string.cp_at(pos - 1))){\n return ok\n }\n if(pos > 0 && string.cp_at(pos) !== undefined){\n if((tester(string.cp_at(pos - 1))) !==\n tester(cp)){\n return ok\n }\n }\n return false\n }\n break\n case 'B':\n this.test_func = function(string, pos){\n var tester = is_word\n if(this.is_bytes || (this.flags.value & ASCII.value)){\n tester = is_ascii_word\n }\n\n var cp = string.cp_at(pos),\n ok = {nb_min: 0, nb_max: 0}\n // test is true if char at pos is not at the beginning or\n // start of a word\n if(pos == 0 && cp === undefined){\n // empty string\n return false\n }\n if(pos == 0 && tester(cp)){\n return false\n }\n if(cp === undefined &&\n tester(string.cp_at(pos - 1))){\n return false\n }\n if(pos > 0 && cp !== undefined){\n if(tester(string.cp_at(pos - 1)) !== tester(cp)){\n return false\n }\n }\n return ok\n }\n break\n case 'w':\n this.test_func = function(string, pos){\n var tester = is_word\n if(this.is_bytes || (this.flags.value & ASCII.value)){\n tester = is_ascii_word\n }\n return tester(string.cp_at(pos))\n }\n break\n case 'W':\n this.test_func = function(string, pos){\n var tester = is_word\n if(this.is_bytes || (this.flags.value & ASCII.value)){\n tester = is_ascii_word\n }\n return ! tester(string.cp_at(pos))\n }\n break\n case 'Z':\n this.test_func = function(string, pos){\n if(string.cp_at(pos) === undefined){\n return {nb_min: 0, nb_max: 0}\n }\n }\n break\n }\n}\n\nCharacterClass.prototype.fixed_length = function(){\n return this.repeat ? false : 1\n}\n\nCharacterClass.prototype.match = function(string, pos, endpos){\n // Returns {pos1, pos2} such that \"this\" matches all the substrings\n // string[pos:i] with pos1 <= i < pos2, or false if no match\n if(pos === undefined){\n console.log('no pos')\n throw Error()\n }\n var len = string.length\n this.repeat = this.repeat || {min: 1, max: 1}\n\n // browse string codepoints until they don't match, or the number of\n // matches is above the maximum allowed\n var i = 0\n while(i < this.repeat.max && i < len){\n var test = this.test_func(string, pos + i, this.flags)\n if(! test){\n break\n }\n i++\n }\n\n var nb = i\n if(nb >= this.repeat.min){\n // Number of repeats ok\n if('bBAZ'.indexOf(this.value) > -1 ){\n return {nb_min: 0, nb_max: 0}\n }\n return {\n nb_min: this.repeat.min,\n nb_max: nb\n }\n }else{\n return false\n }\n}\n\nCharacterClass.prototype.nb_repeats = Char.prototype.nb_repeats\n\nCharacterClass.prototype.toString = function(){\n return '\\\\' + this.value\n}\n\nvar CharacterSet = function(pos, set, groups){\n // character set\n this.pos = pos\n this.set = set\n this.neg = set.neg\n}\n\nCharacterSet.prototype.fixed_length = function(){\n return 1\n}\n\nCharacterSet.prototype.match = function(string, pos, endpos){\n var ignore_case = this.flags && (this.flags.value & IGNORECASE.value),\n test,\n match = false,\n i = 0,\n cp\n\n this.repeat = this.repeat || {min: 1, max: 1}\n\n while(i < this.repeat.max && (cp = string.cp_at(pos + i)) !== undefined){\n test = false\n\n if(string.cp_at(pos) === undefined){\n cp = EmptyString\n }\n try{\n $B.codepoint2jsstring(cp)\n }catch(err){\n console.log(err.message)\n console.log('cp', cp, '\\nstring', string, 'pos', pos)\n console.log($B.print_stack())\n throw _b_.Exception.$factory('bad codepoint')\n }\n var char = $B.codepoint2jsstring(cp),\n cps = cased_cps(cp, ignore_case, this.flags.value & ASCII.value),\n char_is_cased = cps.length > 1\n\n for(var cp1 of cps){\n for(var item of this.set.items){\n if(Array.isArray(item.ord)){\n if(cp1 >= item.ord[0] &&\n cp1 <= item.ord[1]){\n test = true\n break\n }else if(ignore_case && char_is_cased){\n var start1 = chr(item.ord[0]).toUpperCase(),\n end1 = chr(item.ord[1]).toUpperCase(),\n char1 = char.toUpperCase()\n if(char1 >= start1 && char1 <= end1){\n test = true\n }\n var start1 = chr(item.ord[0]).toLowerCase(),\n end1 = chr(item.ord[1]).toLowerCase(),\n char1 = char.toLowerCase()\n if(char1 >= start1 && char1 <= end1){\n test = true\n }\n }\n }else if(item instanceof CharacterClass){\n test = !! item.match(string, pos + i, endpos) // boolean\n if(test){\n break\n }\n }else{\n if(item.ord == cp1){\n test = true\n break\n }\n item_str = typeof item == 'string' ? item : chr(item.ord)\n if(item_str == char){\n test = true\n break\n }\n if(ignore_case && char_is_cased &&\n (char.toUpperCase() == item_str.toUpperCase() ||\n char.toLowerCase() == item_str.toLowerCase())){\n test = true\n break\n }\n }\n }\n }\n if(this.neg){\n test = ! test\n }\n if(test){\n i++\n }else{\n break\n }\n }\n var nb = i\n if(nb >= this.repeat.min){\n // Number of repeats ok\n return {\n nb_min: this.repeat.min,\n nb_max: nb\n }\n }else{\n return false\n }\n\n}\n\nCharacterSet.prototype.nb_repeats = Char.prototype.nb_repeats\n\nCharacterSet.prototype.toString = function(){\n return 'CharSet'\n}\n\nvar ConditionalBackref = function(pos, group_ref){\n this.type = \"conditional backref\"\n this.pos = pos\n this.group_ref = group_ref\n this.chars = []\n this.match_codepoints = []\n this.nb_success = 0\n this.re_if_exists = new Group(pos)\n this.re_if_not_exists = new Group(pos)\n this.nb_options = 1\n}\n\nConditionalBackref.prototype.add = function(item){\n if(this.nb_options == 1){\n this.re_if_exists.add(item)\n }else if(this.nb_options == 2){\n this.re_if_not_exists.add(item)\n }\n item.parent = this\n}\n\nConditionalBackref.prototype.fixed_length = function(){\n var len = this.re_if_exists.fixed_length()\n if(len !== false && len == this.re_if_not_exists.fixed_length()){\n return len\n }\n return false\n}\n\nConditionalBackref.prototype.match = function(string, pos, endpos, groups){\n var re = groups[this.group_ref] ? this.re_if_exists :\n this.re_if_not_exists,\n pattern = {node: re, text: re + ''},\n mo = match(pattern, string, pos, endpos, false, groups)\n if(mo){\n return {nb_min: mo.end - mo.start, nb_max: mo.end - mo.start}\n }\n return false\n}\n\nConditionalBackref.prototype.toString = function(){\n return 'ConditionalBackref'\n}\n\nvar Group = function(pos, extension){\n this.type = \"group\"\n this.pos = pos\n this.items = []\n this.chars = []\n this.groups = []\n for(var key in extension){\n this[key] = extension[key]\n }\n if(extension && extension.type){\n if(extension.type.indexOf('lookahead') > -1){\n this.is_lookahead = true\n }else if(extension.type.indexOf('lookbehind') > -1){\n this.is_lookbehind = true\n }\n }\n}\n\nGroup.prototype.add = Node.prototype.add\n\nGroup.prototype.toString = function(){\n if(this.num === undefined){\n var res = 'Group ' + this.type + ' ' + this.pattern\n }else{\n var res = 'Group #' + this.num + ' ' + this.pattern\n }\n if(this.repeat !== undefined){\n res += ' repeat {' + this.repeat.min + ',' + this.repeat.max + '}'\n if(this.non_greedy){\n res += '?'\n }\n }\n return res\n}\n\nBackReference.prototype.nb_repeats = Group.prototype.nb_repeats\n\nGroup.prototype.fixed_length = Node.prototype.fixed_length\n\nfunction groups_in(pattern, group_list){\n if(group_list === undefined){\n group_list = new Set()\n }\n if(pattern instanceof Group && pattern.hasOwnProperty('num')){\n group_list.add(pattern.num)\n }\n if(pattern.items){\n for(var subpattern of pattern.items){\n for(var group of groups_in(subpattern, group_list)){\n group_list.add(group)\n }\n }\n }\n return group_list\n}\n\nfunction GroupRef(group_num, item){\n this.num = group_num\n this.item = item\n}\n\nGroupRef.prototype.fixed_length = function(){\n return this.item.fixed_length()\n}\n\nfunction Lookbehind(item){\n this.re = item\n this.neg = this.re.type == \"negative_lookbehind\"\n}\n\nLookbehind.prototype.match = function(string, pos, endpos, groups){\n var ok = {nb_min: 0, nb_max: 0},\n pattern = {node: this.re, text: this.re + ''},\n length = this.re.length,\n mo\n if(pos - length < 0){\n mo = false\n }else{\n mo = match(pattern, string, pos - length, endpos, false, groups)\n }\n if(mo){\n return this.neg ? false : ok\n }else{\n return this.neg ? ok : false\n }\n}\n\nLookbehind.prototype.fixed_length = function(){\n return this.re.fixed_length()\n}\n\nLookbehind.prototype.toString = function(){\n return \"Lookbehind\"\n}\n\nfunction SetFlags(pos, flags){\n this.pos = pos\n this.on_flags = flags.on_flags\n this.off_flags = flags.off_flags\n this.items = []\n}\n\nSetFlags.prototype.add = Node.prototype.add\n\nfunction StringStart(pos){\n this.pos = pos\n}\n\nStringStart.prototype.match = function(string, pos, endpos){\n var ok = {nb_min:0, nb_max: 0}\n if(this.flags.value & MULTILINE.value){\n return (pos == 0 || string.cp_at(pos - 1) == 10) ? ok : false\n }\n return pos == 0 ? ok : false\n}\n\nStringStart.prototype.fixed_length = function(){\n return 0\n}\n\nStringStart.prototype.toString = function(){\n return '^'\n}\n\nfunction StringEnd(pos){\n this.pos = pos\n}\n\nStringEnd.prototype.match = function(string, pos, endpos){\n var ok = {nb_min:0, nb_max: 0},\n cp = string.cp_at(pos)\n if(this.flags.value & MULTILINE.value){\n return (pos > string.codepoints.length - 1 ||\n cp == 10) ? ok : false\n }\n return pos > endpos - 1 ? ok :\n (pos == endpos - 1 && cp == 10) ? ok : false\n}\n\nStringEnd.prototype.fixed_length = function(){\n return 0\n}\n\nStringEnd.prototype.toString = function(){\n return '$'\n}\n\nvar cache = new Map()\n\nfunction compile(pattern, flags){\n if(pattern.__class__ === Pattern){\n if(flags !== no_flag){\n throw _b_.ValueError.$factory(\"no flags\")\n }\n return pattern\n }\n if(cache.has(pattern.py_obj)){\n if(cache.get(pattern.py_obj).has(flags.value || 0)){\n return cache.get(pattern.py_obj).get(flags.value || 0)\n }\n }\n var original_pattern = pattern,\n original_flags = flags,\n type = pattern.type,\n choices,\n allow_global_flags = true\n pattern = pattern.codepoints\n var is_bytes = type !== \"str\"\n if(is_bytes && flags && (flags.value & U.value)){\n throw _b_.ValueError.$factory(\"cannot use UNICODE flag with \" +\n \"a bytes pattern\")\n }\n if(flags && (flags.value & U.value) &&\n (flags.value & ASCII.value)){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n if(is_bytes){\n // bytes patterns ignore re.ASCII flag\n flags = Flag.$factory(flags.value || 0)\n //flags.value &= ~ASCII.value\n }\n var group_num = 0,\n group_stack = [],\n groups = {},\n pos,\n lookbehind,\n node = new Node(),\n accept_inline_flag = true,\n verbose = (flags.value || 0) & VERBOSE.value,\n comment = false,\n backrefs = {}\n node.$groups = groups\n for(var item of tokenize(pattern, type, verbose)){\n item.flags = flags\n item.is_bytes = is_bytes\n if(lookbehind){\n item.lookbehind = lookbehind\n lookbehind.parent = item\n lookbehind = false\n }\n if(allow_global_flags &&\n (group_stack.length > 0 || ! (item instanceof SetFlags))){\n allow_global_flags = false\n }\n if(item instanceof Group){\n group_stack.push(item)\n node.add(item)\n item.state = \"open\"\n group_num++\n item.num = group_num\n node = item // next items will be stored as group's items\n pos = item.pos\n if(item.non_capturing){\n delete item.num\n group_num--\n }else if(item.type == \"name_def\"){\n var value = item.value\n if(groups[value.string] !== undefined){\n fail(`redefinition of group name` +\n ` '${value.string}' as group ${group_num}; was group` +\n ` ${groups[value.string].num}`, pos)\n }\n item.name = value.string\n groups[value.string] = groups[group_num] =\n new GroupRef(group_num, item)\n }else if(item.is_lookahead){\n // a lookahead assertion is relative to the previous regexp\n group_num--\n while(node.items.length > 0){\n item.add(node.items.shift())\n }\n node = item\n }else if(item.is_lookbehind){\n // a lookbehind assertion is relative to the next regexp\n node.parent.items.pop() // remove from node items\n // temporarily create a group\n groups[group_num] = new GroupRef(group_num, item)\n }else if(item.type == \"flags\"){\n // save flags before a group with inline flags, eg \"(?i:a)\"\n item.flags_before = Flag.$factory(flags.value | 0)\n }else{\n groups[group_num] = new GroupRef(group_num, item)\n }\n }else if(item instanceof GroupEnd){\n end_pos = item.pos\n if(group_stack.length == 0){\n fail(\"unbalanced parenthesis\", end_pos, original_pattern)\n }\n var item = group_stack.pop()\n item.end_pos = end_pos\n try{\n item.pattern = from_codepoint_list(\n pattern.slice(item.pos, end_pos + 1))\n }catch(err){\n console.log(\"err avec pattern substring\", pattern)\n throw err\n }\n if(item.is_lookbehind){\n delete groups[group_num]\n group_num--\n // check that all elements have a fixed length\n item.length = item.fixed_length()\n if(item.length === false){\n fail(\"look-behind requires fixed-width pattern\", pos)\n }\n item.parent.add(new Lookbehind(item))\n item.non_capturing = true\n // store in variable \"lookbehind\", will be applied to next item\n lookbehind = item\n }else if(item.is_lookahead){\n delete item.num\n }\n if(item instanceof Group && item.items.length == 0){\n item.add(EmptyString)\n }else if(item instanceof ConditionalBackref){\n if(groups[item.group_ref] === undefined){\n // might be defined later; store in backrefs and check\n // when all items have been processed\n backrefs[item.group_ref] = backrefs[item.group_ref] | pos + 3\n }\n if(item.re_if_exists.items.length == 0){\n item.re_if_exists.add(EmptyString)\n }else if(item.re_if_not_exists.items.length == 0){\n item.re_if_not_exists.pos = pos\n item.re_if_not_exists.add(EmptyString)\n }\n }else if(item.type == \"flags\"){\n // restore flags when entering the group\n flags = Flag.$factory(item.flags_before.value)\n }\n item.state = 'closed'\n node = item.parent\n }else if(item instanceof ConditionalBackref){\n var pos = item.pos,\n group_ref = item.group_ref\n if(typeof group_ref == \"number\"){\n if(group_ref == 0){\n fail(`bad group number`, pos + 3)\n }else if(group_ref >= MAXGROUPS){\n fail(`invalid group reference ${group_ref}`, pos + 1)\n }else if(groups[group_ref] &&\n groups[group_ref].item.state == \"open\"){\n fail(\"cannot refer to an open group\", pos)\n }\n }else if(groups[group_ref] !== undefined){\n if(groups[group_ref].item.state == \"open\"){\n fail(\"cannot refer to an open group\", pos)\n }\n }else{\n fail(`unknown group name '${group_ref}'`, pos)\n }\n group_stack.push(item)\n node.add(item)\n item.state = \"open\"\n node = item // next items will be stored as group's items\n }else if(item instanceof BackReference){\n pos = item.pos\n if(item.type == \"num\" && item.value > 99){\n var head = item.value.toString().substr(0, 2)\n fail(`invalid group reference ${head}`, pos + 1)\n }\n if(groups[item.value] !== undefined){\n if(groups[item.value].item.state == \"open\"){\n fail(\"cannot refer to an open group\", pos)\n }\n var ref_item = groups[item.value].item.parent\n while(ref_item){\n if(ref_item.is_lookbehind){\n fail(\"cannot refer to group defined in the same lookbehind subpattern\", pos)\n }\n ref_item = ref_item.parent\n }\n }else if(item.type == \"name\"){\n fail(`unknown group name '${item.value}'`, pos)\n }else if(item.type == \"num\"){\n fail(`invalid group reference ${item.value}`, pos)\n }\n node.add(item)\n }else if(item instanceof Char ||\n item instanceof CharacterClass ||\n item instanceof CharacterSet){\n if(item instanceof CharacterSet){\n for(var elt of item.set.items){\n elt.flags = flags\n }\n }\n var added_to_charseq = false\n if(item instanceof Char){\n if(node.items && node.items.length > 0){\n var previous = $last(node.items)\n if(previous instanceof CharSeq){\n previous.add_char(item)\n added_to_charseq = true\n }else if(previous instanceof Char && ! previous.repeater){\n node.items.pop()\n node.items.push(new CharSeq([previous, item], flags))\n added_to_charseq = true\n }\n }\n }\n if(! added_to_charseq){\n node.add(item)\n }\n }else if(item instanceof Repeater){\n // check that item is not in a lookbehind group\n var pnode = node\n while(pnode){\n if(pnode.extension && pnode.extension.type &&\n pnode.extension.type.indexOf(\"lookbehind\") > -1){\n fail(\"look-behind requires fixed-width pattern\", pos)\n }\n pnode = pnode.parent\n }\n pos = item.pos\n if(node.items.length == 0){\n fail(\"nothing to repeat\", pos)\n }\n previous = $last(node.items)\n if(previous instanceof Char ||\n previous instanceof CharSeq ||\n previous instanceof CharacterClass ||\n previous instanceof CharacterSet ||\n previous instanceof Group ||\n previous instanceof BackReference){\n if(previous instanceof GroupEnd){\n // associate repeat with Group\n previous = previous.group\n }else if(previous instanceof CharSeq){\n previous = $last(previous.chars)\n }\n if(previous.repeater){\n if(item.op == '?' && ! previous.non_greedy){\n if(previous.possessive){\n fail('multiple repeat', pos)\n }\n previous.non_greedy = true\n if(previous instanceof CharacterClass &&\n previous.value == '.'){\n previous.min_repeat_one = true\n }\n }else{\n if(item instanceof Repeater && item.op == '+'){\n if(previous.possessive || previous.non_greedy){\n fail('multiple repeat', pos)\n }\n previous.possessive = true\n }else{\n fail(\"multiple repeat\", pos)\n }\n }\n }else{\n // convert to minimum and maximum number of repeats\n var min = 1,\n max = 1\n if(Array.isArray(item.op)){\n min = item.op[0]\n if(min >= MAXREPEAT){\n throw _b_.OverflowError.$factory(\n \"the repetition number is too large\")\n }\n max = item.op[1] === undefined ? min : item.op[1]\n if(isFinite(max) && max >= MAXREPEAT){\n throw _b_.OverflowError.$factory(\n \"the repetition number is too large\")\n }\n if(max < min){\n fail('min repeat greater than max repeat', pos)\n }\n }else if(item.op == \"?\"){\n min = 0\n max = 1\n }else if(item.op == \"*\"){\n min = 0\n max = Number.POSITIVE_INFINITY\n }else if(item.op == \"+\"){\n min = 1\n max = Number.POSITIVE_INFINITY\n }\n previous.repeater = item\n previous.repeat = {min, max}\n // mark all parents of item as no fixed length\n var parent = item\n while(parent){\n parent.fixed_length = false\n parent = parent.parent\n }\n }\n }else{\n fail(\"nothing to repeat\", pos)\n }\n }else if(item instanceof Or){\n if(group_stack.length > 0){\n item.group = group_stack[group_stack.length - 1]\n }else{\n item.group = false\n }\n pos = item.pos\n if(node instanceof ConditionalBackref){\n // case '(?(num)a|'\n if(node.nb_options == 1){\n node.nb_options++\n }else{\n fail('conditional backref with more than ' +\n 'two branches', pos)\n }\n }else if(node.items.length == 0){\n // token \"|\" in \"(|...)\" : first option is the empty string\n var choice = new Choice(),\n case1 = new Case()\n case1.add(new Char(pos, EmptyString))\n choice.add(case1)\n node.add(choice)\n var case2 = new Case()\n choice.add(case2)\n node = case2\n }else if(node instanceof Case){\n // node.parent is already a Choice\n var new_case = new Case()\n node.parent.add(new_case)\n node = new_case\n }else{\n // token \"|\" in \"(ab|...)\"\n var previous = node.items[node.items.length - 1]\n if(previous instanceof Case){\n var new_case = new Case()\n previous.add(new_case)\n node = new_case\n }else{\n var choice = new Choice(),\n case1 = new Case(),\n first_rank = node.items[0].rank\n while(node.items.length > 0){\n case1.add(node.items.shift())\n }\n case1.groups = node.$groups\n for(var group of group_stack){\n choice.groups.push(group)\n }\n choice.add(case1)\n node.add(choice)\n var case2 = new Case()\n choice.add(case2)\n node = case2\n }\n }\n }else if(item instanceof StringStart ||\n item instanceof StringEnd){\n node.add(item)\n }else if(item instanceof SetFlags){\n if(group_stack.length == 0 && ! allow_global_flags){\n // pattern like (?x) only allowed as first in reg exp\n fail('global flags not at the start of the ' +\n 'expression', item.pos)\n }\n // copy flags, otherwise re.ASCII etc might be modified\n flags = Flag.$factory(flags.value || U.value)\n if(item.on_flags.indexOf('u') > -1){\n if(is_bytes){\n fail(\"re.error: bad inline flags: cannot use 'u' flag \" +\n \"with a bytes pattern\", pos)\n }\n if(flags && flags.value & ASCII.value){\n // switch to Unicode\n flags.value ^= ASCII.value\n }\n if(group_stack.length == 0 &&\n original_flags && original_flags.value & ASCII.value){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n if(item.on_flags.indexOf('a') > -1){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n }\n if(item.on_flags.indexOf('a') > -1){\n if(group_stack.length == 0 &&\n original_flags && original_flags.value & U.value){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n if(flags && flags.value & U.value){\n // switch to ASCII\n flags.value ^= U.value\n }\n if(item.on_flags.indexOf('u') > -1){\n throw _b_.ValueError.$factory(\"ASCII and UNICODE flags \" +\n \"are incompatible\")\n }\n }\n if(flags.value === undefined){\n flags.value = 32\n }\n if(item.items.length == 0){\n if(! accept_inline_flag && group_stack.length == 0){\n var s = from_codepoint_list(pattern)\n warn(_b_.DeprecationWarning,\n `Flags not at the start of the expression '${s}'`,\n pos)\n }\n for(var on_flag of item.on_flags){\n if(! is_bytes || on_flag !== 'a'){\n flags.value |= inline_flags[on_flag].value\n }\n }\n for(var off_flag of item.off_flags){\n if(! is_bytes || off_flag !== 'a'){\n flags.value ^= inline_flags[off_flag].value\n }\n }\n }else{\n node.add(item)\n }\n }else{\n fail(\"unknown item type \" + item, pos)\n }\n if(! (item instanceof SetFlags) &&\n ! (item instanceof Group && item.type == \"flags\")){\n accept_inline_flag = false\n }\n }\n for(ref in backrefs){\n if(groups[ref] === undefined){\n fail('invalid group name ' + ref, backrefs[ref])\n }\n }\n if(group_stack.length > 0){\n var last = group_stack[group_stack.length - 1]\n fail(\"missing ), unterminated subpattern\", last.pos)\n }\n while(node.parent){\n node = node.parent\n }\n node.pattern = from_codepoint_list(pattern)\n node.groups = group_num\n flags = flags === no_flag ? 32 : flags\n node.flags = flags\n var res = {\n node,\n groups,\n flags,\n original_flags,\n text: from_codepoint_list(pattern),\n type, // \"str\" or \"bytes\"\n fixed_length: node.fixed_length()\n }\n if(! cache.has(original_pattern.py_obj)){\n cache.set(original_pattern.py_obj, new Map())\n }\n cache.get(original_pattern.py_obj).set(original_flags.value || 0, res)\n if(_debug.value){\n show(node)\n }\n return res\n}\n\nfunction show(node, indent){\n indent = indent === undefined ? 0 : indent\n if(indent == 0){\n log('root', node)\n }\n log(' '.repeat(indent) + node)\n if(node.items !== undefined){\n for(var item of node.items){\n show(item, indent + 1)\n }\n }\n}\n\nfunction to_codepoint_list(s){\n var items = []\n if(typeof s == \"string\" || $B.$isinstance(s, _b_.str)){\n if(typeof s != \"string\"){\n s = s.valueOf()\n }\n for(var char of s){\n items.push(char.codePointAt(0))\n }\n items.type = \"unicode\"\n }else if($B.$isinstance(s, [_b_.bytes, _b_.bytearray, _b_.memoryview])){\n if($B.$isinstance(s, _b_.memoryview)){\n items = s.obj.source\n }else{\n items = s.source\n }\n items.type = \"bytes\"\n }else{\n throw Error('invalid type ' + $B.class_name(s))\n }\n return items\n}\n\n$B.nb_from_cp = 0\nfunction from_codepoint_list(codepoints, type){\n $B.nb_from_cp++\n // Return a string\n if(type == \"bytes\"){\n return _b_.bytes.$factory(codepoints)\n }\n var s = ''\n for(var cp of codepoints){\n s += _b_.chr(cp)\n }\n return $B.String(s)\n}\n\nfunction string2bytes(s){\n var t = []\n for(var i = 0, len = s.length; i < len; i++){\n t.push(s.charCodeAt(i))\n }\n return _b_.bytes.$factory(t)\n}\n\nfunction check_pattern_flags(pattern, flags){\n if(pattern.__class__ === Pattern){\n if(flags !== no_flag){\n throw _b_.ValueError.$factory(\n \"cannot process flags argument with a compiled pattern\")\n }\n }\n return pattern\n}\n\nfunction StringObj(obj){\n // A StringObj object is a bridge between a Python string or bytes-like\n // object and Javascript\n // obj is the Python object\n // this.string is a Javascript string\n this.py_obj = obj\n this.codepoints = []\n this.type = \"str\"\n this.is_string = typeof obj == 'string'\n if(typeof obj == \"string\" ||\n (obj instanceof String && ! obj.codepoints)){\n // Python object represented as a Javascript string\n this.string = obj\n // Maps a position in codepoints to position in string\n this.index_map = {}\n for(var i = 0, len = obj.length; i < len; i++){\n this.index_map[this.codepoints.length] = i\n var cp = obj.codePointAt(i)\n this.codepoints.push(cp)\n if(cp >= 0x10000){\n i++\n }\n }\n this.length = _b_.str.__len__(obj)\n if(obj instanceof String){\n // store for next use\n obj.codepoints = this.codepoints\n obj.index_map = this.index_map\n }\n }else if(obj instanceof String){\n // string with surrogate pairs\n this.string = obj.string\n this.codepoints = obj.codepoints\n this.index_map = obj.index_map\n this.length = _b_.str.__len__(obj)\n }else if($B.$isinstance(obj, _b_.str)){ // str subclass\n var so = new StringObj(_b_.str.$factory(obj))\n this.string = so.string\n this.codepoints = so.codepoints\n this.length = _b_.str.__len__(obj)\n }else if($B.$isinstance(obj, [_b_.bytes, _b_.bytearray])){\n this.string = _b_.bytes.decode(obj, 'latin1')\n this.codepoints = obj.source\n this.type = \"bytes\"\n }else if($B.$isinstance(obj, _b_.memoryview)){\n this.string = _b_.bytes.decode(obj.obj, 'latin1')\n this.codepoints = obj.obj.source\n this.type = \"bytes\"\n }else if(obj.__class__ && obj.__class__.$buffer_protocol){\n // eg array.array\n this.codepoints = _b_.list.$factory(obj)\n this.string = from_codepoint_list(this.codepoints, \"bytes\")\n this.type = \"bytes\"\n }else if(Array.isArray(obj)){\n // list of codepoints\n this.codepoints = obj\n }else{\n throw _b_.TypeError.$factory(\n `expected string or bytes-like object, got '${$B.class_name(obj)}'`)\n }\n if(this.length === undefined){\n this.length = this.codepoints.length\n }\n}\n\nStringObj.prototype.cp_at = function(pos){\n if(pos >= this.length){\n return undefined\n }\n /*\n if(typeof this.string == 'string'){\n return this.string.charCodeAt(pos)\n }\n */\n var res = this.codepoints[pos]\n if(res !== undefined){\n return res\n }\n}\n\nStringObj.prototype.substring = function(start, end){\n // Returns a string\n var s\n if(this.string && this.index_map){\n if(this.index_map[start] === undefined){\n return ''\n }\n if(end === undefined){\n return this.string.substr(this.index_map[start])\n }\n return this.string.substring(this.index_map[start],\n this.index_map[end])\n }\n var codepoints,\n res = ''\n if(end === undefined){\n codepoints = this.codepoints.slice(start)\n }else{\n codepoints = this.codepoints.slice(start, end)\n }\n return from_codepoint_list(codepoints, this.type)\n}\n\nStringObj.prototype.to_str = function(){\n if(this.hasOwnProperty('string')){\n return this.string\n }\n return from_codepoint_list(this.codepoints, this.type)\n}\n\nStringObj.from_codepoints = function(cps){\n var res = new StringObj('')\n res.codepoints = cps\n for(var cp of cps){\n res.string += _b_.chr(cp)\n }\n return res\n}\n\nfunction prepare(args){\n // Check that all arguments are of the same type (string or bytes-like).\n // Return an object with all attributes transformed into StringObj\n // instances\n var res = {},\n keys = Object.keys(args),\n first = keys[0]\n res[first] = new StringObj(args[first])\n res.type = res[first].type\n for(var key of keys.slice(1)){\n res[key] = new StringObj(args[key])\n if(res[key].type != res.type){\n throw _b_.TypeError.$factory(`not the same type for ${first} and ${key}`)\n }\n }\n return res\n}\n\n\nfunction subn(pattern, repl, string, count, flags){\n // string is a StringObj instance\n // pattern is either a Pattern instance or a StringObj instance\n var res = '',\n pos = 0,\n nb_sub = 0\n\n if(pattern instanceof StringObj){\n pattern = compile(pattern, flags)\n }\n if(typeof repl != \"function\"){\n var data1 = transform_repl({repl}, pattern)\n repl1 = data1.repl1\n }\n pos = 0\n var s = string.to_str()\n for(var bmo of module.finditer(Pattern.$factory(pattern), s).js_gen){\n // finditer yields instances of MatchObject\n var mo = bmo.mo // instance of MO\n res += from_codepoint_list(string.codepoints.slice(pos, mo.start))\n if(typeof repl == \"function\"){\n var x = $B.$call(repl)(bmo)\n if(x.__class__ === _b_.bytes){\n x = _b_.bytes.decode(x, 'latin-1')\n }\n res += x // $B.$call(repl)(bmo)\n }else{\n res += repl1\n }\n nb_sub++\n pos = mo.end\n if(count != 0 && nb_sub >= count){\n break\n }\n }\n if(string.is_string){\n res += string.string.substr(pos)\n }else{\n res += from_codepoint_list(string.codepoints.slice(pos))\n }\n if(pattern.type === \"bytes\"){\n res = _b_.str.encode(res, \"latin-1\")\n }\n return [res, nb_sub]\n}\n\n// escaped chars : '\\t\\n\\x0b\\x0c\\r #$&()*+-.?[\\\\]^{|}~'\nvar escaped = [9, 10, 11, 12, 13, 32, 35, 36, 38, 40, 41, 42, 43, 45, 46, 63,\n 91, 92, 93, 94, 123, 124, 125, 126]\n\nfunction starts_with_string_start(pattern){\n // returns true if the pattern starts with ^ or \\A\n if(pattern.node){\n pattern = pattern.node\n }\n if(pattern.items){\n if(pattern.items.length == 0){\n return false\n }\n return starts_with_string_start(pattern.items[0])\n }else if(pattern instanceof CharacterClass){\n return pattern.value == 'A'\n }else if(pattern instanceof StringStart){\n return true\n }else{\n return false\n }\n}\n\nfunction* iterator(pattern, string, flags, original_string, pos, endpos){\n var result = [],\n pos = pos | 0,\n cp,\n accept_one = true // used to test one position after string end\n while((cp = string.cp_at(pos)) !== undefined || accept_one){\n var mo = match(pattern, string, pos, endpos)\n if(mo){\n yield MatchObject.$factory(mo)\n if(mo.end == mo.start){\n // If match has zero with, retry at the same position but\n // with the flag no_zero_width set, to avoid infinite loops\n mo = match(pattern, string, pos, endpos, true)\n if(mo){\n yield MatchObject.$factory(mo)\n pos = mo.end\n }else{\n pos++ // at least 1, else infinite loop\n }\n }else{\n pos = mo.end\n }\n }else{\n pos++\n }\n if(cp === undefined){\n accept_one = false\n }\n if (starts_with_string_start(pattern) && !(flags.value & MULTILINE.value)) {\n break\n }\n }\n delete original_string.in_iteration\n}\n\n\nfunction MO(node, pos, mo, len){\n // Match Object\n this.node = node\n this.start = pos\n this.mo = mo\n this.nb_min = mo.nb_min\n this.nb_max = mo.nb_max\n this.len = len\n this.nb = this.node.non_greedy ? mo.nb_min : mo.nb_max\n this.end = pos + len * this.nb\n}\n\nMO.prototype.backtrack = function(string, groups){\n if(this.node.possessive){\n return false\n }\n if(this.node.non_greedy && this.nb < this.nb_max){\n this.nb++\n this.end = this.start + this.len * this.nb\n return true\n }else if((! this.node.non_greedy) && this.nb > this.nb_min){\n this.nb--\n this.end = this.start + this.len * this.nb\n return true\n }else{\n return false\n }\n}\n\nfunction del_groups(groups, node){\n if(node.num !== undefined){\n delete groups[node.num]\n groups.$last.splice(groups.$last.indexOf(node.num), 1)\n if(node.name !== undefined){\n delete groups[node.name]\n }\n }\n for(var child of node.items){\n if(child instanceof Group){\n del_groups(groups, child)\n }\n }\n}\n\nfunction GroupMO(node, start, matches, string, groups, endpos){\n // Match Object for Groups\n this.node = node\n this.start = start\n this._matches = matches\n this.matches = this.node.non_greedy ? matches.slice(0, this.node.repeat.min) : matches.slice()\n this.string = string\n this.end = this.matches.length > 0 ? $last(matches).end : start\n this.endpos = endpos === undefined\n ? matches.length > 0\n ? $last(matches).end\n : start\n : endpos\n this.$groups = groups\n}\n\nGroupMO.prototype.backtrack = function(string, groups){\n if(_debug.value){\n console.log('group MO backtrack, this', this)\n alert()\n }\n // Try backtracking in the last match\n if(this.node.possessive || this.node.atomic){\n return false\n }\n if(this.matches.length > 0){\n var _match = $last(this.matches),\n mos = _match.mos,\n nb0 = mos.length\n while(mos.length > 0){\n var mo = mos.pop()\n if(mo.node instanceof Case){\n var rank = mo.node.parent.items.indexOf(mo.node)\n for(var _case of mo.node.parent.items.slice(rank + 1)){\n var _mo = match({node: _case, text: _case.text},\n string, mo.start)\n if(_mo){\n // update GroupMO object\n mos.push(_mo)\n this.end = _mo.end\n if(this.$groups.$last.length > 0){\n var ix = this.$groups.$last[this.$groups.$last.length - 1]\n this.$groups[ix].end = _mo.end\n }\n return true\n }\n }\n }\n if(mo.backtrack(string, groups)){\n mos.push(mo)\n if(this.node.num !== undefined){\n groups[this.node.num].end = mo.end\n }\n this.end = mo.end\n return true\n }\n }\n }\n // Else, remove last match if possible\n if(this.node.non_greedy){\n if(this.matches.length < this._matches.length){\n this.matches.push(this._matches[this.matches.length])\n this.end = $last(this.matches).end\n return true\n }else{\n // remove this group and its children from groups\n del_groups(groups, this.node)\n this.end = this.start\n }\n }else{\n if(this.matches.length > this.node.repeat.min &&\n this.matches.length >= 1){\n this.matches.pop()\n if(this.matches.length > 0){\n this.end = $last(this.matches).end\n }else{\n // remove this group and its children from groups\n del_groups(groups, this.node)\n this.end = this.start\n }\n return true\n }\n }\n // Group fails; if some of its subgroups succeded, remove them from\n // groups\n if(this.node.repeat.min > 0){\n del_groups(groups, this.node)\n }\n return false\n}\n\nGroupMO.prototype.toString = function(){\n var repr = _b_.repr(this.string.substring(this.start, this.end))\n repr = repr.substring(0, 50)\n return ''\n}\n\nGroupMO.prototype.groups = function(_default){\n var res = [],\n groupobj = this.$groups\n\n for(var key in this.node.$groups){\n if(isFinite(key)){\n res[key] = groupobj[key] === undefined ? _default :\n this.string.substring(groupobj[key].start, groupobj[key].end)\n }\n }\n res.shift()\n return $B.fast_tuple(res)\n}\n\n// Brython MatchObject\nvar MatchObject = $B.make_class(\"Match\",\n function(mo){\n return {\n __class__: MatchObject,\n mo\n }\n }\n)\n\nMatchObject.__copy__ = function(self){\n return self\n}\n\nMatchObject.__deepcopy__ = function(self){\n return self\n}\n\nMatchObject.__getitem__ = function(){\n var $ = $B.args(\"__getitem__\", 2, {self: null, key: null},\n ['self', 'key'], arguments, {}, null, null),\n self = $.self,\n key = $.key\n if(Array.isArray(key)){\n throw _b_.IndexError.$factory(\"no such group\")\n }\n if(key == 0){\n return self.mo.string.substring(self.mo.start, self.mo.end)\n }\n var match = self.mo.$groups[key]\n if(match !== undefined){\n return self.mo.string.substring(match.start, match.end)\n }else if(self.mo.node.$groups[key] !== undefined){\n return _b_.None\n }\n throw _b_.IndexError.$factory(\"no such group\")\n}\n\nMatchObject.__repr__ = MatchObject.__str__ = function(self){\n return self.mo.toString()\n}\n\nMatchObject.end = function(self){\n var $ = $B.args('end', 2, {self: null, group: null}, ['self', 'group'],\n arguments, {group: 0}, null, null)\n var group = MatchObject.group(self, $.group)\n if(group === _b_.None){\n return -1\n }else if($.group == 0){\n return self.mo.end\n }else{\n return self.mo.$groups[$.group].end\n }\n}\n\nMatchObject.endpos = _b_.property.$factory(\n function(self){\n return self.mo.endpos\n }\n)\n\nMatchObject.expand = function(){\n var $ = $B.args(\"expand\", 2, {self: null, template: null},\n ['self', 'template'], arguments, {}, null, null)\n var data = {\n repl: new StringObj($.template),\n }\n data = transform_repl(data, {groups: $.self.mo.node.$groups})\n if(typeof data.repl == \"function\"){\n return $B.$call(data.repl)(MatchObject.$factory($.self.mo))\n }else{\n return data.repl1\n }\n}\n\nMatchObject.group = function(self){\n var $ = $B.args(\"group\", 1, {self: null}, ['self'], arguments,\n {}, 'args', null),\n self = $.self,\n args = $.args\n if(args.length == 0){\n args[0] = 0\n }\n var groupobj = self.mo.$groups,\n result = []\n for(var group_id of args){\n if($B.rich_comp('__eq__', group_id, 0)){\n result.push(self.mo.string.substring(self.mo.start, self.mo.end))\n continue\n }\n try{\n // Convert group_id to int if possible\n group_id = $B.PyNumber_Index(group_id) // in py_utils.js\n }catch(err){\n // group_id can be an identifier\n }\n if(self.mo.node.$groups[group_id] === undefined){\n throw _b_.IndexError.$factory(\"no such group\")\n }\n var group = groupobj[group_id] // found in match\n result.push(group === undefined ?\n _b_.None :\n self.mo.string.substring(group.start, group.end))\n }\n if(args.length == 1){\n return result[0]\n }\n return $B.fast_tuple(result)\n}\n\nMatchObject.groupdict = function(){\n /*\n Return a dictionary containing all the named subgroups of the match, keyed\n by the subgroup name. The default argument is used for groups that did not\n participate in the match; it defaults to None.\n */\n var $ = $B.args(\"groupdict\", 2, {self: null, default: null},\n ['self', 'default'], arguments, {default: _b_.None},\n null, null),\n self = $.self,\n groupobj = $.self.mo.$groups,\n d = $B.empty_dict()\n for(var key in $.self.mo.node.$groups){\n if(! isFinite(key)){\n var value = groupobj[key] === undefined ? $.default :\n groupobj[key]\n if(value !== $.default){\n value = self.mo.string.substring(value.start, value.end)\n }\n _b_.dict.$setitem(d, key, value)\n }\n }\n return d\n}\n\nMatchObject.groups = function(self){\n var $ = $B.args(\"group\", 2, {self: null, default: null},\n ['self', 'default'], arguments,\n {default: _b_.None}, null, null),\n self = $.self,\n _default = $.default\n return self.mo.groups(_default)\n}\n\nMatchObject.lastindex = _b_.property.$factory(\n function(self){\n /* The integer index of the last matched capturing group, or None if\n no group was matched at all.\n */\n var last = self.mo.$groups.$last\n if(last.length == 0){\n return _b_.None\n }\n return parseInt($last(last))\n }\n)\n\nMatchObject.lastgroup = _b_.property.$factory(\n function(self){\n /* The name of the last matched capturing group, or None if the group\n didn't have a name, or if no group was matched at all.\n */\n var lastindex = MatchObject.lastindex.fget(self)\n if(lastindex === _b_.None){\n return _b_.None\n }\n var group = self.mo.node.$groups[lastindex],\n name = group.item.name\n return name === undefined ? _b_.None : name\n }\n)\n\nMatchObject.pos = _b_.property.$factory(\n function(self){\n return self.mo.start\n }\n)\n\nMatchObject.re = _b_.property.$factory(\n function(self){\n return self.mo.node.pattern\n }\n)\n\nMatchObject.regs = _b_.property.$factory(\n function(self){\n var res = [$B.fast_tuple($B.fast_tuple([self.mo.start, self.mo.end]))]\n for(var group_num in self.mo.node.$groups){\n if(isFinite(group_num)){\n var group = self.mo.node.$groups[group_num].item\n // group.pattern includes the opening and closing brackets\n res.push($B.fast_tuple([group.pos,\n group.pos + group.pattern.length - 2]))\n }\n }\n return $B.fast_tuple(res)\n }\n)\n\nMatchObject.span = function(){\n /*\n Match.span([group])\n\n For a match m, return the 2-tuple (m.start(group), m.end(group)). Note\n that if group did not contribute to the match, this is (-1, -1). group\n defaults to zero, the entire match.\n */\n var $ = $B.args(\"span\", 2, {self: null, group: null},\n ['self', 'group'], arguments,\n {group: 0}, null, null),\n self = $.self,\n group = $.group\n if(group == 0){\n return $B.fast_tuple([self.mo.start, self.mo.end])\n }\n var span = self.mo.$groups[group]\n if(span === undefined){\n return $B.fast_tuple([-1, -1])\n }\n return $B.fast_tuple([span.start, span.end])\n}\n\nMatchObject.start = function(self){\n var $ = $B.args('end', 2, {self: null, group: null}, ['self', 'group'],\n arguments, {group: 0}, null, null)\n var group = MatchObject.group(self, $.group)\n if(group === _b_.None){\n return -1\n }else if($.group == 0){\n return self.mo.start\n }else{\n return self.mo.$groups[$.group].start\n }\n}\n\nMatchObject.string = _b_.property.$factory(\n function(self){\n return self.mo.string.to_str()\n }\n)\n\n$B.set_func_names(MatchObject, 're')\n\nfunction log(){\n if(_debug.value){\n console.log.apply(null, arguments)\n }\n}\n\nfunction create_fullmatch_pattern(pattern){\n // transform into \"(?:)$\"\n // use a new pattern object, otherwise if pattern is in cache the\n // value in cache would be changed\n var new_pattern = {}\n for(var key in pattern){\n if(key == 'node'){\n continue\n }\n new_pattern[key] = pattern[key]\n }\n\n var ncgroup = new Group() // non-capturing group\n ncgroup.pos = 0\n ncgroup.non_capturing = true\n for(var item of pattern.node.items){\n ncgroup.add(item)\n }\n var se = new StringEnd()\n se.flags = Flag.$factory(32)\n new_pattern.node = new Node()\n new_pattern.node.add(ncgroup)\n new_pattern.node.add(se)\n return new_pattern\n}\n\nfunction match(pattern, string, pos, endpos, no_zero_width, groups){\n // Follow the pattern tree structure\n if(_debug.value){\n console.log('match pattern', pattern.text, 'pos', pos, string.substring(pos))\n if(pattern.text == \"\\\\.\"){\n console.log(' ', pattern)\n }\n alert()\n }\n if(endpos !== undefined){\n if(endpos < pos){\n return false\n }\n }else{\n endpos = string.length\n }\n if(pattern.node instanceof Node){\n show(pattern.node)\n }\n if(groups === undefined){\n groups = {$last:[]}\n }\n if(pattern.text === undefined){\n console.log('no text', pattern)\n }\n var node = pattern.node,\n mo\n if(node.items){\n // node is either a Choice between several items, or a sequence of\n // items\n if(node instanceof Choice){\n mo = false\n for(var _case of node.items){\n mo = match({node: _case, text: _case.text}, string, pos,\n endpos, no_zero_width, groups)\n if(mo){\n // remove groups inside choice and before successful case\n // that did not contribute to the match\n var groups_succeed = groups_in(_case),\n min_num = Math.min(Array.from(groups_succeed))\n for(var group_num of groups_in(node)){\n if(group_num < min_num){\n delete groups[group_num]\n }\n }\n if(_debug.value){\n console.log('case', _case + '', 'of choice', node +\n ' succeeds, groups', groups)\n }\n return mo\n }else{\n if(_debug.value){\n console.log('case', _case + '', 'of choice', node +\n ' fails')\n }\n }\n }\n return false\n }else{\n // sequence of items\n node.repeat = node.repeat === undefined ? {min: 1, max: 1} :\n node.repeat\n var start = pos,\n nb_repeat = 0,\n nb_zerolength_repeat = 0,\n matches = [],\n mos,\n match_start,\n empty_matches = {}\n // loop until we get enough repetitions\n while(true){\n if(empty_matches[pos]){\n // no use trying again\n return matches.length == 0 ? false :\n new GroupMO(node, start, matches, string, groups,\n endpos)\n }\n var initial_groups = Object.keys(groups)\n mos = []\n match_start = pos\n if(_debug.value){\n console.log(\"pattern\", pattern.text,\n \"loop in group match, match start\", match_start)\n }\n var i = 0\n while(i < node.items.length){\n var item = node.items[i]\n if(_debug.value){\n console.log('item', i, '/', node.items.length - 1,\n 'of pattern', pattern.text)\n }\n var mo = match({node: item, text: item + ''}, string, pos,\n endpos, no_zero_width, groups)\n if(mo){\n if(item instanceof Group &&\n item.type == \"lookahead_assertion\"){\n log(\"lookahead assertion\", item + '',\n \"succeeds, mo\", mo)\n }else{\n mos.push(mo)\n pos = mo.end\n }\n i++\n }else{\n if(_debug.value){\n console.log('item ' + item, 'of group fails, nb_repeat',\n nb_repeat, 'node repeat', node.repeat)\n }\n var backtrack = false\n while(mos.length > 0){\n var mo = mos.pop()\n if(mo.backtrack === undefined){\n log('no backtrack for', mo)\n }\n if(_debug.value){\n console.log('try backtrack on mo', mo)\n }\n if(mo.backtrack(string, groups)){\n log('can backtrack, mo', mo)\n mos.push(mo)\n i = mos.length\n log('mos', mos, 'restart at item', i)\n pos = mo.end\n backtrack = true\n break\n }\n }\n if(backtrack){\n log('backtrack ok')\n continue\n }else{\n if(node.type == \"negative_lookahead_assertion\"){\n // If a negative lookahead assertion fails,\n // return a match\n var res = new GroupMO(node, start, matches,\n string, groups, endpos)\n return res\n }\n if(nb_repeat == 0){\n // remove the groups introduced before\n // reaching this point\n for(var key in groups){\n if(initial_groups.indexOf(key) == -1){\n delete groups[key]\n }\n }\n }\n if(nb_repeat >= node.repeat.min){\n log(\"enough repetitions for node\", node)\n if(node.type == \"negative_lookahead_assertion\"){\n return false\n }\n return new GroupMO(node, start, matches, string,\n groups, endpos)\n }\n return false\n }\n }\n }\n if(node.type == \"negative_lookahead_assertion\"){\n // If a negative lookahead succeeds, return false\n return false\n }\n nb_repeat++\n if(pos > match_start){\n nb_zerolength_repeat = 0\n }else{\n nb_zerolength_repeat++\n empty_matches[pos] = true\n }\n matches.push({start: match_start, end: pos, mos})\n if(node.num !== undefined){\n groups[node.num] = $last(matches)\n if(node.name !== undefined){\n groups[node.name] = groups[node.num]\n }\n if(node.num != $last(groups.$last)){\n var ix = groups.$last.indexOf(node.num)\n if(ix > -1){\n groups.$last.splice(ix, 1)\n }\n groups.$last.push(node.num)\n }\n }\n if(nb_repeat >= node.repeat.max){\n var res = new GroupMO(node, start, matches, string,\n groups, endpos)\n if(res.start == res.end && no_zero_width){\n // no_zero_width is set when previous match in\n // iterator() had length 0; avoids infinite loops\n return false\n }\n return res\n }\n log('loop on group', pattern.text, 'nb repeats', nb_repeat,\n 'nb zero length', nb_zerolength_repeat, 'groups', groups)\n if(nb_zerolength_repeat == 65535){\n return matches.length == 0 ? false :\n new GroupMO(node, start, matches, string, groups,\n endpos)\n }\n }\n }\n }else{\n // for BackReference, Char, CharSeq, CharacterClass, CharacterSet,\n // ConditionalBackref, Lookbehind, StringStart, StringEnd\n var mo = node.match(string, pos, endpos, groups)\n if(_debug.value){\n console.log(node + '', \"mo\", mo)\n }\n if(mo){\n var len = mo.group_len === undefined ? 1 : mo.group_len,\n ix = node.non_greedy ? mo.nb_min : mo.nb_max,\n end = pos + len * ix\n return new MO(node, pos, mo, len)\n }else{\n return false\n }\n }\n}\n\n// expose re module API\nvar module = {\n cache: cache,\n compile: function(){\n var $ = $B.args(\"compile\", 2, {pattern: null, flags: null},\n ['pattern', 'flags'], arguments, {flags: no_flag},\n null, null)\n if($.pattern && $.pattern.__class__ === Pattern){\n if($.flags !== no_flag){\n throw _b_.ValueError.$factory(\n \"cannot process flags argument with a compiled pattern\")\n }\n return $.pattern\n }\n $.pattern = check_pattern_flags($.pattern, $.flags)\n var data = prepare({pattern: $.pattern})\n if(typeof $.flags == \"number\"){\n $.flags = Flag.$factory($.flags)\n }\n var jspat = compile(data.pattern, $.flags)\n return Pattern.$factory(jspat)\n },\n error: error,\n escape: function(){\n var $ = $B.args(\"escape\", 1, {pattern: null}, ['pattern'], arguments,\n {}, null, null),\n data = prepare({pattern: $.pattern}),\n pattern = data.pattern,\n res = []\n for(var cp of pattern.codepoints){\n if(escaped.indexOf(cp) > -1){\n res.push(BACKSLASH)\n }\n res.push(cp)\n }\n res = from_codepoint_list(res, data.type)\n if(data.type == \"bytes\" && $B.$isinstance(res, _b_.str)){\n res = _b_.str.encode(res, 'latin1')\n }\n return res\n },\n findall: function(){\n /* Return all non-overlapping matches of pattern in string, as a list\n of strings. The string is scanned left-to-right, and matches are\n returned in the order found. If one or more groups are present in\n the pattern, return a list of groups; this will be a list of tuples\n if the pattern has more than one group. Empty matches are included\n in the result.\n */\n var $ = $B.args(\"findall\", 3,\n {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags,\n data\n pattern = check_pattern_flags(pattern, flags)\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n }else{\n data = prepare({string, pattern})\n pattern = Pattern.$factory(compile(data.pattern, flags))\n }\n if(data.type === \"str\"){\n function conv(s){\n return s === EmptyString ? '' : s\n }\n }else{\n function conv(s){\n return string2bytes(s)\n }\n }\n\n var iter = module.finditer.apply(null, arguments).js_gen,\n res = []\n while(true){\n var next = iter.next()\n if(next.done){\n return $B.$list(res)\n }\n var bmo = next.value,\n mo = bmo.mo,\n groups = MatchObject.groups(bmo)\n\n // replace None by the empty string\n for(var i = 0, len = groups.length; i < len; i++){\n groups[i] = groups[i] === _b_.None ? \"\" : groups[i]\n }\n if(groups.length > 0){\n if(groups.length == 1){\n res.push(groups[0])\n }else{\n res.push($B.fast_tuple(groups))\n }\n }else{\n res.push(mo.string.substring(mo.start, mo.end))\n }\n }\n console.log(\"end findall\")\n },\n finditer: function(){\n var $ = $B.args(\"finditer\", 3,\n {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags\n if($B.$isinstance(string, [_b_.bytearray, _b_.memoryview])){\n string.in_iteration = true\n }\n var original_string = string,\n data\n pattern = check_pattern_flags(pattern, flags)\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n flags = pattern.flags\n }else{\n data = prepare({string, pattern})\n pattern = Pattern.$factory(compile(data.pattern, flags))\n }\n if(pattern.__class__ !== Pattern){\n throw Error(\"pattern not a Python object\")\n }\n return $B.generator.$factory(iterator)(pattern.$pattern, data.string,\n flags, original_string)\n },\n fullmatch: function(){\n var $ = $B.args(\"fullmatch\", 3, {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags\n pattern = check_pattern_flags(pattern, flags)\n var data\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n pattern = pattern.$pattern\n }else{\n data = prepare({pattern, string})\n pattern = compile(data.pattern, flags)\n }\n\n var new_pattern = create_fullmatch_pattern(pattern)\n\n // match transformed RE\n var res = match(new_pattern, data.string, 0)\n var bmo = res === false ? _b_.None : MatchObject.$factory(res)\n if(bmo !== _b_.None){\n if(bmo.mo.string.codepoints.length != bmo.mo.end - bmo.mo.start){\n return _b_.None\n }else{\n return bmo\n }\n }\n return _b_.None\n },\n Match: MatchObject,\n match: function(){\n var $ = $B.args(\"match\", 3, {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags\n pattern = check_pattern_flags(pattern, flags)\n var data\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n pattern = pattern.$pattern\n }else{\n data = prepare({pattern, string})\n pattern = compile(data.pattern, flags)\n }\n var res = match(pattern, data.string, 0)\n return res === false ? _b_.None : MatchObject.$factory(res)\n },\n Pattern,\n purge: function(){\n var $ = $B.args(\"purge\", 0, {}, [], arguments, {}, null, null)\n cache.clear()\n return _b_.None\n },\n _reconstructor,\n Scanner,\n search: function(){\n var $ = $B.args(\"search\", 3, {pattern: null, string: null, flags: null},\n ['pattern', 'string', 'flags'], arguments,\n {flags: no_flag}, null, null),\n pattern = $.pattern,\n string = $.string,\n flags = $.flags,\n data\n pattern = check_pattern_flags(pattern, flags)\n if(pattern.__class__ === Pattern){\n data = prepare({string})\n }else{\n data = prepare({string, pattern})\n pattern = Pattern.$factory(compile(data.pattern, flags))\n }\n data.pattern = pattern\n // optimizations\n if(pattern.pattern.startsWith('\\\\A') ||\n pattern.pattern.startsWith('^')){\n if(! (pattern.$pattern.node.items[0] instanceof Choice)){\n var mo = match(data.pattern.$pattern, data.string, 0)\n if(mo){\n return MatchObject.$factory(mo)\n }else if(pattern.flags.value & MULTILINE.value){\n var pos = 0,\n cp\n while((cp = data.string.cp_at(pos)) !== undefined){\n if(cp == LINEFEED){\n mo = match(data.pattern.$pattern, data.string, pos + 1)\n if(mo){\n return MatchObject.$factory(mo)\n }\n }\n pos++\n }\n }else{\n return _b_.None\n }\n }\n }\n if(pattern.$pattern.fixed_length !== false &&\n isFinite(pattern.$pattern.fixed_length) &&\n pattern.pattern.endsWith('$') &&\n ! (pattern.flags.value & MULTILINE.value)){\n var mo = match(data.pattern.$pattern, data.string,\n data.string.length - pattern.$pattern.fixed_length)\n if(mo){\n return MatchObject.$factory(mo)\n }\n return _b_.None\n }\n var pos = 0\n if(data.string.codepoints.length == 0){\n mo = match(data.pattern.$pattern, data.string, 0)\n if(mo){\n mo.start = mo.end = 0\n }\n return mo ? MatchObject.$factory(mo) : _b_.None\n }\n while(pos < data.string.codepoints.length){\n var mo = match(data.pattern.$pattern, data.string, pos)\n if(mo){\n return MatchObject.$factory(mo)\n }else{\n pos++\n }\n }\n return _b_.None\n },\n set_debug: function(value){\n _debug.value = value\n },\n split: function(){\n var $ = $B.args(\"split\", 4,\n {pattern: null, string: null, maxsplit: null, flags: null},\n ['pattern', 'string', 'maxsplit', 'flags'],\n arguments, {maxsplit: 0, flags: no_flag}, null, null)\n var res = [],\n pattern = $.pattern,\n string = $.string,\n flags = $.flags,\n pos = 0,\n nb_split = 0,\n data\n if(pattern.__class__ !== Pattern){\n data = prepare({pattern, string})\n var comp = compile(data.pattern, flags)\n pattern = Pattern.$factory(comp)\n }else{\n data = {pattern, string}\n }\n for(var bmo of module.finditer(pattern, $.string).js_gen){\n var mo = bmo.mo, // finditer returns instances of MatchObject\n groupobj = mo.$groups\n res.push(data.string.substring(pos, mo.start))\n for(var key in mo.node.$groups){\n if(isFinite(key)){\n if(groupobj[key] !== undefined){\n res.push(data.string.substring(groupobj[key].start,\n groupobj[key].end))\n }else{\n res.push(_b_.None)\n }\n }\n }\n nb_split++\n pos = mo.end\n if(pos >= $.string.length){\n break\n }\n if($.maxsplit != 0 && nb_split >= $.maxsplit){\n break\n }\n }\n res.push(data.string.substring(pos))\n if(data.type === \"bytes\"){\n res = res.map(\n function(x){\n return $B.$isinstance(x, _b_.bytes) ?\n x :\n _b_.str.encode(x, \"latin-1\")\n }\n )\n }\n return $B.$list(res)\n },\n sub: function(){\n var $ = $B.args(\"sub\", 5,\n {pattern: null, repl: null, string: null, count: null, flags: null},\n ['pattern', 'repl', 'string', 'count', 'flags'],\n arguments, {count: 0, flags: no_flag}, null, null),\n pattern = $.pattern,\n repl = $.repl,\n string = $.string,\n count = $.count,\n flags = $.flags,\n data\n check_pattern_flags(pattern, flags)\n if(typeof repl != \"function\"){\n if(pattern.__class__ != Pattern){\n data = prepare({pattern, string, repl})\n pattern = compile(data.pattern, flags)\n }else{\n data = prepare({string, repl})\n flags = pattern.flags\n pattern = pattern.$pattern\n }\n data = transform_repl(data, pattern)\n }else{\n if(pattern.__class__ != Pattern){\n data = prepare({pattern, string})\n pattern = compile(data.pattern, flags)\n }else{\n data = prepare({string})\n flags = pattern.flags\n pattern = pattern.$pattern\n }\n data.repl = repl\n }\n return subn(pattern, data.repl, data.string, count, flags)[0]\n },\n subn: function(){\n var $ = $B.args(\"sub\", 5,\n {pattern: null, repl: null, string: null, count: null, flags: null},\n ['pattern', 'repl', 'string', 'count', 'flags'],\n arguments, {count: 0, flags: no_flag}, null, null),\n pattern = $.pattern,\n repl = $.repl,\n string = $.string,\n count = $.count,\n flags = $.flags,\n data\n if(pattern.__class__ != Pattern){\n data = prepare({pattern, repl, string})\n }else{\n data = prepare({repl, string})\n data.pattern = pattern.$pattern\n }\n return $B.fast_tuple(subn(data.pattern, data.repl, data.string, count,\n flags))\n }\n\n}\n\nvar ASCII = module.A = module.ASCII = Flag.$factory(256)\nvar IGNORECASE = module.I = module.IGNORECASE = Flag.$factory(2)\nvar LOCALE = module.L = module.LOCALE = Flag.$factory(4)\nvar MULTILINE = module.M = module.MULTILINE = Flag.$factory(8)\nvar DOTALL = module.S = module.DOTALL = Flag.$factory(16)\nvar U = module.U = module.UNICODE = Flag.$factory(32)\nvar VERBOSE = module.X = module.VERBOSE = Flag.$factory(64)\nmodule.cache = cache\nmodule._compile = module.compile\n\n\nvar inline_flags = {\n i: IGNORECASE,\n L: LOCALE,\n m: MULTILINE,\n s: DOTALL,\n u: U,\n x: VERBOSE,\n a: ASCII\n}\n\nvar flag_names = {\n i: 'IGNORECASE',\n L: 'LOCALE',\n m: 'MULTILINE',\n s: 'DOTALL',\n u: 'U',\n x: 'VERBOSE',\n a: 'ASCII'\n}\n\n$B.addToImported('python_re', module)\n\n})(__BRYTHON__)"], "unicodedata": [".js", "// Implementation of unicodedata\n(function($B){\n\n var _b_ = $B.builtins\n\n // Load unicode table if not already loaded\n if($B.unicodedb === undefined){\n var xhr = new XMLHttpRequest\n xhr.open(\"GET\",\n $B.brython_path + \"unicode.txt\", false)\n xhr.onreadystatechange = function(){\n if(this.readyState == 4){\n if(this.status == 200){\n $B.unicodedb = this.responseText\n }else{\n console.log(\"Warning - could not \" +\n \"load unicode.txt\")\n }\n }\n }\n xhr.send()\n }\n\n function _info(chr){\n var ord = _b_.ord(chr),\n hex = ord.toString(16).toUpperCase()\n while(hex.length < 4){hex = \"0\" + hex}\n var re = new RegExp(\"^\" + hex +\";(.+?);(.*?);(.*?);(.*?);(.*?);(.*);(.*);(.*)$\",\n \"m\"),\n search = re.exec($B.unicodedb)\n if(search === null){\n return null\n }else{\n return {\n name: search[1],\n category: search[2],\n combining: search[3],\n bidirectional: search[4],\n decomposition: search[5],\n decimal: search[6],\n digit: search[7],\n numeric: search[8]\n }\n }\n }\n\n function bidirectional(chr){\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr, hex)\n throw _b_.KeyError.$factory(chr)\n }\n return search.bidirectional\n }\n\n function category(chr){\n // Returns the general category assigned to the character chr as\n // string.\n if(/\\p{Cn}/u.test(chr.charAt(0))){\n return \"Cn\"\n }\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return search.category\n }\n\n function combining(chr){\n // Returns the general category assigned to the character chr as\n // string.\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return parseInt(search.combining)\n }\n\n function decimal(chr, _default){\n // Returns the decimal value assigned to the character chr as integer.\n // If no such value is defined, default is returned, or, if not given,\n // ValueError is raised.\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return parseInt(search.decimal)\n }\n\n function decomposition(chr, _default){\n // Returns the decimal value assigned to the character chr as integer.\n // If no such value is defined, default is returned, or, if not given,\n // ValueError is raised.\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return search.decomposition\n }\n\n function digit(chr, _default){\n // Returns the decimal value assigned to the character chr as integer.\n // If no such value is defined, default is returned, or, if not given,\n // ValueError is raised.\n var search = _info(chr)\n if(search === null){\n console.log(\"error\", chr)\n throw _b_.KeyError.$factory(chr)\n }\n return parseInt(search.digit)\n }\n\n function lookup(name){\n // Look up character by name. If a character with the given name is\n // found, return the corresponding character. If not found, KeyError\n // is raised.\n var re = new RegExp(\"^([0-9A-F]+);\" +\n name + \";(.*)$\", \"m\")\n search = re.exec($B.unicodedb)\n if(search === null){\n throw _b_.KeyError.$factory(\"undefined character name '\" +\n name + \"'\")\n }\n var res = parseInt(search[1], 16)\n return _b_.chr(res)\n }\n\n function name(chr, _default){\n // Returns the name assigned to the character chr as a string. If no\n // name is defined, default is returned, or, if not given, ValueError\n // is raised.\n var search = _info(chr)\n if(search === null){\n if(_default){return _default}\n throw _b_.KeyError.$factory(\"undefined character name '\" +\n chr + \"'\")\n }\n return search.name\n }\n\n function _norm(form, chr){\n var search = _info(chr)\n if(search === null){\n throw _b_.KeyError.$factory(chr)\n }\n switch(form){\n case \"NFC\":\n return chr\n case \"NFD\":\n var decomp = decomposition(chr),\n parts = decomp.split(\" \"),\n res = \"\"\n if(parts[0].startsWith(\"<\")){\n return chr\n }\n parts.forEach(function(part){\n if(! part.startsWith(\"<\")){\n res += _b_.chr(parseInt(part, 16))\n }\n })\n return res\n case \"NFKC\":\n var decomp = decomposition(chr),\n parts = decomp.split(\" \")\n if(parts[0] == \"\"){\n var res = \"\"\n parts.slice(1).forEach(function(part){\n res += _b_.chr(parseInt(part, 16))\n })\n return res\n }\n return chr\n case \"NFKD\":\n var decomp = decomposition(chr),\n parts = decomp.split(\" \")\n if(parts[0] == \"\"){\n var res = \"\"\n parts.slice(1).forEach(function(part){\n res += _b_.chr(parseInt(part, 16))\n })\n return res\n }\n return chr\n\n default:\n throw _b_.ValueError.$factory(\"invalid normalization form\")\n }\n }\n\n function normalize(form, unistr){\n var res = \"\"\n for(var i = 0, len = unistr.length; i < len; i++){\n res += _norm(form, unistr.charAt(i))\n }\n return res\n }\n\n function numeric(chr, _default){\n // Returns the decimal value assigned to the character chr as integer.\n // If no such value is defined, default is returned, or, if not given,\n // ValueError is raised.\n var search = _info(chr)\n if(search === null){\n if(_default){return _default}\n throw _b_.KeyError.$factory(chr)\n }\n var parts = search.numeric.split('/'),\n value\n if(parts.length == 1){\n value = parseFloat(search.numeric)\n }else{\n value = parseInt(parts[0]) / parseInt(parts[1])\n }\n return $B.fast_float(value)\n }\n\n var module = {\n bidirectional: bidirectional,\n category: category,\n combining: combining,\n decimal: decimal,\n decomposition: decomposition,\n digit: digit,\n lookup: lookup,\n name: name,\n normalize: normalize,\n numeric: numeric,\n unidata_version: \"11.0.0\"\n }\n module.ucd_3_2_0 = {}\n for(var key in module){\n if(key == \"unidata_version\"){\n module.ucd_3_2_0[key] = '3.2.0'\n }else{\n module.ucd_3_2_0[key] = module[key] // approximation...\n }\n }\n $B.addToImported('unicodedata', module)\n\n})(__BRYTHON__)"], "xml_helpers": [".js", "var _b_ = $B.builtins\n\nvar FAIL = {FAIL: true}\nvar DONE = {DONE: true}\nvar END = {END: true}\n\nfunction is_id_start(char){\n return char !== END && char.match(/[a-zA-Z_]/)\n}\n\nfunction is_id_continue(char){\n return char !== END && (\".-:_\".includes(char) || char.match(/[a-zA-Z_0-9]/))\n}\n\nfunction is_space(char){\n return char !== END && ' \\t\\r\\n'.includes(char)\n}\n\nfunction is_num(char){\n return char !== END && char.match(/\\d/)\n}\n\nfunction is_char(char){\n return char !== END && ! '<&\"'.includes(char)\n}\n\nfunction get_top(element){\n while(element.origin){\n element = element.origin\n }\n return element\n}\n\nfunction get_pos(element){\n return get_top(element)._pos\n}\n\nfunction get_sub(element, start, end){\n return get_top(element)._buffer.substring(start, end)\n}\n\nfunction show_position(element, pos){\n var src = get_top(element)._buffer\n console.log(' ' + src)\n console.log(' ' + ' '.repeat(pos) + '^')\n}\n\nfunction reset_pos(element, pos){\n if(pos === undefined){\n throw Error('reset at undefined')\n }\n get_top(element)._pos = pos\n}\n\nfunction update_pos(element, pos){\n element.pos = pos\n}\n\nfunction show_path(rule){\n if(rule.constructor === undefined){\n console.log('rule', rule, 'no constructor')\n alert()\n }\n var name = rule.constructor.name\n if(name.endsWith('_rule')){\n name = name.substr(0, name.length - 5)\n }\n var t = [name + '@' + rule.pos]\n while(rule.origin){\n if(rule.origin.constructor === Object){\n break\n }\n name = rule.origin.constructor.name\n if(name.endsWith('_rule_')){\n name = name.substr(0, name.length - 5)\n }\n t.push(name + '@' + rule.origin.pos)\n rule = rule.origin\n }\n\n console.log('show path', t)\n}\n\nfunction set_expect(element, expect){\n var test = false // element.constructor.name == 'Attribute_rule' && expect == 1\n if(test){\n console.log('set expect of', element)\n console.log(` >>> set expect of ${element.constructor.name} to ${expect}`)\n alert()\n }\n element.expect = expect\n if(element.rules[expect]){\n var rule = element.rules[expect]\n rule.start = get_pos(element)\n }\n if(test){\n console.log(' !!! after set expect', element)\n alert()\n }\n}\n\nfunction read_char(element){\n var parser = get_top(element)\n return parser._buffer[parser._pos] || END\n}\n\nfunction raise_error_known_position(parser, message){\n var pos = parser._pos\n message += ' at position ' + pos\n var ix = pos\n while(ix >= 0 && parser._buffer[ix] !== '\\\\n'){\n ix--\n }\n message += '\\\\n' + parser._buffer.substring(ix, pos + 1)\n message += '\\\\n' + ' '.repeat(pos - ix - 1) + '^'\n throw Error(message)\n}\n\nfunction raise_error(element, char){\n var head = element\n while(head.origin){\n head = head.origin\n }\n console.log('head', head)\n var cls = element.constructor.name,\n message = cls + ' expected ' + element.expect +\n ', got: ' + char\n raise_error_known_position(head, message)\n}\n\nfunction get_string(rule){\n if(rule instanceof LITERAL){\n return rule.string\n }else if(rule instanceof Letter_rule ||\n rule instanceof CHARSET_rule){\n var s = get_sub(rule, rule.pos, rule.pos + 1)\n return s\n }\n if(rule.items === undefined){\n console.log('no items for rule', rule)\n }\n if(rule.constructor.name == 'element_rule'){\n console.log('get string of', rule)\n alert()\n }\n var s = ''\n for(var i = 0, len = rule.items.length; i < len; i++){\n var item = rule.items[i],\n last = item[item.length - 1]\n if(rule.result_store[i] === undefined){\n continue\n }\n if('?+*'.includes(last)){\n s += rule.result_store[i].join('')\n }else{\n s += rule.result_store[i]\n }\n }\n return s\n}\n\nfunction get_value(rule){\n // get string value for rule\n if(rule === undefined){\n console.log(Error().stack)\n }\n var res = ''\n if(rule.value){\n return rule.value\n }else if(rule.alt && rule.selected_rule){\n if(false){ //get_parent(rule, tmp_7_rule)){\n console.log('get_value, selected rule', rule.selected_rule)\n }\n return get_value(rule.selected_rule)\n }else{\n for(var rank in rule.result_store){\n var rules = rule.result_store[rank]\n if(Array.isArray(rules)){\n res += rules.map(get_value).join('')\n }else{\n res += get_value(rules)\n }\n }\n }\n return res\n}\n\nfunction get_rank(rule){\n return parseInt(Object.keys(rule.result_store)[0])\n}\n\nfunction get_parent(rule, type){\n var parent = rule.origin\n while(parent){\n if(parent instanceof type){\n return parent\n }\n parent = parent.origin\n }\n return null\n}\n\nfunction get_doctype_info(rule){\n console.log('get doctype info', rule)\n var systemId = _b_.None,\n publicId = _b_.None\n if(get_value(rule.rules[3])){\n ext_id = external_id(rule.rules[3].rules[1])\n console.log('ext_id 259', ext_id)\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n }\n var name = get_value(rule.rules[2])\n return {name, systemId, publicId}\n}\n\nfunction external_id(ext_id){\n var ext_id_value = get_value(ext_id),\n systemId = _b_.None,\n publicId = _b_.None\n if(ext_id_value){\n switch(ext_id.selected_option){\n case 0:\n systemId = get_value(ext_id.selected_rule.rules[2])\n systemId = systemId.substr(1, systemId.length - 2)\n break\n case 1:\n publicId = get_value(ext_id.selected_rule.rules[2])\n systemId = get_value(ext_id.selected_rule.rules[4])\n publicId = publicId.substr(1, publicId.length - 2)\n systemId = systemId.substr(1, systemId.length - 2)\n break\n }\n }\n return {publicId, systemId}\n}\n\nfunction fromCharRef(v){\n if(v.startsWith('&#x')){\n v = String.fromCodePoint(parseInt(v.substr(3)))\n }else if(v.startsWith('&#')){\n v = String.fromCodePoint(parseInt(v.substr(2)))\n }\n return v\n}\n\nvar handler = {\n AttDef: function(parser, rule){\n // S Name S AttType S DefaultDecl\n var defaultdecl = rule.rules[5],\n def_value = _b_.None,\n required = 0\n switch(defaultdecl.selected_option){\n case 0:\n required = true\n break\n case 2:\n def_value = get_value(defaultdecl.rules[2].rules[1])\n break\n }\n var res = {\n elname: get_value(rule.origin.rules[2]),\n attname: get_value(rule.rules[1]),\n type: get_value(rule.rules[3]),\n default: def_value,\n required\n }\n var f = $B.$getattr(parser, \"AttlistDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.elname, res.attname, res.type, res.default, res.required)\n }\n return res\n },\n CData: function(parser, rule){\n var f = $B.$getattr(parser, \"StartCdataSectionHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n var chardata = get_value(rule)\n var f = $B.$getattr(parser, \"CharacterDataHandler\", null)\n if(f !== null){\n $B.$call(f)(chardata)\n }\n var f = $B.$getattr(parser, \"EndCdataSectionHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n return {value: get_value(rule)}\n },\n CharData: function(parser, rule){\n console.log('chardata', rule)\n var value = get_value(rule)\n var f = $B.$getattr(parser, \"CharacterDataHandler\", null)\n if(f !== null){\n $B.$call(f)(value)\n }\n return {value: get_value(rule)}\n },\n Comment: function(parser, rule){\n console.log('comment', rule)\n var value = get_value(rule.rules[1])\n var f = $B.$getattr(parser, \"CommentHandler\", null)\n if(f !== null){\n $B.$call(f)(value)\n }\n return {value}\n },\n doctypedecl: function(parser, rule){\n console.log('doctype', rule, 'ext id', get_value(rule.rules[3]))\n if(! rule.start_done){\n // if doctype has no intSubset\n var info = get_doctype_info(rule)\n var f = $B.$getattr(parser, \"StartDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(info.name, info.systemId, info.publicId, false)\n }\n }\n if(rule.hasExternal && parser.standalone == 0){\n var f = $B.$getattr(parser, \"NotStandaloneHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n }\n var f = $B.$getattr(parser, \"EndDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n\n },\n elementdecl: function(parser, rule){\n console.log('element decl', rule)\n var name = get_value(rule.rules[2]),\n model = get_value(rule.rules[4])\n switch(model){\n case 'ANY':\n model = $B.fast_tuple([models.XML_CTYPE_ANY, 0, _b_.None, $B.fast_tuple([])])\n break\n }\n var f = $B.$getattr(parser, \"ElementDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(name, model)\n }\n\n return {name, model}\n },\n ETag: function(parser, rule){\n var name = get_value(rule.rules[1]),\n is_ns_decl\n if(parser.namespaces && parser.namespaces.hasOwnProperty(name)){\n var ns_name = name.split(':')[0]\n is_ns_decl = true\n name = parser.namespaces[name]\n }\n var f = $B.$getattr(parser, \"EndElementHandler\", null)\n if(f !== null){\n $B.$call(f)(name)\n }\n if(is_ns_decl){\n var f = $B.$getattr(parser, \"EndNamespaceDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(ns_name)\n }\n }\n return {name: get_value(rule.rules[1])}\n },\n ExternalID: function(parser, rule){\n var doctype = get_parent(rule, doctypedecl_rule)\n doctype.hasExternal = true\n },\n GEDecl: function(parser, rule){\n // ''\n var entitydef = rule.rules[4],\n value = _b_.None,\n base = _b_.None,\n systemId = _b_.None,\n publicId = _b_.None,\n notationName = _b_.None\n // EntityValue | (ExternalID NDataDecl?)\n switch(entitydef.selected_option){\n case 0:\n // EntityValue ::= '\"' ([^%&\"] | PEReference | Reference)* '\"'\n // | \"'\" ([^%&'] | PEReference | Reference)* \"'\"\n var entity_value = entitydef.selected_rule.selected_rule\n console.log('entity value', entity_value)\n var value = ''\n for(var item of entity_value.result_store[1]){\n var v = get_value(entity_value.result_store[1][0])\n value += fromCharRef(v)\n }\n console.log('value', v)\n break\n case 1:\n var ext_id = external_id(entitydef.selected_rule.rules[0])\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n if(entitydef.selected_rule.result_store[1]){\n // NDataDecl ::= S 'NDATA' S Name\n notationName = get_value(entitydef.selected_rule.rules[1].rules[3])\n }\n }\n // EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)\n var res = {\n name: get_value(rule.rules[2]),\n is_parameter_entity: 0,\n value,\n systemId,\n publicId,\n notationName\n }\n var unparsed_handled\n if(res.name == \"unparsed_entity\"){\n var f = $B.$getattr(parser, \"UnparsedEntityDeclHandler\", null)\n if(f !== null){\n unparsed_handled = true\n $B.$call(f)(res.name, base,\n res.systemId, res.publicId, res.notationName)\n }\n }\n if(! unparsed_handled){\n var f = $B.$getattr(parser, \"EntityDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.name, res.is_parameter_entity, res.value, base,\n res.systemId, res.publicId, res.notationName)\n }\n }\n return res\n },\n start_intSubset: function(parser, rule){\n // Found when starting an internal subset inside a doctype declaration\n // Used to call StartDoctypeHandler with has_internal_subset set\n var doctype_decl = get_parent(rule, doctypedecl_rule),\n info = get_doctype_info(doctype_decl)\n if(doctype_decl.hasExternal && ! parser.standalone){\n var f = $B.$getattr(parser, \"NotStandaloneHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n }\n doctype_decl.start_done = true\n delete doctype_decl.sentNotStandalone\n var f = $B.$getattr(parser, \"StartDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(info.name, info.systemId, info.publicId, true)\n }\n\n },\n NotationDecl: function(parser, rule){\n // ''\n var base = _b_.None,\n systemId = _b_.None,\n publicId = _b_.None,\n ext_or_public = rule.rules[4]\n\n switch(ext_or_public.selected_option){\n case 0:\n var ext_id = external_id(ext_or_public.selected_rule)\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n break\n case 1:\n publicId = get_value(ext_or_public.selected_rule.rules[2])\n break\n }\n var res = {\n name: get_value(rule.rules[2]),\n base,\n systemId,\n publicId\n }\n var f = $B.$getattr(parser, \"NotationDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.name, res.base, res.systemId, res.publicId)\n }\n\n return res\n },\n PI: function(parser, rule){\n console.log('PI', rule)\n var name = get_value(rule.rules[1].rules[0]),\n attrs = get_value(rule.rules[2]).trimLeft()\n var f = $B.$getattr(parser, \"ProcessingInstructionHandler\", null)\n if(f !== null){\n $B.$call(f)(name, attrs)\n }\n return {name, attrs}\n },\n STag: function(parser, rule){\n var name = get_value(rule.rules[1])\n var attrs = rule.result_store[2],\n attr_result = $B.empty_dict()\n if(attrs){\n for(var attr of attrs){\n var attr_value_store = attr.result_store[1].result_store[2].selected_rule.result_store[1],\n attr_value = ''\n for(var item of attr_value_store){\n var v = get_value(item)\n attr_value += fromCharRef(v)\n }\n var attr_name = get_value(attr.result_store[1].result_store[0])\n if(attr_name.startsWith('xmlns:')){\n var prefix = attr_name.substr(6),\n uri = attr_value\n var name1 = uri + '!' + name.split(':')[1]\n parser.namespaces = parser.namespaces ?? {}\n parser.namespaces[name] = name1\n name = name1\n var f = $B.$getattr(parser, \"StartNamespaceDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(prefix, uri)\n }\n }else{\n _b_.dict.$setitem(attr_result, attr_name, attr_value)\n }\n }\n }\n var f = $B.$getattr(parser, \"StartElementHandler\", null)\n if(f !== null){\n $B.$call(f)(name, attr_result)\n }\n return {name, attr_result}\n },\n XMLDecl: function(parser, rule){\n // ''\n var encoding,\n standalone = -1\n if(rule.result_store[2]){\n // S 'encoding' Eq ('\"' EncName '\"' | \"'\" EncName \"'\" )\n encoding = get_value(rule.rules[2].rules[3].selected_rule.rules[1])\n }\n if(rule.result_store[3]){\n // S 'standalone' Eq ((\"'\" ('yes' | 'no') \"'\") | ('\"' ('yes' | 'no') '\"'))\n sddecl = rule.rules[3]\n standalone = get_value(sddecl.rules[3].selected_rule.rules[1])\n standalone = standalone == 'yes' ? 1 : 0\n }\n parser.standalone = standalone // used for NotStandaloneHandler\n var attr_result = $B.empty_dict(),\n attrs = {\n version: get_value(rule.rules[1].rules[3].selected_rule.rules[1]),\n encoding,\n standalone\n }\n for(var attr in attrs){\n _b_.dict.$setitem(attr_result, attr, attrs[attr])\n }\n var f = $B.$getattr(parser, \"XmlDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(attrs.version, attrs.encoding, attrs.standalone)\n }\n return {name, attr_result}\n }\n}\n\n\nfunction emit(rule){\n // called when a rule is done\n var rname = rule.constructor.name\n rname = rname.substr(0, rname.length - 5)\n if(handler[rname]){\n var parser = get_top(rule)\n // console.log('emit', rname)\n handler[rname](parser, rule)\n }\n}\n\nfunction handle_simple(element, next_if_ok, rule, char){\n if(char === FAIL){\n if(typeof element.origin.feed !== 'function'){\n console.log('not a func', element)\n }\n return element.origin.feed(FAIL)\n }else if(char === DONE){\n element.result_store[element.expect] = rule // get_sub(rule, rule.pos, get_pos(rule)) // get_string(rule)\n var test = (rule.constructor.name == 'element_rule' ||\n rule.constructor.name == 'Attribute_rule')\n rule.reset()\n emit(rule)\n set_expect(element, next_if_ok)\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_plus(element, rank, next_if_ok, rule, char){\n if(char === FAIL){\n if(element.repeats[rank] == 0){\n reset_pos(element, rule.pos)\n return element.origin.feed(FAIL)\n }\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n //rule.reset()\n emit(rule)\n set_expect(element, next_if_ok)\n delete element.rules[rank]\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_star(element, rank, next_if_ok, rule, char){\n var test = false // rule instanceof tmp_6_rule\n if(test){\n console.log('HANDLE STAR', rule, 'char', char)\n }\n if(char === FAIL){\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n if(test){\n console.log(rule, 'DONE')\n }\n if(rule.alt){\n element.selected_option = element.expect\n element.selected_rule = rule\n }\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n //rule.reset()\n emit(rule)\n delete element.rules[rank]\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_zero_or_one(element, rank, next_if_ok, rule, char){\n if(char === FAIL){\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n emit(rule)\n rule.reset()\n set_expect(element, next_if_ok)\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_alt(element, alt_index, rule, char){\n if(char === FAIL){\n set_expect(element, alt_index)\n reset_pos(element, element.pos)\n return element.origin.feed(read_char(element))\n }else if(char === DONE){\n if(['AttValue_rule'].includes(rule.constructor.name)){\n console.log('DONE', rule.constructor.name, get_sub(rule, rule.pos, get_pos(rule)))\n console.log(' ', rule)\n alert()\n }\n element.selected_option = element.expect\n element.selected_rule = rule\n element.result_store[element.expect] = rule\n emit(rule)\n rule.reset()\n return element.origin.feed(char)\n }else if(char === END){\n set_expect(element, -1)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_last(element, rule, char){\n var test = false // element instanceof tmp_6_rule\n if(test){\n console.log('handle_last', rule, char)\n alert()\n }\n if(char === FAIL){\n return element.origin.feed(FAIL)\n }else if(char === DONE){\n element.result_store[element.expect] = rule\n if(element.alt){\n element.selected_option = element.expect\n element.selected_rule = rule\n if(test){\n console.log('set selected', element)\n console.log('value', get_value(rule))\n element.coucou = 'ici'\n alert()\n }\n }\n emit(rule)\n rule.reset()\n set_expect(element, -1)\n if(test){\n console.log('return control to element', element)\n alert()\n }\n return element.feed(char)\n }else if(char === END){\n set_expect(element, -1)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction expect_literal(element, literal, char){\n if(! element.hasOwnProperty('expected_pos')){\n element.expected_pos = 0\n }\n if(literal[element.expected_pos] == char){\n element.expected_pos++\n if(element.expected_pos == literal.length){\n delete element.expected_pos\n return {value: literal}\n }else{\n return {value: null}\n }\n }\n return FAIL\n}\n\nfunction LITERAL(origin, string, next_if_ok, args){\n this.origin = origin\n this.string = string\n this.next_if_ok = next_if_ok\n this.args = args\n this.pos = get_pos(this)\n this.str_pos = 0\n}\n\nLITERAL.prototype.reset = function(){\n this.str_pos = 0\n}\n\nLITERAL.prototype.feed = function(char){\n //console.log('LITERAL', this.string, 'expects', this.string[this.str_pos], 'char', char)\n if(this.string == ''){\n console.log('LITERAL feed', this.string, char, this.str_pos)\n }\n if(this.str_pos == this.string.length){\n this.value = this.string\n return this.origin.feed(DONE)\n }\n if(char == this.string[this.str_pos]){\n this.str_pos++\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction NAME_rule(origin, next_if_ok){\n this.origin = origin\n this.rank = this.origin.expect\n this.next_if_ok = next_if_ok\n this.value = ''\n this.pos = get_pos(this)\n}\n\nNAME_rule.prototype.reset = function(){\n this.value = ''\n}\n\nNAME_rule.prototype.feed = function(char){\n console.log('NAME_rule, value', this.value, 'char', char)\n if(this.value == ''){\n if(is_id_start(char)){\n this.value = char\n }else{\n return this.origin.feed(FAIL)\n }\n }else if(is_id_continue(char)){\n this.value += char\n }else{\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction NUMBER_rule(origin, next_if_ok, args){\n this.origin = origin\n this.rank = this.origin.expect\n this.next_if_ok = next_if_ok\n this.args = args\n this.pos = get_pos(this)\n this.value = ''\n}\n\nNUMBER_rule.prototype.reset = function(){\n this.value = ''\n}\n\nNUMBER_rule.prototype.feed = function(char){\n if(this.value == ''){\n if(is_num(char)){\n this.value = char\n }else if(this.args.next_if_fail !== undefined){\n this.origin.expect = this.args.next_if_fail\n return this.origin.feed(char)\n }else{\n return FAIL\n }\n }else if(is_num(char)){\n this.value += char\n }else{\n this.origin.expect = this.next_if_ok\n this.origin.store_result(this)\n return this.origin.feed(char)\n }\n return this\n}\n\nfunction start_intSubset_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.rank = this.origin.expect\n this.value = ''\n}\n\nstart_intSubset_rule.prototype.feed = function(char){\n // always succeeds\n return this.origin.feed(DONE)\n}\n\nstart_intSubset_rule.prototype.reset = function(){\n // ignore\n}\n\nfunction S_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.rank = this.origin.expect\n this.value = ''\n}\n\nS_rule.prototype.reset = function(){\n this.value = ''\n}\n\nS_rule.prototype.feed = function(char){\n if(is_space(char)){\n this.value += char\n return this\n }else if(this.value.length > 0){\n return this.origin.feed(DONE)\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction CHAR_rule(origin, next_if_ok, args){\n this.origin = origin\n this.next_if_ok = next_if_ok\n this.args = args\n}\n\nCHAR_rule.prototype.feed = function(char){\n if(is_char(char)){\n this.value = char\n return this.origin\n }else{\n return FAIL\n }\n}\n\nvar hex_range_re = /^#x([a-fA-F0-9]+)-#x([a-fA-F0-9]+)$/\nvar charset_range_re = /(\\w)-(\\w)/g\n\n\nfunction CHARSET_rule(origin, charset, next_if_ok){\n this.origin = origin\n this.charset = charset\n this.next_if_ok = next_if_ok\n this.pos = get_pos(origin)\n this.value = ''\n var negative = charset.startsWith('^'),\n body = negative ? charset.substr(1) : charset\n\n var mo = body.match(hex_range_re)\n if(mo){\n var left = parseInt(`0x${mo[1]}`, 16),\n right = parseInt(`0x${mo[2]}`, 16)\n if(negative){\n this.test = function(char){\n var cp = char.charCodeAt(0)\n return (cp < left) || (cp > right)\n }\n }else{\n this.test = function(char){\n var cp = char.charCodeAt(0)\n return (cp >= left) && (cp <= right)\n }\n }\n return\n }\n\n var ranges = []\n for(var mo of body.matchAll(charset_range_re)){\n ranges.push(mo.slice(1))\n }\n if(ranges.length > 0){\n if(negative){\n this.test = function(char){\n for(var range of ranges){\n if(char >= range[0] && char <= range[1]){\n return false\n }\n }\n return true\n }\n }else{\n this.test = function(char){\n for(var range of ranges){\n if(char >= range[0] && char <= range[1]){\n return true\n }\n }\n return false\n }\n }\n return\n }\n\n if(charset.startsWith('^')){\n this.test = char => ! charset.substr(1).includes(char)\n }else{\n this.test = char => charset.includes(char)\n }\n}\n\nCHARSET_rule.prototype.reset = function(){\n delete this.done\n}\n\nCHARSET_rule.prototype.feed = function(char){\n if(char !== END && this.test(char)){\n this.value += char\n return this\n }else if(this.value.length > 0){\n return this.origin.feed(DONE)\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction BaseChar_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n}\n\nBaseChar_rule.prototype.reset = function(){\n delete this.done\n}\n\nBaseChar_rule.prototype.feed = function(char){\n //console.log('BaseChar_rule, char', char, 'this.done', this.done)\n if(this.done){\n return this.origin.feed(DONE)\n }else if(/\\p{L}/u.exec(char)){\n this.done = true\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction Letter_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n}\n\nLetter_rule.prototype.reset = function(){\n delete this.done\n}\n\nLetter_rule.prototype.feed = function(char){\n if(this.done){\n return this.origin.feed(DONE)\n }else if(/\\p{L}/u.exec(char)){\n this.done = true\n this.value = char\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction NameChar_rule(origin){\n this.origin = origin\n this.rank = origin.expect\n this.value = ''\n var result_store = this.origin.result_store\n result_store[this.rank] = result_store[this.rank] ?? []\n this.pos = get_pos(origin)\n}\n\nNameChar_rule.prototype.reset = function(){\n delete this.done\n}\n\nNameChar_rule.prototype.feed = function(char){\n if(this.done){\n return this.origin.feed(DONE)\n }else if(is_id_continue(char)){\n this.value += char\n return this\n }else{\n if(this.value == ''){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n}\n\nfunction PIText_rule(origin){\n this.origin = origin\n this.value = ''\n this.pos = get_pos(origin)\n}\n\nPIText_rule.prototype.reset = function(){}\n\nPIText_rule.prototype.feed = function(char){\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('?>')){\n reset_pos(this, get_pos(this) - 1)\n this.value = this.value.substr(0, this.value.length - 2)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CommentText_rule(origin){\n this.origin = origin\n this.value = ''\n this.pos = get_pos(origin)\n}\n\nCommentText_rule.prototype.reset = function(){}\n\nCommentText_rule.prototype.feed = function(char){\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('-->')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n if(this.value.endsWith('-')){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CharData_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nCharData_rule.prototype.reset = function(){}\n\nCharData_rule.prototype.feed = function(char){\n // [^<&]* - ([^<&]* ']]>' [^<&]*)\n if(char === END){\n return this.origin.feed(FAIL)\n }\n if('<&'.includes(char)){\n return this.origin.feed(DONE)\n }\n this.value += char\n if(this.value.endsWith(']]>')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CData_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nCData_rule.prototype.reset = function(){}\n\nCData_rule.prototype.feed = function(char){\n // (Char* - (Char* ']]>' Char*))\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith(']]>')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction Ignore_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nIgnore_rule.prototype.reset = function(){}\n\nIgnore_rule.prototype.feed = function(char){\n // Char* - (Char* ('') Char*)\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction PITarget_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'tmp_21']\n this.rules = []\n this.repeats = []\n}\n\nPITarget_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case 1: // tmp_21\n if(! this.rules[1]){\n this.rules[1] = new tmp_21_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n var value = get_value(this)\n if(value.toLowerCase() == 'xml'){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPITarget_rule.prototype.reset = function(){\n this.expect = 0\n}\n"], "xml_parser": [".js", "(function($B){\nvar _b_ = $B.builtins\n\nvar FAIL = {FAIL: true}\nvar DONE = {DONE: true}\nvar END = {END: true}\n\nfunction is_id_start(char){\n return char !== END && char.match(/[a-zA-Z_]/)\n}\n\nfunction is_id_continue(char){\n return char !== END && (\".-:_\".includes(char) || char.match(/[a-zA-Z_0-9]/))\n}\n\nfunction is_space(char){\n return char !== END && ' \\t\\r\\n'.includes(char)\n}\n\nfunction is_num(char){\n return char !== END && char.match(/\\d/)\n}\n\nfunction is_char(char){\n return char !== END && ! '<&\"'.includes(char)\n}\n\nfunction get_top(element){\n while(element.origin){\n element = element.origin\n }\n return element\n}\n\nfunction get_pos(element){\n return get_top(element)._pos\n}\n\nfunction get_sub(element, start, end){\n return get_top(element)._buffer.substring(start, end)\n}\n\nfunction show_position(element, pos){\n var src = get_top(element)._buffer\n console.log(' ' + src)\n console.log(' ' + ' '.repeat(pos) + '^')\n}\n\nfunction reset_pos(element, pos){\n if(pos === undefined){\n throw Error('reset at undefined')\n }\n get_top(element)._pos = pos\n}\n\nfunction update_pos(element, pos){\n element.pos = pos\n}\n\nfunction show_path(rule){\n if(rule.constructor === undefined){\n console.log('rule', rule, 'no constructor')\n alert()\n }\n var name = rule.constructor.name\n if(name.endsWith('_rule')){\n name = name.substr(0, name.length - 5)\n }\n var t = [name + '@' + rule.pos]\n while(rule.origin){\n if(rule.origin.constructor === Object){\n break\n }\n name = rule.origin.constructor.name\n if(name.endsWith('_rule_')){\n name = name.substr(0, name.length - 5)\n }\n t.push(name + '@' + rule.origin.pos)\n rule = rule.origin\n }\n\n console.log('show path', t)\n}\n\nfunction set_expect(element, expect){\n var test = false // element.constructor.name == 'Attribute_rule' && expect == 1\n if(test){\n console.log('set expect of', element)\n console.log(` >>> set expect of ${element.constructor.name} to ${expect}`)\n alert()\n }\n element.expect = expect\n if(element.rules[expect]){\n var rule = element.rules[expect]\n rule.start = get_pos(element)\n }\n if(test){\n console.log(' !!! after set expect', element)\n alert()\n }\n}\n\nfunction read_char(element){\n var parser = get_top(element)\n return parser._buffer[parser._pos] || END\n}\n\nfunction raise_error_known_position(parser, message){\n var pos = parser._pos\n message += ' at position ' + pos\n var ix = pos\n while(ix >= 0 && parser._buffer[ix] !== '\\\\n'){\n ix--\n }\n message += '\\\\n' + parser._buffer.substring(ix, pos + 1)\n message += '\\\\n' + ' '.repeat(pos - ix - 1) + '^'\n throw Error(message)\n}\n\nfunction raise_error(element, char){\n var head = element\n while(head.origin){\n head = head.origin\n }\n console.log('head', head)\n var cls = element.constructor.name,\n message = cls + ' expected ' + element.expect +\n ', got: ' + char\n raise_error_known_position(head, message)\n}\n\nfunction get_string(rule){\n if(rule instanceof LITERAL){\n return rule.string\n }else if(rule instanceof Letter_rule ||\n rule instanceof CHARSET_rule){\n var s = get_sub(rule, rule.pos, rule.pos + 1)\n return s\n }\n if(rule.items === undefined){\n console.log('no items for rule', rule)\n }\n if(rule.constructor.name == 'element_rule'){\n console.log('get string of', rule)\n alert()\n }\n var s = ''\n for(var i = 0, len = rule.items.length; i < len; i++){\n var item = rule.items[i],\n last = item[item.length - 1]\n if(rule.result_store[i] === undefined){\n continue\n }\n if('?+*'.includes(last)){\n s += rule.result_store[i].join('')\n }else{\n s += rule.result_store[i]\n }\n }\n return s\n}\n\nfunction get_value(rule){\n // get string value for rule\n if(rule === undefined){\n console.log(Error().stack)\n }\n var res = ''\n if(rule.value){\n return rule.value\n }else if(rule.alt && rule.selected_rule){\n if(false){ //get_parent(rule, tmp_7_rule)){\n console.log('get_value, selected rule', rule.selected_rule)\n }\n return get_value(rule.selected_rule)\n }else{\n for(var rank in rule.result_store){\n var rules = rule.result_store[rank]\n if(Array.isArray(rules)){\n res += rules.map(get_value).join('')\n }else{\n res += get_value(rules)\n }\n }\n }\n return res\n}\n\nfunction get_rank(rule){\n return parseInt(Object.keys(rule.result_store)[0])\n}\n\nfunction get_parent(rule, type){\n var parent = rule.origin\n while(parent){\n if(parent instanceof type){\n return parent\n }\n parent = parent.origin\n }\n return null\n}\n\nfunction get_doctype_info(rule){\n console.log('get doctype info', rule)\n var systemId = _b_.None,\n publicId = _b_.None\n if(get_value(rule.rules[3])){\n ext_id = external_id(rule.rules[3].rules[1])\n console.log('ext_id 259', ext_id)\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n }\n var name = get_value(rule.rules[2])\n return {name, systemId, publicId}\n}\n\nfunction external_id(ext_id){\n var ext_id_value = get_value(ext_id),\n systemId = _b_.None,\n publicId = _b_.None\n if(ext_id_value){\n switch(ext_id.selected_option){\n case 0:\n systemId = get_value(ext_id.selected_rule.rules[2])\n systemId = systemId.substr(1, systemId.length - 2)\n break\n case 1:\n publicId = get_value(ext_id.selected_rule.rules[2])\n systemId = get_value(ext_id.selected_rule.rules[4])\n publicId = publicId.substr(1, publicId.length - 2)\n systemId = systemId.substr(1, systemId.length - 2)\n break\n }\n }\n return {publicId, systemId}\n}\n\nfunction fromCharRef(v){\n if(v.startsWith('&#x')){\n v = String.fromCodePoint(parseInt(v.substr(3)))\n }else if(v.startsWith('&#')){\n v = String.fromCodePoint(parseInt(v.substr(2)))\n }\n return v\n}\n\nvar handler = {\n AttDef: function(parser, rule){\n // S Name S AttType S DefaultDecl\n var defaultdecl = rule.rules[5],\n def_value = _b_.None,\n required = 0\n switch(defaultdecl.selected_option){\n case 0:\n required = true\n break\n case 2:\n def_value = get_value(defaultdecl.rules[2].rules[1])\n break\n }\n var res = {\n elname: get_value(rule.origin.rules[2]),\n attname: get_value(rule.rules[1]),\n type: get_value(rule.rules[3]),\n default: def_value,\n required\n }\n var f = $B.$getattr(parser, \"AttlistDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.elname, res.attname, res.type, res.default, res.required)\n }\n return res\n },\n CData: function(parser, rule){\n var f = $B.$getattr(parser, \"StartCdataSectionHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n var chardata = get_value(rule)\n var f = $B.$getattr(parser, \"CharacterDataHandler\", null)\n if(f !== null){\n $B.$call(f)(chardata)\n }\n var f = $B.$getattr(parser, \"EndCdataSectionHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n return {value: get_value(rule)}\n },\n CharData: function(parser, rule){\n console.log('chardata', rule)\n var value = get_value(rule)\n var f = $B.$getattr(parser, \"CharacterDataHandler\", null)\n if(f !== null){\n $B.$call(f)(value)\n }\n return {value: get_value(rule)}\n },\n Comment: function(parser, rule){\n console.log('comment', rule)\n var value = get_value(rule.rules[1])\n var f = $B.$getattr(parser, \"CommentHandler\", null)\n if(f !== null){\n $B.$call(f)(value)\n }\n return {value}\n },\n doctypedecl: function(parser, rule){\n console.log('doctype', rule, 'ext id', get_value(rule.rules[3]))\n if(! rule.start_done){\n // if doctype has no intSubset\n var info = get_doctype_info(rule)\n var f = $B.$getattr(parser, \"StartDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(info.name, info.systemId, info.publicId, false)\n }\n }\n if(rule.hasExternal && parser.standalone == 0){\n var f = $B.$getattr(parser, \"NotStandaloneHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n }\n var f = $B.$getattr(parser, \"EndDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n\n },\n elementdecl: function(parser, rule){\n console.log('element decl', rule)\n var name = get_value(rule.rules[2]),\n model = get_value(rule.rules[4])\n switch(model){\n case 'ANY':\n model = $B.fast_tuple([models.XML_CTYPE_ANY, 0, _b_.None, $B.fast_tuple([])])\n break\n }\n var f = $B.$getattr(parser, \"ElementDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(name, model)\n }\n\n return {name, model}\n },\n ETag: function(parser, rule){\n var name = get_value(rule.rules[1]),\n is_ns_decl\n if(parser.namespaces && parser.namespaces.hasOwnProperty(name)){\n var ns_name = name.split(':')[0]\n is_ns_decl = true\n name = parser.namespaces[name]\n }\n var f = $B.$getattr(parser, \"EndElementHandler\", null)\n if(f !== null){\n $B.$call(f)(name)\n }\n if(is_ns_decl){\n var f = $B.$getattr(parser, \"EndNamespaceDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(ns_name)\n }\n }\n return {name: get_value(rule.rules[1])}\n },\n ExternalID: function(parser, rule){\n var doctype = get_parent(rule, doctypedecl_rule)\n doctype.hasExternal = true\n },\n GEDecl: function(parser, rule){\n // ''\n var entitydef = rule.rules[4],\n value = _b_.None,\n base = _b_.None,\n systemId = _b_.None,\n publicId = _b_.None,\n notationName = _b_.None\n // EntityValue | (ExternalID NDataDecl?)\n switch(entitydef.selected_option){\n case 0:\n // EntityValue ::= '\"' ([^%&\"] | PEReference | Reference)* '\"'\n // | \"'\" ([^%&'] | PEReference | Reference)* \"'\"\n var entity_value = entitydef.selected_rule.selected_rule\n console.log('entity value', entity_value)\n var value = ''\n for(var item of entity_value.result_store[1]){\n var v = get_value(entity_value.result_store[1][0])\n value += fromCharRef(v)\n }\n console.log('value', v)\n break\n case 1:\n var ext_id = external_id(entitydef.selected_rule.rules[0])\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n if(entitydef.selected_rule.result_store[1]){\n // NDataDecl ::= S 'NDATA' S Name\n notationName = get_value(entitydef.selected_rule.rules[1].rules[3])\n }\n }\n // EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)\n var res = {\n name: get_value(rule.rules[2]),\n is_parameter_entity: 0,\n value,\n systemId,\n publicId,\n notationName\n }\n var unparsed_handled\n if(res.name == \"unparsed_entity\"){\n var f = $B.$getattr(parser, \"UnparsedEntityDeclHandler\", null)\n if(f !== null){\n unparsed_handled = true\n $B.$call(f)(res.name, base,\n res.systemId, res.publicId, res.notationName)\n }\n }\n if(! unparsed_handled){\n var f = $B.$getattr(parser, \"EntityDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.name, res.is_parameter_entity, res.value, base,\n res.systemId, res.publicId, res.notationName)\n }\n }\n return res\n },\n start_intSubset: function(parser, rule){\n // Found when starting an internal subset inside a doctype declaration\n // Used to call StartDoctypeHandler with has_internal_subset set\n var doctype_decl = get_parent(rule, doctypedecl_rule),\n info = get_doctype_info(doctype_decl)\n if(doctype_decl.hasExternal && ! parser.standalone){\n var f = $B.$getattr(parser, \"NotStandaloneHandler\", null)\n if(f !== null){\n $B.$call(f)()\n }\n }\n doctype_decl.start_done = true\n delete doctype_decl.sentNotStandalone\n var f = $B.$getattr(parser, \"StartDoctypeDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(info.name, info.systemId, info.publicId, true)\n }\n\n },\n NotationDecl: function(parser, rule){\n // ''\n var base = _b_.None,\n systemId = _b_.None,\n publicId = _b_.None,\n ext_or_public = rule.rules[4]\n\n switch(ext_or_public.selected_option){\n case 0:\n var ext_id = external_id(ext_or_public.selected_rule)\n systemId = ext_id.systemId\n publicId = ext_id.publicId\n break\n case 1:\n publicId = get_value(ext_or_public.selected_rule.rules[2])\n break\n }\n var res = {\n name: get_value(rule.rules[2]),\n base,\n systemId,\n publicId\n }\n var f = $B.$getattr(parser, \"NotationDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(res.name, res.base, res.systemId, res.publicId)\n }\n\n return res\n },\n PI: function(parser, rule){\n console.log('PI', rule)\n var name = get_value(rule.rules[1].rules[0]),\n attrs = get_value(rule.rules[2]).trimLeft()\n var f = $B.$getattr(parser, \"ProcessingInstructionHandler\", null)\n if(f !== null){\n $B.$call(f)(name, attrs)\n }\n return {name, attrs}\n },\n STag: function(parser, rule){\n var name = get_value(rule.rules[1])\n var attrs = rule.result_store[2],\n attr_result = $B.empty_dict()\n if(attrs){\n for(var attr of attrs){\n var attr_value_store = attr.result_store[1].result_store[2].selected_rule.result_store[1],\n attr_value = ''\n for(var item of attr_value_store){\n var v = get_value(item)\n attr_value += fromCharRef(v)\n }\n var attr_name = get_value(attr.result_store[1].result_store[0])\n if(attr_name.startsWith('xmlns:')){\n var prefix = attr_name.substr(6),\n uri = attr_value\n var name1 = uri + '!' + name.split(':')[1]\n parser.namespaces = parser.namespaces ?? {}\n parser.namespaces[name] = name1\n name = name1\n var f = $B.$getattr(parser, \"StartNamespaceDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(prefix, uri)\n }\n }else{\n _b_.dict.$setitem(attr_result, attr_name, attr_value)\n }\n }\n }\n var f = $B.$getattr(parser, \"StartElementHandler\", null)\n if(f !== null){\n $B.$call(f)(name, attr_result)\n }\n return {name, attr_result}\n },\n XMLDecl: function(parser, rule){\n // ''\n var encoding,\n standalone = -1\n if(rule.result_store[2]){\n // S 'encoding' Eq ('\"' EncName '\"' | \"'\" EncName \"'\" )\n encoding = get_value(rule.rules[2].rules[3].selected_rule.rules[1])\n }\n if(rule.result_store[3]){\n // S 'standalone' Eq ((\"'\" ('yes' | 'no') \"'\") | ('\"' ('yes' | 'no') '\"'))\n sddecl = rule.rules[3]\n standalone = get_value(sddecl.rules[3].selected_rule.rules[1])\n standalone = standalone == 'yes' ? 1 : 0\n }\n parser.standalone = standalone // used for NotStandaloneHandler\n var attr_result = $B.empty_dict(),\n attrs = {\n version: get_value(rule.rules[1].rules[3].selected_rule.rules[1]),\n encoding,\n standalone\n }\n for(var attr in attrs){\n _b_.dict.$setitem(attr_result, attr, attrs[attr])\n }\n var f = $B.$getattr(parser, \"XmlDeclHandler\", null)\n if(f !== null){\n $B.$call(f)(attrs.version, attrs.encoding, attrs.standalone)\n }\n return {name, attr_result}\n }\n}\n\n\nfunction emit(rule){\n // called when a rule is done\n var rname = rule.constructor.name\n rname = rname.substr(0, rname.length - 5)\n if(handler[rname]){\n var parser = get_top(rule)\n // console.log('emit', rname)\n handler[rname](parser, rule)\n }\n}\n\nfunction handle_simple(element, next_if_ok, rule, char){\n if(char === FAIL){\n if(typeof element.origin.feed !== 'function'){\n console.log('not a func', element)\n }\n return element.origin.feed(FAIL)\n }else if(char === DONE){\n element.result_store[element.expect] = rule // get_sub(rule, rule.pos, get_pos(rule)) // get_string(rule)\n var test = (rule.constructor.name == 'element_rule' ||\n rule.constructor.name == 'Attribute_rule')\n rule.reset()\n emit(rule)\n set_expect(element, next_if_ok)\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_plus(element, rank, next_if_ok, rule, char){\n if(char === FAIL){\n if(element.repeats[rank] == 0){\n reset_pos(element, rule.pos)\n return element.origin.feed(FAIL)\n }\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n //rule.reset()\n emit(rule)\n set_expect(element, next_if_ok)\n delete element.rules[rank]\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_star(element, rank, next_if_ok, rule, char){\n var test = false // rule instanceof tmp_6_rule\n if(test){\n console.log('HANDLE STAR', rule, 'char', char)\n }\n if(char === FAIL){\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n if(test){\n console.log(rule, 'DONE')\n }\n if(rule.alt){\n element.selected_option = element.expect\n element.selected_rule = rule\n }\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n //rule.reset()\n emit(rule)\n delete element.rules[rank]\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_zero_or_one(element, rank, next_if_ok, rule, char){\n if(char === FAIL){\n set_expect(element, next_if_ok)\n reset_pos(element, rule.pos)\n rule.reset()\n return element.feed(read_char(element))\n }else if(char === DONE){\n element.result_store[rank] = element.result_store[rank] || []\n element.result_store[rank].push(rule)\n element.repeats[rank] += 1\n update_pos(element, get_pos(element))\n emit(rule)\n rule.reset()\n set_expect(element, next_if_ok)\n return element.feed(read_char(element))\n }else if(char === END){\n set_expect(element, next_if_ok)\n return element.feed(char)\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_alt(element, alt_index, rule, char){\n if(char === FAIL){\n set_expect(element, alt_index)\n reset_pos(element, element.pos)\n return element.origin.feed(read_char(element))\n }else if(char === DONE){\n if(['AttValue_rule'].includes(rule.constructor.name)){\n console.log('DONE', rule.constructor.name, get_sub(rule, rule.pos, get_pos(rule)))\n console.log(' ', rule)\n alert()\n }\n element.selected_option = element.expect\n element.selected_rule = rule\n element.result_store[element.expect] = rule\n emit(rule)\n rule.reset()\n return element.origin.feed(char)\n }else if(char === END){\n set_expect(element, -1)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction handle_last(element, rule, char){\n var test = false // element instanceof tmp_6_rule\n if(test){\n console.log('handle_last', rule, char)\n alert()\n }\n if(char === FAIL){\n return element.origin.feed(FAIL)\n }else if(char === DONE){\n element.result_store[element.expect] = rule\n if(element.alt){\n element.selected_option = element.expect\n element.selected_rule = rule\n if(test){\n console.log('set selected', element)\n console.log('value', get_value(rule))\n element.coucou = 'ici'\n alert()\n }\n }\n emit(rule)\n rule.reset()\n set_expect(element, -1)\n if(test){\n console.log('return control to element', element)\n alert()\n }\n return element.feed(char)\n }else if(char === END){\n set_expect(element, -1)\n return element\n }else{\n return rule.feed(char)\n }\n}\n\nfunction expect_literal(element, literal, char){\n if(! element.hasOwnProperty('expected_pos')){\n element.expected_pos = 0\n }\n if(literal[element.expected_pos] == char){\n element.expected_pos++\n if(element.expected_pos == literal.length){\n delete element.expected_pos\n return {value: literal}\n }else{\n return {value: null}\n }\n }\n return FAIL\n}\n\nfunction LITERAL(origin, string, next_if_ok, args){\n this.origin = origin\n this.string = string\n this.next_if_ok = next_if_ok\n this.args = args\n this.pos = get_pos(this)\n this.str_pos = 0\n}\n\nLITERAL.prototype.reset = function(){\n this.str_pos = 0\n}\n\nLITERAL.prototype.feed = function(char){\n //console.log('LITERAL', this.string, 'expects', this.string[this.str_pos], 'char', char)\n if(this.string == ''){\n console.log('LITERAL feed', this.string, char, this.str_pos)\n }\n if(this.str_pos == this.string.length){\n this.value = this.string\n return this.origin.feed(DONE)\n }\n if(char == this.string[this.str_pos]){\n this.str_pos++\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction NAME_rule(origin, next_if_ok){\n this.origin = origin\n this.rank = this.origin.expect\n this.next_if_ok = next_if_ok\n this.value = ''\n this.pos = get_pos(this)\n}\n\nNAME_rule.prototype.reset = function(){\n this.value = ''\n}\n\nNAME_rule.prototype.feed = function(char){\n console.log('NAME_rule, value', this.value, 'char', char)\n if(this.value == ''){\n if(is_id_start(char)){\n this.value = char\n }else{\n return this.origin.feed(FAIL)\n }\n }else if(is_id_continue(char)){\n this.value += char\n }else{\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction NUMBER_rule(origin, next_if_ok, args){\n this.origin = origin\n this.rank = this.origin.expect\n this.next_if_ok = next_if_ok\n this.args = args\n this.pos = get_pos(this)\n this.value = ''\n}\n\nNUMBER_rule.prototype.reset = function(){\n this.value = ''\n}\n\nNUMBER_rule.prototype.feed = function(char){\n if(this.value == ''){\n if(is_num(char)){\n this.value = char\n }else if(this.args.next_if_fail !== undefined){\n this.origin.expect = this.args.next_if_fail\n return this.origin.feed(char)\n }else{\n return FAIL\n }\n }else if(is_num(char)){\n this.value += char\n }else{\n this.origin.expect = this.next_if_ok\n this.origin.store_result(this)\n return this.origin.feed(char)\n }\n return this\n}\n\nfunction start_intSubset_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.rank = this.origin.expect\n this.value = ''\n}\n\nstart_intSubset_rule.prototype.feed = function(char){\n // always succeeds\n return this.origin.feed(DONE)\n}\n\nstart_intSubset_rule.prototype.reset = function(){\n // ignore\n}\n\nfunction S_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.rank = this.origin.expect\n this.value = ''\n}\n\nS_rule.prototype.reset = function(){\n this.value = ''\n}\n\nS_rule.prototype.feed = function(char){\n if(is_space(char)){\n this.value += char\n return this\n }else if(this.value.length > 0){\n return this.origin.feed(DONE)\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction CHAR_rule(origin, next_if_ok, args){\n this.origin = origin\n this.next_if_ok = next_if_ok\n this.args = args\n}\n\nCHAR_rule.prototype.feed = function(char){\n if(is_char(char)){\n this.value = char\n return this.origin\n }else{\n return FAIL\n }\n}\n\nvar hex_range_re = /^#x([a-fA-F0-9]+)-#x([a-fA-F0-9]+)$/\nvar charset_range_re = /(\\w)-(\\w)/g\n\n\nfunction CHARSET_rule(origin, charset, next_if_ok){\n this.origin = origin\n this.charset = charset\n this.next_if_ok = next_if_ok\n this.pos = get_pos(origin)\n this.value = ''\n var negative = charset.startsWith('^'),\n body = negative ? charset.substr(1) : charset\n\n var mo = body.match(hex_range_re)\n if(mo){\n var left = parseInt(`0x${mo[1]}`, 16),\n right = parseInt(`0x${mo[2]}`, 16)\n if(negative){\n this.test = function(char){\n var cp = char.charCodeAt(0)\n return (cp < left) || (cp > right)\n }\n }else{\n this.test = function(char){\n var cp = char.charCodeAt(0)\n return (cp >= left) && (cp <= right)\n }\n }\n return\n }\n\n var ranges = []\n for(var mo of body.matchAll(charset_range_re)){\n ranges.push(mo.slice(1))\n }\n if(ranges.length > 0){\n if(negative){\n this.test = function(char){\n for(var range of ranges){\n if(char >= range[0] && char <= range[1]){\n return false\n }\n }\n return true\n }\n }else{\n this.test = function(char){\n for(var range of ranges){\n if(char >= range[0] && char <= range[1]){\n return true\n }\n }\n return false\n }\n }\n return\n }\n\n if(charset.startsWith('^')){\n this.test = char => ! charset.substr(1).includes(char)\n }else{\n this.test = char => charset.includes(char)\n }\n}\n\nCHARSET_rule.prototype.reset = function(){\n delete this.done\n}\n\nCHARSET_rule.prototype.feed = function(char){\n if(char !== END && this.test(char)){\n this.value += char\n return this\n }else if(this.value.length > 0){\n return this.origin.feed(DONE)\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction BaseChar_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n}\n\nBaseChar_rule.prototype.reset = function(){\n delete this.done\n}\n\nBaseChar_rule.prototype.feed = function(char){\n //console.log('BaseChar_rule, char', char, 'this.done', this.done)\n if(this.done){\n return this.origin.feed(DONE)\n }else if(/\\p{L}/u.exec(char)){\n this.done = true\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction Letter_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n}\n\nLetter_rule.prototype.reset = function(){\n delete this.done\n}\n\nLetter_rule.prototype.feed = function(char){\n if(this.done){\n return this.origin.feed(DONE)\n }else if(/\\p{L}/u.exec(char)){\n this.done = true\n this.value = char\n return this\n }else{\n return this.origin.feed(FAIL)\n }\n}\n\nfunction NameChar_rule(origin){\n this.origin = origin\n this.rank = origin.expect\n this.value = ''\n var result_store = this.origin.result_store\n result_store[this.rank] = result_store[this.rank] ?? []\n this.pos = get_pos(origin)\n}\n\nNameChar_rule.prototype.reset = function(){\n delete this.done\n}\n\nNameChar_rule.prototype.feed = function(char){\n if(this.done){\n return this.origin.feed(DONE)\n }else if(is_id_continue(char)){\n this.value += char\n return this\n }else{\n if(this.value == ''){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n}\n\nfunction PIText_rule(origin){\n this.origin = origin\n this.value = ''\n this.pos = get_pos(origin)\n}\n\nPIText_rule.prototype.reset = function(){}\n\nPIText_rule.prototype.feed = function(char){\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('?>')){\n reset_pos(this, get_pos(this) - 1)\n this.value = this.value.substr(0, this.value.length - 2)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CommentText_rule(origin){\n this.origin = origin\n this.value = ''\n this.pos = get_pos(origin)\n}\n\nCommentText_rule.prototype.reset = function(){}\n\nCommentText_rule.prototype.feed = function(char){\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('-->')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n if(this.value.endsWith('-')){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CharData_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nCharData_rule.prototype.reset = function(){}\n\nCharData_rule.prototype.feed = function(char){\n // [^<&]* - ([^<&]* ']]>' [^<&]*)\n if(char === END){\n return this.origin.feed(FAIL)\n }\n if('<&'.includes(char)){\n return this.origin.feed(DONE)\n }\n this.value += char\n if(this.value.endsWith(']]>')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction CData_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nCData_rule.prototype.reset = function(){}\n\nCData_rule.prototype.feed = function(char){\n // (Char* - (Char* ']]>' Char*))\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith(']]>')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction Ignore_rule(origin){\n this.origin = origin\n this.pos = get_pos(origin)\n this.value = ''\n}\n\nIgnore_rule.prototype.reset = function(){}\n\nIgnore_rule.prototype.feed = function(char){\n // Char* - (Char* ('') Char*)\n if(char === END){\n return this.origin.feed(FAIL)\n }\n this.value += char\n if(this.value.endsWith('')){\n reset_pos(this, get_pos(this) - 2)\n this.value = this.value.substr(0, this.value.length - 3)\n return this.origin.feed(DONE)\n }\n return this\n}\n\nfunction PITarget_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'tmp_21']\n this.rules = []\n this.repeats = []\n}\n\nPITarget_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case 1: // tmp_21\n if(! this.rules[1]){\n this.rules[1] = new tmp_21_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n var value = get_value(this)\n if(value.toLowerCase() == 'xml'){\n return this.origin.feed(FAIL)\n }\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPITarget_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nvar rules = {\ndocument: `[prolog, element, Misc*, ]`,\nChar: `['\\\\t', '\\\\n', '\\\\r', [#x20-#xD7FF], [#xE000-#xFFFD], [#x10000-#x10FFFF]]`,\nS: `[tmp_1+]`,\ntmp_1: `[' ', '\\\\t', '\\\\r', '\\\\n']`,\nName: `[tmp_2, NameChar*]`,\ntmp_2: `[Letter, '_', ':']`,\nNames: `[Name, tmp_3*]`,\ntmp_3: `[' ', Name]`,\nNmtoken: `[NameChar+]`,\nNmtokens: `[Nmtoken, tmp_4*]`,\ntmp_4: `[' ', Nmtoken]`,\nEntityValue: `[tmp_7, tmp_8]`,\ntmp_5: `[[^%&'], PEReference, Reference]`,\ntmp_6: `[[^%&\"], PEReference, Reference]`,\ntmp_7: `['\"', tmp_6*, '\"']`,\ntmp_8: `[\"'\", tmp_5*, \"'\"]`,\nAttValue: `[tmp_11, tmp_12]`,\ntmp_9: `[[^<&'], Reference]`,\ntmp_10: `[[^<&\"], Reference]`,\ntmp_11: `['\"', tmp_10*, '\"']`,\ntmp_12: `[\"'\", tmp_9*, \"'\"]`,\nSystemLiteral: `[tmp_14, tmp_13]`,\ntmp_13: `[\"'\", [^'], \"'\"]`,\ntmp_14: `['\"', [^\"], '\"']`,\nPubidLiteral: `[tmp_15, tmp_16]`,\ntmp_15: `['\"', PubidChar*, '\"']`,\ntmp_16: `[\"'\", PubidCharNoQuote*, \"'\"]`,\nPubidChar: `[' ', '\\\\r', '\\\\n', [a-zA-Z0-9], [-'()+,./:=?;!*#@$_%]]`,\nPubidCharNoQuote: `[' ', '\\\\r', '\\\\n', [a-zA-Z0-9], [-()+,./:=?;!*#@$_%]]`,\nComment: `['']`,\nPI: `['']`,\ntmp_17: `[S, PIText]`,\nCDSect: `[CDStart, CData, CDEnd]`,\nCDStart: `['']`,\nprolog: `[XMLDecl?, Misc*, tmp_18?]`,\ntmp_18: `[doctypedecl, Misc*]`,\nXMLDecl: `['']`,\nVersionInfo: `[S, 'version', Eq, tmp_19]`,\ntmp_19: `[tmp_20, tmp_21]`,\ntmp_20: `[\"'\", VersionNum, \"'\"]`,\ntmp_21: `['\"', VersionNum, '\"']`,\nEq: `[S?, '=', S?]`,\nVersionNum: `['1.0']`,\nMisc: `[Comment, PI, S]`,\ndoctypedecl: `['']`,\ntmp_22: `['[', start_intSubset, intSubset, ']', S?]`,\ntmp_23: `[S, ExternalID]`,\nDeclSep: `[PEReference, S]`,\nintSubset: `[tmp_24*]`,\ntmp_24: `[markupdecl, DeclSep]`,\nmarkupdecl: `[elementdecl, AttlistDecl, EntityDecl, NotationDecl, PI, Comment]`,\nextSubset: `[TextDecl?, extSubsetDecl]`,\nextSubsetDecl: `[tmp_25*]`,\ntmp_25: `[markupdecl, conditionalSect, DeclSep]`,\nSDDecl: `[S, 'standalone', Eq, tmp_30]`,\ntmp_26: `['yes', 'no']`,\ntmp_27: `['yes', 'no']`,\ntmp_28: `['\"', tmp_26, '\"']`,\ntmp_29: `[\"'\", tmp_27, \"'\"]`,\ntmp_30: `[tmp_29, tmp_28]`,\nelement: `[EmptyElemTag, tmp_31]`,\ntmp_31: `[STag, content, ETag]`,\nSTag: `['<', Name, tmp_32*, S?, '>']`,\ntmp_32: `[S, Attribute]`,\nAttribute: `[Name, Eq, AttValue]`,\nETag: `['']`,\ncontent: `[CharData?, tmp_34*]`,\ntmp_33: `[element, Reference, CDSect, PI, Comment]`,\ntmp_34: `[tmp_33, CharData?]`,\nEmptyElemTag: `['<', Name, tmp_35*, S?, '/>']`,\ntmp_35: `[S, Attribute]`,\nelementdecl: `['']`,\ncontentspec: `['EMPTY', 'ANY', Mixed, children]`,\nchildren: `[tmp_37, tmp_36?]`,\ntmp_36: `['?', '*', '+']`,\ntmp_37: `[choice, seq]`,\ncp: `[tmp_39, tmp_38?]`,\ntmp_38: `['?', '*', '+']`,\ntmp_39: `[Name, choice, seq]`,\nchoice: `['(', S?, cp, tmp_40+, S?, ')']`,\ntmp_40: `[S?, '|', S?, cp]`,\nseq: `['(', S?, cp, tmp_41*, S?, ')']`,\ntmp_41: `[S?, ',', S?, cp]`,\nMixed: `[tmp_43, tmp_44]`,\ntmp_42: `[S?, '|', S?, Name]`,\ntmp_43: `['(', S?, '#PCDATA', tmp_42*, S?, ')*']`,\ntmp_44: `['(', S?, '#PCDATA', S?, ')']`,\nAttlistDecl: `['']`,\nAttDef: `[S, Name, S, AttType, S, DefaultDecl]`,\nAttType: `[StringType, TokenizedType, EnumeratedType]`,\nStringType: `['CDATA']`,\nTokenizedType: `['ID', 'IDREF', 'IDREFS', 'ENTITY', 'ENTITIES', 'NMTOKEN', 'NMTOKENS']`,\nEnumeratedType: `[NotationType, Enumeration]`,\nNotationType: `['NOTATION', S, '(', S?, Name, tmp_45*, S?, ')']`,\ntmp_45: `[S?, '|', S?, Name]`,\nEnumeration: `['(', S?, Nmtoken, tmp_46*, S?, ')']`,\ntmp_46: `[S?, '|', S?, Nmtoken]`,\nDefaultDecl: `['#REQUIRED', '#IMPLIED', tmp_48]`,\ntmp_47: `['#FIXED', S]`,\ntmp_48: `[tmp_47?, AttValue]`,\nconditionalSect: `[includeSect, ignoreSect]`,\nincludeSect: `['']`,\nignoreSect: `['']`,\nignoreSectContents: `[Ignore, tmp_49*]`,\ntmp_49: `['', Ignore]`,\nCharRef: `[tmp_50, tmp_51]`,\ntmp_50: `['&#', [0-9], ';']`,\ntmp_51: `['&#x', [0-9a-fA-F], ';']`,\nReference: `[EntityRef, CharRef]`,\nEntityRef: `['&', Name, ';']`,\nPEReference: `['%', Name, ';']`,\nEntityDecl: `[GEDecl, PEDecl]`,\nGEDecl: `['']`,\nPEDecl: `['']`,\nEntityDef: `[EntityValue, tmp_52]`,\ntmp_52: `[ExternalID, NDataDecl?]`,\nPEDef: `[EntityValue, ExternalID]`,\nExternalID: `[tmp_53, tmp_54]`,\ntmp_53: `['SYSTEM', S, SystemLiteral]`,\ntmp_54: `['PUBLIC', S, PubidLiteral, S, SystemLiteral]`,\nNDataDecl: `[S, 'NDATA', S, Name]`,\nTextDecl: `['']`,\nextParsedEnt: `[TextDecl?, content]`,\nEncodingDecl: `[S, 'encoding', Eq, tmp_55]`,\ntmp_55: `[tmp_56, tmp_57]`,\ntmp_56: `['\"', EncName, '\"']`,\ntmp_57: `[\"'\", EncName, \"'\"]`,\nEncName: `[[A-Za-z], tmp_58*]`,\ntmp_58: `[[A-Za-z0-9._], '-']`,\nNotationDecl: `['']`,\ntmp_59: `[ExternalID, PublicID]`,\nPublicID: `['PUBLIC', S, PubidLiteral]`,\n}\nfunction document_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // prolog\n this.items = ['prolog', 'element', 'Misc*', \"\"]\n this.rules = []\n this.repeats = []\n}\n\ndocument_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // prolog\n if(! this.rules[0]){\n this.rules[0] = new prolog_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // element\n if(! this.rules[1]){\n this.rules[1] = new element_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // Misc*\n if(! this.rules[2]){\n this.rules[2] = new Misc_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 2, 3, rule, char)\n case -1:\n case 3:\n if(char == END){\n return DONE\n }\n return FAIL\n }\n return this\n}\n\ndocument_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Char_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\\t'\n this.items = [\"'\\\\t'\", \"'\\\\n'\", \"'\\\\r'\", '[#x20-#xD7FF]', '[#xE000-#xFFFD]', '[#x10000-#x10FFFF]']\n this.rules = []\n this.repeats = []\n}\n\nChar_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\\t'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(9))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '\\n'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, String.fromCharCode(10))\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '\\r'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, String.fromCharCode(13))\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // [#x20-#xD7FF]\n if(! this.rules[3]){\n this.rules[3] = new CHARSET_rule(this, '#x20-#xD7FF')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // [#xE000-#xFFFD]\n if(! this.rules[4]){\n this.rules[4] = new CHARSET_rule(this, '#xE000-#xFFFD')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 5, rule, char)\n case 5: // [#x10000-#x10FFFF]\n if(! this.rules[5]){\n this.rules[5] = new CHARSET_rule(this, '#x10000-#x10FFFF')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nChar_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction S_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_1+\n this.items = ['tmp_1+']\n this.rules = []\n this.repeats = []\n}\n\nS_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_1+\n if(! this.rules[0]){\n this.rules[0] = new tmp_1_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 0,-1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nS_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_1_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", \"'\\\\t'\", \"'\\\\r'\", \"'\\\\n'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_1_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '\\t'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, String.fromCharCode(9))\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '\\r'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, String.fromCharCode(13))\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // '\\n'\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, String.fromCharCode(10))\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_1_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Name_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_2\n this.items = ['tmp_2', 'NameChar*']\n this.rules = []\n this.repeats = []\n}\n\nName_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_2\n if(! this.rules[0]){\n this.rules[0] = new tmp_2_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // NameChar*\n if(! this.rules[1]){\n this.rules[1] = new NameChar_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nName_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_2_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Letter\n this.items = ['Letter', \"'_'\", \"':'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_2_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Letter\n if(! this.rules[0]){\n this.rules[0] = new Letter_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '_'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '_')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // ':'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ':')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_2_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Names_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'tmp_3*']\n this.rules = []\n this.repeats = []\n}\n\nNames_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_3*\n if(! this.rules[1]){\n this.rules[1] = new tmp_3_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNames_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_3_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", 'Name']\n this.rules = []\n this.repeats = []\n}\n\ntmp_3_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_3_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Nmtoken_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // NameChar+\n this.items = ['NameChar+']\n this.rules = []\n this.repeats = []\n}\n\nNmtoken_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // NameChar+\n if(! this.rules[0]){\n this.rules[0] = new NameChar_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 0,-1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNmtoken_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Nmtokens_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Nmtoken\n this.items = ['Nmtoken', 'tmp_4*']\n this.rules = []\n this.repeats = []\n}\n\nNmtokens_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Nmtoken\n if(! this.rules[0]){\n this.rules[0] = new Nmtoken_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_4*\n if(! this.rules[1]){\n this.rules[1] = new tmp_4_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNmtokens_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_4_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", 'Nmtoken']\n this.rules = []\n this.repeats = []\n}\n\ntmp_4_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Nmtoken\n if(! this.rules[1]){\n this.rules[1] = new Nmtoken_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_4_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EntityValue_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_7\n this.items = ['tmp_7', 'tmp_8']\n this.rules = []\n this.repeats = []\n}\n\nEntityValue_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_7\n if(! this.rules[0]){\n this.rules[0] = new tmp_7_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_8\n if(! this.rules[1]){\n this.rules[1] = new tmp_8_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEntityValue_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_5_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [^%&']\n this.items = [\"[^%&']\", 'PEReference', 'Reference']\n this.rules = []\n this.repeats = []\n}\n\ntmp_5_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [^%&']\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, '^%&\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PEReference\n if(! this.rules[1]){\n this.rules[1] = new PEReference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // Reference\n if(! this.rules[2]){\n this.rules[2] = new Reference_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_5_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_6_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [^%&\"]\n this.items = ['[^%&\"]', 'PEReference', 'Reference']\n this.rules = []\n this.repeats = []\n}\n\ntmp_6_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [^%&\"]\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, '^%&\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PEReference\n if(! this.rules[1]){\n this.rules[1] = new PEReference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // Reference\n if(! this.rules[2]){\n this.rules[2] = new Reference_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_6_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_7_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'tmp_6*', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_7_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_6*\n if(! this.rules[1]){\n this.rules[1] = new tmp_6_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_7_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_8_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'tmp_5*', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_8_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_5*\n if(! this.rules[1]){\n this.rules[1] = new tmp_5_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_8_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction AttValue_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_11\n this.items = ['tmp_11', 'tmp_12']\n this.rules = []\n this.repeats = []\n}\n\nAttValue_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_11\n if(! this.rules[0]){\n this.rules[0] = new tmp_11_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_12\n if(! this.rules[1]){\n this.rules[1] = new tmp_12_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttValue_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_9_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [^<&']\n this.items = [\"[^<&']\", 'Reference']\n this.rules = []\n this.repeats = []\n}\n\ntmp_9_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [^<&']\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, '^<&\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // Reference\n if(! this.rules[1]){\n this.rules[1] = new Reference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_9_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_10_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [^<&\"]\n this.items = ['[^<&\"]', 'Reference']\n this.rules = []\n this.repeats = []\n}\n\ntmp_10_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [^<&\"]\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, '^<&\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // Reference\n if(! this.rules[1]){\n this.rules[1] = new Reference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_10_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_11_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'tmp_10*', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_11_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_10*\n if(! this.rules[1]){\n this.rules[1] = new tmp_10_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_11_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_12_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'tmp_9*', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_12_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_9*\n if(! this.rules[1]){\n this.rules[1] = new tmp_9_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_12_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction SystemLiteral_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_14\n this.items = ['tmp_14', 'tmp_13']\n this.rules = []\n this.repeats = []\n}\n\nSystemLiteral_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_14\n if(! this.rules[0]){\n this.rules[0] = new tmp_14_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_13\n if(! this.rules[1]){\n this.rules[1] = new tmp_13_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nSystemLiteral_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_13_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', \"[^']\", '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_13_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // [^']\n if(! this.rules[1]){\n this.rules[1] = new CHARSET_rule(this, '^\\'')\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_13_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_14_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', '[^\"]', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_14_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // [^\"]\n if(! this.rules[1]){\n this.rules[1] = new CHARSET_rule(this, '^\"')\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_14_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PubidLiteral_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_15\n this.items = ['tmp_15', 'tmp_16']\n this.rules = []\n this.repeats = []\n}\n\nPubidLiteral_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_15\n if(! this.rules[0]){\n this.rules[0] = new tmp_15_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_16\n if(! this.rules[1]){\n this.rules[1] = new tmp_16_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPubidLiteral_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_15_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'PubidChar*', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_15_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // PubidChar*\n if(! this.rules[1]){\n this.rules[1] = new PubidChar_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_15_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_16_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'PubidCharNoQuote*', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_16_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // PubidCharNoQuote*\n if(! this.rules[1]){\n this.rules[1] = new PubidCharNoQuote_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_16_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PubidChar_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", \"'\\\\r'\", \"'\\\\n'\", '[a-zA-Z0-9]', \"[-'()+,./:=?;!*#@$_%]\"]\n this.rules = []\n this.repeats = []\n}\n\nPubidChar_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '\\r'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, String.fromCharCode(13))\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '\\n'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, String.fromCharCode(10))\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // [a-zA-Z0-9]\n if(! this.rules[3]){\n this.rules[3] = new CHARSET_rule(this, 'a-zA-Z0-9')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // [-'()+,./:=?;!*#@$_%]\n if(! this.rules[4]){\n this.rules[4] = new CHARSET_rule(this, '-\\'()+,./:=?;!*#@$_%')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPubidChar_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PubidCharNoQuote_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ' '\n this.items = [\"' '\", \"'\\\\r'\", \"'\\\\n'\", '[a-zA-Z0-9]', '[-()+,./:=?;!*#@$_%]']\n this.rules = []\n this.repeats = []\n}\n\nPubidCharNoQuote_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ' '\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, String.fromCharCode(32))\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '\\r'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, String.fromCharCode(13))\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '\\n'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, String.fromCharCode(10))\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // [a-zA-Z0-9]\n if(! this.rules[3]){\n this.rules[3] = new CHARSET_rule(this, 'a-zA-Z0-9')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // [-()+,./:=?;!*#@$_%]\n if(! this.rules[4]){\n this.rules[4] = new CHARSET_rule(this, '-()+,./:=?;!*#@$_%')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPubidCharNoQuote_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Comment_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nComment_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '-->')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nComment_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PI_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nPI_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, '?>')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPI_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_17_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'PIText']\n this.rules = []\n this.repeats = []\n}\n\ntmp_17_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // PIText\n if(! this.rules[1]){\n this.rules[1] = new PIText_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_17_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction CDSect_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // CDStart\n this.items = ['CDStart', 'CData', 'CDEnd']\n this.rules = []\n this.repeats = []\n}\n\nCDSect_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // CDStart\n if(! this.rules[0]){\n this.rules[0] = new CDStart_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // CData\n if(! this.rules[1]){\n this.rules[1] = new CData_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // CDEnd\n if(! this.rules[2]){\n this.rules[2] = new CDEnd_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nCDSect_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction CDStart_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\n this.items = [\"']]>'\"]\n this.rules = []\n this.repeats = []\n}\n\nCDEnd_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ']]>'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, ']]>')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nCDEnd_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction prolog_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // XMLDecl?\n this.items = ['XMLDecl?', 'Misc*', 'tmp_18?']\n this.rules = []\n this.repeats = []\n}\n\nprolog_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // XMLDecl?\n if(! this.rules[0]){\n this.rules[0] = new XMLDecl_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // Misc*\n if(! this.rules[1]){\n this.rules[1] = new Misc_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, 2, rule, char)\n case 2: // tmp_18?\n if(! this.rules[2]){\n this.rules[2] = new tmp_18_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nprolog_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_18_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // doctypedecl\n this.items = ['doctypedecl', 'Misc*']\n this.rules = []\n this.repeats = []\n}\n\ntmp_18_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // doctypedecl\n if(! this.rules[0]){\n this.rules[0] = new doctypedecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Misc*\n if(! this.rules[1]){\n this.rules[1] = new Misc_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_18_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction XMLDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nXMLDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, '?>')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nXMLDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction VersionInfo_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', \"'version'\", 'Eq', 'tmp_19']\n this.rules = []\n this.repeats = []\n}\n\nVersionInfo_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // 'version'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'version')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // Eq\n if(! this.rules[2]){\n this.rules[2] = new Eq_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_19\n if(! this.rules[3]){\n this.rules[3] = new tmp_19_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nVersionInfo_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_19_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_20\n this.items = ['tmp_20', 'tmp_21']\n this.rules = []\n this.repeats = []\n}\n\ntmp_19_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_20\n if(! this.rules[0]){\n this.rules[0] = new tmp_20_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_21\n if(! this.rules[1]){\n this.rules[1] = new tmp_21_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_19_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_20_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'VersionNum', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_20_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // VersionNum\n if(! this.rules[1]){\n this.rules[1] = new VersionNum_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_20_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_21_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'VersionNum', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_21_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // VersionNum\n if(! this.rules[1]){\n this.rules[1] = new VersionNum_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_21_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Eq_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'='\", 'S?']\n this.rules = []\n this.repeats = []\n}\n\nEq_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '='\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '=')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEq_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction VersionNum_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '1.0'\n this.items = [\"'1.0'\"]\n this.rules = []\n this.repeats = []\n}\n\nVersionNum_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '1.0'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '1.0')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nVersionNum_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Misc_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Comment\n this.items = ['Comment', 'PI', 'S']\n this.rules = []\n this.repeats = []\n}\n\nMisc_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Comment\n if(! this.rules[0]){\n this.rules[0] = new Comment_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PI\n if(! this.rules[1]){\n this.rules[1] = new PI_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // S\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nMisc_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction doctypedecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\ndoctypedecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, '>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ndoctypedecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_22_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '['\n this.items = [\"'['\", 'start_intSubset', 'intSubset', \"']'\", 'S?']\n this.rules = []\n this.repeats = []\n}\n\ntmp_22_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '['\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '[')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // start_intSubset\n if(! this.rules[1]){\n this.rules[1] = new start_intSubset_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // intSubset\n if(! this.rules[2]){\n this.rules[2] = new intSubset_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // ']'\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, ']')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_22_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_23_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'ExternalID']\n this.rules = []\n this.repeats = []\n}\n\ntmp_23_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // ExternalID\n if(! this.rules[1]){\n this.rules[1] = new ExternalID_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_23_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction DeclSep_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // PEReference\n this.items = ['PEReference', 'S']\n this.rules = []\n this.repeats = []\n}\n\nDeclSep_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // PEReference\n if(! this.rules[0]){\n this.rules[0] = new PEReference_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nDeclSep_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction intSubset_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_24*\n this.items = ['tmp_24*']\n this.rules = []\n this.repeats = []\n}\n\nintSubset_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_24*\n if(! this.rules[0]){\n this.rules[0] = new tmp_24_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 0, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nintSubset_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_24_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // markupdecl\n this.items = ['markupdecl', 'DeclSep']\n this.rules = []\n this.repeats = []\n}\n\ntmp_24_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // markupdecl\n if(! this.rules[0]){\n this.rules[0] = new markupdecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // DeclSep\n if(! this.rules[1]){\n this.rules[1] = new DeclSep_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_24_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction markupdecl_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // elementdecl\n this.items = ['elementdecl', 'AttlistDecl', 'EntityDecl', 'NotationDecl', 'PI', 'Comment']\n this.rules = []\n this.repeats = []\n}\n\nmarkupdecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // elementdecl\n if(! this.rules[0]){\n this.rules[0] = new elementdecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // AttlistDecl\n if(! this.rules[1]){\n this.rules[1] = new AttlistDecl_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // EntityDecl\n if(! this.rules[2]){\n this.rules[2] = new EntityDecl_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // NotationDecl\n if(! this.rules[3]){\n this.rules[3] = new NotationDecl_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // PI\n if(! this.rules[4]){\n this.rules[4] = new PI_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 5, rule, char)\n case 5: // Comment\n if(! this.rules[5]){\n this.rules[5] = new Comment_rule(this)\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nmarkupdecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction extSubset_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // TextDecl?\n this.items = ['TextDecl?', 'extSubsetDecl']\n this.rules = []\n this.repeats = []\n}\n\nextSubset_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // TextDecl?\n if(! this.rules[0]){\n this.rules[0] = new TextDecl_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // extSubsetDecl\n if(! this.rules[1]){\n this.rules[1] = new extSubsetDecl_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nextSubset_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction extSubsetDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_25*\n this.items = ['tmp_25*']\n this.rules = []\n this.repeats = []\n}\n\nextSubsetDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_25*\n if(! this.rules[0]){\n this.rules[0] = new tmp_25_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 0, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nextSubsetDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_25_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // markupdecl\n this.items = ['markupdecl', 'conditionalSect', 'DeclSep']\n this.rules = []\n this.repeats = []\n}\n\ntmp_25_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // markupdecl\n if(! this.rules[0]){\n this.rules[0] = new markupdecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // conditionalSect\n if(! this.rules[1]){\n this.rules[1] = new conditionalSect_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // DeclSep\n if(! this.rules[2]){\n this.rules[2] = new DeclSep_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_25_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction SDDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', \"'standalone'\", 'Eq', 'tmp_30']\n this.rules = []\n this.repeats = []\n}\n\nSDDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // 'standalone'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'standalone')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // Eq\n if(! this.rules[2]){\n this.rules[2] = new Eq_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_30\n if(! this.rules[3]){\n this.rules[3] = new tmp_30_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nSDDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_26_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'yes'\n this.items = [\"'yes'\", \"'no'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_26_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'yes'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'yes')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // 'no'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'no')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_26_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_27_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'yes'\n this.items = [\"'yes'\", \"'no'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_27_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'yes'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'yes')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // 'no'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'no')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_27_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_28_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'tmp_26', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_28_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_26\n if(! this.rules[1]){\n this.rules[1] = new tmp_26_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_28_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_29_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'tmp_27', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_29_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_27\n if(! this.rules[1]){\n this.rules[1] = new tmp_27_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_29_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_30_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_29\n this.items = ['tmp_29', 'tmp_28']\n this.rules = []\n this.repeats = []\n}\n\ntmp_30_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_29\n if(! this.rules[0]){\n this.rules[0] = new tmp_29_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_28\n if(! this.rules[1]){\n this.rules[1] = new tmp_28_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_30_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction element_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // EmptyElemTag\n this.items = ['EmptyElemTag', 'tmp_31']\n this.rules = []\n this.repeats = []\n}\n\nelement_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // EmptyElemTag\n if(! this.rules[0]){\n this.rules[0] = new EmptyElemTag_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_31\n if(! this.rules[1]){\n this.rules[1] = new tmp_31_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nelement_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_31_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // STag\n this.items = ['STag', 'content', 'ETag']\n this.rules = []\n this.repeats = []\n}\n\ntmp_31_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // STag\n if(! this.rules[0]){\n this.rules[0] = new STag_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // content\n if(! this.rules[1]){\n this.rules[1] = new content_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // ETag\n if(! this.rules[2]){\n this.rules[2] = new ETag_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_31_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction STag_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '<'\n this.items = [\"'<'\", 'Name', 'tmp_32*', 'S?', \"'>'\"]\n this.rules = []\n this.repeats = []\n}\n\nSTag_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '<'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '<')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // tmp_32*\n if(! this.rules[2]){\n this.rules[2] = new tmp_32_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 2, 3, rule, char)\n case 3: // S?\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 3, 4, rule, char)\n case 4: // '>'\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, '>')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nSTag_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_32_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'Attribute']\n this.rules = []\n this.repeats = []\n}\n\ntmp_32_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Attribute\n if(! this.rules[1]){\n this.rules[1] = new Attribute_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_32_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Attribute_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'Eq', 'AttValue']\n this.rules = []\n this.repeats = []\n}\n\nAttribute_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Eq\n if(! this.rules[1]){\n this.rules[1] = new Eq_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // AttValue\n if(! this.rules[2]){\n this.rules[2] = new AttValue_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttribute_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction ETag_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nETag_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, '>')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nETag_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction content_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // CharData?\n this.items = ['CharData?', 'tmp_34*']\n this.rules = []\n this.repeats = []\n}\n\ncontent_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // CharData?\n if(! this.rules[0]){\n this.rules[0] = new CharData_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // tmp_34*\n if(! this.rules[1]){\n this.rules[1] = new tmp_34_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ncontent_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_33_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // element\n this.items = ['element', 'Reference', 'CDSect', 'PI', 'Comment']\n this.rules = []\n this.repeats = []\n}\n\ntmp_33_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // element\n if(! this.rules[0]){\n this.rules[0] = new element_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // Reference\n if(! this.rules[1]){\n this.rules[1] = new Reference_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // CDSect\n if(! this.rules[2]){\n this.rules[2] = new CDSect_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // PI\n if(! this.rules[3]){\n this.rules[3] = new PI_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // Comment\n if(! this.rules[4]){\n this.rules[4] = new Comment_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_33_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_34_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_33\n this.items = ['tmp_33', 'CharData?']\n this.rules = []\n this.repeats = []\n}\n\ntmp_34_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_33\n if(! this.rules[0]){\n this.rules[0] = new tmp_33_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // CharData?\n if(! this.rules[1]){\n this.rules[1] = new CharData_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_34_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EmptyElemTag_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '<'\n this.items = [\"'<'\", 'Name', 'tmp_35*', 'S?', \"'/>'\"]\n this.rules = []\n this.repeats = []\n}\n\nEmptyElemTag_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '<'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '<')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // tmp_35*\n if(! this.rules[2]){\n this.rules[2] = new tmp_35_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 2, 3, rule, char)\n case 3: // S?\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 3, 4, rule, char)\n case 4: // '/>'\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, '/>')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEmptyElemTag_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_35_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'Attribute']\n this.rules = []\n this.repeats = []\n}\n\ntmp_35_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Attribute\n if(! this.rules[1]){\n this.rules[1] = new Attribute_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_35_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction elementdecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nelementdecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, '>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nelementdecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction contentspec_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'EMPTY'\n this.items = [\"'EMPTY'\", \"'ANY'\", 'Mixed', 'children']\n this.rules = []\n this.repeats = []\n}\n\ncontentspec_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'EMPTY'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'EMPTY')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // 'ANY'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'ANY')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // Mixed\n if(! this.rules[2]){\n this.rules[2] = new Mixed_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // children\n if(! this.rules[3]){\n this.rules[3] = new children_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ncontentspec_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction children_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_37\n this.items = ['tmp_37', 'tmp_36?']\n this.rules = []\n this.repeats = []\n}\n\nchildren_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_37\n if(! this.rules[0]){\n this.rules[0] = new tmp_37_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_36?\n if(! this.rules[1]){\n this.rules[1] = new tmp_36_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nchildren_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_36_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '?'\n this.items = [\"'?'\", \"'*'\", \"'+'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_36_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '?'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '?')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '*'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '*')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '+'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '+')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_36_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_37_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // choice\n this.items = ['choice', 'seq']\n this.rules = []\n this.repeats = []\n}\n\ntmp_37_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // choice\n if(! this.rules[0]){\n this.rules[0] = new choice_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // seq\n if(! this.rules[1]){\n this.rules[1] = new seq_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_37_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction cp_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_39\n this.items = ['tmp_39', 'tmp_38?']\n this.rules = []\n this.repeats = []\n}\n\ncp_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_39\n if(! this.rules[0]){\n this.rules[0] = new tmp_39_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_38?\n if(! this.rules[1]){\n this.rules[1] = new tmp_38_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ncp_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_38_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '?'\n this.items = [\"'?'\", \"'*'\", \"'+'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_38_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '?'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '?')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '*'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '*')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // '+'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '+')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_38_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_39_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Name\n this.items = ['Name', 'choice', 'seq']\n this.rules = []\n this.repeats = []\n}\n\ntmp_39_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Name\n if(! this.rules[0]){\n this.rules[0] = new Name_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // choice\n if(! this.rules[1]){\n this.rules[1] = new choice_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // seq\n if(! this.rules[2]){\n this.rules[2] = new seq_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_39_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction choice_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', 'cp', 'tmp_40+', 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\nchoice_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // cp\n if(! this.rules[2]){\n this.rules[2] = new cp_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_40+\n if(! this.rules[3]){\n this.rules[3] = new tmp_40_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 3,4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, 5, rule, char)\n case 5: // ')'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, ')')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nchoice_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_40_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'|'\", 'S?', 'cp']\n this.rules = []\n this.repeats = []\n}\n\ntmp_40_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '|'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '|')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // cp\n if(! this.rules[3]){\n this.rules[3] = new cp_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_40_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction seq_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', 'cp', 'tmp_41*', 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\nseq_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // cp\n if(! this.rules[2]){\n this.rules[2] = new cp_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_41*\n if(! this.rules[3]){\n this.rules[3] = new tmp_41_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 3, 4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, 5, rule, char)\n case 5: // ')'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, ')')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nseq_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_41_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"','\", 'S?', 'cp']\n this.rules = []\n this.repeats = []\n}\n\ntmp_41_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // ','\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, ',')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // cp\n if(! this.rules[3]){\n this.rules[3] = new cp_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_41_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Mixed_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_43\n this.items = ['tmp_43', 'tmp_44']\n this.rules = []\n this.repeats = []\n}\n\nMixed_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_43\n if(! this.rules[0]){\n this.rules[0] = new tmp_43_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_44\n if(! this.rules[1]){\n this.rules[1] = new tmp_44_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nMixed_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_42_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'|'\", 'S?', 'Name']\n this.rules = []\n this.repeats = []\n}\n\ntmp_42_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '|'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '|')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // Name\n if(! this.rules[3]){\n this.rules[3] = new Name_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_42_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_43_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', \"'#PCDATA'\", 'tmp_42*', 'S?', \"')*'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_43_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // '#PCDATA'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '#PCDATA')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_42*\n if(! this.rules[3]){\n this.rules[3] = new tmp_42_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 3, 4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, 5, rule, char)\n case 5: // ')*'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, ')*')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_43_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_44_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', \"'#PCDATA'\", 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_44_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // '#PCDATA'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '#PCDATA')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // S?\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 3, 4, rule, char)\n case 4: // ')'\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, ')')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_44_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction AttlistDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nAttlistDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, '>')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttlistDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction AttDef_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', 'Name', 'S', 'AttType', 'S', 'DefaultDecl']\n this.rules = []\n this.repeats = []\n}\n\nAttDef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // AttType\n if(! this.rules[3]){\n this.rules[3] = new AttType_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 4, rule, char)\n case 4: // S\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 5, rule, char)\n case 5: // DefaultDecl\n if(! this.rules[5]){\n this.rules[5] = new DefaultDecl_rule(this)\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttDef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction AttType_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // StringType\n this.items = ['StringType', 'TokenizedType', 'EnumeratedType']\n this.rules = []\n this.repeats = []\n}\n\nAttType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // StringType\n if(! this.rules[0]){\n this.rules[0] = new StringType_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // TokenizedType\n if(! this.rules[1]){\n this.rules[1] = new TokenizedType_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // EnumeratedType\n if(! this.rules[2]){\n this.rules[2] = new EnumeratedType_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nAttType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction StringType_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'CDATA'\n this.items = [\"'CDATA'\"]\n this.rules = []\n this.repeats = []\n}\n\nStringType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'CDATA'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'CDATA')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nStringType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction TokenizedType_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'ID'\n this.items = [\"'ID'\", \"'IDREF'\", \"'IDREFS'\", \"'ENTITY'\", \"'ENTITIES'\", \"'NMTOKEN'\", \"'NMTOKENS'\"]\n this.rules = []\n this.repeats = []\n}\n\nTokenizedType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'ID'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'ID')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // 'IDREF'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'IDREF')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // 'IDREFS'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, 'IDREFS')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 3, rule, char)\n case 3: // 'ENTITY'\n if(! this.rules[3]){\n this.rules[3] = new LITERAL(this, 'ENTITY')\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 4, rule, char)\n case 4: // 'ENTITIES'\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, 'ENTITIES')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 5, rule, char)\n case 5: // 'NMTOKEN'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, 'NMTOKEN')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 6, rule, char)\n case 6: // 'NMTOKENS'\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, 'NMTOKENS')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nTokenizedType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EnumeratedType_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // NotationType\n this.items = ['NotationType', 'Enumeration']\n this.rules = []\n this.repeats = []\n}\n\nEnumeratedType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // NotationType\n if(! this.rules[0]){\n this.rules[0] = new NotationType_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // Enumeration\n if(! this.rules[1]){\n this.rules[1] = new Enumeration_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEnumeratedType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction NotationType_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'NOTATION'\n this.items = [\"'NOTATION'\", 'S', \"'('\", 'S?', 'Name', 'tmp_45*', 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\nNotationType_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'NOTATION'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'NOTATION')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // '('\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '(')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // S?\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 3, 4, rule, char)\n case 4: // Name\n if(! this.rules[4]){\n this.rules[4] = new Name_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 5, rule, char)\n case 5: // tmp_45*\n if(! this.rules[5]){\n this.rules[5] = new tmp_45_rule(this)\n this.repeats[5] = 0\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 5, 6, rule, char)\n case 6: // S?\n if(! this.rules[6]){\n this.rules[6] = new S_rule(this)\n this.repeats[6] = 0\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 6, 7, rule, char)\n case 7: // ')'\n if(! this.rules[7]){\n this.rules[7] = new LITERAL(this, ')')\n }\n rule = this.rules[7]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNotationType_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_45_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'|'\", 'S?', 'Name']\n this.rules = []\n this.repeats = []\n}\n\ntmp_45_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '|'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '|')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // Name\n if(! this.rules[3]){\n this.rules[3] = new Name_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_45_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Enumeration_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '('\n this.items = [\"'('\", 'S?', 'Nmtoken', 'tmp_46*', 'S?', \"')'\"]\n this.rules = []\n this.repeats = []\n}\n\nEnumeration_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '('\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '(')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S?\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, 2, rule, char)\n case 2: // Nmtoken\n if(! this.rules[2]){\n this.rules[2] = new Nmtoken_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_46*\n if(! this.rules[3]){\n this.rules[3] = new tmp_46_rule(this)\n this.repeats[3] = 0\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 3, 4, rule, char)\n case 4: // S?\n if(! this.rules[4]){\n this.rules[4] = new S_rule(this)\n this.repeats[4] = 0\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 4, 5, rule, char)\n case 5: // ')'\n if(! this.rules[5]){\n this.rules[5] = new LITERAL(this, ')')\n }\n rule = this.rules[5]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEnumeration_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_46_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S?\n this.items = ['S?', \"'|'\", 'S?', 'Nmtoken']\n this.rules = []\n this.repeats = []\n}\n\ntmp_46_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S?\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // '|'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '|')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S?\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n this.repeats[2] = 0\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 2, 3, rule, char)\n case 3: // Nmtoken\n if(! this.rules[3]){\n this.rules[3] = new Nmtoken_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_46_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction DefaultDecl_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '#REQUIRED'\n this.items = [\"'#REQUIRED'\", \"'#IMPLIED'\", 'tmp_48']\n this.rules = []\n this.repeats = []\n}\n\nDefaultDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '#REQUIRED'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '#REQUIRED')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '#IMPLIED'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '#IMPLIED')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 2, rule, char)\n case 2: // tmp_48\n if(! this.rules[2]){\n this.rules[2] = new tmp_48_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nDefaultDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_47_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '#FIXED'\n this.items = [\"'#FIXED'\", 'S']\n this.rules = []\n this.repeats = []\n}\n\ntmp_47_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '#FIXED'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '#FIXED')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_47_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_48_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_47?\n this.items = ['tmp_47?', 'AttValue']\n this.rules = []\n this.repeats = []\n}\n\ntmp_48_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_47?\n if(! this.rules[0]){\n this.rules[0] = new tmp_47_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // AttValue\n if(! this.rules[1]){\n this.rules[1] = new AttValue_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_48_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction conditionalSect_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // includeSect\n this.items = ['includeSect', 'ignoreSect']\n this.rules = []\n this.repeats = []\n}\n\nconditionalSect_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // includeSect\n if(! this.rules[0]){\n this.rules[0] = new includeSect_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // ignoreSect\n if(! this.rules[1]){\n this.rules[1] = new ignoreSect_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nconditionalSect_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction includeSect_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nincludeSect_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, ']]>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nincludeSect_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction ignoreSect_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nignoreSect_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, ']]>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nignoreSect_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction ignoreSectContents_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // Ignore\n this.items = ['Ignore', 'tmp_49*']\n this.rules = []\n this.repeats = []\n}\n\nignoreSectContents_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // Ignore\n if(! this.rules[0]){\n this.rules[0] = new Ignore_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_49*\n if(! this.rules[1]){\n this.rules[1] = new tmp_49_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nignoreSectContents_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_49_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\", 'Ignore']\n this.rules = []\n this.repeats = []\n}\n\ntmp_49_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ']]>')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // Ignore\n if(! this.rules[3]){\n this.rules[3] = new Ignore_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_49_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction CharRef_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_50\n this.items = ['tmp_50', 'tmp_51']\n this.rules = []\n this.repeats = []\n}\n\nCharRef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_50\n if(! this.rules[0]){\n this.rules[0] = new tmp_50_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_51\n if(! this.rules[1]){\n this.rules[1] = new tmp_51_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nCharRef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_50_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '&#'\n this.items = [\"'&#'\", '[0-9]', \"';'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_50_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '&#'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '&#')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // [0-9]\n if(! this.rules[1]){\n this.rules[1] = new CHARSET_rule(this, '0-9')\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 1,2, rule, char)\n case 2: // ';'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ';')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_50_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_51_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '&#x'\n this.items = [\"'&#x'\", '[0-9a-fA-F]', \"';'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_51_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '&#x'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '&#x')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // [0-9a-fA-F]\n if(! this.rules[1]){\n this.rules[1] = new CHARSET_rule(this, '0-9a-fA-F')\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_plus(this, 1,2, rule, char)\n case 2: // ';'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ';')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_51_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction Reference_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // EntityRef\n this.items = ['EntityRef', 'CharRef']\n this.rules = []\n this.repeats = []\n}\n\nReference_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // EntityRef\n if(! this.rules[0]){\n this.rules[0] = new EntityRef_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // CharRef\n if(! this.rules[1]){\n this.rules[1] = new CharRef_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nReference_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EntityRef_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '&'\n this.items = [\"'&'\", 'Name', \"';'\"]\n this.rules = []\n this.repeats = []\n}\n\nEntityRef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '&'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '&')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // ';'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ';')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEntityRef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PEReference_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '%'\n this.items = [\"'%'\", 'Name', \"';'\"]\n this.rules = []\n this.repeats = []\n}\n\nPEReference_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '%'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '%')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // Name\n if(! this.rules[1]){\n this.rules[1] = new Name_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // ';'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, ';')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPEReference_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EntityDecl_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // GEDecl\n this.items = ['GEDecl', 'PEDecl']\n this.rules = []\n this.repeats = []\n}\n\nEntityDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // GEDecl\n if(! this.rules[0]){\n this.rules[0] = new GEDecl_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PEDecl\n if(! this.rules[1]){\n this.rules[1] = new PEDecl_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEntityDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction GEDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nGEDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, '>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nGEDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PEDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nPEDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[8]){\n this.rules[8] = new LITERAL(this, '>')\n }\n rule = this.rules[8]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPEDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EntityDef_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // EntityValue\n this.items = ['EntityValue', 'tmp_52']\n this.rules = []\n this.repeats = []\n}\n\nEntityDef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // EntityValue\n if(! this.rules[0]){\n this.rules[0] = new EntityValue_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_52\n if(! this.rules[1]){\n this.rules[1] = new tmp_52_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEntityDef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_52_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ExternalID\n this.items = ['ExternalID', 'NDataDecl?']\n this.rules = []\n this.repeats = []\n}\n\ntmp_52_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ExternalID\n if(! this.rules[0]){\n this.rules[0] = new ExternalID_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // NDataDecl?\n if(! this.rules[1]){\n this.rules[1] = new NDataDecl_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_52_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PEDef_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // EntityValue\n this.items = ['EntityValue', 'ExternalID']\n this.rules = []\n this.repeats = []\n}\n\nPEDef_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // EntityValue\n if(! this.rules[0]){\n this.rules[0] = new EntityValue_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // ExternalID\n if(! this.rules[1]){\n this.rules[1] = new ExternalID_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPEDef_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction ExternalID_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_53\n this.items = ['tmp_53', 'tmp_54']\n this.rules = []\n this.repeats = []\n}\n\nExternalID_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_53\n if(! this.rules[0]){\n this.rules[0] = new tmp_53_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_54\n if(! this.rules[1]){\n this.rules[1] = new tmp_54_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nExternalID_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_53_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'SYSTEM'\n this.items = [\"'SYSTEM'\", 'S', 'SystemLiteral']\n this.rules = []\n this.repeats = []\n}\n\ntmp_53_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'SYSTEM'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'SYSTEM')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // SystemLiteral\n if(! this.rules[2]){\n this.rules[2] = new SystemLiteral_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_53_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_54_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'PUBLIC'\n this.items = [\"'PUBLIC'\", 'S', 'PubidLiteral', 'S', 'SystemLiteral']\n this.rules = []\n this.repeats = []\n}\n\ntmp_54_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'PUBLIC'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'PUBLIC')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // PubidLiteral\n if(! this.rules[2]){\n this.rules[2] = new PubidLiteral_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // S\n if(! this.rules[3]){\n this.rules[3] = new S_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 4, rule, char)\n case 4: // SystemLiteral\n if(! this.rules[4]){\n this.rules[4] = new SystemLiteral_rule(this)\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_54_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction NDataDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', \"'NDATA'\", 'S', 'Name']\n this.rules = []\n this.repeats = []\n}\n\nNDataDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // 'NDATA'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'NDATA')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // S\n if(! this.rules[2]){\n this.rules[2] = new S_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // Name\n if(! this.rules[3]){\n this.rules[3] = new Name_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNDataDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction TextDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nTextDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[4]){\n this.rules[4] = new LITERAL(this, '?>')\n }\n rule = this.rules[4]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nTextDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction extParsedEnt_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // TextDecl?\n this.items = ['TextDecl?', 'content']\n this.rules = []\n this.repeats = []\n}\n\nextParsedEnt_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // TextDecl?\n if(! this.rules[0]){\n this.rules[0] = new TextDecl_rule(this)\n this.repeats[0] = 0\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_zero_or_one(this, 0, 1, rule, char)\n case 1: // content\n if(! this.rules[1]){\n this.rules[1] = new content_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nextParsedEnt_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EncodingDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // S\n this.items = ['S', \"'encoding'\", 'Eq', 'tmp_55']\n this.rules = []\n this.repeats = []\n}\n\nEncodingDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // S\n if(! this.rules[0]){\n this.rules[0] = new S_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // 'encoding'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, 'encoding')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // Eq\n if(! this.rules[2]){\n this.rules[2] = new Eq_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 3, rule, char)\n case 3: // tmp_55\n if(! this.rules[3]){\n this.rules[3] = new tmp_55_rule(this)\n }\n rule = this.rules[3]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEncodingDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_55_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // tmp_56\n this.items = ['tmp_56', 'tmp_57']\n this.rules = []\n this.repeats = []\n}\n\ntmp_55_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // tmp_56\n if(! this.rules[0]){\n this.rules[0] = new tmp_56_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // tmp_57\n if(! this.rules[1]){\n this.rules[1] = new tmp_57_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_55_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_56_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // '\"'\n this.items = ['\\'\"\\'', 'EncName', '\\'\"\\'']\n this.rules = []\n this.repeats = []\n}\n\ntmp_56_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // '\"'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\"')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // EncName\n if(! this.rules[1]){\n this.rules[1] = new EncName_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // '\"'\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\"')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_56_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_57_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // \"'\"\n this.items = ['\"\\'\"', 'EncName', '\"\\'\"']\n this.rules = []\n this.repeats = []\n}\n\ntmp_57_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // \"'\"\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, '\\'')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // EncName\n if(! this.rules[1]){\n this.rules[1] = new EncName_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // \"'\"\n if(! this.rules[2]){\n this.rules[2] = new LITERAL(this, '\\'')\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_57_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction EncName_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [A-Za-z]\n this.items = ['[A-Za-z]', 'tmp_58*']\n this.rules = []\n this.repeats = []\n}\n\nEncName_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [A-Za-z]\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, 'A-Za-z')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // tmp_58*\n if(! this.rules[1]){\n this.rules[1] = new tmp_58_rule(this)\n this.repeats[1] = 0\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_star(this, 1, -1, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nEncName_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_58_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // [A-Za-z0-9._]\n this.items = ['[A-Za-z0-9._]', \"'-'\"]\n this.rules = []\n this.repeats = []\n}\n\ntmp_58_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // [A-Za-z0-9._]\n if(! this.rules[0]){\n this.rules[0] = new CHARSET_rule(this, 'A-Za-z0-9._')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // '-'\n if(! this.rules[1]){\n this.rules[1] = new LITERAL(this, '-')\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_58_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction NotationDecl_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ''\"]\n this.rules = []\n this.repeats = []\n}\n\nNotationDecl_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ''\n if(! this.rules[6]){\n this.rules[6] = new LITERAL(this, '>')\n }\n rule = this.rules[6]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nNotationDecl_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction tmp_59_rule(origin){\n this.alt = true\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // ExternalID\n this.items = ['ExternalID', 'PublicID']\n this.rules = []\n this.repeats = []\n}\n\ntmp_59_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // ExternalID\n if(! this.rules[0]){\n this.rules[0] = new ExternalID_rule(this)\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_alt(this, 1, rule, char)\n case 1: // PublicID\n if(! this.rules[1]){\n this.rules[1] = new PublicID_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\ntmp_59_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nfunction PublicID_rule(origin){\n this.origin = origin\n this.pos = get_pos(this)\n this.result_store = {}\n this.expect = 0 // 'PUBLIC'\n this.items = [\"'PUBLIC'\", 'S', 'PubidLiteral']\n this.rules = []\n this.repeats = []\n}\n\nPublicID_rule.prototype.feed = function(char){\n var res, rule\n switch(this.expect){\n case 0: // 'PUBLIC'\n if(! this.rules[0]){\n this.rules[0] = new LITERAL(this, 'PUBLIC')\n }\n rule = this.rules[0]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 1, rule, char)\n case 1: // S\n if(! this.rules[1]){\n this.rules[1] = new S_rule(this)\n }\n rule = this.rules[1]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_simple(this, 2, rule, char)\n case 2: // PubidLiteral\n if(! this.rules[2]){\n this.rules[2] = new PubidLiteral_rule(this)\n }\n rule = this.rules[2]\n rule.pos = rule.pos ?? get_pos(this)\n return handle_last(this, rule, char)\n case -1:\n return this.origin.feed(DONE)\n }\n return this\n}\n\nPublicID_rule.prototype.reset = function(){\n this.expect = 0\n}\n\nvar models = {\n XML_CTYPE_ANY: 2,\n XML_CTYPE_CHOICE: 5,\n XML_CTYPE_EMPTY: 1,\n XML_CTYPE_MIXED: 3,\n XML_CTYPE_NAME: 4,\n XML_CTYPE_SEQ: 6,\n}\n\n__BRYTHON__.addToImported('xml_parser', {\n DOCUMENT: document_rule,\n models\n})\n\n})(__BRYTHON__)"], "_ajax": [".js", "// ajax\n__BRYTHON__.imported._ajax = (function($B){\n\n\nvar $N = $B.builtins.None,\n _b_ = $B.builtins\n\nvar add_to_res = function(res, key, val) {\n if($B.$isinstance(val, _b_.list)){\n for (j = 0; j < val.length; j++) {\n add_to_res(res, key, val[j])\n }\n }else if (val instanceof File || val instanceof Blob){\n res.append(key, val)\n }else{\n res.append(key, _b_.str.$factory(val))\n }\n}\n\nfunction set_timeout(self, timeout){\n if(timeout.seconds !== undefined){\n self.js.$requestTimer = setTimeout(\n function() {\n self.js.abort()\n if(timeout.func){\n timeout.func()\n }\n },\n timeout.seconds * 1000)\n }\n}\n\nfunction _read(req){\n var xhr = req.js\n if(xhr.responseType == \"json\"){\n return $B.structuredclone2pyobj(xhr.response)\n }\n if(req.charset_user_defined){\n // on blocking mode, xhr.response is a string\n var bytes = []\n for(var i = 0, len = xhr.response.length; i < len; i++){\n var cp = xhr.response.codePointAt(i)\n if(cp > 0xf700){\n bytes.push(cp - 0xf700)\n }else{\n bytes.push(cp)\n }\n }\n }else if(typeof xhr.response == \"string\"){\n if(req.mode == 'binary'){\n return _b_.str.encode(xhr.response,\n $B.$getattr(req, 'encoding', 'utf-8'))\n }\n return xhr.response\n }else{\n // else it's an ArrayBuffer\n var buf = new Uint8Array(xhr.response),\n bytes = Array.from(buf.values())\n }\n var b = _b_.bytes.$factory(bytes),\n mode = $B.$getattr(req, 'mode', null)\n if(mode == \"binary\"){\n return b\n }else if(mode == \"document\"){\n return $B.jsobj2pyobj(xhr.response)\n }else{\n var encoding = $B.$getattr(req, 'encoding', \"utf-8\")\n return _b_.bytes.decode(b, encoding)\n }\n}\n\nfunction stringify(d){\n var items = []\n for(var entry of _b_.dict.$iter_items(d)){\n items.push(encodeURIComponent(entry.key) + \"=\" +\n encodeURIComponent(entry.value))\n }\n return items.join(\"&\")\n}\n\nfunction handle_kwargs(self, kw, method){\n var data,\n encoding,\n headers = {},\n cache,\n mode = \"text\",\n timeout = {},\n rawdata\n\n for(var item of _b_.dict.$iter_items(kw)){\n var key = item.key\n if(key == \"data\"){\n var rawdata = item.value\n if(typeof rawdata == \"string\" || rawdata instanceof FormData){\n data = rawdata\n }else if(rawdata.__class__ === _b_.dict){\n data = stringify(rawdata)\n }else{\n throw _b_.TypeError.$factory(\"wrong type for data: \" +\n $B.class_name(rawdata))\n }\n }else if(key == \"encoding\"){\n encoding = item.value\n }else if(key == \"headers\"){\n var value = item.value\n if(! $B.$isinstance(value, _b_.dict)){\n throw _b_.ValueError.$factory(\n \"headers must be a dict, not \" + $B.class_name(value))\n }\n for(var subitem of _b_.dict.$iter_items(value)){\n headers[subitem.key.toLowerCase()] = subitem.value\n }\n }else if(key.startsWith(\"on\")){\n var event = key.substr(2)\n if(event == \"timeout\"){\n timeout.func = item.value\n }else{\n var f = item.value\n ajax.bind(self, event, f)\n }\n }else if(key == \"mode\"){\n var mode = item.value\n }else if(key == \"timeout\"){\n timeout.seconds = item.value\n }else if(key == \"cache\"){\n cache = item.value\n }\n }\n if(encoding && mode != \"text\"){\n throw _b_.ValueError.$factory(\"encoding not supported for mode \" +\n mode)\n }\n if((method == \"post\" || method == \"put\") && ! headers){\n // For POST requests, set default header\n self.js.setRequestHeader(\"Content-type\",\n \"application/x-www-form-urlencoded\")\n }\n\n return {cache, data, rawdata, encoding, headers, mode, timeout}\n}\n\nvar ajax = $B.make_class('ajax')\n\najax.__repr__ = function(self){\n return ''\n}\n\najax.__getattribute__ = function(self, attr){\n if(ajax[attr] !== undefined){\n return function(){\n return ajax[attr].call(null, self, ...arguments)\n }\n }else if(attr == \"text\"){\n return _read(self)\n }else if(attr == \"json\"){\n if(self.js.responseType == \"json\"){\n return _read(self)\n }else{\n var resp = _read(self)\n try{\n return $B.structuredclone2pyobj(JSON.parse(resp))\n }catch(err){\n console.log('attr json, invalid resp', resp)\n throw err\n }\n }\n }else if(self.js[attr] !== undefined){\n if(typeof self.js[attr] == \"function\"){\n return function(){\n if(attr == \"setRequestHeader\"){\n ajax.set_header.call(null, self, ...arguments)\n }else{\n if(attr == 'overrideMimeType'){\n console.log('override mime type')\n self.hasMimeType = true\n }\n return self.js[attr](...arguments)\n }\n }\n }else{\n return self.js[attr]\n }\n }else if(attr == \"xml\"){\n return $B.jsobj2pyobj(self.js.responseXML)\n }\n return _b_.object.__getattribute__(self, attr)\n}\n\najax.bind = function(self, evt, func){\n // req.bind(evt,func) is the same as req.onevt = func\n self.js['on' + evt] = function(){\n try{\n return func.apply(null, arguments)\n }catch(err){\n $B.handle_error(err)\n }\n }\n return _b_.None\n}\n\najax.open = function(){\n var $ = $B.args('open', 4,\n {self: null, method: null, url: null, async: null},\n ['self', 'method', 'url', 'async'], arguments,\n {async: true}, null, null),\n self = $.self,\n method = $.method,\n url = $.url,\n async = $.async\n if(typeof method !== \"string\"){\n throw _b_.TypeError.$factory(\n 'open() argument method should be string, got ' +\n $B.class_name(method))\n }\n if(typeof url !== \"string\"){\n throw _b_.TypeError.$factory(\n 'open() argument url should be string, got ' +\n $B.class_name(url))\n }\n self.$method = method\n self.blocking = ! self.async\n self.js.open(method, url, async)\n}\n\najax.read = function(self){\n return _read(self)\n}\n\najax.send = function(self, params){\n // params can be Python dictionary or string\n var content_type\n for(var key in self.headers){\n var value = self.headers[key]\n self.js.setRequestHeader(key, value)\n if(key == 'content-type'){\n content_type = value\n }\n }\n if(($B.$getattr(self, 'encoding', false) ||\n $B.$getattr(self, 'blocking', false)) && ! self.hasMimeType){\n // On blocking mode, or if an encoding has been specified,\n // override Mime type so that bytes are not processed\n // (unless the Mime type has been explicitely set)\n self.js.overrideMimeType('text/plain;charset=x-user-defined')\n self.charset_user_defined = true\n }\n var res = ''\n if(! params){\n self.js.send()\n return _b_.None\n }\n if($B.$isinstance(params, _b_.str)){\n res = params\n }else if($B.$isinstance(params, _b_.dict)){\n if(content_type == 'multipart/form-data'){\n // The FormData object serializes the data in the 'multipart/form-data'\n // content-type so we may as well override that header if it was set\n // by the user.\n res = new FormData()\n var items = _b_.list.$factory(_b_.dict.items(params))\n for(var i = 0, len = items.length; i < len; i++){\n add_to_res(res, _b_.str.$factory(items[i][0]), items[i][1])\n }\n }else{\n if(self.$method && self.$method.toUpperCase() == \"POST\" &&\n ! content_type){\n // Set default Content-Type for POST requests\n self.js.setRequestHeader(\"Content-Type\",\n \"application/x-www-form-urlencoded\")\n }\n var items = _b_.list.$factory(_b_.dict.items(params))\n for(var i = 0, len = items.length; i < len; i++){\n var key = encodeURIComponent(_b_.str.$factory(items[i][0]));\n if($B.$isinstance(items[i][1], _b_.list)){\n for (j = 0; j < items[i][1].length; j++) {\n res += key +'=' +\n encodeURIComponent(_b_.str.$factory(items[i][1][j])) + '&'\n }\n }else{\n res += key + '=' +\n encodeURIComponent(_b_.str.$factory(items[i][1])) + '&'\n }\n }\n res = res.substr(0, res.length - 1)\n }\n }else if(params instanceof FormData){\n res = params\n }else{\n throw _b_.TypeError.$factory(\n \"send() argument must be string or dictionary, not '\" +\n _b_.str.$factory(params.__class__) + \"'\")\n }\n self.js.send(res)\n return _b_.None\n}\n\najax.responseType = _b_.property.$factory(\n function(_self){\n return _self.responseType\n },\n function(_self, value){\n _self.js.responseType = value\n }\n)\n\najax.withCredentials = _b_.property.$factory(\n function(_self){\n return _self.withCredentials\n },\n function(_self, value){\n _self.js.withCredentials = value\n }\n)\n\najax.set_header = function(self, key, value){\n self.headers[key.toLowerCase()] = value\n}\n\najax.set_timeout = function(self, seconds, func){\n self.js.$requestTimer = setTimeout(\n function() {\n self.js.abort()\n func()\n },\n seconds * 1000)\n}\n\najax.$factory = function(){\n\n var xmlhttp = new XMLHttpRequest()\n\n xmlhttp.onreadystatechange = function(){\n // here, \"this\" refers to xmlhttp\n var state = this.readyState\n if(this.responseType == \"\" || this.responseType == \"text\"){\n res.js.text = this.responseText\n }\n var timer = this.$requestTimer\n if(state == 0 && this.onuninitialized){\n this.onuninitialized(res)\n }else if(state == 1 && this.onloading){\n this.onloading(res)\n }else if(state == 2 && this.onloaded){\n this.onloaded(res)\n }else if(state == 3 && this.oninteractive){\n this.oninteractive(res)\n }else if(state == 4 && this.oncomplete){\n if(timer !== null){\n globalThis.clearTimeout(timer)\n }\n this.oncomplete(res)\n }\n }\n var res = {\n __class__: ajax,\n __dict__: $B.empty_dict(),\n js: xmlhttp,\n headers: {}\n }\n return res\n}\n\n\nfunction _request_without_body(method){\n var $ = $B.args(method, 3, {method: null, url: null, blocking: null},\n [\"method\", \"url\", \"blocking\"], arguments, {blocking: false},\n null, \"kw\"),\n method = $.method,\n url = $.url,\n async = !$.blocking,\n kw = $.kw\n\n var self = ajax.$factory()\n self.blocking = $.blocking\n var items = handle_kwargs(self, kw, method),\n mode = items.mode,\n encoding = items.encoding,\n qs = items.data\n $B.$setattr(self, 'mode', mode)\n $B.$setattr(self, 'encoding', encoding)\n if(qs){\n url += \"?\" + qs\n }\n if(! (items.cache === true)){\n url += (qs ? \"&\" : \"?\") + (new Date()).getTime()\n }\n self.js.open(method.toUpperCase(), url, async)\n\n if(async){\n if(mode == \"json\" || mode == \"document\"){\n self.js.responseType = mode\n }else{\n self.js.responseType = \"arraybuffer\"\n if(mode != \"text\" && mode != \"binary\"){\n throw _b_.ValueError.$factory(\"invalid mode: \" + mode)\n }\n }\n }else{\n self.js.overrideMimeType('text/plain;charset=x-user-defined')\n self.charset_user_defined = true\n }\n for(var key in items.headers){\n self.js.setRequestHeader(key, items.headers[key])\n }\n var timeout = items.timeout\n if(timeout.seconds){\n ajax.set_timeout(self, timeout.seconds, timeout.func)\n }\n // Add function read() to return str or bytes according to mode\n self.js.send()\n}\n\nfunction _request_with_body(method){\n var $ = $B.args(method, 3, {method: null, url: null, blocking: null},\n [\"method\", \"url\", \"blocking\"], arguments, {blocking: false},\n null, \"kw\"),\n method = $.method,\n url = $.url,\n async = !$.blocking,\n kw = $.kw,\n content_type\n var self = ajax.$factory()\n self.js.open(method.toUpperCase(), url, async)\n var items = handle_kwargs(self, kw, method), // common with browser.aio\n data = items.data\n\n if($B.$isinstance(data, _b_.dict)){\n data = stringify(data)\n }\n for(var key in items.headers){\n var value = items.headers[key]\n self.js.setRequestHeader(key, value)\n if(key == 'content-type'){\n content_type = value\n }\n }\n if(method.toUpperCase() == 'POST' && !content_type){\n // set default Content-Type for POST requests\n self.js.setRequestHeader('Content-Type',\n 'application/x-www-form-urlencoded')\n }\n\n // Add function read() to return str or bytes according to mode\n self.js.read = function(){\n return _read(self)\n }\n self.js.send(data)\n}\n\nfunction form_data(form){\n var missing = {},\n $ = $B.args('form_data', 1, {form: null}, ['form'], arguments,\n {form: missing}, null, null)\n if($.form === missing){\n return new FormData()\n }else{\n return new FormData($.form)\n }\n}\n\nfunction connect(){\n _request_without_body.call(null, \"connect\", ...arguments)\n}\n\nfunction _delete(){\n _request_without_body.call(null, \"delete\", ...arguments)\n}\n\nfunction get(){\n _request_without_body.call(null, \"get\", ...arguments)\n}\n\nfunction head(){\n _request_without_body.call(null, \"head\", ...arguments)\n}\n\nfunction options(){\n _request_without_body.call(null, \"options\", ...arguments)\n}\n\nfunction patch(){\n _request_with_body.call(null, \"put\", ...arguments)\n}\n\nfunction post(){\n _request_with_body.call(null, \"post\", ...arguments)\n}\n\nfunction put(){\n _request_with_body.call(null, \"put\", ...arguments)\n}\n\nfunction trace(){\n _request_without_body.call(null, \"trace\", ...arguments)\n}\n\nfunction file_upload(){\n // ajax.file_upload(url, file, method=\"POST\", **callbacks)\n var $ = $B.args(\"file_upload\", 2, {url: null, \"file\": file},\n [\"url\", \"file\"], arguments, {}, null, \"kw\"),\n url = $.url,\n file = $.file,\n kw = $.kw\n\n var self = ajax.$factory()\n\n var items = handle_kwargs(self, kw, method),\n rawdata = items.rawdata,\n headers = items.headers\n\n for(var key in headers){\n var value = headers[key]\n self.js.setRequestHeader(key, value)\n if(key == 'content-type'){\n content_type = value\n }\n }\n\n var timeout = items.timeout\n if(timeout.seconds){\n ajax.set_timeout(self, timeout.seconds, timeout.func)\n }\n\n var method = _b_.dict.$get_string(kw, 'method', 'POST'),\n field_name = _b_.dict.$get_string(kw, 'field_name', 'filetosave')\n\n var formdata = new FormData()\n formdata.append(field_name, file, file.name)\n\n if(rawdata){\n if(rawdata instanceof FormData){\n // append additional data\n for(var d of rawdata){\n formdata.append(d[0], d[1])\n }\n }else if($B.$isinstance(rawdata, _b_.dict)){\n for(var item of _b_.dict.$iter_items(rawdata)){\n formdata.append(item.key, item.value)\n }\n }else{\n throw _b_.ValueError.$factory(\n 'data value must be a dict of form_data')\n }\n }\n\n self.js.open(method, url, _b_.True)\n self.js.send(formdata)\n\n}\n\n$B.set_func_names(ajax)\n\nreturn {\n ajax: ajax,\n Ajax: ajax,\n delete: _delete,\n file_upload: file_upload,\n connect,\n form_data,\n get,\n head,\n options,\n patch,\n post,\n put,\n trace\n}\n\n})(__BRYTHON__)\n"], "_ast": [".js", "(function($B){\n\nvar _b_ = $B.builtins,\n ast = $B.ast, // created in py2js\n mod = {}\nmod.PyCF_ONLY_AST = $B.PyCF_ONLY_AST\nmod.PyCF_TYPE_COMMENTS = $B.PyCF_TYPE_COMMENTS\nmod.AST = $B.AST // in builtin_modules.js\n$B.create_python_ast_classes() // in py_ast.js\nfor(var klass in ast){\n mod[klass] = $B.python_ast_classes[klass]\n}\n\nvar Load = 'Load',\n Store = 'Store',\n Del = 'Del'\n\n// Note: the ensure_literal_* functions are only used to validate a restricted\n// set of non-recursive literals that have already been checked with\n// validate_expr, so they don't accept the validator state\nfunction ensure_literal_number(exp, allow_real, allow_imaginary){\n if(exp.__class__ !== mod.Constant){\n return false\n }\n var value = exp.value\n if(allow_real && $B.$isinstance(value, [_b_.int, _b_.float])){\n return true\n }\n if(allow_imaginary && $B.$isinstance(value, _b_.complex)){\n return true\n }\n return false\n}\n\nfunction ensure_literal_negative(exp, allow_real, allow_imaginary){\n if(exp.__class__ !== mod.UnaryOp){\n return false\n }\n // Must be negation ...\n if(exp.op !== mod.USub) {\n return false\n }\n // ... of a constant ...\n var operand = exp.operand\n if(operand.__class__ !== mod.Constant){\n return false\n }\n // ... number\n return ensure_literal_number(operand, allow_real, allow_imaginary)\n}\n\nfunction ensure_literal_complex(exp){\n if(exp.__class__ !== mod.BinOp){\n return false\n }\n var left = exp.left,\n right = exp.right;\n // Ensure op is addition or subtraction\n if(exp.op !== mod.Add && exp.op !== mod.Sub){\n return false\n }\n // Check LHS is a real number (potentially signed)\n switch(left.__class__){\n case mod.Constant:\n if(!ensure_literal_number(left, true, false)){\n return false\n }\n break;\n case mod.UnaryOp:\n if(!ensure_literal_negative(left, true, false)){\n return false\n }\n break;\n default:\n return false\n }\n // Check RHS is an imaginary number (no separate sign allowed)\n switch(right.__class__){\n case mod.Constant:\n if(!ensure_literal_number(right, false, true)){\n return false\n }\n break;\n default:\n return false\n }\n return true\n}\n\nfunction validate_arguments(args){\n validate_args(args.posonlyargs)\n validate_args(args.args)\n if(args.vararg && args.vararg.annotation){\n validate_expr(args.vararg.annotation, Load)\n }\n validate_args(args.kwonlyargs)\n if(args.kwarg && args.kwarg.annotation){\n validate_expr(args.kwarg.annotation, Load)\n }\n if(args.defaults.length > args.posonlyargs.length + args.args.length){\n throw _b_.ValueError.$factory(\n \"more positional defaults than args on arguments\")\n }\n if(args.kw_defaults.length != args.kwonlyargs.length){\n throw _b_.ValueError.$factory(\n \"length of kwonlyargs is not the same as \" +\n \"kw_defaults on arguments\")\n }\n validate_exprs(args.defaults, Load, 0)\n validate_exprs(args.kw_defaults, Load, 1)\n}\n\nfunction validate_pattern(p, star_ok){\n var ret = -1\n switch(p.__class__) {\n case mod.MatchValue:\n validate_pattern_match_value(p.value)\n break;\n case mod.MatchSingleton:\n if([_b_.None, _b_.True, _b_.False].indexOf(p.value) == -1){\n throw _b_.ValueError(\n \"MatchSingleton can only contain True, False and None\")\n }\n break;\n case mod.MatchSequence:\n validate_patterns(p.patterns, 1);\n break;\n case mod.MatchMapping:\n if(p.keys.length != p.patterns.length){\n throw _b_.ValueError.$factory(\n \"MatchMapping doesn't have the same number of keys as patterns\");\n }\n if(p.rest){\n validate_capture(p.rest)\n }\n\n var keys = p.keys;\n for(var key of keys){\n if(key.__class__ === mod.Constant) {\n var literal = key.value;\n if([_b_.None, _b_.True, _b_.False].indexOf(literal) > -1){\n /* validate_pattern_match_value will ensure the key\n doesn't contain True, False and None but it is\n syntactically valid, so we will pass those on in\n a special case. */\n continue;\n }\n }\n validate_pattern_match_value(key)\n }\n validate_patterns(p.patterns, 0);\n break;\n case mod.MatchClass:\n if(p.kwd_attrs.length != p.kwd_patterns.length){\n throw _b_.ValueError.$factory(\n \"MatchClass doesn't have the same number of \" +\n \"keyword attributes as patterns\")\n }\n validate_expr(p.cls, Load)\n var cls = p.cls;\n while(true){\n if(cls.__class__ === mod.Name){\n break\n }else if(cls.__class__ === mod.Attribute) {\n cls = cls.value;\n continue;\n }else {\n throw _b_.ValueError.$factory(\n \"MatchClass cls field can only contain Name \" +\n \"or Attribute nodes.\")\n }\n }\n\n for(var identifier of p.kwd_attrs){\n validate_name(identifier)\n }\n\n validate_patterns(p.patterns, 0)\n validate_patterns(p.kwd_patterns, 0);\n break;\n case mod.MatchStar:\n if (!star_ok) {\n throw _b_.ValueError.$factory(\"can't use MatchStar here\")\n }\n if(p.name === undefined){\n validate_capture(p.name)\n }\n break;\n case mod.MatchAs:\n if(p.name){\n validate_capture(p.name)\n }\n if(p.pattern == undefined){\n ret = 1;\n }else if(p.name == undefined){\n throw _b_.ValueError.$factory(\n \"MatchAs must specify a target name if a pattern is given\")\n }else{\n validate_pattern(p.pattern, 0);\n }\n break;\n case mod.MatchOr:\n if(p.patterns.length < 2){\n throw _b_.ValueError.$factory(\n \"MatchOr requires at least 2 patterns\")\n }\n validate_patterns(p.patterns, 0)\n break;\n // No default case, so the compiler will emit a warning if new pattern\n // kinds are added without being handled here\n }\n if(ret < 0){\n throw _b_.SystemError.$factory(\"unexpected pattern\")\n }\n return true\n}\n\nfunction validate_patterns(patterns, star_ok){\n for(var pattern of patterns){\n validate_pattern(pattern, star_ok)\n }\n return true\n}\n\nfunction validate_pattern_match_value(exp){\n validate_expr(exp, Load)\n switch (exp.__class__){\n case mod.Constant:\n /* Ellipsis and immutable sequences are not allowed.\n For True, False and None, MatchSingleton() should\n be used */\n validate_expr(exp, Load)\n var literal = exp.value\n if($B.$isinstance(literal, [_b_.int, _b_.float, _b_.bytes,\n _b_.complex, _b_.str])){\n return true\n }\n throw _b_.ValueError.$factory(\n \"unexpected constant inside of a literal pattern\")\n case mod.Attribute:\n // Constants and attribute lookups are always permitted\n return true\n case mod.UnaryOp:\n // Negated numbers are permitted (whether real or imaginary)\n // Compiler will complain if AST folding doesn't create a constant\n if(ensure_literal_negative(exp, true, true)){\n return true\n }\n break;\n case mod.BinOp:\n // Complex literals are permitted\n // Compiler will complain if AST folding doesn't create a constant\n if(ensure_literal_complex(exp)){\n return true\n }\n break;\n case mod.JoinedStr:\n // Handled in the later stages\n return 1;\n default:\n break;\n }\n throw _b_.ValueError.$factory(\n \"patterns may only match literals and attribute lookups\")\n}\n\nfunction validate_capture(name){\n if(name == \"_\"){\n throw _b_.ValueError.$factory(\"can't capture name '_' in patterns\")\n }\n validate_name(name)\n}\n\nfunction validate_name(name){\n var forbidden = [\"None\", \"True\", \"False\"]\n if(forbidden.indexOf(name) > -1){\n throw _b_.ValueError.$factory(`identifier field can't represent` +\n ` '${name}' constant\", forbidden[i]`)\n }\n return true\n}\n\nfunction validate_comprehension(gens){\n if(gens.length == 0) {\n throw _b_.ValueError.$factory(\"comprehension with no generators\")\n }\n for(var comp of gens){\n validate_expr(comp.target, Store)\n validate_expr(comp.iter, Load)\n validate_exprs(comp.ifs, Load, 0)\n }\n return true\n}\n\nfunction validate_keywords(keywords){\n for(var keyword of keywords){\n validate_expr(keyword.value, Load)\n }\n return true\n}\n\nfunction validate_args(args){\n for(var arg of args){\n if(arg.annotation){\n validate_expr(arg.annotation, Load)\n }\n }\n return true\n}\n\nfunction validate_nonempty_seq(seq, what, owner){\n if(seq.length > 0){\n return true\n }\n throw _b_.ValueError.$factory(`empty ${what} on ${owner}`)\n}\n\nfunction validate_assignlist(targets, ctx){\n validate_nonempty_seq(targets, \"targets\", ctx == Del ? \"Delete\" : \"Assign\")\n validate_exprs(targets, ctx, 0)\n}\n\nfunction validate_body(body, owner){\n validate_nonempty_seq(body, \"body\", owner)\n validate_stmts(body)\n}\n\nfunction validate_exprs(exprs, ctx, null_ok){\n for(var expr of exprs){\n if(expr !== _b_.None){\n validate_expr(expr, ctx)\n }else if(!null_ok){\n throw _b_.ValueError.$factory(\n \"None disallowed in expression list\")\n }\n\n }\n return true\n}\n\nfunction validate_expr(exp, ctx){\n var check_ctx = 1,\n actual_ctx;\n\n /* First check expression context. */\n switch (exp.__class__) {\n case mod.Name:\n validate_name(exp.id)\n actual_ctx = exp.ctx\n break;\n case mod.Attribute:\n case mod.Subscript:\n case mod.Starred:\n case mod.List:\n case mod.Tuple:\n actual_ctx = exp.ctx;\n break\n default:\n if(ctx != Load){\n throw _b_.ValueError.$factory(\"expression which can't be \" +\n `assigned to in ${ctx} context`)\n }\n check_ctx = 0;\n /* set actual_ctx to prevent gcc warning */\n actual_ctx = 0;\n }\n actual_ctx = actual_ctx === 0 ? actual_ctx :\n actual_ctx.__class__.__name__\n if(check_ctx && actual_ctx != ctx){\n throw _b_.ValueError.$factory(`expression must have ` +\n `${ctx} context but has ${actual_ctx} instead`)\n }\n\n /* Now validate expression. */\n switch (exp.__class__) {\n case mod.BoolOp:\n if(exp.values.length < 2){\n throw _b_.ValueError.$factory(\"BoolOp with less than 2 values\")\n }\n validate_exprs(exp.values, Load, 0);\n break;\n case mod.BinOp:\n validate_expr(exp.left, Load)\n validate_expr(exp.right, Load)\n break;\n case mod.UnaryOp:\n validate_expr(exp.operand, Load);\n break;\n case mod.Lambda:\n validate_arguments(exp.args)\n validate_expr(exp.body, Load);\n break;\n case mod.IfExp:\n validate_expr(exp.test, Load)\n validate_expr(exp.body, Load)\n validate_expr(exp.orelse, Load)\n break;\n case mod.Dict:\n if(exp.keys.length != exp.values.length){\n throw _b_.ValueError.$factory(\n \"Dict doesn't have the same number of keys as values\");\n }\n /* null_ok=1 for keys expressions to allow dict unpacking to work in\n dict literals, i.e. ``{**{a:b}}`` */\n validate_exprs(exp.keys, Load, 1)\n validate_exprs(exp.values, Load, 0);\n break;\n case mod.Set:\n validate_exprs(exp.elts, Load, 0);\n break;\n case mod.ListComp:\n case mod.SetComp:\n case mod.GeneratorExp:\n validate_comprehension(exp.generators)\n validate_expr(exp.elt, Load)\n break;\n case mod.DictComp:\n validate_comprehension(exp.generators)\n validate_expr(exp.key, Load)\n validate_expr(exp.value, Load)\n break;\n case mod.Yield:\n if(exp.value){\n validate_expr(exp.value, Load)\n }\n break;\n case mod.YieldFrom:\n validate_expr(exp.value, Load)\n break;\n case mod.Await:\n validate_expr(exp.value, Load)\n break;\n case mod.Compare:\n if(exp.comparators.length == 0){\n throw _b_.ValueError.$factory(\"Compare with no comparators\")\n }\n if(exp.comparators.length != exp.ops){\n throw _b_.ValueError.$factory(\"Compare has a different number \" +\n \"of comparators and operands\")\n }\n validate_exprs(exp.comparators, Load, 0)\n validate_expr(exp.left, Load)\n break;\n case mod.Call:\n validate_expr(exp.func, Load)\n validate_exprs(exp.args, Load, 0)\n validate_keywords(exp.keywords)\n break;\n case mod.Constant:\n validate_constant(exp.value)\n break;\n case mod.JoinedStr:\n validate_exprs(exp.values, Load, 0)\n break;\n case mod.FormattedValue:\n validate_expr(exp.value, Load)\n if (exp.format_spec) {\n validate_expr(exp.format_spec, Load)\n break;\n }\n break;\n case mod.Attribute:\n validate_expr(exp.value, Load)\n break;\n case mod.Subscript:\n validate_expr(exp.slice, Load)\n validate_expr(exp.value, Load)\n break;\n case mod.Starred:\n validate_expr(exp.value, ctx)\n break;\n case mod.Slice:\n if(exp.lower){\n validate_expr(exp.lower, Load)\n }\n if(exp.upper){\n validate_expr(exp.upper, Load)\n }\n if(exp.step){\n validate_expr(exp.step, Load)\n }\n break;\n case mod.List:\n validate_exprs(exp.elts, ctx, 0)\n break;\n case mod.Tuple:\n validate_exprs(exp.elts, ctx, 0)\n break;\n case mod.NamedExpr:\n validate_expr(exp.value, Load)\n break;\n /* This last case doesn't have any checking. */\n case mod.Name:\n ret = 1;\n break;\n // No default case mod.so compiler emits warning for unhandled cases\n }\n return true\n}\n\nfunction validate_constant(value){\n if (value == _b_.None || value == _b_.Ellipsis){\n return true\n }\n if($B.$isinstance(value,\n [_b_.int, _b_.float, _b_.complex, _b_.bool, _b_.bytes, _b_.str])){\n return true\n }\n\n if($B.$isinstance(value, [_b_.tuple, _b_.frozenset])){\n var it = _b_.iter(value)\n while(true){\n try{\n var item = _b_.next(it)\n validate_constant(item)\n }catch(err){\n if($B.is_exc(err, [_b_.StopIteration])){\n return true\n }\n throw err\n }\n }\n }\n}\n\nfunction validate_stmts(seq){\n for(var stmt of seq) {\n if(stmt !== _b_.None){\n validate_stmt(stmt)\n }else{\n throw _b_.ValueError.$factory(\"None disallowed in statement list\");\n }\n }\n}\n\nfunction validate_stmt(stmt){\n switch (stmt.__class__) {\n case mod.FunctionDef:\n validate_body(stmt.body, \"FunctionDef\")\n validate_arguments(stmt.args)\n validate_exprs(stmt.decorator_list, Load, 0)\n if(stmt.returns){\n validate_expr(stmt.returns, Load)\n }\n break;\n case mod.ClassDef:\n validate_body(stmt.body, \"ClassDef\")\n validate_exprs(stmt.bases, Load, 0)\n validate_keywords(stmt.keywords)\n validate_exprs(stmtdecorator_list, Load, 0)\n break;\n case mod.Return:\n if(stmt.value){\n validate_expr(stmt.value, Load)\n }\n break;\n case mod.Delete:\n validate_assignlist(stmt.targets, Del);\n break;\n case mod.Assign:\n validate_assignlist(stmt.targets, Store)\n validate_expr(stmt.value, Load)\n break;\n case mod.AugAssign:\n validate_expr(stmt.target, Store) &&\n validate_expr(stmt.value, Load);\n break;\n case mod.AnnAssign:\n if(stmt.target.__class__ != mod.Name && stmt.simple){\n throw _b_.TypeError.$factory(\n \"AnnAssign with simple non-Name target\")\n }\n validate_expr(stmt.target, Store)\n if(stmt.value){\n validate_expr(stmt.value, Load)\n validate_expr(stmt.annotation, Load);\n }\n break;\n case mod.For:\n validate_expr(stmt.target, Store)\n validate_expr(stmt.iter, Load)\n validate_body(stmt.body, \"For\")\n validate_stmts(stmt.orelse)\n break;\n case mod.AsyncFor:\n validate_expr(stmt.target, Store)\n validate_expr(stmt.iter, Load)\n validate_body(stmt.body, \"AsyncFor\")\n validate_stmts(stmt.orelse)\n break;\n case mod.While:\n validate_expr(stmt.test, Load)\n validate_body(stmt.body, \"While\")\n validate_stmts(stmt.orelse)\n break;\n case mod.If:\n validate_expr(stmt.test, Load)\n validate_body(stmt.body, \"If\")\n validate_stmts(stmt.orelse)\n break;\n case mod.With:\n validate_nonempty_seq(stmt.items, \"items\", \"With\")\n for (var item of stmt.items){\n validate_expr(item.context_expr, Load) &&\n (! item.optional_vars || validate_expr(item.optional_vars, Store))\n }\n validate_body(stmt.body, \"With\");\n break;\n case mod.AsyncWith:\n validate_nonempty_seq(stmt.items, \"items\", \"AsyncWith\")\n for(var item of stmt.items){\n validate_expr(item.context_expr, Load)\n if(item.optional_vars){\n validate_expr(item.optional_vars, Store)\n }\n }\n validate_body(stmt.body, \"AsyncWith\");\n break;\n case mod.Match:\n validate_expr(stmt.subject, Load)\n validate_nonempty_seq(stmt.cases, \"cases\", \"Match\")\n for(var m of stmt.cases){\n validate_pattern(m.pattern, 0)\n if(m.guard){\n validate_expr(m.guard, Load)\n }\n validate_body(m.body, \"match_case\")\n }\n break;\n case mod.Raise:\n if(stmt.exc){\n validate_expr(stmt.exc, Load)\n if(stmt.cause){\n validate_expr(stmt.cause, Load)\n }\n break;\n }\n if(stmt.cause) {\n throw _b_.ValueError.$factory(\"Raise with cause but no exception\");\n }\n break;\n case mod.Try:\n validate_body(stmt.body, \"Try\")\n if(stmt.handlers.length == 0 + stmt.finalbody.length == 0){\n throw _b_.ValueError.$factor(\n \"Try has neither except handlers nor finalbody\");\n }\n if(stmt.handlers.length == 0 && stmt.orelse.length > 0){\n throw _b_.ValueError.$factory(\n \"Try has orelse but no except handlers\");\n }\n for(var handler of stmt.handlers){\n if(handler.type){\n validate_expr(handler.type, Load)\n validate_body(handler.body, \"ExceptHandler\")\n }\n }\n if(stmt.finalbody.length > 0){\n validate_stmts(stmt.finalbody)\n }\n if(stmt.orelse.length > 0){\n validate_stmts(stmt.orelse)\n }\n break;\n case mod.TryStar:\n validate_body(stmt.body, \"TryStar\")\n if(stmt.handlers.length + stmt.finalbody.length == 0){\n throw _b_.ValueError.$factory(\n \"TryStar has neither except handlers nor finalbody\");\n }\n if(stmt.handlers.length == 0 && stmt.orelse.length > 0){\n throw _b_.ValueError.$factory(\n \"TryStar has orelse but no except handlers\");\n }\n for(var handler of stm.handlers){\n if(handler.type){\n validate_expr(handler.type, Load)\n validate_body(handler.body, \"ExceptHandler\")\n }\n }\n if(stmt.finalbody.length > 0){\n validate_stmts(stmt.finalbody)\n }\n if(stmt.orelse.length > 0){\n validate_stmts(stmt.orelse)\n }\n break;\n case mod.Assert:\n validate_expr(stmt.test, Load)\n if(stmt.msg){\n validate_expr(stmt.msg, Load)\n }\n break;\n case mod.Import:\n validate_nonempty_seq(stmt.names, \"names\", \"Import\");\n break;\n case mod.ImportFrom:\n if(stmt.level < 0) {\n throw _b_.ValueError.$factory(\"Negative ImportFrom level\")\n }\n validate_nonempty_seq(stmt.names, \"names\", \"ImportFrom\");\n break;\n case mod.Global:\n validate_nonempty_seq(stmt.names, \"names\", \"Global\");\n break;\n case mod.Nonlocal:\n validate_nonempty_seq(stmt.names, \"names\", \"Nonlocal\");\n break;\n case mod.Expr:\n validate_expr(stmt.value, Load);\n break;\n case mod.AsyncFunctionDef:\n validate_body(stmt.body, \"AsyncFunctionDef\")\n validate_arguments(stmt.args)\n validate_exprs(stmt.decorator_list, Load, 0)\n if(stmt.returns){\n validate_expr(stmt.returns, Load)\n }\n break;\n case mod.Pass:\n case mod.Break:\n case mod.Continue:\n break;\n // No default case so compiler emits warning for unhandled cases\n }\n}\n\n\nmod._validate = function(ast_obj){\n switch (ast_obj.__class__) {\n case mod.Module:\n validate_stmts(ast_obj.body);\n break;\n case mod.Interactive:\n validate_stmts(ast_obj.body);\n break;\n case mod.Expression:\n validate_expr(ast_obj.body, Load);\n break;\n case mod.FunctionType:\n validate_exprs(ast_obj.argtypes, Load, 0) &&\n validate_expr(ast_obj.returns, Load);\n break;\n // No default case so compiler emits warning for unhandled cases\n }\n}\n\n$B.imported._ast = mod\n\n}\n)(__BRYTHON__)\n"], "_base64": [".js", "(function($B){\n\nvar _b_ = $B.builtins,\n _keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"\n\nfunction make_alphabet(altchars){\n var alphabet = _keyStr\n if(altchars !== undefined && altchars !== _b_.None){\n // altchars is an instance of Python bytes\n var source = altchars.source\n alphabet = alphabet.substr(0,alphabet.length-3) +\n _b_.chr(source[0]) + _b_.chr(source[1]) + '='\n }\n return alphabet\n}\n\nvar Base64 = {\n error: function(){return 'binascii_error'},\n\n encode: function(bytes, altchars){\n\n var input = bytes.source,\n output = \"\",\n chr1, chr2, chr3, enc1, enc2, enc3, enc4\n var i = 0\n\n var alphabet = make_alphabet(altchars)\n\n while(i < input.length){\n\n chr1 = input[i++]\n chr2 = input[i++]\n chr3 = input[i++]\n\n enc1 = chr1 >> 2\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)\n enc4 = chr3 & 63\n\n if(isNaN(chr2)){\n enc3 = enc4 = 64\n }else if(isNaN(chr3)){\n enc4 = 64\n }\n\n output = output + alphabet.charAt(enc1) +\n alphabet.charAt(enc2) +\n alphabet.charAt(enc3) +\n alphabet.charAt(enc4)\n\n }\n return _b_.bytes.$factory(output, 'utf-8', 'strict')\n },\n\n\n decode: function(bytes, altchars, validate){\n var output = [],\n chr1, chr2, chr3,\n enc1, enc2, enc3, enc4\n\n var alphabet = make_alphabet(altchars)\n\n var input = bytes.source\n\n // If validate is set, check that all characters in input\n // are in the alphabet\n var _input = ''\n var padding = 0\n for(var i = 0, len = input.length; i < len; i++){\n var car = String.fromCharCode(input[i])\n var char_num = alphabet.indexOf(car)\n if(char_num == -1){\n if(validate){\n throw Base64.error(\"Non-base64 digit found: \" + car)\n }\n }else if(char_num == 64 && i < input.length - 2){\n if(validate){\n throw Base64.error(\"Non-base64 digit found: \" + car)\n }\n }else if(char_num == 64 && i >= input.length - 2){\n padding++\n _input += car\n }else{\n _input += car\n }\n }\n input = _input\n if(_input.length == padding){\n return _b_.bytes.$factory([])\n }\n if( _input.length % 4 > 0){\n throw Base64.error(\"Incorrect padding\")\n }\n\n var i = 0\n while(i < input.length){\n\n enc1 = alphabet.indexOf(input.charAt(i++))\n enc2 = alphabet.indexOf(input.charAt(i++))\n enc3 = alphabet.indexOf(input.charAt(i++))\n enc4 = alphabet.indexOf(input.charAt(i++))\n\n chr1 = (enc1 << 2) | (enc2 >> 4)\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)\n chr3 = ((enc3 & 3) << 6) | enc4\n\n output.push(chr1)\n\n if(enc3 != 64){\n output.push(chr2)\n }\n if(enc4 != 64){\n output.push(chr3)\n }\n\n }\n // return Python bytes\n return _b_.bytes.$factory(output, 'utf-8', 'strict')\n\n },\n\n _utf8_encode: function(string){\n string = string.replace(/\\r\\n/g, \"\\n\")\n var utftext = \"\";\n\n for(var n = 0; n < string.length; n++){\n\n var c = string.charCodeAt(n)\n\n if(c < 128){\n utftext += String.fromCharCode(c)\n }else if((c > 127) && (c < 2048)){\n utftext += String.fromCharCode((c >> 6) | 192)\n utftext += String.fromCharCode((c & 63) | 128)\n }else{\n utftext += String.fromCharCode((c >> 12) | 224)\n utftext += String.fromCharCode(((c >> 6) & 63) | 128)\n utftext += String.fromCharCode((c & 63) | 128)\n }\n\n }\n\n return utftext\n },\n\n _utf8_decode: function(utftext) {\n var string = \"\",\n i = 0,\n c = c1 = c2 = 0\n\n while(i < utftext.length){\n\n c = utftext.charCodeAt(i)\n\n if(c < 128){\n string += String.fromCharCode(c)\n i++\n }else if((c > 191) && (c < 224)){\n c2 = utftext.charCodeAt(i + 1)\n string += String.fromCharCode(((c & 31) << 6) | (c2 & 63))\n i += 2\n }else{\n c2 = utftext.charCodeAt(i + 1)\n c3 = utftext.charCodeAt(i + 2)\n string += String.fromCharCode(\n ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))\n i += 3\n }\n\n }\n\n return string\n }\n\n}\n\n$B.addToImported('_base64', {Base64:Base64})\n}\n\n)(__BRYTHON__)"], "_binascii": [".js", "(function($B){\n\nvar _b_ = $B.builtins,\n _keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"\n\nvar error = $B.make_class(\"error\", _b_.Exception.$factory)\nerror.__bases__ = [_b_.Exception]\n$B.set_func_names(error, \"binascii\")\n\nfunction decode(bytes, altchars, validate){\n var output = [],\n chr1, chr2, chr3,\n enc1, enc2, enc3, enc4\n\n var alphabet = make_alphabet(altchars)\n\n var input = bytes.source\n\n // If validate is set, check that all characters in input\n // are in the alphabet\n var _input = ''\n var padding = 0\n for(var i = 0, len = input.length; i < len; i++){\n var car = String.fromCharCode(input[i])\n var char_num = alphabet.indexOf(car)\n if(char_num == -1){\n if(validate){\n throw error.$factory(\"Non-base64 digit found: \" + car)\n }\n }else if(char_num == 64 && i < input.length - 2){\n if(validate){\n throw error.$factory(\"Non-base64 digit found: \" + car)\n }\n }else if(char_num == 64 && i >= input.length - 2){\n padding++\n _input += car\n }else{\n _input += car\n }\n }\n input = _input\n if(_input.length == padding){\n return _b_.bytes.$factory([])\n }\n if( _input.length % 4 > 0){\n throw error.$factory(\"Incorrect padding\")\n }\n\n var i = 0\n while(i < input.length){\n\n enc1 = alphabet.indexOf(input.charAt(i++))\n enc2 = alphabet.indexOf(input.charAt(i++))\n enc3 = alphabet.indexOf(input.charAt(i++))\n enc4 = alphabet.indexOf(input.charAt(i++))\n\n chr1 = (enc1 << 2) | (enc2 >> 4)\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)\n chr3 = ((enc3 & 3) << 6) | enc4\n\n output.push(chr1)\n\n if(enc3 != 64){output.push(chr2)}\n if(enc4 != 64){output.push(chr3)}\n\n }\n // return Python bytes\n return _b_.bytes.$factory(output)\n}\n\n\nvar hex2int = {},\n hex = '0123456789abcdef'\nfor(var i = 0; i < hex.length; i++){\n hex2int[hex[i]] = i\n hex2int[hex[i].toUpperCase()] = i\n}\n\nfunction make_alphabet(altchars){\n var alphabet = _keyStr\n if(altchars !== undefined && altchars !== _b_.None){\n // altchars is an instance of Python bytes\n var source = altchars.source\n alphabet = alphabet.substr(0,alphabet.length-3) +\n _b_.chr(source[0]) + _b_.chr(source[1]) + '='\n }\n return alphabet\n}\n\nvar module = {\n a2b_base64: function(){\n var $ = $B.args(\"a2b_base64\", 2, {s: null, strict_mode: null},\n ['s', 'strict_mode'],\n arguments, {strict_mode: false}, null, null)\n var bytes\n if($B.$isinstance($.s, _b_.str)){\n bytes = _b_.str.encode($.s, 'ascii')\n }else if($B.$isinstance($.s, [_b_.bytes, _b_.bytearray])){\n bytes = $.s\n }else{\n throw _b_.TypeError.$factory('wrong type: ' + $B.class_name($.s))\n }\n return decode(bytes)\n },\n a2b_hex: function(){\n var $ = $B.args(\"a2b_hex\", 1, {s: null}, ['s'],\n arguments, {}, null, null),\n s = $.s\n if($B.$isinstance(s, _b_.bytes)){\n s = _b_.bytes.decode(s, 'ascii')\n }\n if(typeof s !== \"string\"){\n throw _b_.TypeError.$factory(\"argument should be bytes, \" +\n \"buffer or ASCII string, not '\" + $B.class_name(s) + \"'\")\n }\n\n var len = s.length\n if(len % 2 == 1){\n throw _b_.TypeError.$factory('Odd-length string')\n }\n\n var res = []\n for(var i = 0; i < len; i += 2){\n res.push((hex2int[s.charAt(i)] << 4) + hex2int[s.charAt(i + 1)])\n }\n return _b_.bytes.$factory(res)\n },\n b2a_base64: function(){\n var $ = $B.args(\"b2a_base64\", 1, {data: null}, ['data'],\n arguments, {}, null, \"kw\")\n var newline = _b_.dict.$get_string($.kw, 'newline', false)\n\n var string = $B.to_bytes($.data),\n res = btoa(String.fromCharCode.apply(null, string))\n if(newline){\n res += \"\\n\"\n }\n return _b_.bytes.$factory(res, \"ascii\")\n },\n b2a_hex: function(obj){\n var string = $B.to_bytes(obj),\n res = []\n function conv(c){\n if(c > 9){\n c = c + 'a'.charCodeAt(0) - 10\n }else{\n c = c + '0'.charCodeAt(0)\n }\n return c\n }\n string.forEach(function(char){\n res.push(conv((char >> 4) & 0xf))\n res.push(conv(char & 0xf))\n })\n return _b_.bytes.$factory(res)\n },\n b2a_uu: function(obj){\n var string = _b_.bytes.decode(obj, 'ascii')\n var len = string.length,\n res = String.fromCharCode((0x20 + len) & 0x3F)\n while(string.length > 0){\n var s = string.slice(0, 3)\n while(s.length < 3){s.push(String.fromCharCode(0))}\n var A = s[0],\n B = s[1],\n C = s[2]\n var a = (A >> 2) & 0x3F,\n b = ((A << 4) | ((B >> 4) & 0xF)) & 0x3F,\n c = (((B << 2) | ((C >> 6) & 0x3)) & 0x3F),\n d = C & 0x3F\n res += String.fromCharCode(0x20 + a, 0x20 + b, 0x20 + c, 0x20 + d)\n string = string.slice(3)\n }\n return _b_.bytes.$factory(res + \"\\n\", \"ascii\")\n },\n error: error\n}\n\nmodule.hexlify = module.b2a_hex\nmodule.unhexlify = module.a2b_hex\n\n$B.imported._binascii = module\n}\n)(__BRYTHON__)"], "_io_classes": [".js", "var _b_ = __BRYTHON__.builtins\n\nfunction get_self(name, args){\n return $B.args(name, 1, {self: null}, [\"self\"], args, {}, null, null).self\n}\n\nvar _IOBase = $B.make_class(\"_IOBase\")\n_IOBase.__mro__ = [_b_.object]\n\n_IOBase.close = function(){\n get_self(\"close\", arguments).__closed = true\n}\n\n_IOBase.flush = function(){\n get_self(\"flush\", arguments)\n return _b_.None\n}\n\n$B.set_func_names(_IOBase, '_io')\n\n// Base class for binary streams that support some kind of buffering.\nvar _BufferedIOBase = $B.make_class(\"_BufferedIOBase\")\n_BufferedIOBase.__mro__ = [_IOBase, _b_.object]\n\n_BufferedIOBase.__enter__ = function(self){\n return self\n}\n_BufferedIOBase.__exit__ = function(self, type, value, traceback){\n try{\n $B.$call($B.$getattr(self, 'close'))()\n self.__closed = true\n return true\n }catch(err){\n return false\n }\n}\n\n$B.set_func_names(_BufferedIOBase, '_io')\n\n// Base class for raw binary I/O.\nvar _RawIOBase = $B.make_class(\"_RawIOBase\")\n\n_RawIOBase.__mro__ = [_IOBase, _b_.object]\n\n_RawIOBase.read = function(){\n var $ = $B.args(\"read\", 2, {self: null, size: null}, [\"self\", \"size\"],\n arguments, {size: -1}, null, null),\n self = $.self,\n size = $.size,\n res\n self.$pos = self.$pos || 0\n if(size == -1){\n if(self.$pos == 0){\n res = self.$content\n }else{\n res = _b_.bytes.$factory(self.$content.source.slice(self.$pos))\n }\n self.$pos = self.$content.source.length - 1\n }else{\n res = _b_.bytes.$factory(self.$content.source.slice(self.$pos, size))\n self.$pos += size\n }\n return res\n}\n\n_RawIOBase.readall = function(){\n return _RawIOBase.read(get_self(\"readall\", arguments))\n}\n\n$B.set_func_names(_RawIOBase, '_io')\n\n// Base class for text streams.\n_TextIOBase = $B.make_class(\"_TextIOBase\")\n_TextIOBase.__mro__ = [_IOBase, _b_.object]\n\nvar StringIO = $B.make_class(\"StringIO\",\n function(){\n var $ = $B.args(\"StringIO\", 2, {value: null, newline: null},\n [\"value\", \"newline\"], arguments, {value: '', newline: \"\\n\"},\n null, null)\n return {\n __class__: StringIO,\n $counter: 0,\n $content: $.value\n }\n }\n)\n\nStringIO.__mro__ = [$B.Reader, _b_.object]\n\nStringIO.getvalue = function(){\n var $ = $B.args(\"getvalue\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n return $.self.$content.substr(0) // copy\n}\n\nStringIO.truncate = function(self, size){\n var $ = $B.args('truncate', 2, {self: null, size: null}, ['self', 'size'],\n arguments, {size: _b_.None}, null, null),\n self = $.self,\n size = $.size\n if(size === _b_.None){\n size = self.$counter\n }\n self.$content = self.$content.substr(0, size)\n self.$counter = self.$content.length\n return self.$counter\n}\n\nStringIO.write = function(){\n var $ = $B.args(\"write\", 2, {self: null, data: null},\n [\"self\", \"data\"], arguments, {}, null, null)\n if(! $B.$isinstance($.data, _b_.str)){\n throw _b_.TypeError.$factory('string argument expected, got ' +\n `'${$B.class_name($.data)}'`)\n }\n var text = $.self.$content,\n position = $.self.$counter\n if(position > text.length){\n text += String.fromCodePoint(0).repeat(position - text.length)\n }\n text = text.substr(0, position) + $.data +\n text.substr(position + $.data.length)\n $.self.$content = text\n $.self.$counter = position + $.data.length\n return $.data.length\n}\n\n$B.set_func_names(StringIO, \"_io\")\n\nvar BytesIO = $B.make_class(\"BytesIO\",\n function(){\n var $ = $B.args(\"BytesIO\", 1, {value: null},\n [\"value\"], arguments, {value: _b_.bytes.$factory()},\n null, null)\n return {\n __class__: BytesIO,\n $binary: true,\n $content: $.value,\n $length: $.value.source.length,\n $counter: 0\n }\n }\n)\nBytesIO.__mro__ = [$B.Reader, _b_.object]\n\nBytesIO.getbuffer = function(){\n var self = get_self(\"getbuffer\", arguments)\n return _b_.memoryview.$factory(self.$content)\n}\n\nBytesIO.getvalue = function(){\n var self = get_self(\"getvalue\", arguments)\n return self.$content\n}\n\nBytesIO.read = function(){\n var $ = $B.args(\"read\", 2, {self: null, nbytes: null},\n [\"self\", \"nbytes\"], arguments, {nbytes: _b_.None}, null, null),\n self = $.self,\n nbytes = $.nbytes,\n res\n var source = self.$content.source\n if(nbytes === _b_.None){\n res = $B.fast_bytes(source.slice(self.$counter))\n self.$counter = source.length\n }else if(! _b_.isinstance(nbytes, _b_.int)){\n throw _b_.TypeError.$factory('number of bytes should be int, not ' +\n $B.class_name(nbytes))\n }else{\n res = $B.fast_bytes(source.slice(self.$counter,\n self.$counter + nbytes))\n self.$counter = Math.min(self.$counter + nbytes, source.length)\n }\n return res\n}\n\nBytesIO.write = function(){\n var $ = $B.args(\"write\", 2, {self: null, data: null},\n [\"self\", \"data\"], arguments, {}, null, null)\n var data_cls = $B.get_class($.data)\n if(! data_cls.$buffer_protocol){\n throw _b_.TypeError.$factory('a bytes-like object is required, ' +\n `not '${$B.class_name($.data)}'`)\n }\n var source = $.self.$content.source,\n counter = $.self.$counter,\n data = _b_.bytes.$factory($.data)\n if(counter > source.length){\n // pad with 0's\n var padding = (new Array(counter - source.length)).fill(0)\n source.splice(source.length, 0, ...padding)\n }\n source.splice(counter, data.source.length, ...data.source)\n $.self.$counter += data.source.length\n return _b_.None\n}\n\n$B.set_func_names(BytesIO, \"_io\")\n\nvar BlockingIOError = $B.make_class('BlockingIOError')\nBlockingIOError.__bases__ = [_b_.OSError]\n\n$B.set_func_names(BlockingIOError, '_io')\n\nvar $module = (function($B){\n return {\n _BufferedIOBase,\n _IOBase,\n _RawIOBase,\n _TextIOBase: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n BlockingIOError,\n BytesIO: BytesIO,\n FileIO: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n StringIO: StringIO,\n BufferedReader: $B.BufferedReader,\n BufferedWriter: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n BufferedRWPair: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n BufferedRandom: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n IncrementalNewlineDecoder: $B.make_class(\"_TextIOBase\",\n function(){\n return \"fileio\"\n }\n ),\n TextIOWrapper: $B.TextIOWrapper\n }\n})(__BRYTHON__)\n$module._IOBase.__doc__ = \"_IOBase\"\n\n__BRYTHON__.imported._io_classes = $module"], "_json": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nfunction simple(obj){\n switch(typeof obj){\n case 'string':\n case 'number':\n case 'boolean':\n return true\n }\n if(obj instanceof Number ||\n Array.isArray(obj) ||\n $B.$isinstance(obj, [_b_.list, _b_.tuple, _b_.dict])){\n return true\n }\n return false\n}\n\nfunction to_json(obj, level){\n var $defaults = {skipkeys:_b_.False, ensure_ascii:_b_.True,\n check_circular:_b_.True, allow_nan:_b_.True, cls:_b_.None,\n indent:_b_.None, separators:_b_.None, \"default\":_b_.None,\n sort_keys:_b_.False},\n $ = $B.args(\"to_json\", 2, {obj: null, level: null}, ['obj', 'level'],\n arguments, {level: 1}, null, \"kw\")\n\n var kw = _b_.dict.$to_obj($.kw)\n for(var key in $defaults){\n if(! kw.hasOwnProperty(key)){\n kw[key] = $defaults[key]\n }\n }\n\n var indent = kw.indent,\n ensure_ascii = kw.ensure_ascii,\n separators = kw.separators === _b_.None ?\n kw.indent === _b_.None ? [', ', ': '] : [',', ': '] :\n kw.separators,\n skipkeys = kw.skipkeys,\n _default = kw.default,\n sort_keys = kw.sort_keys,\n allow_nan = kw.allow_nan,\n check_circular = kw.check_circular\n\n var item_separator = separators[0],\n key_separator = separators[1]\n if(indent !== _b_.None){\n var indent_str\n if(typeof indent == \"string\"){\n indent_str = indent\n }else if(typeof indent == \"number\" && indent >= 1){\n indent_str = \" \".repeat(indent)\n }else{\n throw _b_.ValueError.$factory(\"invalid indent: \" +\n _b_.str.$factory(indent))\n }\n }\n var kwarg = {$kw: [{}]}\n for(var key in kw){\n kwarg.$kw[0][key] = kw[key]\n }\n\n switch(typeof obj){\n case 'string':\n var res = JSON.stringify(obj)\n if(ensure_ascii){\n var escaped = ''\n for(var i = 0, len = res.length; i < len; i++){\n var u = res.codePointAt(i)\n if(u > 127){\n u = u.toString(16)\n while(u.length < 4){\n u = \"0\" + u\n }\n escaped += '\\\\u' + u\n }else{\n escaped += res.charAt(i)\n }\n }\n return escaped\n }\n return res\n case 'boolean':\n return obj.toString()\n case 'number':\n if([Infinity, -Infinity].indexOf(obj) > -1 ||\n isNaN(obj)){\n if(! allow_nan){\n throw _b_.ValueError.$factory(\n 'Out of range float values are not JSON compliant')\n }\n }\n return obj.toString()\n }\n if(obj instanceof String){\n if(! ensure_ascii){\n return $B.String(obj)\n }\n // string with surrogate pairs. cf. issue #1903.\n var res = ''\n if(obj.surrogates){\n var s_ix = 0,\n s_pos = obj.surrogates[s_ix]\n for(var i = 0, len = obj.length; i < len; i++){\n if(i == s_pos){\n var code = obj.codePointAt(i) - 0x10000\n res += '\\\\u' + (0xD800 | (code >> 10)).toString(16) +\n '\\\\u' + (0xDC00 | (code & 0x3FF)).toString(16)\n i++\n s_ix++\n s_pos = obj.surrogates[s_ix]\n }else{\n var code = obj.charCodeAt(i)\n if(code < 127){\n var x = _b_.repr(obj[i])\n res += x.substr(1, x.length - 2)\n }else{\n var x = code.toString(16)\n while(x.length < 4){\n x = '0' + x\n }\n res += '\\\\u' + x\n }\n }\n }\n }\n return '\"' + res.replace(new RegExp('\"', \"g\"), '\\\\\"') + '\"'\n }\n\n if($B.$isinstance(obj, _b_.list)){\n var res = []\n var sep = item_separator,\n first = '[',\n last = ']'\n if(indent !== _b_.None){\n sep += \"\\n\" + indent_str.repeat(level)\n first = '[' + '\\n' + indent_str.repeat(level)\n last = '\\n' + indent_str.repeat(level - 1) + ']'\n level++\n }\n for(var i = 0, len = obj.length; i < len; i++){\n res.push(to_json(obj[i], level, kwarg))\n }\n return first + res.join(sep) + last\n }else if($B.$isinstance(obj, _b_.float)){\n return obj.value\n }else if(obj.__class__ === $B.long_int){\n return obj.value.toString()\n }else if(obj === _b_.None){\n return \"null\"\n }else if($B.$isinstance(obj, _b_.dict)){\n var res = [],\n items = Array.from($B.make_js_iterator(_b_.dict.items(obj)))\n if(sort_keys){\n // Sort keys by alphabetical order\n items.sort()\n }\n var sep = item_separator,\n first = '{',\n last = '}'\n if(indent !== _b_.None){\n sep += \"\\n\" + indent_str.repeat(level)\n first = '{' + '\\n' + indent_str.repeat(level)\n last = '\\n' + indent_str.repeat(level - 1) + '}'\n level++\n }\n for(var i = 0, len = items.length; i < len; i++){\n var item = items[i]\n if(! simple(item[0])){\n if(! skipkeys){\n throw _b_.TypeError.$factory(\"keys must be str, int, \" +\n \"float, bool or None, not \" + $B.class_name(obj))\n }\n }else{\n // In the result, key must be a string\n var key = _b_.str.$factory(item[0])\n // Check circular reference\n if(check_circular && $B.repr.enter(item[1])){\n throw _b_.ValueError.$factory(\"Circular reference detected\")\n }\n res.push(\n [to_json(key, level, kwarg), to_json(item[1], level, kwarg)].\n join(key_separator))\n if(check_circular){\n $B.repr.leave(item[1])\n }\n }\n }\n return first + res.join(sep) + last\n }\n // For other types, use function default if provided\n if(_default == _b_.None){\n throw _b_.TypeError.$factory(\"Object of type \" + $B.class_name(obj) +\n \" is not JSON serializable\")\n }else{\n return to_json($B.$call(_default)(obj), level, kwarg)\n }\n}\n\nfunction loads(s){\n var args = []\n for(var i = 1, len = arguments.length; i < len; i++){\n args.push(arguments[i])\n }\n var decoder = JSONDecoder.$factory.apply(null, args)\n return JSONDecoder.decode(decoder, s)\n}\n\nfunction to_py(obj, kw){\n // Conversion to Python objects\n // kw are the keyword arguments to loads()\n var res\n if(obj instanceof List){\n return $B.$list(obj.items.map(x => to_py(x, kw)))\n }else if(obj instanceof Dict){\n if(kw.object_pairs_hook !== _b_.None){\n var pairs = []\n for(var i = 0, len = obj.keys.length; i < len; i++){\n pairs.push($B.fast_tuple([obj.keys[i],\n to_py(obj.values[i], kw)]))\n }\n return $B.$call(kw.object_pairs_hook)(pairs)\n }else{\n var dict = $B.empty_dict()\n for(var i = 0, len = obj.keys.length; i < len; i++){\n _b_.dict.$setitem(dict, obj.keys[i], to_py(obj.values[i], kw))\n }\n return kw.object_hook === _b_.None ? dict :\n $B.$call(kw.object_hook)(dict)\n }\n }else if(obj.type == 'str'){\n return obj.value\n }else if(obj.type == 'num'){\n if(obj.value.search(/[.eE]/) > -1){\n // float\n if(kw.parse_float !== _b_.None){\n return $B.$call(kw.parse_float)(obj.value)\n }\n return $B.fast_float(parseFloat(obj.value))\n }else{\n // integer\n if(kw.parse_int !== _b_.None){\n return $B.$call(kw.parse_int)(obj.value)\n }\n var int = parseInt(obj.value)\n if(Math.abs(int) < $B.max_int){\n return int\n }else{\n return $B.fast_long_int(BigInt(obj.value))\n }\n }\n }else{\n if(obj instanceof Number && kw.parse_float !== _b_.None){\n return $B.$call(kw.parse_float)(obj)\n }else if(kw.parse_int !== _b_.None &&\n (typeof obj == 'number' || obj.__class__ === $B.long_int)){\n return $B.$call(kw.parse_int)(obj)\n }else if(kw.parse_constant !== _b_.None && ! isFinite(obj)){\n return kw.parse_constant(obj)\n }\n return obj\n }\n}\n\nvar escapes = {'n': '\\n',\n 't': '\\t',\n 'b': '\\b',\n 'r': '\\r',\n 'f': '\\f',\n '\\\\': '\\\\',\n '\"': '\\\"',\n \"'\": \"\\\\'\",\n '/': '/'\n }\n\nfunction string_at(s, i){\n var error = $B.$call($B.imported[\"json\"].JSONDecodeError)\n\n var j = i + 1,\n escaped = false,\n len = s.length,\n value = ''\n while(j < len){\n if(s[j] == '\"' && ! escaped){\n return [{type: 'str', value}, j + 1]\n }else if(! escaped && s[j] == '\\\\'){\n escaped = ! escaped\n j++\n }else if(escaped){\n var esc = escapes[s[j]]\n if(esc){\n value += esc\n j++\n escaped = false\n }else if(s[j] == 'u' &&\n s.substr(j + 1, 4).match(/[0-9a-fA-f]{4}/)){\n // unicode escape\n value += String.fromCharCode(parseInt(s.substr(j + 1, 4), 16))\n j += 5\n escaped = ! escaped\n }else{\n throw error('invalid escape \"' + s[j] + '\"', s, j)\n }\n }else{\n value += s[j]\n j++\n }\n }\n}\n\nfunction to_num(num_string, nb_dots, exp){\n // convert to correct Brython type\n if(exp || nb_dots){\n return new Number(num_string)\n }else{\n var int = parseInt(num_string)\n if(Math.abs(int) < $B.max_int){\n return int\n }else{\n if(num_string.startsWith('-')){\n return $B.fast_long_int(num_string.substr(1), false)\n }else{\n return $B.fast_long_int(num_string, true)\n }\n }\n }\n}\n\nfunction num_at(s, i){\n var res = s[i],\n j = i + 1,\n nb_dots = 0,\n exp = false,\n len = s.length\n while(j < len){\n if(s[j].match(/\\d/)){\n j++\n }else if(s[j] == '.' && nb_dots == 0){\n nb_dots++\n j++\n }else if('eE'.indexOf(s[j]) > -1 && ! exp){\n exp = ! exp\n j++\n }else if(s[j] == '-' && 'eE'.includes(s[j-1])){\n j++\n }else{\n return [{type: 'num', value: s.substring(i, j)}, j]\n }\n }\n return [{type: 'num', value: s.substring(i, j)}, j]\n}\n\nvar JSONError = $B.make_class('json.decoder.JSONError')\nJSONError.__bases__ = [_b_.Exception]\nJSONError.__mro__ = _b_.type.mro(JSONError)\n\n\nfunction* tokenize(s){\n var i = 0,\n len = s.length,\n line_num = 1,\n column_start = 0,\n value,\n end\n while(i < len){\n if(s[i] == \" \" || s[i] == '\\r' || s[i] == '\\n' || s[i] == '\\t'){\n i++\n line_num++\n column_start = i\n }else if('[]{}:,'.indexOf(s[i]) > -1){\n yield [s[i], i]\n i++\n }else if(s.substr(i, 4) == 'null'){\n yield [_b_.None , i]\n i += 4\n }else if(s.substr(i, 4) == 'true'){\n yield [true, i]\n i += 4\n }else if(s.substr(i, 5) == 'false'){\n yield [false, i]\n i += 5\n }else if(s.substr(i, 8) == 'Infinity'){\n yield [{type: 'num', value: 'Infinity'}, i]\n i += 8\n }else if(s.substr(i, 9) == '-Infinity'){\n yield [{type: 'num', value: '-Infinity'}, i]\n i += 9\n }else if(s.substr(i, 3) == 'NaN'){\n yield [{type: 'num', value: 'NaN'}, i]\n i += 3\n }else if(s[i] == '\"'){\n value = string_at(s, i)\n yield value\n i = value[1]\n }else if(s[i].match(/\\d/) || s[i] == '-'){\n value = num_at(s, i)\n yield value\n i = value[1]\n }else{\n throw $B.$call(JSONError)('Extra data: ' +\n `line ${line_num} column ${1 + i - column_start}`)\n }\n }\n}\n\nfunction Node(parent){\n this.parent = parent\n if(parent instanceof List){\n this.list = parent.items\n }else if(parent instanceof Dict){\n this.list = parent.values\n }else if(parent === undefined){\n this.list = []\n }\n}\n\nNode.prototype.transition = function(token){\n if([true, false, _b_.None].includes(token) ||\n ['str', 'num'].includes(token.type)){\n if(this.parent === undefined &&\n (this.list.length > 0 || this.content)){\n throw Error('Extra data')\n }\n this.list.push(token)\n return this.parent ? this.parent : this\n }else if(token == '{'){\n if(this.parent === undefined){\n this.content = new Dict(this)\n return this.content\n }\n return new Dict(this.parent)\n }else if(token == '['){\n if(this.parent === undefined){\n this.content = new List(this)\n return this.content\n }\n return new List(this.parent)\n }else{\n throw Error('unexpected item:' + token)\n }\n}\n\nfunction Dict(parent){\n this.parent = parent\n this.keys = []\n this.values = []\n this.expect = 'key'\n if(parent instanceof List){\n parent.items.push(this)\n }else if(parent instanceof Dict){\n parent.values.push(this)\n }\n}\n\nDict.prototype.transition = function(token){\n if(this.expect == 'key'){\n if(token.type == 'str'){\n this.keys.push(token.value)\n this.expect = ':'\n return this\n }else if(token == '}' && this.keys.length == 0){\n return this.parent\n }else{\n throw Error('expected str')\n }\n }else if(this.expect == ':'){\n if(token == ':'){\n this.expect = '}'\n return new Node(this)\n }else{\n throw Error('expected :')\n }\n }else if(this.expect == '}'){\n if(token == '}'){\n return this.parent\n }else if(token == ','){\n this.expect = 'key'\n return this\n }\n throw Error('expected }')\n }\n}\n\nfunction List(parent){\n if(parent instanceof List){\n parent.items.push(this)\n }\n this.parent = parent\n this.items = []\n this.expect = 'item'\n}\n\nList.prototype.transition = function(token){\n if(this.expect == 'item'){\n this.expect = ','\n if([true, false, _b_.None].indexOf(token) > -1){\n this.items.push(token)\n return this\n }else if(token.type == 'num' || token.type == 'str'){\n this.items.push(token)\n return this\n }else if(token == '{'){\n return new Dict(this)\n }else if(token == '['){\n return new List(this)\n }else if(token == ']'){\n if(this.items.length == 0){\n if(this.parent instanceof Dict){\n this.parent.values.push(this)\n }\n return this.parent\n }\n throw Error('unexpected ]')\n }else{\n console.log('token', token)\n throw Error('unexpected item:' + token)\n }\n\n }else if(this.expect == ','){\n this.expect = 'item'\n if(token == ','){\n return this\n }else if(token == ']'){\n if(this.parent instanceof Dict){\n this.parent.values.push(this)\n }\n return this.parent\n }else{\n throw Error('expected :')\n }\n }\n}\n\nfunction parse(s){\n var res,\n state,\n node = new Node(),\n root = node,\n token\n for(var item of tokenize(s)){\n token = item[0]\n try{\n node = node.transition(token)\n }catch(err){\n console.log('error, item', item)\n console.log(err, err.message)\n console.log('node', node)\n if(err.__class__){\n throw err\n }else{\n var error = $B.$call($B.imported[\"json\"].JSONDecodeError)\n throw error(err.message, s, item[1])\n }\n }\n }\n return root.content ? root.content : root.list[0]\n}\n\nvar JSONDecoder = $B.make_class(\"JSONDecoder\",\n function(){\n var $defaults = {cls: _b_.None, object_hook: _b_.None,\n parse_float: _b_.None, parse_int: _b_.None,\n parse_constant: _b_.None, object_pairs_hook: _b_.None},\n $ = $B.args(\"decode\", 0, {}, [], arguments, {}, null, \"kw\")\n var kw = _b_.dict.$to_obj($.kw)\n for(var key in $defaults){\n if(kw[key] === undefined){\n kw[key] = $defaults[key]\n }\n }\n return {\n __class__: JSONDecoder,\n object_hook: kw.object_hook,\n parse_float: kw.parse_float,\n parse_int: kw.parse_int,\n parse_constant: kw.parse_constant,\n object_pairs_hook: kw.object_pairs_hook,\n memo: $B.empty_dict()\n }\n }\n)\n\nJSONDecoder.decode = function(self, s){\n return to_py(parse(s), self)\n}\n\n$B.imported._json = {\n dumps: function(){\n return _b_.str.$factory(to_json.apply(null, arguments))\n },\n loads,\n JSONDecoder\n}\n\n})(__BRYTHON__)"], "_jsre": [".js", "(function($B){\n\n var _b_ = $B.builtins\n\n var MatchObject = $B.make_class(\"Match\",\n function(jsmatch, string, pattern){\n return {\n __class__: MatchObject,\n jsmatch: jsmatch,\n string: string\n }\n }\n )\n MatchObject.item = function(self, rank){\n return self.jsmatch[rank]\n }\n MatchObject.group = function(self){\n var res = []\n for(var i = 0, _len_i = arguments.length; i < _len_i; i++){\n if(self.jsmatch[arguments[i]] === undefined){res.push(_b_.None)}\n else{res.push(self.jsmatch[arguments[i]])}\n }\n if(arguments.length == 1){return res[0]}\n return _b_.tuple.$factory(res)\n }\n MatchObject.groups = function(self, _default){\n if(_default === undefined){_default = _b_.None}\n var res = []\n for(var i = 1, _len_i = self.length; i < _len_i; i++){\n if(self.jsmatch[i] === undefined){res.push(_default)}\n else{res.push(self.jsmatch[i])}\n }\n return _b_.tuple.$factory(res)\n }\n MatchObject.start = function(self){\n return self.index\n }\n MatchObject.end = function(self){\n return self.length - self.index\n }\n\n $B.set_func_names(MatchObject, '_jsre')\n\n var obj = {\n __str__: function(){return \"\"}\n }\n obj.A = obj.ASCII = 256\n obj.I = obj.IGNORECASE = 2 // 'i'\n obj.L = obj.LOCALE = 4\n obj.M = obj.MULTILINE = 8 // 'm'\n obj.S = obj.DOTALL = 16\n obj.U = obj.UNICODE = 32\n obj.X = obj.VERBOSE = 64\n obj._is_valid = function(pattern) {\n if ($B.$options.re == 'pyre'){return false} //force use of python's re module\n if ($B.$options.re == 'jsre'){return true} //force use of brythons re module\n // FIXME: Improve\n\n if(! $B.$isinstance(pattern, _b_.str)){\n // this is probably a SRE_PATTERN, so return false, and let\n // python's re module handle this.\n return false\n }\n var is_valid = false\n try{\n new RegExp(pattern)\n is_valid = true\n }\n catch(e){}\n if(! is_valid){return false} //if js won't parse the pattern return false\n\n // using reference http://www.regular-expressions.info/\n // to compare python re and javascript regex libraries\n\n // look for things javascript does not support\n // check for name capturing group\n var mylist = ['?P=', '?P<', '(?#', '(?<=', '(? -1) return false\n }\n\n var re_list=['\\{,\\d+\\}']\n for(var i=0, _len_i = re_list.length; i < _len_i; i++) {\n var _re = new RegExp(re_list[i])\n if (_re.test(pattern)){return false}\n }\n\n // it looks like the pattern has passed all our tests so lets assume\n // javascript can handle this pattern.\n return true\n }\n var $SRE_PatternDict = {\n __class__:_b_.type,\n $infos:{\n __name__:'SRE_Pattern'\n }\n }\n $SRE_PatternDict.__mro__ = [_b_.object]\n $SRE_PatternDict.findall = function(self, string){\n return obj.findall(self.pattern, string, self.flags)\n }\n $SRE_PatternDict.finditer = function(self, string){\n return obj.finditer(self.pattern, string, self.flags)\n }\n $SRE_PatternDict.match = function(self, string){\n return obj.match(self.pattern, string, self.flags)\n }\n $SRE_PatternDict.search = function(self, string){\n return obj.search(self.pattern, string, self.flags)\n }\n $SRE_PatternDict.sub = function(self,repl,string){\n return obj.sub(self.pattern,repl,string,self.flags)\n }\n $B.set_func_names($SRE_PatternDict, \"_jsre\")\n // TODO: groups\n // TODO: groupindex\n function normflags(flags){\n return ((flags & obj.I)? 'i' : '') + ((flags & obj.M)? 'm' : '');\n }\n // TODO: fullmatch()\n // TODO: split()\n // TODO: subn()\n obj.compile = function(pattern, flags){\n return {\n __class__: $SRE_PatternDict,\n pattern: pattern,\n flags: normflags(flags)\n }\n }\n obj.escape = function(string){\n // Escape all the characters in pattern except ASCII letters, numbers\n // and '_'. This is useful if you want to match an arbitrary literal\n // string that may have regular expression metacharacters in it.\n var res = ''\n var ok = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'\n for(var i = 0, _len_i = string.length; i < _len_i; i++){\n if(ok.search(string.charAt(i))>-1){res += string.charAt(i)}\n }\n return res\n }\n obj.findall = function(pattern, string, flags){\n var $ns=$B.args('re.findall', 2,\n {pattern:null, string:null}, ['pattern', 'string'],\n arguments,{}, 'args', 'kw') ,\n args = $ns['args'] ,\n _flags = 0;\n if(args.length>0){var flags = args[0]}\n else{var _flags = $B.$getattr($ns['kw'], 'get')('flags', 0)}\n\n var flags = normflags()\n flags += 'gm'\n var jsp = new RegExp(pattern,flags),\n jsmatch = string.match(jsp)\n if(jsmatch === null){return []}\n return jsmatch\n }\n obj.finditer = function(pattern, string, flags){\n var $ns=$B.args('re.finditer', 2,\n {pattern:null, string:null}, ['pattern', 'string'],\n arguments,{},'args','kw'),\n args = $ns['args'],\n _flags = 0;\n if(args.length>0){var flags=args[0]}\n else{var _flags = $B.$getattr($ns['kw'], 'get')('flags', 0)}\n\n var flags = normflags()\n flags += 'gm'\n var jsp = new RegExp(pattern, flags),\n jsmatch = string.match(jsp);\n if(jsmatch === null){return []}\n\n var _list = []\n for(var j = 0, _len_j = jsmatch.length; j < _len_j; j++) {\n var mo = {}\n mo._match=jsmatch[j]\n mo.group = function(){\n var res = []\n for(var i=0, _len_i = arguments.length; i < _len_i;i++){\n if(jsmatch[arguments[i]] === undefined){res.push(_b_.None)}\n else{res.push(jsmatch[arguments[i]])}\n }\n if(arguments.length == 1){return res[0]}\n return _b_.tuple.$factory(res)\n }\n mo.groups = function(_default){\n if(_default === undefined){_default = _b_.None}\n var res = []\n for(var i = 1, _len_i = jsmatch.length; i < _len_i; i++){\n if(jsmatch[i] === undefined){res.push(_default)}\n else{res.push(jsmatch[i])}\n }\n return _b_.tuple.$factory(res)\n }\n mo.start = function(){return mo._match.index}\n mo.end = function(){return mo._match.length - mo._match.index}\n mo.string = string\n _list.push(mo)\n }\n return _list\n }\n obj.search = function(pattern, string){\n var $ns = $B.args('re.search', 2,\n {pattern:null, string:null},['pattern', 'string'],\n arguments, {}, 'args', 'kw')\n var args = $ns['args']\n if(args.length>0){var flags = args[0]}\n else{var flags = $B.$getattr($ns['kw'], 'get')('flags', '')}\n flags = normflags(flags)\n var jsp = new RegExp(pattern, flags)\n var jsmatch = string.match(jsp)\n if(jsmatch === null){return _b_.None}\n return MatchObject.$factory(jsmatch, string, pattern)\n }\n obj.sub = function(pattern, repl, string){\n var $ns=$B.args('re.search', 3,\n {pattern: null, repl: null, string: null},\n ['pattern', 'repl', 'string'],\n arguments,{}, 'args', 'kw')\n for($var in $ns){eval(\"var \" + $var + \"=$ns[$var]\")}\n var args = $ns['args']\n var count = _b_.dict.get($ns['kw'], 'count', 0)\n var flags = _b_.dict.get($ns['kw'], 'flags', '')\n if(args.length > 0){var count = args[0]}\n if(args.length > 1){var flags = args[1]}\n flags = normflags(flags)\n if(typeof repl == \"string\"){\n // backreferences are \\1, \\2... in Python but $1,$2... in Javascript\n repl = repl.replace(/\\\\(\\d+)/g, '$$$1')\n }else if(typeof repl == \"function\"){\n // the argument passed to the Python function is the match object\n // the arguments passed to the Javascript function are :\n // - the matched substring\n // - the matched groups\n // - the offset of the matched substring inside the string\n // - the string being examined\n var $repl1 = function(){\n var mo = Object()\n mo.string = arguments[arguments.length - 1]\n var matched = arguments[0];\n var start = arguments[arguments.length - 2]\n var end = start + matched.length\n mo.start = function(){return start}\n mo.end = function(){return end}\n groups = []\n for(var i = 1, _len_i = arguments.length-2; i < _len_i; i++){\n groups.push(arguments[i])\n }\n mo.groups = function(_default){\n if(_default === undefined){_default = _b_.None}\n var res = []\n for(var i = 0, _len_i = groups.length; i < _len_i; i++){\n if(groups[i] === undefined){res.push(_default)}\n else{res.push(groups[i])}\n }\n return res\n }\n mo.group = function(i){\n if(i==0){return matched}\n return groups[i-1]\n }\n return repl(mo)\n }\n }\n if(count == 0){flags += 'g'}\n var jsp = new RegExp(pattern, flags)\n if(typeof repl == 'function'){return string.replace(jsp, $repl1)}\n else{return string.replace(jsp, repl)}\n }\n obj.match = (function(search_func){\n return function(){\n // match is like search but pattern must start with ^\n var pattern = arguments[0]\n if(pattern.charAt(0) != '^'){pattern = '^'+pattern}\n var args = [pattern]\n for(var i = 1, _len_i = arguments.length; i < _len_i; i++){\n args.push(arguments[i])\n }\n return search_func.apply(null, args)\n }\n })(obj.search)\n\n $B.addToImported('_jsre', obj)\n}\n)(__BRYTHON__)\n"], "_locale": [".js", "var am = {\n \"C\": \"AM\",\n \"aa\": \"saaku\",\n \"ab\": \"AM\",\n \"ae\": \"AM\",\n \"af\": \"vm.\",\n \"ak\": \"AN\",\n \"am\": \"\\u1325\\u12cb\\u1275\",\n \"an\": \"AM\",\n \"ar\": \"\\u0635\",\n \"as\": \"\\u09f0\\u09be\\u09a4\\u09bf\\u09aa\\u09c1\",\n \"av\": \"AM\",\n \"ay\": \"AM\",\n \"az\": \"AM\",\n \"ba\": \"\",\n \"be\": \"\",\n \"bg\": \"\",\n \"bh\": \"AM\",\n \"bi\": \"AM\",\n \"bm\": \"AM\",\n \"bn\": \"AM\",\n \"bo\": \"\\u0f66\\u0f94\\u0f0b\\u0f51\\u0fb2\\u0f7c\",\n \"br\": \"A.M.\",\n \"bs\": \"prijepodne\",\n \"ca\": \"a. m.\",\n \"ce\": \"AM\",\n \"ch\": \"AM\",\n \"co\": \"\",\n \"cr\": \"AM\",\n \"cs\": \"dop.\",\n \"cu\": \"\\u0414\\u041f\",\n \"cv\": \"AM\",\n \"cy\": \"yb\",\n \"da\": \"\",\n \"de\": \"\",\n \"dv\": \"\\u0789\\u0786\",\n \"dz\": \"\\u0f66\\u0f94\\u0f0b\\u0f46\\u0f0b\",\n \"ee\": \"\\u014bdi\",\n \"el\": \"\\u03c0\\u03bc\",\n \"en\": \"AM\",\n \"eo\": \"atm\",\n \"es\": \"\",\n \"et\": \"AM\",\n \"eu\": \"AM\",\n \"fa\": \"\\u0642.\\u0638\",\n \"ff\": \"\",\n \"fi\": \"ap.\",\n \"fj\": \"AM\",\n \"fo\": \"um fyr.\",\n \"fr\": \"\",\n \"fy\": \"AM\",\n \"ga\": \"r.n.\",\n \"gd\": \"m\",\n \"gl\": \"a.m.\",\n \"gn\": \"a.m.\",\n \"gu\": \"\\u0aaa\\u0ac2\\u0ab0\\u0acd\\u0ab5\\u00a0\\u0aae\\u0aa7\\u0acd\\u0aaf\\u0abe\\u0ab9\\u0acd\\u0aa8\",\n \"gv\": \"a.m.\",\n \"ha\": \"AM\",\n \"he\": \"AM\",\n \"hi\": \"\\u092a\\u0942\\u0930\\u094d\\u0935\\u093e\\u0939\\u094d\\u0928\",\n \"ho\": \"AM\",\n \"hr\": \"\",\n \"ht\": \"AM\",\n \"hu\": \"de.\",\n \"hy\": \"\",\n \"hz\": \"AM\",\n \"ia\": \"a.m.\",\n \"id\": \"AM\",\n \"ie\": \"AM\",\n \"ig\": \"A.M.\",\n \"ii\": \"\\ua0b5\\ua1aa\\ua20c\\ua210\",\n \"ik\": \"AM\",\n \"io\": \"AM\",\n \"is\": \"f.h.\",\n \"it\": \"\",\n \"iu\": \"AM\",\n \"ja\": \"\\u5348\\u524d\",\n \"jv\": \"\",\n \"ka\": \"AM\",\n \"kg\": \"AM\",\n \"ki\": \"Kiroko\",\n \"kj\": \"AM\",\n \"kk\": \"AM\",\n \"kl\": \"\",\n \"km\": \"\\u1796\\u17d2\\u179a\\u17b9\\u1780\",\n \"kn\": \"\\u0caa\\u0cc2\\u0cb0\\u0ccd\\u0cb5\\u0cbe\\u0cb9\\u0ccd\\u0ca8\",\n \"ko\": \"\\uc624\\uc804\",\n \"kr\": \"AM\",\n \"ks\": \"AM\",\n \"ku\": \"\\u067e.\\u0646\",\n \"kv\": \"AM\",\n \"kw\": \"a.m.\",\n \"ky\": \"\",\n \"la\": \"\",\n \"lb\": \"\",\n \"lg\": \"AM\",\n \"li\": \"AM\",\n \"ln\": \"nt\\u0254\\u0301ng\\u0254\\u0301\",\n \"lo\": \"\\u0e81\\u0ec8\\u0ead\\u0e99\\u0e97\\u0ec8\\u0ebd\\u0e87\",\n \"lt\": \"prie\\u0161piet\",\n \"lu\": \"Dinda\",\n \"lv\": \"priek\\u0161p.\",\n \"mg\": \"AM\",\n \"mh\": \"AM\",\n \"mi\": \"a.m.\",\n \"mk\": \"\\u043f\\u0440\\u0435\\u0442\\u043f\\u043b.\",\n \"ml\": \"AM\",\n \"mn\": \"??\",\n \"mo\": \"AM\",\n \"mr\": \"\\u092e.\\u092a\\u0942.\",\n \"ms\": \"PG\",\n \"mt\": \"AM\",\n \"my\": \"\\u1014\\u1036\\u1014\\u1000\\u103a\",\n \"na\": \"AM\",\n \"nb\": \"a.m.\",\n \"nd\": \"AM\",\n \"ne\": \"\\u092a\\u0942\\u0930\\u094d\\u0935\\u093e\\u0939\\u094d\\u0928\",\n \"ng\": \"AM\",\n \"nl\": \"\",\n \"nn\": \"f.m.\",\n \"no\": \"a.m.\",\n \"nr\": \"AM\",\n \"nv\": \"AM\",\n \"ny\": \"AM\",\n \"oc\": \"AM\",\n \"oj\": \"AM\",\n \"om\": \"WD\",\n \"or\": \"AM\",\n \"os\": \"AM\",\n \"pa\": \"\\u0a38\\u0a35\\u0a47\\u0a30\",\n \"pi\": \"AM\",\n \"pl\": \"AM\",\n \"ps\": \"\\u063a.\\u0645.\",\n \"pt\": \"\",\n \"qu\": \"a.m.\",\n \"rc\": \"AM\",\n \"rm\": \"AM\",\n \"rn\": \"Z.MU.\",\n \"ro\": \"a.m.\",\n \"ru\": \"\",\n \"rw\": \"AM\",\n \"sa\": \"\\u092e\\u0927\\u094d\\u092f\\u093e\\u0928\\u092a\\u0942\\u0930\\u094d\\u0935\",\n \"sc\": \"AM\",\n \"sd\": \"AM\",\n \"se\": \"i.b.\",\n \"sg\": \"ND\",\n \"sh\": \"AM\",\n \"si\": \"\\u0db4\\u0dd9.\\u0dc0.\",\n \"sk\": \"AM\",\n \"sl\": \"dop.\",\n \"sm\": \"AM\",\n \"sn\": \"AM\",\n \"so\": \"sn.\",\n \"sq\": \"e paradites\",\n \"sr\": \"pre podne\",\n \"ss\": \"AM\",\n \"st\": \"AM\",\n \"su\": \"AM\",\n \"sv\": \"\",\n \"sw\": \"AM\",\n \"ta\": \"\\u0b95\\u0bbe\\u0bb2\\u0bc8\",\n \"te\": \"\\u0c2a\\u0c42\\u0c30\\u0c4d\\u0c35\\u0c3e\\u0c39\\u0c4d\\u0c28\",\n \"tg\": \"\",\n \"th\": \"AM\",\n \"ti\": \"\\u1295\\u1309\\u1206 \\u1230\\u12d3\\u1270\",\n \"tk\": \"\",\n \"tl\": \"AM\",\n \"tn\": \"AM\",\n \"to\": \"AM\",\n \"tr\": \"\\u00d6\\u00d6\",\n \"ts\": \"AM\",\n \"tt\": \"\",\n \"tw\": \"AM\",\n \"ty\": \"AM\",\n \"ug\": \"\\u0686?\\u0634\\u062a\\u0649\\u0646 \\u0628?\\u0631?\\u0646\",\n \"uk\": \"AM\",\n \"ur\": \"AM\",\n \"uz\": \"TO\",\n \"ve\": \"AM\",\n \"vi\": \"SA\",\n \"vo\": \"AM\",\n \"wa\": \"AM\",\n \"wo\": \"\",\n \"xh\": \"AM\",\n \"yi\": \"\\ua0b5\\ua1aa\\ua20c\\ua210\",\n \"yo\": \"\\u00c0\\u00e1r?`\",\n \"za\": \"AM\",\n \"zh\": \"\\u4e0a\\u5348\",\n \"zu\": \"AM\"\n}\nvar pm = {\n \"C\": \"PM\",\n \"aa\": \"carra\",\n \"ab\": \"PM\",\n \"ae\": \"PM\",\n \"af\": \"nm.\",\n \"ak\": \"EW\",\n \"am\": \"\\u12a8\\u1230\\u12d3\\u1275\",\n \"an\": \"PM\",\n \"ar\": \"\\u0645\",\n \"as\": \"\\u0986\\u09ac\\u09c7\\u09b2\\u09bf\",\n \"av\": \"PM\",\n \"ay\": \"PM\",\n \"az\": \"PM\",\n \"ba\": \"\",\n \"be\": \"\",\n \"bg\": \"\",\n \"bh\": \"PM\",\n \"bi\": \"PM\",\n \"bm\": \"PM\",\n \"bn\": \"PM\",\n \"bo\": \"\\u0f55\\u0fb1\\u0f72\\u0f0b\\u0f51\\u0fb2\\u0f7c\",\n \"br\": \"G.M.\",\n \"bs\": \"popodne\",\n \"ca\": \"p. m.\",\n \"ce\": \"PM\",\n \"ch\": \"PM\",\n \"co\": \"\",\n \"cr\": \"PM\",\n \"cs\": \"odp.\",\n \"cu\": \"\\u041f\\u041f\",\n \"cv\": \"PM\",\n \"cy\": \"yh\",\n \"da\": \"\",\n \"de\": \"\",\n \"dv\": \"\\u0789\\u078a\",\n \"dz\": \"\\u0f55\\u0fb1\\u0f72\\u0f0b\\u0f46\\u0f0b\",\n \"ee\": \"\\u0263etr\\u0254\",\n \"el\": \"\\u03bc\\u03bc\",\n \"en\": \"PM\",\n \"eo\": \"ptm\",\n \"es\": \"\",\n \"et\": \"PM\",\n \"eu\": \"PM\",\n \"fa\": \"\\u0628.\\u0638\",\n \"ff\": \"\",\n \"fi\": \"ip.\",\n \"fj\": \"PM\",\n \"fo\": \"um sein.\",\n \"fr\": \"\",\n \"fy\": \"PM\",\n \"ga\": \"i.n.\",\n \"gd\": \"f\",\n \"gl\": \"p.m.\",\n \"gn\": \"p.m.\",\n \"gu\": \"\\u0a89\\u0aa4\\u0acd\\u0aa4\\u0ab0\\u00a0\\u0aae\\u0aa7\\u0acd\\u0aaf\\u0abe\\u0ab9\\u0acd\\u0aa8\",\n \"gv\": \"p.m.\",\n \"ha\": \"PM\",\n \"he\": \"PM\",\n \"hi\": \"\\u0905\\u092a\\u0930\\u093e\\u0939\\u094d\\u0928\",\n \"ho\": \"PM\",\n \"hr\": \"\",\n \"ht\": \"PM\",\n \"hu\": \"du.\",\n \"hy\": \"\",\n \"hz\": \"PM\",\n \"ia\": \"p.m.\",\n \"id\": \"PM\",\n \"ie\": \"PM\",\n \"ig\": \"P.M.\",\n \"ii\": \"\\ua0b5\\ua1aa\\ua20c\\ua248\",\n \"ik\": \"PM\",\n \"io\": \"PM\",\n \"is\": \"e.h.\",\n \"it\": \"\",\n \"iu\": \"PM\",\n \"ja\": \"\\u5348\\u5f8c\",\n \"jv\": \"\",\n \"ka\": \"PM\",\n \"kg\": \"PM\",\n \"ki\": \"Hwa\\u0129-in\\u0129\",\n \"kj\": \"PM\",\n \"kk\": \"PM\",\n \"kl\": \"\",\n \"km\": \"\\u179b\\u17d2\\u1784\\u17b6\\u1785\",\n \"kn\": \"\\u0c85\\u0caa\\u0cb0\\u0cbe\\u0cb9\\u0ccd\\u0ca8\",\n \"ko\": \"\\uc624\\ud6c4\",\n \"kr\": \"PM\",\n \"ks\": \"PM\",\n \"ku\": \"\\u062f.\\u0646\",\n \"kv\": \"PM\",\n \"kw\": \"p.m.\",\n \"ky\": \"\",\n \"la\": \"\",\n \"lb\": \"\",\n \"lg\": \"PM\",\n \"li\": \"PM\",\n \"ln\": \"mp\\u00f3kwa\",\n \"lo\": \"\\u0eab\\u0ebc\\u0eb1\\u0e87\\u0e97\\u0ec8\\u0ebd\\u0e87\",\n \"lt\": \"popiet\",\n \"lu\": \"Dilolo\",\n \"lv\": \"p\\u0113cp.\",\n \"mg\": \"PM\",\n \"mh\": \"PM\",\n \"mi\": \"p.m.\",\n \"mk\": \"\\u043f\\u043e\\u043f\\u043b.\",\n \"ml\": \"PM\",\n \"mn\": \"?\\u0425\",\n \"mo\": \"PM\",\n \"mr\": \"\\u092e.\\u0928\\u0902.\",\n \"ms\": \"PTG\",\n \"mt\": \"PM\",\n \"my\": \"\\u100a\\u1014\\u1031\",\n \"na\": \"PM\",\n \"nb\": \"p.m.\",\n \"nd\": \"PM\",\n \"ne\": \"\\u0905\\u092a\\u0930\\u093e\\u0939\\u094d\\u0928\",\n \"ng\": \"PM\",\n \"nl\": \"\",\n \"nn\": \"e.m.\",\n \"no\": \"p.m.\",\n \"nr\": \"PM\",\n \"nv\": \"PM\",\n \"ny\": \"PM\",\n \"oc\": \"PM\",\n \"oj\": \"PM\",\n \"om\": \"WB\",\n \"or\": \"PM\",\n \"os\": \"PM\",\n \"pa\": \"\\u0a36\\u0a3e\\u0a2e\",\n \"pi\": \"PM\",\n \"pl\": \"PM\",\n \"ps\": \"\\u063a.\\u0648.\",\n \"pt\": \"\",\n \"qu\": \"p.m.\",\n \"rc\": \"PM\",\n \"rm\": \"PM\",\n \"rn\": \"Z.MW.\",\n \"ro\": \"p.m.\",\n \"ru\": \"\",\n \"rw\": \"PM\",\n \"sa\": \"\\u092e\\u0927\\u094d\\u092f\\u093e\\u0928\\u092a\\u091a\\u094d\\u092f\\u093e\\u0924\",\n \"sc\": \"PM\",\n \"sd\": \"PM\",\n \"se\": \"e.b.\",\n \"sg\": \"LK\",\n \"sh\": \"PM\",\n \"si\": \"\\u0db4.\\u0dc0.\",\n \"sk\": \"PM\",\n \"sl\": \"pop.\",\n \"sm\": \"PM\",\n \"sn\": \"PM\",\n \"so\": \"gn.\",\n \"sq\": \"e pasdites\",\n \"sr\": \"po podne\",\n \"ss\": \"PM\",\n \"st\": \"PM\",\n \"su\": \"PM\",\n \"sv\": \"\",\n \"sw\": \"PM\",\n \"ta\": \"\\u0bae\\u0bbe\\u0bb2\\u0bc8\",\n \"te\": \"\\u0c05\\u0c2a\\u0c30\\u0c3e\\u0c39\\u0c4d\\u0c28\",\n \"tg\": \"\",\n \"th\": \"PM\",\n \"ti\": \"\\u12f5\\u1215\\u122d \\u1230\\u12d3\\u1275\",\n \"tk\": \"\",\n \"tl\": \"PM\",\n \"tn\": \"PM\",\n \"to\": \"PM\",\n \"tr\": \"\\u00d6S\",\n \"ts\": \"PM\",\n \"tt\": \"\",\n \"tw\": \"PM\",\n \"ty\": \"PM\",\n \"ug\": \"\\u0686?\\u0634\\u062a\\u0649\\u0646 \\u0643?\\u064a\\u0649\\u0646\",\n \"uk\": \"PM\",\n \"ur\": \"PM\",\n \"uz\": \"TK\",\n \"ve\": \"PM\",\n \"vi\": \"CH\",\n \"vo\": \"PM\",\n \"wa\": \"PM\",\n \"wo\": \"\",\n \"xh\": \"PM\",\n \"yi\": \"\\ua0b5\\ua1aa\\ua20c\\ua248\",\n \"yo\": \"?`s\\u00e1n\",\n \"za\": \"PM\",\n \"zh\": \"\\u4e0b\\u5348\",\n \"zu\": \"PM\"\n}\n\nvar X_format = {\n \"%H:%M:%S\": [\n \"C\",\n \"ab\",\n \"ae\",\n \"af\",\n \"an\",\n \"av\",\n \"ay\",\n \"az\",\n \"ba\",\n \"be\",\n \"bg\",\n \"bh\",\n \"bi\",\n \"bm\",\n \"bo\",\n \"br\",\n \"bs\",\n \"ca\",\n \"ce\",\n \"ch\",\n \"co\",\n \"cr\",\n \"cs\",\n \"cu\",\n \"cv\",\n \"cy\",\n \"da\",\n \"de\",\n \"dv\",\n \"eo\",\n \"es\",\n \"et\",\n \"eu\",\n \"ff\",\n \"fj\",\n \"fo\",\n \"fr\",\n \"fy\",\n \"ga\",\n \"gd\",\n \"gl\",\n \"gn\",\n \"gu\",\n \"gv\",\n \"ha\",\n \"he\",\n \"hi\",\n \"ho\",\n \"hr\",\n \"ht\",\n \"hu\",\n \"hy\",\n \"hz\",\n \"ia\",\n \"ie\",\n \"ig\",\n \"ik\",\n \"io\",\n \"is\",\n \"it\",\n \"ja\",\n \"ka\",\n \"kg\",\n \"ki\",\n \"kj\",\n \"kk\",\n \"kl\",\n \"km\",\n \"kn\",\n \"kv\",\n \"kw\",\n \"ky\",\n \"la\",\n \"lb\",\n \"lg\",\n \"li\",\n \"ln\",\n \"lo\",\n \"lt\",\n \"lu\",\n \"lv\",\n \"mg\",\n \"mh\",\n \"mk\",\n \"mn\",\n \"mo\",\n \"mr\",\n \"mt\",\n \"my\",\n \"na\",\n \"nb\",\n \"nd\",\n \"ng\",\n \"nl\",\n \"nn\",\n \"no\",\n \"nr\",\n \"nv\",\n \"ny\",\n \"oj\",\n \"or\",\n \"os\",\n \"pi\",\n \"pl\",\n \"ps\",\n \"pt\",\n \"rc\",\n \"rm\",\n \"rn\",\n \"ro\",\n \"ru\",\n \"rw\",\n \"sa\",\n \"sc\",\n \"se\",\n \"sg\",\n \"sh\",\n \"sk\",\n \"sl\",\n \"sm\",\n \"sn\",\n \"sr\",\n \"ss\",\n \"st\",\n \"su\",\n \"sv\",\n \"sw\",\n \"ta\",\n \"te\",\n \"tg\",\n \"th\",\n \"tk\",\n \"tl\",\n \"tn\",\n \"tr\",\n \"ts\",\n \"tt\",\n \"tw\",\n \"ty\",\n \"ug\",\n \"uk\",\n \"uz\",\n \"ve\",\n \"vo\",\n \"wa\",\n \"wo\",\n \"xh\",\n \"yo\",\n \"za\",\n \"zh\",\n \"zu\"\n ],\n \"%i:%M:%S %p\": [\n \"aa\",\n \"ak\",\n \"am\",\n \"bn\",\n \"el\",\n \"en\",\n \"iu\",\n \"kr\",\n \"ks\",\n \"mi\",\n \"ml\",\n \"ms\",\n \"ne\",\n \"om\",\n \"sd\",\n \"so\",\n \"sq\",\n \"ti\",\n \"to\",\n \"ur\",\n \"vi\"\n ],\n \"%I:%M:%S %p\": [\n \"ar\",\n \"fa\",\n \"ku\",\n \"qu\"\n ],\n \"%p %i:%M:%S\": [\n \"as\",\n \"ii\",\n \"ko\",\n \"yi\"\n ],\n \"\\u0f46\\u0f74\\u0f0b\\u0f5a\\u0f7c\\u0f51\\u0f0b%i:%M:%S %p\": [\n \"dz\"\n ],\n \"%p ga %i:%M:%S\": [\n \"ee\"\n ],\n \"%H.%M.%S\": [\n \"fi\",\n \"id\",\n \"jv\",\n \"oc\",\n \"si\"\n ],\n \"%p %I:%M:%S\": [\n \"pa\"\n ]\n}\nvar x_format = {\n \"%m/%d/%y\": [\n \"C\"\n ],\n \"%d/%m/%Y\": [\n \"aa\",\n \"am\",\n \"bm\",\n \"bn\",\n \"ca\",\n \"co\",\n \"cy\",\n \"el\",\n \"es\",\n \"ff\",\n \"fr\",\n \"ga\",\n \"gd\",\n \"gl\",\n \"gn\",\n \"gv\",\n \"ha\",\n \"he\",\n \"id\",\n \"ig\",\n \"it\",\n \"iu\",\n \"jv\",\n \"ki\",\n \"kr\",\n \"kw\",\n \"la\",\n \"lg\",\n \"ln\",\n \"lo\",\n \"lu\",\n \"mi\",\n \"ml\",\n \"ms\",\n \"mt\",\n \"nd\",\n \"oc\",\n \"om\",\n \"pt\",\n \"qu\",\n \"rn\",\n \"sd\",\n \"sg\",\n \"so\",\n \"sw\",\n \"ti\",\n \"to\",\n \"uk\",\n \"ur\",\n \"uz\",\n \"vi\",\n \"wo\",\n \"yo\"\n ],\n \"%m/%d/%Y\": [\n \"ab\",\n \"ae\",\n \"an\",\n \"av\",\n \"ay\",\n \"bh\",\n \"bi\",\n \"ch\",\n \"cr\",\n \"cv\",\n \"ee\",\n \"en\",\n \"fj\",\n \"ho\",\n \"ht\",\n \"hz\",\n \"ie\",\n \"ik\",\n \"io\",\n \"kg\",\n \"kj\",\n \"ks\",\n \"kv\",\n \"li\",\n \"mh\",\n \"mo\",\n \"na\",\n \"ne\",\n \"ng\",\n \"nv\",\n \"ny\",\n \"oj\",\n \"pi\",\n \"rc\",\n \"sc\",\n \"sh\",\n \"sm\",\n \"su\",\n \"tl\",\n \"tw\",\n \"ty\",\n \"wa\",\n \"za\",\n \"zu\"\n ],\n \"%Y-%m-%d\": [\n \"af\",\n \"br\",\n \"ce\",\n \"dz\",\n \"eo\",\n \"ko\",\n \"lt\",\n \"mg\",\n \"nr\",\n \"rw\",\n \"se\",\n \"si\",\n \"sn\",\n \"ss\",\n \"st\",\n \"sv\",\n \"tn\",\n \"ts\",\n \"ug\",\n \"ve\",\n \"vo\",\n \"xh\"\n ],\n \"%Y/%m/%d\": [\n \"ak\",\n \"bo\",\n \"eu\",\n \"ia\",\n \"ii\",\n \"ja\",\n \"ku\",\n \"yi\",\n \"zh\"\n ],\n \"null\": [\n \"ar\",\n \"fa\",\n \"ps\",\n \"th\"\n ],\n \"%d-%m-%Y\": [\n \"as\",\n \"da\",\n \"fy\",\n \"hi\",\n \"kl\",\n \"mr\",\n \"my\",\n \"nl\",\n \"rm\",\n \"sa\",\n \"ta\"\n ],\n \"%d.%m.%Y\": [\n \"az\",\n \"cs\",\n \"de\",\n \"et\",\n \"fi\",\n \"fo\",\n \"hy\",\n \"is\",\n \"ka\",\n \"kk\",\n \"lv\",\n \"mk\",\n \"nb\",\n \"nn\",\n \"no\",\n \"os\",\n \"pl\",\n \"ro\",\n \"ru\",\n \"sq\",\n \"tg\",\n \"tr\",\n \"tt\"\n ],\n \"%d.%m.%y\": [\n \"ba\",\n \"be\",\n \"lb\"\n ],\n \"%d.%m.%Y \\u0433.\": [\n \"bg\"\n ],\n \"%d.%m.%Y.\": [\n \"bs\",\n \"hr\",\n \"sr\"\n ],\n \"%Y.%m.%d\": [\n \"cu\",\n \"mn\"\n ],\n \"%d/%m/%y\": [\n \"dv\",\n \"km\"\n ],\n \"%d-%m-%y\": [\n \"gu\",\n \"kn\",\n \"or\",\n \"pa\",\n \"te\"\n ],\n \"%Y. %m. %d.\": [\n \"hu\"\n ],\n \"%d-%b %y\": [\n \"ky\"\n ],\n \"%d. %m. %Y\": [\n \"sk\",\n \"sl\"\n ],\n \"%d.%m.%y \\u00fd.\": [\n \"tk\"\n ]\n}\n\n\n\n__BRYTHON__.imported._locale = (function($B){\n var _b_ = $B.builtins\n return {\n CHAR_MAX: 127,\n LC_ALL: 6,\n LC_COLLATE: 3,\n LC_CTYPE: 0,\n LC_MESSAGES: 5,\n LC_MONETARY: 4,\n LC_NUMERIC: 1,\n LC_TIME: 2,\n Error: _b_.ValueError,\n\n _date_format: function(spec, hour){\n var t,\n locale = __BRYTHON__.locale.substr(0, 2)\n\n if(spec == \"p\"){\n var res = hours < 12 ? am[locale] : pm[locale]\n if(res === undefined){\n throw _b_.ValueError.$factory(\"no format \" + spec + \" for locale \" +\n locale)\n }\n return res\n }\n else if(spec == \"x\"){\n t = x_format\n }else if(spec == \"X\"){\n t = X_format\n }else{\n throw _b_.ValueError.$factory(\"invalid format\", spec)\n }\n for(var key in t){\n if(t[key].indexOf(locale) > -1){\n return key\n }\n }\n throw _b_.ValueError.$factory(\"no format \" + spec + \" for locale \" +\n locale)\n },\n\n localeconv: function(){\n var conv = {'grouping': $B.$list([127]),\n 'currency_symbol': '',\n 'n_sign_posn': 127,\n 'p_cs_precedes': 127,\n 'n_cs_precedes': 127,\n 'mon_grouping': $B.$list([]),\n 'n_sep_by_space': 127,\n 'decimal_point': '.',\n 'negative_sign': '',\n 'positive_sign': '',\n 'p_sep_by_space': 127,\n 'int_curr_symbol': '',\n 'p_sign_posn': 127,\n 'thousands_sep': '',\n 'mon_thousands_sep': '',\n 'frac_digits': 127,\n 'mon_decimal_point': '',\n 'int_frac_digits': 127\n }\n var res = $B.empty_dict()\n for(var key in conv){\n _b_.dict.$setitem(res, key, conv[key])\n }\n\n return res\n },\n\n setlocale : function(){\n var $ = $B.args(\"setlocale\", 2, {category: null, locale: null},\n [\"category\", \"locale\"], arguments, {locale: _b_.None},\n null, null)\n /// XXX category is currently ignored\n if($.locale == \"\"){\n // use browser language setting, if it is set\n var LANG = ($B.language || \"\").substr(0, 2)\n if(am.hasOwnProperty(LANG)){\n $B.locale = LANG\n return LANG\n }else{\n console.log(\"Unknown locale: \" + LANG)\n }\n }else if($.locale === _b_.None){\n // return current locale\n return $B.locale\n }else{\n // Only use 2 first characters\n try{$.locale.substr(0, 2)}\n catch(err){\n throw $module.Error.$factory(\"Invalid locale: \" + $.locale)\n }\n if(am.hasOwnProperty($.locale.substr(0, 2))){\n $B.locale = $.locale\n return $.locale\n }else{\n throw $module.Error.$factory(\"Unknown locale: \" + $.locale)\n }\n }\n }\n }\n})(__BRYTHON__)\n"], "_multiprocessing": [".js", "// multiprocessing\n(function($B){\n\nvar _b_ = $B.builtins\n\nvar Process = $B.make_class('Process')\n\nvar $convert_args=function(args) {\n var _list=[]\n for(var i=0, _len_i = args.length; i < _len_i; i++) {\n var _a=args[i]\n if($B.$isinstance(_a, _b_.str)){_list.push(\"'\"+_a+\"'\")} else {_list.push(_a)}\n }\n\n return _list.join(',')\n}\n\nProcess.is_alive = function(self){return self.$alive}\n\nProcess.join = function(self, timeout){\n // need to block until process is complete\n // could probably use a addEventListener to execute all existing code\n // after this join statement\n\n self.$worker.addEventListener('message', function (e) {\n var data=e.data\n if (data.stdout != '') { // output stdout from process\n $B.stdout.write(data.stdout)\n }\n }, false);\n}\n\nProcess.run = function(self){\n //fix me\n}\n\nProcess.start = function(self){\n self.$worker.postMessage({target: self.$target,\n args: $convert_args(self.$args),\n // kwargs: self.$kwargs\n })\n self.$worker.addEventListener('error', function(e) { throw e})\n self.$alive=true\n}\n\nProcess.terminate = function(self){\n self.$worker.terminate()\n self.$alive=false\n}\n\n// variables\n//name\n//daemon\n//pid\n//exitcode\n\nProcess. $factory = function(){\n //arguments group=None, target=None, name=None, args=(), kwargs=()\n\n var $ns=$B.args('Process',0,{},[],arguments,{},null,'kw')\n var kw=$ns['kw']\n\n var target=_b_.dict.get($ns['kw'],'target', _b_.None)\n var args=_b_.dict.get($ns['kw'],'args', _b_.tuple.$factory())\n\n var worker = new Worker('/src/web_workers/multiprocessing.js')\n\n var res = {\n __class__: Process,\n $worker: worker,\n name: $ns['name'] || _b_.None,\n $target: target + '',\n $args: args,\n $alive: false\n }\n return res\n}\n\n$B.set_func_names(Process, \"multiprocessing\")\n\nvar Pool = $B.make_class(\"Pool\")\n\nPool.__enter__ = function(self){}\nPool.__exit__ = function(self){}\n\nPool.__str__ = Pool.toString = Pool.__repr__=function(self){\n return ''\n}\n\nPool.map = function(){\n\n var $ns=$B.args('Pool.map', 3,\n {self:null, func:null, fargs:null}, ['self', 'func', 'fargs'],\n arguments,{},'args','kw')\n var func = $ns['func']\n var fargs = $ns['fargs']\n\n var _results = []\n\n fargs = _b_.iter(fargs)\n\n var _pos = 0\n var _workers =[]\n for(var i=0; i < self.$processes; i++) {\n _workers[i] = new Worker('/src/web_workers/multiprocessing.js')\n var arg\n\n try{\n arg = $B.$getattr(fargs, '__next__')()\n }catch(err) {\n if(err.__class__ !== _b_.StopIteration){\n throw err\n }\n }\n console.log(arg)\n _workers[i].finished = false\n _workers[i].postMessage({target: func+'', pos: _pos,\n args: $convert_args([arg])})\n _pos++\n\n _workers[i].addEventListener('message', function(e) {\n _results[e.data.pos]=e.data.result\n if (_results.length == args.length){\n return _results\n }\n try{\n arg = $B.$getattr(fargs, '__next__')()\n e.currentTarget.postMessage({target: func+'', pos: _pos,\n args: $convert_args([arg])})\n _pos++\n }catch(err){\n if (err.__class__ !== _b_.StopIteration){\n throw err\n }\n this.finished = true\n }\n }, false);\n }\n}\n\nPool.apply_async = function(){\n\n var $ns = $B.$args('apply_async', 3,\n {self:null, func:null, fargs:null}, ['self', 'func', 'fargs'],\n arguments,{},'args','kw')\n var func = $ns['func']\n var fargs = $ns['fargs']\n\n fargs = _b_.iter(fargs)\n\n async_result = {}\n async_result.get = function(timeout){\n console.log(results)\n console.log(fargs)\n return this.results}\n async_result.results=[]\n\n var _pos=0\n\n _workers=[]\n for(var i=0; i < self.$processes; i++) {\n _workers[i] = new Worker('/src/web_workers/multiprocessing.js')\n var arg\n\n try{\n arg = $B.$getattr(fargs, '__next__')()\n }catch(err) {\n if (err.__class__ !== _b_.StopIteration){\n throw err\n }\n }\n _workers[i].postMessage({target: func+'', pos: _pos,\n args: $convert_args([arg])})\n _pos++\n\n _workers[i].addEventListener('message', function(e) {\n async_result.results[e.data.pos]=e.data.result\n //if (_results.length == args.length) return _results\n\n try {\n arg = $B.$getattr(fargs, '__next__')()\n e.currentTarget.postMessage({target: func+'', pos: _pos,\n args: $convert_args([arg])})\n _pos++\n } catch(err) {\n if (err.__class__ !== _b_.StopIteration){\n throw err\n }\n this.finished=true\n }\n }, false);\n }\n\n return async_result\n}\n\nPool.$factory = function(){\n var $ns = $B.args('Pool',1,\n {processes:null},['processes'],arguments,{},'args','kw')\n\n var processes = $ns['processes']\n\n if (processes === _b_.None) {\n // look to see if we have stored cpu_count in local storage\n // maybe we should create a brython config file with settings,etc..??\n\n // if not there use a tool such as Core Estimator to calculate number of cpu's\n // http://eligrey.com/blog/post/cpu-core-estimation-with-javascript\n }\n\n var res = {\n __class__: Pool,\n $processes: processes\n }\n return res\n}\n\n$B.set_func_names(Pool, \"multiprocessing\")\n\n$B.imported._multiprocessing = {Process, Pool}\n\n})(__BRYTHON__)\n"], "_posixsubprocess": [".js", "(function($B){\n\n $B.imported._posixsubprocess = {\n cloexec_pipe: function() {}, // fixme\n fork_exec: function(){}\n }\n})(__BRYTHON__)\n"], "_profile": [".js", "// Private interface to the profiling instrumentation implemented in py_utils.js.\n// Uses local a copy of the eval function from py_builtin_functions.js\n\nvar $module=(function($B) {\n eval($B.InjectBuiltins());\n return {\n brython:$B,\n data:$B.$profile_data,\n start:$B.$profile.start,\n stop:$B.$profile.stop,\n pause:$B.$profile.pause,\n status:$B.$profile.status,\n clear:$B.$profile.clear,\n elapsed:$B.$profile.elapsed,\n run:function(src,_globals,_locals,nruns) {\n var current_frame = $B.frames_stack[$B.frames_stack.length-1]\n if(current_frame!==undefined){\n var current_locals_id = current_frame[0].replace(/\\./,'_'),\n current_globals_id = current_frame[2].replace(/\\./,'_')\n }\n\n var is_exec = true,\n leave = false\n\n // code will be run in a specific block\n var globals_id = '$profile_'+$B.UUID(),\n locals_id\n\n if(_locals===_globals){\n locals_id = globals_id\n }else{\n locals_id = '$profile_'+$B.UUID()\n }\n // Initialise the object for block namespaces\n eval('var $locals_'+globals_id+' = {}\\nvar $locals_'+locals_id+' = {}')\n\n // Initialise block globals\n\n // A _globals dictionary is provided, set or reuse its attribute\n // globals_id\n _globals.globals_id = _globals.globals_id || globals_id\n globals_id = _globals.globals_id\n\n if(_locals === _globals || _locals === undefined){\n locals_id = globals_id\n parent_scope = $B.builtins_scope\n }else{\n // The parent block of locals must be set to globals\n parent_scope = {\n id: globals_id,\n parent_block: $B.builtins_scope,\n binding: {}\n }\n for(var attr of _b_.dict.$keys_string(_globals)){\n parent_scope.binding[attr] = true\n }\n }\n\n // Initialise block globals\n if(_globals.$jsobj){\n var items = _globals.$jsobj\n }else{\n var items = {}\n for(var key of _b_.dict.$keys_string(_globals)){\n items[key] = _b_.dict.$getitem_string(_globals, key)\n }\n }\n for(var item in items){\n item1 = to_alias(item)\n try{\n eval('$locals_' + globals_id + '[\"' + item1 +\n '\"] = items[item]')\n }catch(err){\n console.log(err)\n console.log('error setting', item)\n break\n }\n }\n\n // Initialise block locals\n var items = _b_.dict.items(_locals), item\n if(_locals.$jsobj){\n var items = _locals.$jsobj\n }else{\n var items = {}\n for(var key of _b_.dict.$keys_string(_locals)){\n items[key] = _b_.dict.$getitem_string(_locals, key)\n } }\n for(var item in items){\n item1 = to_alias(item)\n try{\n eval('$locals_' + locals_id + '[\"' + item[0] + '\"] = item[1]')\n }catch(err){\n console.log(err)\n console.log('error setting', item)\n break\n }\n }\n //var nb_modules = Object.keys(__BRYTHON__.modules).length\n //console.log('before exec', nb_modules)\n\n console.log(\"call py2js\", src, globals_id, locals_id, parent_scope)\n var root = $B.py2js(src, globals_id, locals_id, parent_scope),\n js, gns, lns\n\n try{\n\n var js = root.to_js()\n\n var i,res,gns;\n for(i=0;i>> i) & 0x1){\n sum = addition32(sum, unsigned32(n2 << i))\n }\n }\n return sum\n }\n\n /* initializes mt[N] with a seed */\n //c//void init_genrand(unsigned long s)\n function init_genrand(s) {\n //c//mt[0]= s & 0xffffffff;\n mt[0] = unsigned32(s & 0xffffffff)\n for(mti = 1; mti < N; mti++){\n mt[mti] =\n //c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);\n addition32(multiplication32(1812433253,\n unsigned32(mt[mti - 1] ^ (mt[mti - 1] >>> 30))), mti)\n /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\n /* In the previous versions, MSBs of the seed affect */\n /* only MSBs of the array mt[]. */\n /* 2002/01/09 modified by Makoto Matsumoto */\n //c//mt[mti] &= 0xffffffff;\n mt[mti] = unsigned32(mt[mti] & 0xffffffff);\n /* for >32 bit machines */\n }\n }\n\n /* initialize by an array with array-length */\n /* init_key is the array for initializing keys */\n /* key_length is its length */\n /* slight change for C++, 2004/2/26 */\n //c//void init_by_array(unsigned long init_key[], int key_length)\n function init_by_array(init_key, key_length) {\n //c//int i, j, k;\n var i, j, k\n init_genrand(19650218)\n i = 1\n j = 0\n k = (N > key_length ? N : key_length)\n for(; k; k--){\n //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))\n //c// + init_key[j] + j; /* non linear */\n mt[i] = addition32(\n addition32(unsigned32(mt[i] ^\n multiplication32(unsigned32(mt[i - 1] ^ (mt[i - 1] >>> 30)),\n 1664525)),\n init_key[j]), j)\n mt[i] =\n //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n unsigned32(mt[i] & 0xffffffff)\n i++\n j++\n if(i >= N){mt[0] = mt[N - 1]; i = 1}\n if(j >= key_length){j = 0}\n }\n for(k = N - 1; k; k--){\n //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))\n //c//- i; /* non linear */\n mt[i] = subtraction32(\n unsigned32(\n (mt[i]) ^\n multiplication32(\n unsigned32(mt[i - 1] ^ (mt[i - 1] >>> 30)),\n 1566083941)),\n i\n )\n //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n mt[i] = unsigned32(mt[i] & 0xffffffff)\n i++\n if(i >= N){mt[0] = mt[N - 1]; i = 1}\n }\n mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */\n }\n\n /* generates a random number on [0,0xffffffff]-interval */\n //c//unsigned long genrand_int32(void)\n function genrand_int32() {\n //c//unsigned long y;\n //c//static unsigned long mag01[2]={0x0UL, MATRIX_A};\n var y;\n var mag01 = [0x0, MATRIX_A];\n /* mag01[x] = x * MATRIX_A for x=0,1 */\n\n if(mti >= N){ /* generate N words at one time */\n //c//int kk;\n var kk\n\n if(mti == N + 1){ /* if init_genrand() has not been called, */\n init_genrand(Date.now()) /* a default initial seed is used */\n }\n\n for(kk = 0; kk < N - M; kk++){\n //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\n //c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[kk]&UPPER_MASK) | (mt[kk + 1]&LOWER_MASK))\n mt[kk] = unsigned32(mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1])\n }\n for(;kk < N - 1; kk++){\n //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\n //c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[kk]&UPPER_MASK) | (mt[kk + 1]&LOWER_MASK))\n mt[kk] = unsigned32(mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1])\n }\n //c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);\n //c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK))\n mt[N - 1] = unsigned32(mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1])\n mti = 0\n }\n\n y = mt[mti++]\n\n /* Tempering */\n //c//y ^= (y >> 11);\n //c//y ^= (y << 7) & 0x9d2c5680;\n //c//y ^= (y << 15) & 0xefc60000;\n //c//y ^= (y >> 18);\n y = unsigned32(y ^ (y >>> 11))\n y = unsigned32(y ^ ((y << 7) & 0x9d2c5680))\n y = unsigned32(y ^ ((y << 15) & 0xefc60000))\n y = unsigned32(y ^ (y >>> 18))\n\n return y\n }\n\n /* generates a random number on [0,0x7fffffff]-interval */\n //c//long genrand_int31(void)\n function genrand_int31(){\n //c//return (genrand_int32()>>1);\n return (genrand_int32()>>>1)\n }\n\n /* generates a random number on [0,1]-real-interval */\n //c//double genrand_real1(void)\n function genrand_real1(){\n return genrand_int32()*(1.0/4294967295.0)\n /* divided by 2^32-1 */\n }\n\n /* generates a random number on [0,1)-real-interval */\n //c//double genrand_real2(void)\n function genrand_real2(){\n return genrand_int32() * (1.0 / 4294967296.0)\n /* divided by 2^32 */\n }\n\n /* generates a random number on (0,1)-real-interval */\n //c//double genrand_real3(void)\n function genrand_real3() {\n return ((genrand_int32()) + 0.5) * (1.0 / 4294967296.0)\n /* divided by 2^32 */\n }\n\n /* generates a random number on [0,1) with 53-bit resolution*/\n //c//double genrand_res53(void)\n function genrand_res53() {\n //c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;\n var a = genrand_int32() >>> 5,\n b = genrand_int32() >>> 6\n return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0)\n }\n /* These real versions are due to Isaku Wada, 2002/01/09 added */\n\n var random = genrand_res53\n\n random.seed = function(seed){\n if(seed === undefined || $B.is_none(seed)){\n const entries = new Uint32Array(N)\n crypto.getRandomValues(entries)\n init_by_array(Array.from(entries), N)\n return\n }\n\n if(!$B.$isinstance(seed, _b_.int)){\n seed = _b_.hash(seed)\n }\n\n // Transform to long integer\n if(typeof seed == \"number\"){\n seed = BigInt(seed)\n }else if(seed.__class__ === $B.long_int){\n seed = seed.value\n }else{\n return random.seed(seed.$brython_value)\n }\n\n // Take abs(seed)\n seed = seed > 0 ? seed : -seed\n\n var keys = []\n var int32_1 = 2n ** 32n - 1n\n\n // decomposition in factors of 2 ** 32\n while(seed >= int32_1){\n var quot = seed / int32_1,\n rest = seed % int32_1\n // Rest is a JS number (< 2 ** 32)\n keys.push(Number(rest))\n // Quotient is either a JS number or a instance of long_int\n // but seed must be long_int\n seed = quot\n }\n keys.push(Number(seed))\n\n init_by_array(keys, keys.length)\n }\n\n random.seed(seed)\n\n random.int31 = genrand_int31\n random.int32 = genrand_int32\n random.real1 = genrand_real1\n random.real2 = genrand_real2\n random.real3 = genrand_real3\n random.res53 = genrand_res53\n\n // Added for compatibility with Python\n random.getstate = function(){\n return $B.fast_tuple(mt.concat([mti]))\n }\n\n random.setstate = function(state){\n mt = state.slice(0, state.length - 1)\n mti = state[state.length - 1]\n }\n\n return random\n\n}\n\nvar Random = $B.make_class(\"Random\",\n function(){\n return {\n __class__: Random,\n _random: RandomStream(Date.now())\n }\n }\n)\n\nRandom.getrandbits = function(){\n var $ = $B.args(\"getrandbits\", 2, {self: null, k:null}, [\"self\", \"k\"],\n arguments, {}, null, null),\n self = $.self,\n k = $B.$GetInt($.k)\n\n if(k < 0)\n throw _b_.ValueError.$factory('number of bits must be non-negative')\n\n if(k === 0)\n return 0\n\n const words = Math.floor((k - 1) / 32) + 1\n const wordarray = new ArrayBuffer(words * 4)\n const wordarray_view = new DataView(wordarray)\n\n /* Fill-out bits of long integer, by 32-bit words, from least significant\n to most significant. */\n for(i = 0; i < words; i++, k -= 32){\n r = self._random.int32()\n if (k < 32)\n r >>>= (32 - k) /* Drop least significant bits */\n wordarray_view.setUint32(i * 4, r, true)\n }\n\n return _b_.int.from_bytes(_b_.bytes.$factory(Array.from(new Uint8Array(wordarray))), \"little\")\n}\n\nRandom.getstate = function(){\n var $ = $B.args('getstate', 1, {self: null},\n [\"self\"], arguments, {}, null, null),\n self = $.self\n return self._random.getstate()\n}\n\nRandom.random = function(){\n var $ = $B.args('random', 1, {self: null}, [\"self\"],\n arguments, {}, null, null),\n self = $.self\n return $B.fast_float(self._random())\n}\n\nRandom.seed = function(){\n var $ = $B.args('seed', 2, {self: null, n: null}, ['self', 'n'],\n arguments, {}, null, null),\n self = $.self,\n n = $.n\n\n if (self._random === undefined){\n self._random = RandomStream(n)\n }else{\n self._random.seed(n)\n }\n}\n\nRandom.setstate = function(){\n var $ = $B.args('setstate', 2, {self: null, state:null}, ['self', 'state'],\n arguments, {}, null, null),\n self = $.self,\n state = $.state\n return self._random.setstate(state)\n}\n\n$B.set_func_names(Random, \"_random\")\n\n$B.imported._random = { Random }\n\n})(__BRYTHON__)\n"], "_sre": [".py", "\n''\n\n\n\n\n\n\n\nMAXREPEAT=2147483648\nMAXGROUPS=2147483647\n\nimport array\nimport operator,sys\nfrom sre_constants import ATCODES,OPCODES,CHCODES\nfrom sre_constants import SRE_INFO_PREFIX,SRE_INFO_LITERAL\nfrom sre_constants import SRE_FLAG_UNICODE,SRE_FLAG_LOCALE\n\n\nfrom _sre_utils import(unicode_iscased,ascii_iscased,unicode_tolower,\nascii_tolower)\n\nimport sys\n\n\n\nMAGIC=20171005\n\n\n\n\n\n\n\n\n\n\n\n\n\nCODESIZE=4\n\ncopyright=\"_sre.py 2.4c Copyright 2005 by Nik Haldimann\"\n\n\ndef getcodesize():\n return CODESIZE\n \ndef compile(pattern,flags,code,groups=0,groupindex={},indexgroup=[None]):\n ''\n \n return SRE_Pattern(pattern,flags,code,groups,groupindex,indexgroup)\n \ndef getlower(char_ord,flags):\n if(char_ord <128)or(flags&SRE_FLAG_UNICODE)\\\n or(flags&SRE_FLAG_LOCALE and char_ord <256):\n \n return ord(chr(char_ord).lower())\n else:\n return char_ord\n \n \nclass SRE_Pattern:\n\n def __init__(self,pattern,flags,code,groups=0,groupindex={},indexgroup=[None]):\n self.pattern=pattern\n self.flags=flags\n self.groups=groups\n self.groupindex=groupindex\n self._indexgroup=indexgroup\n self._code=code\n \n def match(self,string,pos=0,endpos=sys.maxsize):\n ''\n\n \n state=_State(string,pos,endpos,self.flags)\n if state.match(self._code):\n return SRE_Match(self,state)\n return None\n \n def fullmatch(self,string,pos=0,endpos=sys.maxsize):\n ''\n\n \n end=\"$\"if isinstance(string,str)else b\"$\"\n if not string.endswith(end):\n string +=end\n state=_State(string,pos,endpos,self.flags)\n if state.match(self._code):\n return SRE_Match(self,state)\n return None\n \n def search(self,string,pos=0,endpos=sys.maxsize):\n ''\n\n\n \n state=_State(string,pos,endpos,self.flags)\n if state.search(self._code):\n return SRE_Match(self,state)\n else:\n return None\n \n def findall(self,string,pos=0,endpos=sys.maxsize):\n ''\n matchlist=[]\n state=_State(string,pos,endpos,self.flags)\n while state.start <=state.end:\n state.reset()\n state.string_position=state.start\n if not state.search(self._code):\n break\n match=SRE_Match(self,state)\n if self.groups ==0 or self.groups ==1:\n item=match.group(self.groups)\n else:\n item=match.groups(\"\")\n matchlist.append(item)\n if state.string_position ==state.start:\n state.start +=1\n else:\n state.start=state.string_position\n return matchlist\n \n def _subx(self,template,string,count=0,subn=False):\n filter=template\n if not callable(template)and \"\\\\\"in template:\n \n \n \n \n import re as sre\n filter=sre._subx(self,template)\n state=_State(string,0,sys.maxsize,self.flags)\n sublist=[]\n \n n=last_pos=0\n while not count or n 0):\n \n if callable(filter):\n sublist.append(filter(SRE_Match(self,state)))\n else:\n sublist.append(filter)\n last_pos=state.string_position\n n +=1\n if state.string_position ==state.start:\n state.start +=1\n else:\n state.start=state.string_position\n \n if last_pos =0 and group <=self.re.groups:\n return group\n else:\n if group in self.re.groupindex:\n return self.re.groupindex[group]\n raise IndexError(\"no such group\")\n \n def _get_slice(self,group,default):\n group_indices=self.regs[group]\n if group_indices[0]>=0:\n return self.string[group_indices[0]:group_indices[1]]\n else:\n return default\n \n def start(self,group=0):\n ''\n\n \n return self.regs[self._get_index(group)][0]\n \n def end(self,group=0):\n ''\n\n \n return self.regs[self._get_index(group)][1]\n \n def span(self,group=0):\n ''\n return self.start(group),self.end(group)\n \n def expand(self,template):\n ''\n \n import sre\n return sre._expand(self.re,self,template)\n \n def groups(self,default=None):\n ''\n\n \n groups=[]\n for indices in self.regs[1:]:\n if indices[0]>=0:\n groups.append(self.string[indices[0]:indices[1]])\n else:\n groups.append(default)\n return tuple(groups)\n \n def groupdict(self,default=None):\n ''\n\n \n groupdict={}\n for key,value in self.re.groupindex.items():\n groupdict[key]=self._get_slice(value,default)\n return groupdict\n \n def group(self,*args):\n ''\n \n if len(args)==0:\n args=(0,)\n grouplist=[]\n for group in args:\n grouplist.append(self._get_slice(self._get_index(group),None))\n if len(grouplist)==1:\n return grouplist[0]\n else:\n return tuple(grouplist)\n \n def __copy__():\n raise TypeError(\"cannot copy this pattern object\")\n \n def __deepcopy__():\n raise TypeError(\"cannot copy this pattern object\")\n \n def __str__(self):\n start,end=self.start(0),self.end(0)\n return(f\"\")\n \nclass _State:\n\n def __init__(self,string,start,end,flags):\n if isinstance(string,bytearray):\n string=str(bytes(string),\"latin1\")\n if isinstance(string,bytes):\n string=str(string,\"latin1\")\n self.string=string\n if start <0:\n start=0\n if end >len(string):\n end=len(string)\n self.start=start\n self.string_position=self.start\n self.end=end\n self.pos=start\n self.flags=flags\n self.reset()\n \n def reset(self):\n self.marks=[]\n self.lastindex=-1\n self.marks_stack=[]\n self.context_stack=[]\n self.repeat=None\n \n def match(self,pattern_codes):\n \n \n \n \n \n \n \n \n dispatcher=_OpcodeDispatcher()\n self.context_stack.append(_MatchContext(self,pattern_codes))\n has_matched=None\n while len(self.context_stack)>0:\n context=self.context_stack[-1]\n has_matched=dispatcher.match(context)\n if has_matched is not None:\n self.context_stack.pop()\n return has_matched\n \n def search(self,pattern_codes):\n flags=0\n if OPCODES[pattern_codes[0]].name ==\"info\":\n \n \n if pattern_codes[2]&SRE_INFO_PREFIX and pattern_codes[5]>1:\n return self.fast_search(pattern_codes)\n flags=pattern_codes[2]\n pattern_codes=pattern_codes[pattern_codes[1]+1:]\n \n string_position=self.start\n if OPCODES[pattern_codes[0]].name ==\"literal\":\n \n \n character=pattern_codes[1]\n while True:\n while string_position =self.end:\n return False\n self.start=string_position\n string_position +=1\n self.string_position=string_position\n if flags&SRE_INFO_LITERAL:\n return True\n if self.match(pattern_codes[2:]):\n return True\n return False\n \n \n while string_position <=self.end:\n self.reset()\n self.start=self.string_position=string_position\n if self.match(pattern_codes):\n return True\n string_position +=1\n return False\n \n def fast_search(self,pattern_codes):\n ''\n \n \n \n flags=pattern_codes[2]\n prefix_len=pattern_codes[5]\n prefix_skip=pattern_codes[6]\n prefix=pattern_codes[7:7+prefix_len]\n overlap=pattern_codes[7+prefix_len -1:pattern_codes[1]+1]\n pattern_codes=pattern_codes[pattern_codes[1]+1:]\n i=0\n string_position=self.string_position\n while string_position =len(self.marks):\n self.marks.extend([None]*(mark_nr -len(self.marks)+1))\n self.marks[mark_nr]=position\n \n def get_marks(self,group_index):\n marks_index=2 *group_index\n if len(self.marks)>marks_index+1:\n return self.marks[marks_index],self.marks[marks_index+1]\n else:\n return None,None\n \n def marks_push(self):\n self.marks_stack.append((self.marks[:],self.lastindex))\n \n def marks_pop(self):\n self.marks,self.lastindex=self.marks_stack.pop()\n \n def marks_pop_keep(self):\n self.marks,self.lastindex=self.marks_stack[-1]\n \n def marks_pop_discard(self):\n self.marks_stack.pop()\n \n def lower(self,char_ord):\n return getlower(char_ord,self.flags)\n \n \nclass _MatchContext:\n\n def __init__(self,state,pattern_codes):\n self.state=state\n self.pattern_codes=pattern_codes\n self.string_position=state.string_position\n self.code_position=0\n self.has_matched=None\n \n def push_new_context(self,pattern_offset):\n ''\n\n \n child_context=_MatchContext(self.state,\n self.pattern_codes[self.code_position+pattern_offset:])\n \n \n \n \n self.state.context_stack.append(child_context)\n return child_context\n \n def peek_char(self,peek=0):\n return self.state.string[self.string_position+peek]\n \n def skip_char(self,skip_count):\n self.string_position +=skip_count\n \n def remaining_chars(self):\n return self.state.end -self.string_position\n \n def peek_code(self,peek=0):\n return self.pattern_codes[self.code_position+peek]\n \n def skip_code(self,skip_count):\n self.code_position +=skip_count\n \n def remaining_codes(self):\n return len(self.pattern_codes)-self.code_position\n \n def at_beginning(self):\n return self.string_position ==0\n \n def at_end(self):\n return self.string_position ==self.state.end\n \n def at_linebreak(self):\n return not self.at_end()and _is_linebreak(self.peek_char())\n \n def at_boundary(self,word_checker):\n if self.at_beginning()and self.at_end():\n return False\n that=not self.at_beginning()and word_checker(self.peek_char(-1))\n this=not self.at_end()and word_checker(self.peek_char())\n return this !=that\n \n \nclass _RepeatContext(_MatchContext):\n\n def __init__(self,context):\n _MatchContext.__init__(self,context.state,\n context.pattern_codes[context.code_position:])\n self.count=-1\n \n self.previous=context.state.repeat\n self.last_position=None\n \n \nclass _Dispatcher:\n\n DISPATCH_TABLE=None\n \n def dispatch(self,code,context):\n method=self.DISPATCH_TABLE.get(code,self.__class__.unknown)\n return method(self,context)\n \n def unknown(self,code,ctx):\n raise NotImplementedError()\n \n def build_dispatch_table(cls,items,method_prefix):\n if cls.DISPATCH_TABLE is not None:\n return\n table={}\n for item in items:\n key,value=item.name.lower(),int(item)\n if hasattr(cls,\"%s%s\"%(method_prefix,key)):\n table[value]=getattr(cls,\"%s%s\"%(method_prefix,key))\n cls.DISPATCH_TABLE=table\n \n build_dispatch_table=classmethod(build_dispatch_table)\n \n \nclass _OpcodeDispatcher(_Dispatcher):\n\n def __init__(self):\n self.executing_contexts={}\n self.at_dispatcher=_AtcodeDispatcher()\n self.ch_dispatcher=_ChcodeDispatcher()\n self.set_dispatcher=_CharsetDispatcher()\n \n def match(self,context):\n ''\n\n \n while context.remaining_codes()>0 and context.has_matched is None:\n opcode=context.peek_code()\n if not self.dispatch(opcode,context):\n return None\n if context.has_matched is None:\n context.has_matched=False\n return context.has_matched\n \n def dispatch(self,opcode,context):\n ''\n \n \n if id(context)in self.executing_contexts:\n generator=self.executing_contexts[id(context)]\n del self.executing_contexts[id(context)]\n has_finished=next(generator)\n else:\n method=self.DISPATCH_TABLE.get(opcode,_OpcodeDispatcher.unknown)\n has_finished=method(self,context)\n if hasattr(has_finished,\"__next__\"):\n generator=has_finished\n has_finished=next(generator)\n if not has_finished:\n self.executing_contexts[id(context)]=generator\n return has_finished\n \n def op_success(self,ctx):\n \n \n ctx.state.string_position=ctx.string_position\n ctx.has_matched=True\n return True\n \n def op_failure(self,ctx):\n \n \n ctx.has_matched=False\n return True\n \n def general_op_literal(self,ctx,compare,decorate=lambda x:x):\n if ctx.at_end()or not compare(decorate(ord(ctx.peek_char())),\n decorate(ctx.peek_code(1))):\n ctx.has_matched=False\n ctx.skip_code(2)\n ctx.skip_char(1)\n \n def op_literal(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.eq)\n return True\n \n def op_not_literal(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.ne)\n return True\n \n def op_literal_ignore(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.eq,ctx.state.lower)\n return True\n \n def op_literal_uni_ignore(self,ctx):\n self.general_op_literal(ctx,operator.eq,ctx.state.lower)\n return True\n \n def op_not_literal_ignore(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.ne,ctx.state.lower)\n return True\n \n def op_at(self,ctx):\n \n \n \n if not self.at_dispatcher.dispatch(ctx.peek_code(1),ctx):\n ctx.has_matched=False\n \n return True\n ctx.skip_code(2)\n return True\n \n def op_category(self,ctx):\n \n \n \n if ctx.at_end()or not self.ch_dispatcher.dispatch(ctx.peek_code(1),ctx):\n ctx.has_matched=False\n \n return True\n ctx.skip_code(2)\n ctx.skip_char(1)\n return True\n \n def op_any(self,ctx):\n \n \n \n if ctx.at_end()or ctx.at_linebreak():\n ctx.has_matched=False\n \n return True\n ctx.skip_code(1)\n ctx.skip_char(1)\n return True\n \n def op_any_all(self,ctx):\n \n \n \n if ctx.at_end():\n ctx.has_matched=False\n \n return True\n ctx.skip_code(1)\n ctx.skip_char(1)\n return True\n \n def general_op_in(self,ctx,decorate=lambda x:x):\n \n \n if ctx.at_end():\n ctx.has_matched=False\n \n return\n skip=ctx.peek_code(1)\n ctx.skip_code(2)\n \n \n if not self.check_charset(ctx,decorate(ord(ctx.peek_char()))):\n \n ctx.has_matched=False\n return\n ctx.skip_code(skip -1)\n ctx.skip_char(1)\n \n \n def op_in(self,ctx):\n \n \n \n self.general_op_in(ctx)\n return True\n \n def op_in_ignore(self,ctx):\n \n \n \n self.general_op_in(ctx,ctx.state.lower)\n return True\n \n def op_in_uni_ignore(self,ctx):\n self.general_op_in(ctx,ctx.state.lower)\n return True\n \n def op_jump(self,ctx):\n \n \n \n ctx.skip_code(ctx.peek_code(1)+1)\n return True\n \n \n \n op_info=op_jump\n \n def op_mark(self,ctx):\n \n \n \n ctx.state.set_mark(ctx.peek_code(1),ctx.string_position)\n ctx.skip_code(2)\n return True\n \n def op_branch(self,ctx):\n \n \n \n ctx.state.marks_push()\n ctx.skip_code(1)\n current_branch_length=ctx.peek_code(0)\n while current_branch_length:\n \n \n if not(OPCODES[ctx.peek_code(1)].name ==\"literal\"and\\\n (ctx.at_end()or ctx.peek_code(2)!=ord(ctx.peek_char()))):\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(1)\n \n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.state.marks_pop_keep()\n ctx.skip_code(current_branch_length)\n current_branch_length=ctx.peek_code(0)\n ctx.state.marks_pop_discard()\n ctx.has_matched=False\n \n yield True\n \n def op_repeat_one(self,ctx):\n \n \n \n \n mincount=ctx.peek_code(2)\n maxcount=ctx.peek_code(3)\n \n \n \n if ctx.remaining_chars()=mincount and\\\n (ctx.at_end()or ord(ctx.peek_char())!=char):\n ctx.skip_char(-1)\n count -=1\n if count =mincount:\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(ctx.peek_code(1)+1)\n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.skip_char(-1)\n count -=1\n ctx.state.marks_pop_keep()\n \n ctx.state.marks_pop_discard()\n ctx.has_matched=False\n \n yield True\n \n def op_min_repeat_one(self,ctx):\n \n \n mincount=ctx.peek_code(2)\n maxcount=ctx.peek_code(3)\n \n \n if ctx.remaining_chars()=maxcount and maxcount !=MAXREPEAT:\n ctx.has_matched=False\n \n yield True\n repeat.count=count\n child_context=repeat.push_new_context(4)\n yield False\n ctx.has_matched=child_context.has_matched\n if not ctx.has_matched:\n repeat.count=count -1\n ctx.state.string_position=ctx.string_position\n yield True\n \n def general_op_groupref(self,ctx,decorate=lambda x:x):\n group_start,group_end=ctx.state.get_marks(ctx.peek_code(1))\n if group_start is None or group_end is None or group_end =0:\n child_context=ctx.push_new_context(3)\n yield False\n if child_context.has_matched:\n ctx.has_matched=False\n yield True\n ctx.skip_code(ctx.peek_code(1)+1)\n yield True\n \n def unknown(self,ctx):\n \n raise RuntimeError(\"Internal re error. Unknown opcode: %s\"%ctx.peek_code())\n \n def check_charset(self,ctx,char):\n ''\n \n self.set_dispatcher.reset(char)\n save_position=ctx.code_position\n result=None\n while result is None:\n result=self.set_dispatcher.dispatch(ctx.peek_code(),ctx)\n ctx.code_position=save_position\n \n return result\n \n def count_repetitions(self,ctx,maxcount):\n ''\n\n \n count=0\n real_maxcount=ctx.state.end -ctx.string_position\n if maxcount >4)\\\n &(1 <<(char_code&15)):\n return self.ok\n ctx.skip_code(16)\n else:\n if char_code <256 and ctx.peek_code(char_code >>5)\\\n &(1 <<(char_code&31)):\n return self.ok\n ctx.skip_code(8)\n def set_range(self,ctx):\n \n if ctx.peek_code(1)<=self.char <=ctx.peek_code(2):\n return self.ok\n ctx.skip_code(3)\n def set_negate(self,ctx):\n self.ok=not self.ok\n ctx.skip_code(1)\n \n def set_bigcharset(self,ctx):\n \n char_code=self.char\n count=ctx.peek_code(1)\n ctx.skip_code(2)\n if char_code <65536:\n block_index=char_code >>8\n \n a=array.array(\"B\")\n a.fromstring(array.array(CODESIZE ==2 and \"H\"or \"I\",\n [ctx.peek_code(block_index //CODESIZE)]).tostring())\n block=a[block_index %CODESIZE]\n ctx.skip_code(256 //CODESIZE)\n block_value=ctx.peek_code(block *(32 //CODESIZE)\n +((char_code&255)>>(CODESIZE ==2 and 4 or 5)))\n if block_value&(1 <<(char_code&((8 *CODESIZE)-1))):\n return self.ok\n else:\n ctx.skip_code(256 //CODESIZE)\n ctx.skip_code(count *(32 //CODESIZE))\n \n def unknown(self,ctx):\n return False\n \n_CharsetDispatcher.build_dispatch_table(OPCODES,\"set_\")\n\n\nclass _AtcodeDispatcher(_Dispatcher):\n\n def at_beginning(self,ctx):\n return ctx.at_beginning()\n at_beginning_string=at_beginning\n def at_beginning_line(self,ctx):\n return ctx.at_beginning()or _is_linebreak(ctx.peek_char(-1))\n def at_end(self,ctx):\n return(ctx.remaining_chars()==1 and ctx.at_linebreak())or ctx.at_end()\n def at_end_line(self,ctx):\n return ctx.at_linebreak()or ctx.at_end()\n def at_end_string(self,ctx):\n return ctx.at_end()\n def at_boundary(self,ctx):\n return ctx.at_boundary(_is_word)\n def at_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_word)\n def at_loc_boundary(self,ctx):\n return ctx.at_boundary(_is_loc_word)\n def at_loc_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_loc_word)\n def at_uni_boundary(self,ctx):\n return ctx.at_boundary(_is_uni_word)\n def at_uni_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_uni_word)\n def unknown(self,ctx):\n return False\n \n_AtcodeDispatcher.build_dispatch_table(ATCODES,\"\")\n\n\nclass _ChcodeDispatcher(_Dispatcher):\n\n def category_digit(self,ctx):\n return _is_digit(ctx.peek_char())\n def category_not_digit(self,ctx):\n return not _is_digit(ctx.peek_char())\n def category_space(self,ctx):\n return _is_space(ctx.peek_char())\n def category_not_space(self,ctx):\n return not _is_space(ctx.peek_char())\n def category_word(self,ctx):\n return _is_word(ctx.peek_char())\n def category_not_word(self,ctx):\n return not _is_word(ctx.peek_char())\n def category_linebreak(self,ctx):\n return _is_linebreak(ctx.peek_char())\n def category_not_linebreak(self,ctx):\n return not _is_linebreak(ctx.peek_char())\n def category_loc_word(self,ctx):\n return _is_loc_word(ctx.peek_char())\n def category_loc_not_word(self,ctx):\n return not _is_loc_word(ctx.peek_char())\n def category_uni_digit(self,ctx):\n return ctx.peek_char().isdigit()\n def category_uni_not_digit(self,ctx):\n return not ctx.peek_char().isdigit()\n def category_uni_space(self,ctx):\n return ctx.peek_char().isspace()\n def category_uni_not_space(self,ctx):\n return not ctx.peek_char().isspace()\n def category_uni_word(self,ctx):\n return _is_uni_word(ctx.peek_char())\n def category_uni_not_word(self,ctx):\n return not _is_uni_word(ctx.peek_char())\n def category_uni_linebreak(self,ctx):\n return ord(ctx.peek_char())in _uni_linebreaks\n def category_uni_not_linebreak(self,ctx):\n return ord(ctx.peek_char())not in _uni_linebreaks\n def unknown(self,ctx):\n return False\n \n_ChcodeDispatcher.build_dispatch_table(CHCODES,\"\")\n\n\n_ascii_char_info=[0,0,0,0,0,0,0,0,0,2,6,2,\n2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,\n0,0,0,0,0,0,0,0,0,0,0,0,0,25,25,25,25,25,25,25,25,\n25,25,0,0,0,0,0,0,0,24,24,24,24,24,24,24,24,24,24,\n24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,0,0,\n0,0,16,0,24,24,24,24,24,24,24,24,24,24,24,24,24,24,\n24,24,24,24,24,24,24,24,24,24,24,24,0,0,0,0,0]\n\ndef _is_digit(char):\n code=ord(char)\n return code <128 and _ascii_char_info[code]&1\n \ndef _is_space(char):\n code=ord(char)\n return code <128 and _ascii_char_info[code]&2\n \ndef _is_word(char):\n\n code=ord(char)\n return code <128 and _ascii_char_info[code]&16\n \ndef _is_loc_word(char):\n return(not(ord(char)&~255)and char.isalnum())or char =='_'\n \ndef _is_uni_word(char):\n\n\n return chr(ord(char)).isalnum()or char =='_'\n \ndef _is_linebreak(char):\n return char ==\"\\n\"\n \n \n_uni_linebreaks=[10,13,28,29,30,133,8232,8233]\n\ndef _log(message):\n if 0:\n print(message)\n", ["_sre_utils", "array", "operator", "re", "sre", "sre_constants", "sys"]], "_sre_utils": [".js", "var $module=(function($B){\n\n function unicode_iscased(cp){\n // cp : Unicode code point\n var letter = String.fromCodePoint(cp)\n return (letter != letter.toLowerCase() ||\n letter != letter.toUpperCase())\n }\n\n function ascii_iscased(cp){\n if(cp > 255){return false}\n return unicode_iscased(cp)\n }\n\n function unicode_tolower(cp){\n var letter = String.fromCodePoint(cp),\n lower = letter.toLowerCase()\n return lower.charCodeAt(0)\n }\n\n function ascii_tolower(cp){\n return unicode_tolower(cp)\n }\n\nreturn {\n unicode_iscased: unicode_iscased,\n ascii_iscased: ascii_iscased,\n unicode_tolower: unicode_tolower,\n ascii_tolower: ascii_tolower\n}\n\n}\n\n)(__BRYTHON__)"], "_string": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nfunction parts(format_string){\n var result = [],\n _parts = $B.split_format(format_string) // defined in py_string.js\n for(var i = 0; i < _parts.length; i+= 2){\n result.push({pre: _parts[i], fmt: _parts[i + 1]})\n }\n return result\n}\n\nfunction Tuple(){\n var args = []\n for(var i=0, len=arguments.length; i < len; i++){\n args.push(arguments[i])\n }\n return _b_.tuple.$factory(args)\n}\n\n$B.imported._string = {\n\n formatter_field_name_split: function(fieldname){\n // Split the argument as a field name\n var parsed = $B.parse_format(fieldname),\n first = parsed.name,\n rest = []\n if(first.match(/\\d+/)){first = parseInt(first)}\n parsed.name_ext.forEach(function(ext){\n if(ext.startsWith(\"[\")){\n var item = ext.substr(1, ext.length - 2)\n if(item.match(/\\d+/)){\n rest.push(Tuple(false, parseInt(item)))\n }else{\n rest.push(Tuple(false, item))\n }\n }else{\n rest.push(Tuple(true, ext.substr(1)))\n }\n })\n return Tuple(first, _b_.iter(rest))\n },\n formatter_parser: function(format_string){\n // Parse the argument as a format string\n\n if(! _b_.isinstance(format_string, _b_.str)){\n throw _b_.ValueError.$factory(\"Invalid format string type: \" +\n $B.class_name(format_string))\n }\n\n var result = []\n parts(format_string).forEach(function(item){\n var pre = item.pre === undefined ? \"\" : item.pre,\n fmt = item.fmt\n if(fmt === undefined){\n result.push(Tuple(pre, _b_.None, _b_.None, _b_.None))\n }else if(fmt.string == ''){\n result.push(Tuple(pre, '', '', _b_.None))\n }else{\n result.push(Tuple(pre,\n fmt.raw_name + fmt.name_ext.join(\"\"),\n fmt.raw_spec,\n fmt.conv || _b_.None))\n }\n })\n return result\n }\n}\n})(__BRYTHON__)"], "_strptime": [".js", "\n(function($B){\n var _b_ = __BRYTHON__.builtins\n $B.imported._strptime = {\n _strptime_datetime: function(cls, s, fmt){\n var pos_s = 0,\n pos_fmt = 0,\n dt = {}\n function error(time_data, format){\n throw _b_.ValueError.$factory(\n `time data '${time_data}' does not match format '${format}'`)\n }\n\n var locale = __BRYTHON__.locale,\n shortdays = [],\n longdays = [],\n conv_func = locale == \"C\" ?\n function(d, options){\n return d.toLocaleDateString('en-EN', options)\n } :\n function(d, options){\n return d.toLocaleDateString(locale, options)\n }\n\n for(var day = 16; day < 23; day++){\n var d = new Date(Date.UTC(2012, 11, day, 3, 0, 0))\n shortdays.push(conv_func(d, {weekday: 'short'}))\n longdays.push(conv_func(d, {weekday: 'long'}))\n }\n\n var shortmonths = [],\n longmonths = []\n\n for(var month = 0; month < 12; month++){\n var d = new Date(Date.UTC(2012, month, 11, 3, 0, 0))\n shortmonths.push(conv_func(d, {month: 'short'}))\n longmonths.push(conv_func(d, {month: 'long'}))\n }\n\n var shortdays_re = new RegExp(shortdays.join(\"|\").replace(\".\", \"\\\\.\")),\n longdays_re = new RegExp(longdays.join(\"|\")),\n shortmonths_re = new RegExp(shortmonths.join(\"|\").replace(\".\", \"\\\\.\")),\n longmonths_re = new RegExp(longmonths.join(\"|\"))\n\n var regexps = {\n d: [\"day\", new RegExp(\"^[123][0-9]|0?[1-9]\")],\n f: [\"microsecond\", new RegExp(\"^\\\\d{1,6}\")],\n H: [\"hour\", new RegExp(\"^[01][0-9]|2[0-3]|\\\\d\")],\n I: [\"hour\", new RegExp(\"^1[0-2]|0?[0-9]\")],\n m: [\"month\", new RegExp(\"^1[012]|0?[1-9]\")],\n M: [\"minute\", new RegExp(\"^[1-5][0-9]|0?[0-9]\")],\n S: [\"second\", new RegExp(\"^[1-5]\\\\d|0?\\\\d\")],\n y: [\"year\", new RegExp(\"^0{0,2}\\\\d{2}\")],\n Y: [\"year\", new RegExp(\"^\\\\d{4}\")],\n z: [\"tzinfo\", new RegExp(\"Z\")]\n }\n\n for(var key in regexps){\n var re = new RegExp('%' + key, \"g\"),\n mo = fmt.match(re)\n if(mo && mo.length > 1){\n throw _b_.ValueError.$factory('strptime directive %' +\n key + ' defined more than once')\n }\n }\n\n while(pos_fmt < fmt.length){\n var car = fmt.charAt(pos_fmt)\n if(car == \"%\"){\n var spec = fmt.charAt(pos_fmt + 1),\n regexp = regexps[spec]\n if(regexp !== undefined){\n var re = regexp[1],\n attr = regexp[0],\n res = re.exec(s.substr(pos_s))\n if(res === null){\n error(s, fmt)\n }else{\n dt[attr] = parseInt(res[0])\n if(attr == \"microsecond\"){\n while(dt[attr] < 100000){\n dt[attr] *= 10\n }\n }else if(attr == \"tzinfo\"){\n // Only value supported for the moment : Z\n // (UTC)\n var dt_module = $B.imported[cls.__module__]\n dt.tzinfo = dt_module.timezone.utc\n }\n pos_fmt += 2\n pos_s += res[0].length\n }\n }else if(spec == \"a\" || spec == \"A\"){\n // Locale's abbreviated (a) or full (A) weekday name\n var attr = \"weekday\",\n re = spec == \"a\" ? shortdays_re : longdays_re,\n t = spec == \"a\" ? shortdays : longdays\n res = re.exec(s.substr(pos_s))\n if(res === null){\n console.log('error', re, 'string', s.substr(pos_s), 'fmt', fmt)\n error(s, fmt)\n }else{\n var match = res[0],\n ix = t.indexOf(match)\n }\n dt.weekday = ix\n pos_fmt += 2\n pos_s += match.length\n }else if(spec == \"b\" || spec == \"B\"){\n // Locales's abbreviated (b) or full (B) month\n var attr = \"month\",\n re = spec == \"b\" ? shortmonths_re : longmonths_re,\n t = spec == \"b\" ? shortmonths : longmonths,\n res = re.exec(s.substr(pos_s))\n if(res === null){\n error(s, fmt)\n }else{\n var match = res[0],\n ix = t.indexOf(match)\n }\n dt.month = ix + 1\n pos_fmt += 2\n pos_s += match.length\n }else if(spec == \"c\"){\n // Locale's appropriate date and time representation\n var fmt1 = fmt.substr(0, pos_fmt - 1) + _locale_c_format() +\n fmt.substr(pos_fmt + 2)\n fmt = fmt1\n }else if(spec == \"%\"){\n if(s.charAt(pos_s) == \"%\"){\n pos_fmt++\n pos_s++\n }else{\n error(s, fmt)\n }\n }else if(spec == 'p'){\n // AM or PM\n var next2 = s.substr(pos_s, 2)\n if(next2.toUpperCase() == 'AM'){\n if(dt.hasOwnProperty('hour')){\n if(dt.hour > 0 && dt.hour < 12){\n // ok\n }else if(dt.hour == 12){\n dt.hour = 0\n }else{\n error(s, fmt)\n }\n }else{\n error(s, fmt)\n }\n }else if(next2.toUpperCase() == 'PM'){\n if(dt.hasOwnProperty('hour')){\n if(dt.hour > 0 && dt.hour < 12){\n dt.hour += 12\n }else if(dt.hour == 12){\n dt.hour = 12\n }else{\n error(s, fmt)\n }\n }else{\n error(s, fmt)\n }\n }else{\n error(s, fmt)\n }\n pos_fmt += 2\n pos_s += 2\n }else{\n pos_fmt++\n }\n }else{\n if(car == s.charAt(pos_s)){\n pos_fmt++\n pos_s++\n }else{\n error(s, fmt)\n }\n }\n }\n\n if(pos_s < s.length){\n throw _b_.ValueError.$factory('unconverted data remains: ' +\n s.substr(pos_s))\n }\n\n return $B.$call(cls)(dt.year, dt.month, dt.day,\n dt.hour || 0, dt.minute || 0, dt.second || 0,\n dt.microsecond || 0, dt.tzinfo || _b_.None)\n }\n }\n})(__BRYTHON__)\n"], "_svg": [".js", "// creation of a SVG element\n(function($B){\n\nvar _b_ = $B.builtins\nvar TagSum = $B.TagSum // defined in py_dom.js\n\nvar $svgNS = \"http://www.w3.org/2000/svg\"\nvar $xlinkNS = \"http://www.w3.org/1999/xlink\"\n\nfunction makeTagDict(tagName){\n // return the dictionary for the class associated with tagName\n var dict = $B.make_class(tagName)\n\n dict.__init__ = function(){\n var $ns = $B.args('__init__', 1, {self: null}, ['self'],\n arguments, {}, 'args', 'kw'),\n self = $ns['self'],\n args = $ns['args']\n if(args.length == 1){\n var first = args[0]\n if($B.$isinstance(first, [_b_.str, _b_.int, _b_.float])){\n self.appendChild(document.createTextNode(_b_.str.$factory(first)))\n }else if(first.__class__ === TagSum){\n for(var i = 0, len = first.children.length; i < len; i++){\n self.appendChild(first.children[i].elt)\n }\n }else{ // argument is another DOMNode instance\n try{self.appendChild(first.elt)}\n catch(err){throw _b_.ValueError.$factory('wrong element ' + first)}\n }\n }\n\n // attributes\n var items = _b_.list.$factory(_b_.dict.items($ns['kw']))\n for(var item of _b_.dict.$iter_items($ns.kw)){\n // keyword arguments\n var arg = item.key,\n value = $B.py_immutable_to_js(item.value)\n if(arg.toLowerCase().substr(0,2) == \"on\"){\n // Event binding passed as argument \"onclick\", \"onfocus\"...\n // Better use method bind of DOMNode objects\n $B.DOMNode.bind(self,\n arg.toLowerCase().substr(2),\n value)\n }else if(arg.toLowerCase() == \"style\"){\n $B.DOMNode.set_style(self, value)\n }else if(arg.toLowerCase().indexOf(\"href\") !== -1){ // xlink:href\n self.setAttributeNS( \"http://www.w3.org/1999/xlink\",\n \"href\",value)\n }else{\n if(value !== false){\n // option.selected=false sets it to true :-)\n try{\n arg = arg.replace('_', '-')\n self.setAttributeNS(null, arg, value)\n }catch(err){\n throw _b_.ValueError.$factory(\"can't set attribute \" + arg)\n }\n }\n }\n }\n }\n\n dict.__mro__ = [$B.DOMNode, $B.builtins.object]\n\n dict.__new__ = function(cls){\n var res = $B.DOMNode.$factory(document.createElementNS($svgNS, tagName))\n res.__class__ = cls\n return res\n }\n\n dict.$factory = function(){\n var res = $B.DOMNode.$factory(\n document.createElementNS($svgNS, tagName))\n res.__class__ = dict\n // apply __init__\n dict.__init__(res, ...arguments)\n return res\n }\n\n $B.set_func_names(dict, \"browser.svg\")\n\n return dict\n}\n\n\n// SVG\nvar $svg_tags = ['a',\n'altGlyph',\n'altGlyphDef',\n'altGlyphItem',\n'animate',\n'animateColor',\n'animateMotion',\n'animateTransform',\n'circle',\n'clipPath',\n'color_profile', // instead of color-profile\n'cursor',\n'defs',\n'desc',\n'ellipse',\n'feBlend',\n'foreignObject', //patch to enable foreign objects\n'g',\n'image',\n'line',\n'linearGradient',\n'marker',\n'mask',\n'path',\n'pattern',\n'polygon',\n'polyline',\n'radialGradient',\n'rect',\n'set',\n'stop',\n'svg',\n'text',\n'tref',\n'tspan',\n'use']\n\n// create classes\nvar obj = new Object()\nvar dicts = {}\nfor(var i = 0, len = $svg_tags.length; i < len; i++){\n var tag = $svg_tags[i]\n obj[tag] = makeTagDict(tag)\n}\n\n$B.imported._svg = obj\n})(__BRYTHON__)\n"], "_symtable": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\nvar module = $B.SYMBOL_FLAGS // in brython_builtins.js\n\nmodule.symtable = function(){\n var $ = $B.args('symtable', 3,\n {code: null, filename: null, compile_type: null},\n ['code', 'filename', 'compile_type'], arguments,\n {}, null, null)\n var ast = _b_.compile($.code, $.filename, $.compile_type,\n $B.PyCF_ONLY_AST)\n // ast is an instance of Python class\n // _Py_Symtable_Build in symtable.js uses the underlying JS object\n return $B._PySymtable_Build(ast.$js_ast, $.filename)\n}\n\n\n$B.addToImported('_symtable', module)\n\n})(__BRYTHON__)"], "_tokenize": [".js", "(function($B){\n\nvar _b_ = $B.builtins\n\n$B.$import('token')\n\nvar TokenizerIter = $B.make_class('TokenizerIter',\n function(it){\n return {\n __class__: TokenizerIter,\n it\n }\n }\n)\n\nTokenizerIter.__iter__ = function(self){\n var js_iter = function*(){\n var line_num = 0\n while(true){\n try{\n var bytes = self.it()\n }catch(err){\n if($B.is_exc(err, [_b_.StopIteration])){\n token = endmarker\n token.lineno++\n token.end_lineno++\n yield $B.fast_tuple([token.num_type, token.string,\n $B.fast_tuple([token.lineno, token.col_offset]),\n $B.fast_tuple([token.end_lineno, token.end_col_offset]),\n token.line])\n }\n throw err\n }\n line_num++\n var line = _b_.bytes.decode(bytes, 'utf-8')\n for(var token of $B.tokenizer(line, 'test')){\n if(token.num_type == $B.py_tokens.ENCODING){ // skip encoding token\n continue\n }else if(token.num_type == $B.py_tokens.ENDMARKER){\n var endmarker = token\n continue\n }\n token.type = token.num_type\n token.lineno = line_num\n token.end_lineno = line_num\n yield $B.fast_tuple([token.num_type, token.string,\n $B.fast_tuple([token.lineno, token.col_offset]),\n $B.fast_tuple([token.end_lineno, token.end_col_offset]),\n token.line])\n }\n }\n\n }\n return $B.generator.$factory(js_iter)()\n}\n\nTokenizerIter.__next__ = function*(self){\n\n}\n\n$B.set_func_names(TokenizerIter, '_tokenize')\n\n$B.addToImported('_tokenize', {TokenizerIter})\n\n\n})(__BRYTHON__)"], "_webcomponent": [".js", "// module for Web Components\n(function($B){\n\nvar _b_ = $B.builtins\n\nfunction define(tag_name, cls, options){\n var $ = $B.args(\"define\", 3, {tag_name: null, cls: null, options: null},\n [\"tag_name\", \"cls\", \"options\"], arguments, {options: _b_.None},\n null, null),\n tag_name = $.tag_name,\n cls = $.cls,\n options = $.options,\n _extends,\n extend_dom_name = 'HTMLElement'\n if(options !== _b_.None){\n if(! $B.$isinstance(options, _b_.dict)){\n throw _b_.TypeError.$factory('options can only be None or a ' +\n `dict, not '${$B.class_name(options)}'`)\n }\n try{\n _extends = _b_.dict.$getitem(options, 'extends')\n }catch(err){\n // ignore\n }\n }else{\n let stack = [...cls.__bases__];\n while(stack.length) {\n base = stack.pop();\n if(base.__module__ === 'browser.html'){\n _extends = base.__name__.toLowerCase()\n break\n }\n\n stack.push(...base.__bases__);\n }\n }\n\n if(_extends){\n if(typeof _extends != 'string'){\n throw _b_.TypeError.$factory('value for extends must be a ' +\n `string, not '${$B.class_name(_extends)}'`)\n }\n var elt = document.createElement(_extends)\n if(elt instanceof HTMLUnknownElement){\n throw _b_.ValueError.$factory(`'${_extends}' is not a valid ` +\n 'tag name')\n }\n var extend_tag = _extends.toLowerCase()\n extend_dom_name = Object.getPrototypeOf(elt).constructor.name\n }\n if(typeof tag_name != \"string\"){\n throw _b_.TypeError.$factory(\"first argument of define() \" +\n \"must be a string, not '\" + $B.class_name(tag_name) + \"'\")\n }else if(tag_name.indexOf(\"-\") == -1){\n throw _b_.ValueError.$factory(\"custom tag name must \" +\n \"contain a hyphen (-)\")\n }\n if(!$B.$isinstance(cls, _b_.type)){\n throw _b_.TypeError.$factory(\"second argument of define() \" +\n \"must be a class, not '\" + $B.class_name(tag_name) + \"'\")\n }\n cls.$webcomponent = true\n\n // Create the Javascript class used for the component. It must have\n // the same name as the Python class\n var src = String.raw`var WebComponent = class extends HTMLElement {\n constructor(){\n // Always call super first in constructor\n super()\n var html = $B.imported['browser.html']\n // Create tag in module html\n if(html['tag_name'] === undefined){\n html.maketag('tag_name', WebComponent)\n }\n var init = $B.$getattr(cls, \"__init__\", _b_.None)\n if(init !== _b_.None){\n try{\n var _self = $B.DOMNode.$factory(this),\n attrs_before_init = []\n for(var i = 0, len = _self.attributes.length; i < len; i++){\n attrs_before_init.push(_self.attributes.item(i))\n }\n _self.__class__ = cls\n _self.__dict__ = $B.empty_dict()\n $B.$call(init)(_self)\n if(WebComponent.initialized){\n // Check that init() did not introduce new attributes,\n // which is illegal\n // cf. https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-conformance\n for(var i = 0, len = _self.attributes.length; i < len; i++){\n var item = _self.attributes.item(i)\n if(attrs_before_init.indexOf(item) == -1){\n throw _b_.TypeError.$factory(\"Custom element \" +\n \"must not create attributes, found: \" +\n item.name + '=\"' + item.value + '\"')\n }\n }\n }\n }catch(err){\n $B.handle_error(err)\n }\n }\n }\n static get observedAttributes(){\n var obs_attr = $B.$getattr(cls, \"observedAttributes\", null)\n if(obs_attr === null){\n return []\n }\n if($B.$isinstance(obs_attr, _b_.property)){ // issue 2454\n obs_attr = obs_attr.fget(cls)\n }\n if(obs_attr === null){\n return []\n }else if(typeof obs_attr == \"function\"){\n var warning = _b_.DeprecationWarning.$factory(\n \"Setting observedAttributes as a method \" +\n \"is deprecated. Set it as a class attribute.\")\n // module _warning is in builtin_modules.js\n $B.imported._warnings.warn(warning)\n return $B.$call(obs_attr)(this)\n }else if(Array.isArray(obs_attr)){\n return obs_attr\n }else{\n throw _b_.TypeError.$factory(\n \"wrong type for observedAttributes: \" +\n $B.class_name(obs_attr))\n }\n }\n }\n `\n var name = cls.__name__,\n code = src.replace(/WebComponent/g, name).\n replace(/tag_name/g, tag_name).\n replace(/HTMLElement/, extend_dom_name)\n var src = eval(code)\n var webcomp = eval(name) // JS class for component\n webcomp.$cls = cls\n\n // Override __getattribute__ to handle DOMNode attributes such as\n // attachShadow\n cls.__getattribute__ = function(self, attr){\n try{\n return $B.DOMNode.__getattribute__(self, attr)\n }catch(err){\n if($B.DOMNode[attr]){\n if(typeof $B.DOMNode[attr] == 'function'){\n return function(){\n var args = [self]\n for(var i = 0, len = arguments.length; i < len; i++){\n args.push(arguments[i])\n }\n return $B.DOMNode[attr].apply(null, args)\n }\n }else{\n return $B.DOMNode[attr]\n }\n }\n throw err\n }\n }\n\n var mro = [cls].concat(cls.__mro__).reverse()\n for(var i = 0, len = mro.length; i < len; i++){\n var pcls = mro[i]\n for(var key in pcls){\n if((! webcomp.hasOwnProperty(key)) &&\n typeof pcls[key] == \"function\" &&\n // don't set $factory (would make it a class)\n key !== '$factory'\n ){\n webcomp.prototype[key] = (function(attr, klass){\n return function(){\n try{\n return $B.$call(klass[attr])($B.DOMNode.$factory(this), ...arguments)\n }catch(err){\n $B.show_error(err)\n }\n }\n })(key, pcls)\n }\n }\n }\n\n // define WebComp as the class to use for the specified tag name\n if(_extends){\n customElements.define(tag_name, webcomp, {extends: extend_tag})\n }else{\n customElements.define(tag_name, webcomp)\n }\n webcomp.initialized = true\n}\n\nfunction get(name){\n var ce = customElements.get(name)\n if(ce && ce.$cls){return ce.$cls}\n return _b_.None\n}\n\nvar module = {\n define: define,\n get: get\n}\n\n$B.addToImported('_webcomponent', module)\n\n})(__BRYTHON__)\n"], "_webworker": [".js", "// Web Worker implementation\n\n(function($B){\n\nvar _b_ = $B.builtins\n\nvar VFS = $B.brython_modules ? 'brython_modules' :\n $B.use_VFS ? 'brython_stdlib' : null\n\nfunction scripts_to_load(debug_level){\n if(debug_level > 2){\n var brython_scripts = [\n 'brython_builtins',\n\n 'py_ast_classes',\n 'stdlib_paths',\n 'unicode_data',\n 'version_info',\n\n 'py_tokens',\n 'python_tokenizer',\n 'py_ast',\n 'py2js',\n 'loaders',\n 'py_utils',\n 'py_object',\n 'py_type',\n 'py_builtin_functions',\n 'py_sort',\n 'py_exceptions',\n 'py_range_slice',\n 'py_bytes',\n 'py_set',\n 'py_import',\n 'py_string',\n 'py_int',\n 'py_long_int',\n 'py_float',\n 'py_complex',\n 'py_dict',\n 'py_list',\n 'js_objects',\n 'py_generator',\n 'py_dom',\n 'py_pattern_matching',\n 'async',\n 'py_flags',\n 'builtin_modules',\n 'ast_to_js',\n 'symtable',\n\n 'action_helpers_generated_version',\n 'string_parser',\n 'number_parser',\n 'python_parser_peg_version',\n 'pegen',\n 'gen_parse',\n 'brython_ready'\n ]\n }else{\n var brython_scripts = ['brython']\n }\n\n if(VFS !== null){\n brython_scripts.push(VFS)\n }\n return brython_scripts\n}\n\nvar wclass = $B.make_class(\"Worker\",\n function(worker){\n return {\n __class__: wclass,\n worker\n }\n }\n)\n\nwclass.send = function(){\n var $ = $B.args('send', 2, {self: null, message: null}, ['self', 'message'],\n arguments, {}, 'args', null)\n var message = $B.pyobj2structuredclone($.message)\n return $.self.worker.postMessage(message, ...$.args)\n}\n\nwclass.__mro__ = [$B.JSObj, _b_.object]\n\n$B.set_func_names(wclass, \"browser.worker\")\n\n\nvar _Worker = $B.make_class(\"Worker\", function(id, onmessage, onerror){\n $B.warn(_b_.DeprecationWarning,\n \"worker.Worker is deprecated in version 3.12. \" +\n \"Use worker.create_worker instead\")\n var $ = $B.args(\"__init__\", 3, {id: null, onmessage: null, onerror: null},\n ['id', 'onmessage', 'onerror'], arguments,\n {onmessage: _b_.None, onerror: _b_.None}, null, null),\n id = $.id,\n worker_script = $B.webworkers[id]\n\n if(worker_script === undefined){\n throw _b_.KeyError.$factory(id)\n }\n var filepath = worker_script.src ? worker_script.src : $B.script_path + \"#\" + id,\n filename = $B.strip_host(filepath),\n src = $B.file_cache[filename]\n\n var indexedDB = worker_script.attributes &&\n worker_script.attributes.getNamedItem('indexedDB')\n var script_id = \"worker\" + $B.UUID(),\n filename = $B.script_path + \"#\" + id\n $B.url2name[filename] = script_id\n\n var js = $B.py2js({src, filename}, script_id).to_js(),\n header = '';\n var brython_scripts = scripts_to_load(\n $B.get_option_from_filename('debug', filename))\n brython_scripts.forEach(function(script){\n if(script != VFS || VFS == \"brython_stdlib\"){\n var url = $B.brython_path + script + \".js\"\n }else{\n // attribute $B.brython_modules is set to the path of\n // brython_modules.js by the script itself\n var url = $B.brython_modules\n }\n if(! $B.get_option('cache')){ // cf. issue 1954\n url += '?' + (new Date()).getTime()\n }\n header += 'importScripts(\"' + url + '\")\\n'\n })\n // set __BRYTHON__.imported[script_id]\n header += `\n var $B = __BRYTHON__,\n _b_ = $B.builtins\n var module = $B.module.$factory(\"${script_id}\")\n module.__file__ = \"${filename}\"\n module.__doc__ = _b_.None\n $B.imported[\"${script_id}\"] = module\\n`\n // restore brython_path\n header += `$B.brython_path = \"${$B.brython_path}\"\\n`\n // restore path for imports (cf. issue #1305)\n header += `$B.make_import_paths(\"${filename}\")\\n`\n // Call brython() to initialize internal Brython values\n header += `brython(${JSON.stringify($B.$options)})\\n`\n js = header + js\n js = `try{${js}}catch(err){$B.handle_error(err)}`\n\n var blob = new Blob([js], {type: \"application/js\"}),\n url = URL.createObjectURL(blob),\n w = new Worker(url),\n res = wclass.$factory(w)\n return res\n})\n\nfunction create_worker(){\n var $ = $B.args(\"__init__\", 4,\n {id: null, onready: null, onmessage: null, onerror: null},\n ['id', 'onready', 'onmessage', 'onerror'], arguments,\n {onready: _b_.None, onmessage: _b_.None, onerror: _b_.None},\n null, null),\n id = $.id,\n worker_script = $B.webworkers[id],\n onready = $.onready === _b_.None ? _b_.None : $B.$call($.onready),\n onmessage = $.onmessage === _b_.None ? _b_.None : $B.$call($.onmessage),\n onerror = $.onerror === _b_.None ? _b_.None : $B.$call($.onerror)\n\n if(worker_script === undefined){\n throw _b_.RuntimeError.$factory(`No webworker with id '${id}'`)\n }\n var script_id = \"worker\" + $B.UUID(),\n filepath = worker_script.src ? worker_script.src : $B.script_path + \"#\" + id,\n filename = $B.strip_host(filepath),\n src = $B.file_cache[filename]\n $B.url2name[filename] = script_id\n\n var brython_scripts = scripts_to_load(\n $B.get_option_from_filename('debug', filename))\n\n var js = $B.py2js({src, filename}, script_id).to_js(),\n header = '';\n for(var script of brython_scripts){\n if(script != VFS || VFS == \"brython_stdlib\"){\n var url = $B.brython_path + script + \".js\"\n }else{\n // attribute $B.brython_modules is set to the path of\n // brython_modules.js by the script itself\n var url = $B.brython_modules\n }\n if(! $B.get_option('cache')){ // cf. issue 1954\n url += '?' + (new Date()).getTime()\n }\n header += 'importScripts(\"' + url + '\")\\n'\n }\n // set __BRYTHON__.imported[script_id]\n header += `\n var $B = __BRYTHON__,\n _b_ = $B.builtins\n var module = $B.module.$factory(\"${script_id}\")\n module.__file__ = \"${filename}\"\n module.__doc__ = _b_.None\n $B.script_domain = \"${$B.script_domain}\"\n $B.imported[\"${script_id}\"] = module\\n`\n\n header += '$B.file_cache[module.__file__] = `' + src + '`\\n'\n // restore brython_path\n header += `$B.brython_path = \"${$B.brython_path}\"\\n`\n // inject script attributes to get options\n header += `var script = $B.scripts[\"${filename}\"] = new $B.fakeScript()\\n`\n for(var key in $B.brython_options){\n var value = $B.brython_options[key]\n if(Array.isArray(value)){\n value = `[${value.map(x => '\"' + x + '\"')}]`\n }else{\n value = `\"${value}\"`\n }\n header += `script.options[\"${key}\"] = ${value}\\n`\n }\n\n for(var attr of worker_script.attributes){\n header += `script.options[\"${attr.name}\"] = \"${attr.value}\"\\n`\n }\n\n // restore path for imports (cf. issue #1305)\n header += `$B.make_import_paths(\"${filename}\")\\n`\n\n // Call brython() to initialize internal Brython values\n var save_option = JSON.stringify($B.brython_options)\n header += `brython(${save_option})\\n`\n\n // send dummy message to trigger resolution of Promise\n var ok_token = Math.random().toString(36).substr(2, 8),\n error_token = Math.random().toString(36).substr(2, 8)\n\n // open indexedDB cache before running worker code\n js = `$B.idb_open_promise().then(function(){\\n` +\n `try{\\n` +\n `${js}\\n` +\n `self.postMessage('${ok_token}')\\n` +\n `}catch(err){\\n` +\n `self.postMessage('${error_token}Error in worker \"${id}\"\\\\n'` +\n ` + $B.error_trace(err))\\n` +\n `}\\n})`\n js = header + js\n\n var p = new Promise(function(resolve, reject){\n try{\n var blob = new Blob([js], {type: \"application/js\"}),\n url = URL.createObjectURL(blob),\n w = new Worker(url),\n res = wclass.$factory(w)\n }catch(err){\n reject(err)\n }\n\n w.onmessage = function(ev){\n if(ev.data == ok_token){\n resolve(res)\n }else if(typeof ev.data == 'string' &&\n ev.data.startsWith(error_token)){\n reject(_b_.Exception.$factory(ev.data.substr(error_token.length)))\n }else{\n if(onmessage !== _b_.None){\n onmessage(ev)\n }\n try{\n resolve(res)\n }catch(err){\n reject(err)\n }\n }\n }\n\n return res\n })\n\n var error_func = onerror === _b_.None ? $B.handle_error : onerror\n\n if(onready !== _b_.None){\n p.then(onready).catch(error_func)\n }else{\n p.catch(error_func)\n }\n return _b_.None\n}\n\nvar module = {\n Worker: _Worker,\n create_worker\n}\n\n$B.addToImported('_webworker', module)\n\n})(__BRYTHON__)\n"], "_zlib_utils": [".js", "\n\n(function($B){\n\nfunction Text(bytes){\n this.bytes = bytes\n this.length = bytes.length\n this.hash = {} // this.hash[pos] is the hash of the 3-elt sequence at pos\n this.hash_pos = {} // maps hashes to list of positions in bytes\n this.hash_start = -1\n}\n\nText.prototype.at = function(pos){\n return this.bytes[pos]\n}\n\nText.prototype.make_hashes = function(start, end){\n // for all 3-elt sequences from start to end, store the position of the\n // hash\n for(var pos = start; pos < end; pos++){\n if(this.hash.hasOwnProperty(pos)){\n continue\n }\n var hash = this.hash[pos] = this.make_hash(pos)\n if(pos == 27){\n console.log('hash for pos', pos)\n console.log(this.hash_pos[hash])\n alert()\n }\n if(this.hash_pos.hasOwnProperty(hash)){\n var item = this.hash_pos[hash]\n while(item.next !== null){\n item = item.next\n }\n item.next = {pos, next: null}\n }else{\n this.hash_pos[hash] = {pos, next: null}\n\n }\n }\n if(end == 28){\n console.log('start', start, 'end', end)\n console.log(this.hash_pos)\n alert()\n }\n}\n\nText.prototype.make_hash = function(pos){\n return this.at(pos) +\n (this.at(pos + 1) << 8) +\n (this.at(pos + 2) << 16)\n}\n\nfunction HashChain(value, pointer){\n // points to the first position in text where hash == value\n this.pointer = pointer\n}\n\nfunction rfind1(text, start, end, seq){\n // find seq in text starting at start\n var pos = start,\n len = seq.length,\n found\n while(pos < end - len){\n if(text[pos] == seq[0]){\n found = true\n for(var i = 1; i < len; i++){\n if(text[pos + i] != seq[i]){\n found = false\n break\n }\n }\n if(found){\n return pos\n }\n }\n pos++\n }\n return -1\n}\n\nfunction rfind2(text, start, pos){\n //text.make_hashes(start, pos)\n var h = text.make_hash(pos)\n if(! text.hash_pos.hasOwnProperty(h)){\n // hash was not found\n text.hash_pos[h] = {pos, next: null}\n return -1\n }else{\n var item = text.hash_pos[h]\n // discard items before start\n while(item.pos < start){\n if(item.next !== null){\n item = item.next\n text.hash_pos[h] = item\n }else{\n // no item found after start\n text.hash_pos[h] = {pos, next: null}\n return -1\n }\n }\n var found_at = item.pos\n while(item.next !== null){\n item = item.next\n }\n item.next = {pos, next: null}\n return found_at\n }\n}\n\nfunction rfind(buf, seq){\n var buflen = buf.length,\n len = seq.length\n for(var i = buflen - len; i >= 0; i--){\n var chunk = buf.slice(i, i + len),\n found = true\n for(var j = 0; j < len; j++){\n if(chunk[j] != seq[j]){\n found = false\n break\n }\n }\n if(found){\n return i\n }\n }\n return -1\n}\n\nfunction to_str(bytes){\n return bytes.map(x => String.fromCodePoint(x)).join('')\n}\n\nfunction restore(items){\n var s = ''\n for(var item of items){\n if(typeof item == \"number\"){\n s += String.fromCodePoint(item)\n }else{\n var len = item[0],\n distance = item[1]\n s += s.substr(s.length - distance, len)\n }\n }\n return s\n}\n\nvar c;\nvar crcTable = [];\nfor(var n =0; n < 256; n++){\n c = n;\n for(var k =0; k < 8; k++){\n c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n}\n\nvar mod = {\n crc32: function(bytes, crc) {\n var crc = crc ^ (-1);\n\n for (var byte of bytes.source) {\n crc = (crc >>> 8) ^ crcTable[(crc ^ byte) & 0xFF];\n }\n\n return (crc ^ (-1)) >>> 0;\n },\n\n lz_generator: function(text, size, min_len){\n /*\n Returns a list of items based on the LZ algorithm, using the\n specified window size and a minimum match length.\n The items are a tuple (length, distance) if a match has been\n found, and a byte otherwise.\n */\n // 'text' is an instance of Python 'bytes' class, the actual\n // bytes are in text.source\n text = new Text(text.source)\n if(min_len === undefined){\n min_len = 3\n }\n var pos = 0, // position in text\n items = [], // returned items\n start\n var t0 = globalThis.performance.now()\n var nb = 1000,\n delta = 1000\n while(pos < text.length){\n if(pos > text.length - min_len){\n for(var i = pos; i < text.length; i++){\n items.push(text.at(i))\n }\n break\n }\n // Search the sequence in the 'size' previous bytes\n start = Math.max(0, pos - size)\n buf_pos = rfind2(text, start, pos)\n if(buf_pos > -1 && buf_pos < pos - min_len){\n // Match of length 3 found; search a longer one\n var len = 1\n while(len < 258 &&\n buf_pos + len < pos &&\n pos + len < text.length &&\n text.at(pos + len) == text.at(buf_pos + len)){\n len += 1\n }\n // \"Lazy matching\": search longer match starting at next\n // position\n longer_match = false\n if(pos + len < text.length - 2){\n // match2 = text.slice(pos + 1, pos + len + 2)\n var start1 = pos + 1\n end = pos + len + 2\n longer_buf_pos = rfind2(text, start1, end)\n if(longer_buf_pos > -1){\n // found longer match : emit current byte as\n // literal and move 1 byte forward\n longer_match = true\n char = text.at(pos)\n items.push(char)\n pos += 1\n }\n }\n if(! longer_match){\n // position of match start in text is buf_pos\n // distance is pos - buf_pos\n var distance = pos - buf_pos\n items.push($B.fast_tuple([len, distance]))\n if(pos + len == text.length){\n break\n }else{\n pos += len\n items.push(text.at(pos))\n pos += 1\n }\n }\n }else{\n char = text.bytes[pos]\n items.push(char)\n pos += 1\n }\n }\n return $B.$list(items)\n }\n\n}\n\n$B.addToImported('_zlib_utils', mod)\n\n})(__BRYTHON__)\n"], "crypto_js": [".py", "", [], 1], "crypto_js.rollups": [".py", "", [], 1], "crypto_js.rollups.md5": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(s,p){var m={},l=m.lib={},n=function(){},r=l.Base={extend:function(b){n.prototype=this;var h=new n;b&&h.mixIn(b);h.hasOwnProperty(\"init\")||(h.init=function(){h.$super.init.apply(this,arguments)});h.init.prototype=h;h.$super=this;return h},create:function(){var b=this.extend();b.init.apply(b,arguments);return b},init:function(){},mixIn:function(b){for(var h in b)b.hasOwnProperty(h)&&(this[h]=b[h]);b.hasOwnProperty(\"toString\")&&(this.toString=b.toString)},clone:function(){return this.init.prototype.extend(this)}},\nq=l.WordArray=r.extend({init:function(b,h){b=this.words=b||[];this.sigBytes=h!=p?h:4*b.length},toString:function(b){return(b||t).stringify(this)},concat:function(b){var h=this.words,a=b.words,j=this.sigBytes;b=b.sigBytes;this.clamp();if(j%4)for(var g=0;g>>2]|=(a[g>>>2]>>>24-8*(g%4)&255)<<24-8*((j+g)%4);else if(65535>>2]=a[g>>>2];else h.push.apply(h,a);this.sigBytes+=b;return this},clamp:function(){var b=this.words,h=this.sigBytes;b[h>>>2]&=4294967295<<\n32-8*(h%4);b.length=s.ceil(h/4)},clone:function(){var b=r.clone.call(this);b.words=this.words.slice(0);return b},random:function(b){for(var h=[],a=0;a>>2]>>>24-8*(j%4)&255;g.push((k>>>4).toString(16));g.push((k&15).toString(16))}return g.join(\"\")},parse:function(b){for(var a=b.length,g=[],j=0;j>>3]|=parseInt(b.substr(j,\n2),16)<<24-4*(j%8);return new q.init(g,a/2)}},a=v.Latin1={stringify:function(b){var a=b.words;b=b.sigBytes;for(var g=[],j=0;j>>2]>>>24-8*(j%4)&255));return g.join(\"\")},parse:function(b){for(var a=b.length,g=[],j=0;j>>2]|=(b.charCodeAt(j)&255)<<24-8*(j%4);return new q.init(g,a)}},u=v.Utf8={stringify:function(b){try{return decodeURIComponent(escape(a.stringify(b)))}catch(g){throw Error(\"Malformed UTF-8 data\");}},parse:function(b){return a.parse(unescape(encodeURIComponent(b)))}},\ng=l.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(b){\"string\"==typeof b&&(b=u.parse(b));this._data.concat(b);this._nDataBytes+=b.sigBytes},_process:function(b){var a=this._data,g=a.words,j=a.sigBytes,k=this.blockSize,m=j/(4*k),m=b?s.ceil(m):s.max((m|0)-this._minBufferSize,0);b=m*k;j=s.min(4*b,j);if(b){for(var l=0;l>>32-j)+k}function m(a,k,b,h,l,j,m){a=a+(k&h|b&~h)+l+m;return(a<>>32-j)+k}function l(a,k,b,h,l,j,m){a=a+(k^b^h)+l+m;return(a<>>32-j)+k}function n(a,k,b,h,l,j,m){a=a+(b^(k|~h))+l+m;return(a<>>32-j)+k}for(var r=CryptoJS,q=r.lib,v=q.WordArray,t=q.Hasher,q=r.algo,a=[],u=0;64>u;u++)a[u]=4294967296*s.abs(s.sin(u+1))|0;q=q.MD5=t.extend({_doReset:function(){this._hash=new v.init([1732584193,4023233417,2562383102,271733878])},\n_doProcessBlock:function(g,k){for(var b=0;16>b;b++){var h=k+b,w=g[h];g[h]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}var b=this._hash.words,h=g[k+0],w=g[k+1],j=g[k+2],q=g[k+3],r=g[k+4],s=g[k+5],t=g[k+6],u=g[k+7],v=g[k+8],x=g[k+9],y=g[k+10],z=g[k+11],A=g[k+12],B=g[k+13],C=g[k+14],D=g[k+15],c=b[0],d=b[1],e=b[2],f=b[3],c=p(c,d,e,f,h,7,a[0]),f=p(f,c,d,e,w,12,a[1]),e=p(e,f,c,d,j,17,a[2]),d=p(d,e,f,c,q,22,a[3]),c=p(c,d,e,f,r,7,a[4]),f=p(f,c,d,e,s,12,a[5]),e=p(e,f,c,d,t,17,a[6]),d=p(d,e,f,c,u,22,a[7]),\nc=p(c,d,e,f,v,7,a[8]),f=p(f,c,d,e,x,12,a[9]),e=p(e,f,c,d,y,17,a[10]),d=p(d,e,f,c,z,22,a[11]),c=p(c,d,e,f,A,7,a[12]),f=p(f,c,d,e,B,12,a[13]),e=p(e,f,c,d,C,17,a[14]),d=p(d,e,f,c,D,22,a[15]),c=m(c,d,e,f,w,5,a[16]),f=m(f,c,d,e,t,9,a[17]),e=m(e,f,c,d,z,14,a[18]),d=m(d,e,f,c,h,20,a[19]),c=m(c,d,e,f,s,5,a[20]),f=m(f,c,d,e,y,9,a[21]),e=m(e,f,c,d,D,14,a[22]),d=m(d,e,f,c,r,20,a[23]),c=m(c,d,e,f,x,5,a[24]),f=m(f,c,d,e,C,9,a[25]),e=m(e,f,c,d,q,14,a[26]),d=m(d,e,f,c,v,20,a[27]),c=m(c,d,e,f,B,5,a[28]),f=m(f,c,\nd,e,j,9,a[29]),e=m(e,f,c,d,u,14,a[30]),d=m(d,e,f,c,A,20,a[31]),c=l(c,d,e,f,s,4,a[32]),f=l(f,c,d,e,v,11,a[33]),e=l(e,f,c,d,z,16,a[34]),d=l(d,e,f,c,C,23,a[35]),c=l(c,d,e,f,w,4,a[36]),f=l(f,c,d,e,r,11,a[37]),e=l(e,f,c,d,u,16,a[38]),d=l(d,e,f,c,y,23,a[39]),c=l(c,d,e,f,B,4,a[40]),f=l(f,c,d,e,h,11,a[41]),e=l(e,f,c,d,q,16,a[42]),d=l(d,e,f,c,t,23,a[43]),c=l(c,d,e,f,x,4,a[44]),f=l(f,c,d,e,A,11,a[45]),e=l(e,f,c,d,D,16,a[46]),d=l(d,e,f,c,j,23,a[47]),c=n(c,d,e,f,h,6,a[48]),f=n(f,c,d,e,u,10,a[49]),e=n(e,f,c,d,\nC,15,a[50]),d=n(d,e,f,c,s,21,a[51]),c=n(c,d,e,f,A,6,a[52]),f=n(f,c,d,e,q,10,a[53]),e=n(e,f,c,d,y,15,a[54]),d=n(d,e,f,c,w,21,a[55]),c=n(c,d,e,f,v,6,a[56]),f=n(f,c,d,e,D,10,a[57]),e=n(e,f,c,d,t,15,a[58]),d=n(d,e,f,c,B,21,a[59]),c=n(c,d,e,f,r,6,a[60]),f=n(f,c,d,e,z,10,a[61]),e=n(e,f,c,d,j,15,a[62]),d=n(d,e,f,c,x,21,a[63]);b[0]=b[0]+c|0;b[1]=b[1]+d|0;b[2]=b[2]+e|0;b[3]=b[3]+f|0},_doFinalize:function(){var a=this._data,k=a.words,b=8*this._nDataBytes,h=8*a.sigBytes;k[h>>>5]|=128<<24-h%32;var l=s.floor(b/\n4294967296);k[(h+64>>>9<<4)+15]=(l<<8|l>>>24)&16711935|(l<<24|l>>>8)&4278255360;k[(h+64>>>9<<4)+14]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;a.sigBytes=4*(k.length+1);this._process();a=this._hash;k=a.words;for(b=0;4>b;b++)h=k[b],k[b]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360;return a},clone:function(){var a=t.clone.call(this);a._hash=this._hash.clone();return a}});r.MD5=t._createHelper(q);r.HmacMD5=t._createHmacHelper(q)})(Math);\n"], "crypto_js.rollups.sha1": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(e,m){var p={},j=p.lib={},l=function(){},f=j.Base={extend:function(a){l.prototype=this;var c=new l;a&&c.mixIn(a);c.hasOwnProperty(\"init\")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\nn=j.WordArray=f.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=m?c:4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var c=this.words,q=a.words,d=this.sigBytes;a=a.sigBytes;this.clamp();if(d%4)for(var b=0;b>>2]|=(q[b>>>2]>>>24-8*(b%4)&255)<<24-8*((d+b)%4);else if(65535>>2]=q[b>>>2];else c.push.apply(c,q);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<\n32-8*(c%4);a.length=e.ceil(c/4)},clone:function(){var a=f.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b>>2]>>>24-8*(d%4)&255;b.push((f>>>4).toString(16));b.push((f&15).toString(16))}return b.join(\"\")},parse:function(a){for(var c=a.length,b=[],d=0;d>>3]|=parseInt(a.substr(d,\n2),16)<<24-4*(d%8);return new n.init(b,c/2)}},g=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],d=0;d>>2]>>>24-8*(d%4)&255));return b.join(\"\")},parse:function(a){for(var c=a.length,b=[],d=0;d>>2]|=(a.charCodeAt(d)&255)<<24-8*(d%4);return new n.init(b,c)}},r=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(g.stringify(a)))}catch(c){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return g.parse(unescape(encodeURIComponent(a)))}},\nk=j.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new n.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=r.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,b=c.words,d=c.sigBytes,f=this.blockSize,h=d/(4*f),h=a?e.ceil(h):e.max((h|0)-this._minBufferSize,0);a=h*f;d=e.min(4*a,d);if(a){for(var g=0;ga;a++){if(16>a)l[a]=f[n+a]|0;else{var c=l[a-3]^l[a-8]^l[a-14]^l[a-16];l[a]=c<<1|c>>>31}c=(h<<5|h>>>27)+j+l[a];c=20>a?c+((g&e|~g&k)+1518500249):40>a?c+((g^e^k)+1859775393):60>a?c+((g&e|g&k|e&k)-1894007588):c+((g^e^\nk)-899497514);j=k;k=e;e=g<<30|g>>>2;g=h;h=c}b[0]=b[0]+h|0;b[1]=b[1]+g|0;b[2]=b[2]+e|0;b[3]=b[3]+k|0;b[4]=b[4]+j|0},_doFinalize:function(){var f=this._data,e=f.words,b=8*this._nDataBytes,h=8*f.sigBytes;e[h>>>5]|=128<<24-h%32;e[(h+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(h+64>>>9<<4)+15]=b;f.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=j.clone.call(this);e._hash=this._hash.clone();return e}});e.SHA1=j._createHelper(m);e.HmacSHA1=j._createHmacHelper(m)})();\n"], "crypto_js.rollups.sha224": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(g,l){var f={},k=f.lib={},h=function(){},m=k.Base={extend:function(a){h.prototype=this;var c=new h;a&&c.mixIn(a);c.hasOwnProperty(\"init\")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\nq=k.WordArray=m.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=l?c:4*a.length},toString:function(a){return(a||s).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<\n32-8*(c%4);a.length=g.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join(\"\")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b,\n2),16)<<24-4*(b%8);return new q.init(d,c/2)}},n=t.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join(\"\")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new q.init(d,c)}},j=t.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}},\nw=k.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?g.ceil(f):g.max((f|0)-this._minBufferSize,0);a=f*e;b=g.min(4*a,b);if(a){for(var u=0;un;){var j;a:{j=s;for(var w=g.sqrt(j),v=2;v<=w;v++)if(!(j%v)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=t(g.pow(s,0.5))),q[n]=t(g.pow(s,1/3)),n++);s++}var a=[],f=f.SHA256=h.extend({_doReset:function(){this._hash=new k.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],k=b[3],h=b[4],l=b[5],m=b[6],n=b[7],p=0;64>p;p++){if(16>p)a[p]=\nc[d+p]|0;else{var j=a[p-15],r=a[p-2];a[p]=((j<<25|j>>>7)^(j<<14|j>>>18)^j>>>3)+a[p-7]+((r<<15|r>>>17)^(r<<13|r>>>19)^r>>>10)+a[p-16]}j=n+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&l^~h&m)+q[p]+a[p];r=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);n=m;m=l;l=h;h=k+j|0;k=g;g=f;f=e;e=j+r|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+k|0;b[4]=b[4]+h|0;b[5]=b[5]+l|0;b[6]=b[6]+m|0;b[7]=b[7]+n|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes;\nd[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=g.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=h.clone.call(this);a._hash=this._hash.clone();return a}});l.SHA256=h._createHelper(f);l.HmacSHA256=h._createHmacHelper(f)})(Math);\n(function(){var g=CryptoJS,l=g.lib.WordArray,f=g.algo,k=f.SHA256,f=f.SHA224=k.extend({_doReset:function(){this._hash=new l.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var f=k._doFinalize.call(this);f.sigBytes-=4;return f}});g.SHA224=k._createHelper(f);g.HmacSHA224=k._createHmacHelper(f)})();\n"], "crypto_js.rollups.sha256": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(h,s){var f={},t=f.lib={},g=function(){},j=t.Base={extend:function(a){g.prototype=this;var c=new g;a&&c.mixIn(a);c.hasOwnProperty(\"init\")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\nq=t.WordArray=j.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=s?c:4*a.length},toString:function(a){return(a||u).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<\n32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=j.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join(\"\")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b,\n2),16)<<24-4*(b%8);return new q.init(d,c/2)}},k=v.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join(\"\")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new q.init(d,c)}},l=v.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch(c){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}},\nx=t.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=l.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var m=0;mk;){var l;a:{l=u;for(var x=h.sqrt(l),w=2;w<=x;w++)if(!(l%w)){l=!1;break a}l=!0}l&&(8>k&&(j[k]=v(h.pow(u,0.5))),q[k]=v(h.pow(u,1/3)),k++);u++}var a=[],f=f.SHA256=g.extend({_doReset:function(){this._hash=new t.init(j.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],m=b[2],h=b[3],p=b[4],j=b[5],k=b[6],l=b[7],n=0;64>n;n++){if(16>n)a[n]=\nc[d+n]|0;else{var r=a[n-15],g=a[n-2];a[n]=((r<<25|r>>>7)^(r<<14|r>>>18)^r>>>3)+a[n-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+a[n-16]}r=l+((p<<26|p>>>6)^(p<<21|p>>>11)^(p<<7|p>>>25))+(p&j^~p&k)+q[n]+a[n];g=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&m^f&m);l=k;k=j;j=p;p=h+r|0;h=m;m=f;f=e;e=r+g|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+m|0;b[3]=b[3]+h|0;b[4]=b[4]+p|0;b[5]=b[5]+j|0;b[6]=b[6]+k|0;b[7]=b[7]+l|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes;\nd[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=g.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=g._createHelper(f);s.HmacSHA256=g._createHmacHelper(f)})(Math);\n"], "crypto_js.rollups.sha3": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(v,p){var d={},u=d.lib={},r=function(){},f=u.Base={extend:function(a){r.prototype=this;var b=new r;a&&b.mixIn(a);b.hasOwnProperty(\"init\")||(b.init=function(){b.$super.init.apply(this,arguments)});b.init.prototype=b;b.$super=this;return b},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\ns=u.WordArray=f.extend({init:function(a,b){a=this.words=a||[];this.sigBytes=b!=p?b:4*a.length},toString:function(a){return(a||y).stringify(this)},concat:function(a){var b=this.words,c=a.words,j=this.sigBytes;a=a.sigBytes;this.clamp();if(j%4)for(var n=0;n>>2]|=(c[n>>>2]>>>24-8*(n%4)&255)<<24-8*((j+n)%4);else if(65535>>2]=c[n>>>2];else b.push.apply(b,c);this.sigBytes+=a;return this},clamp:function(){var a=this.words,b=this.sigBytes;a[b>>>2]&=4294967295<<\n32-8*(b%4);a.length=v.ceil(b/4)},clone:function(){var a=f.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var b=[],c=0;c>>2]>>>24-8*(j%4)&255;c.push((n>>>4).toString(16));c.push((n&15).toString(16))}return c.join(\"\")},parse:function(a){for(var b=a.length,c=[],j=0;j>>3]|=parseInt(a.substr(j,\n2),16)<<24-4*(j%8);return new s.init(c,b/2)}},e=x.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var c=[],j=0;j>>2]>>>24-8*(j%4)&255));return c.join(\"\")},parse:function(a){for(var b=a.length,c=[],j=0;j>>2]|=(a.charCodeAt(j)&255)<<24-8*(j%4);return new s.init(c,b)}},q=x.Utf8={stringify:function(a){try{return decodeURIComponent(escape(e.stringify(a)))}catch(b){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return e.parse(unescape(encodeURIComponent(a)))}},\nt=u.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new s.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=q.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,c=b.words,j=b.sigBytes,n=this.blockSize,e=j/(4*n),e=a?v.ceil(e):v.max((e|0)-this._minBufferSize,0);a=e*n;j=v.min(4*a,j);if(a){for(var f=0;ft;t++){s[e+5*q]=(t+1)*(t+2)/2%64;var w=(2*e+3*q)%5,e=q%5,q=w}for(e=0;5>e;e++)for(q=0;5>q;q++)x[e+5*q]=q+5*((2*e+3*q)%5);e=1;for(q=0;24>q;q++){for(var a=w=t=0;7>a;a++){if(e&1){var b=(1<b?w^=1<e;e++)c[e]=f.create();d=d.SHA3=r.extend({cfg:r.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=\n[],b=0;25>b;b++)a[b]=new f.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var e=this._state,f=this.blockSize/2,h=0;h>>24)&16711935|(l<<24|l>>>8)&4278255360,m=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360,g=e[h];g.high^=m;g.low^=l}for(f=0;24>f;f++){for(h=0;5>h;h++){for(var d=l=0,k=0;5>k;k++)g=e[h+5*k],l^=g.high,d^=g.low;g=c[h];g.high=l;g.low=d}for(h=0;5>h;h++){g=c[(h+4)%5];l=c[(h+1)%5];m=l.high;k=l.low;l=g.high^\n(m<<1|k>>>31);d=g.low^(k<<1|m>>>31);for(k=0;5>k;k++)g=e[h+5*k],g.high^=l,g.low^=d}for(m=1;25>m;m++)g=e[m],h=g.high,g=g.low,k=s[m],32>k?(l=h<>>32-k,d=g<>>32-k):(l=g<>>64-k,d=h<>>64-k),g=c[x[m]],g.high=l,g.low=d;g=c[0];h=e[0];g.high=h.high;g.low=h.low;for(h=0;5>h;h++)for(k=0;5>k;k++)m=h+5*k,g=e[m],l=c[m],m=c[(h+1)%5+5*k],d=c[(h+2)%5+5*k],g.high=l.high^~m.high&d.high,g.low=l.low^~m.low&d.low;g=e[0];h=y[f];g.high^=h.high;g.low^=h.low}},_doFinalize:function(){var a=this._data,\nb=a.words,c=8*a.sigBytes,e=32*this.blockSize;b[c>>>5]|=1<<24-c%32;b[(v.ceil((c+1)/e)*e>>>5)-1]|=128;a.sigBytes=4*b.length;this._process();for(var a=this._state,b=this.cfg.outputLength/8,c=b/8,e=[],h=0;h>>24)&16711935|(f<<24|f>>>8)&4278255360,d=(d<<8|d>>>24)&16711935|(d<<24|d>>>8)&4278255360;e.push(d);e.push(f)}return new u.init(e,b)},clone:function(){for(var a=r.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});\np.SHA3=r._createHelper(d);p.HmacSHA3=r._createHmacHelper(d)})(Math);\n"], "crypto_js.rollups.sha384": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(a,c){var d={},j=d.lib={},f=function(){},m=j.Base={extend:function(a){f.prototype=this;var b=new f;a&&b.mixIn(a);b.hasOwnProperty(\"init\")||(b.init=function(){b.$super.init.apply(this,arguments)});b.init.prototype=b;b.$super=this;return b},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\nB=j.WordArray=m.extend({init:function(a,b){a=this.words=a||[];this.sigBytes=b!=c?b:4*a.length},toString:function(a){return(a||y).stringify(this)},concat:function(a){var b=this.words,g=a.words,e=this.sigBytes;a=a.sigBytes;this.clamp();if(e%4)for(var k=0;k>>2]|=(g[k>>>2]>>>24-8*(k%4)&255)<<24-8*((e+k)%4);else if(65535>>2]=g[k>>>2];else b.push.apply(b,g);this.sigBytes+=a;return this},clamp:function(){var n=this.words,b=this.sigBytes;n[b>>>2]&=4294967295<<\n32-8*(b%4);n.length=a.ceil(b/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(n){for(var b=[],g=0;g>>2]>>>24-8*(e%4)&255;g.push((k>>>4).toString(16));g.push((k&15).toString(16))}return g.join(\"\")},parse:function(a){for(var b=a.length,g=[],e=0;e>>3]|=parseInt(a.substr(e,\n2),16)<<24-4*(e%8);return new B.init(g,b/2)}},F=v.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var g=[],e=0;e>>2]>>>24-8*(e%4)&255));return g.join(\"\")},parse:function(a){for(var b=a.length,g=[],e=0;e>>2]|=(a.charCodeAt(e)&255)<<24-8*(e%4);return new B.init(g,b)}},ha=v.Utf8={stringify:function(a){try{return decodeURIComponent(escape(F.stringify(a)))}catch(b){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return F.parse(unescape(encodeURIComponent(a)))}},\nZ=j.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new B.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=ha.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(n){var b=this._data,g=b.words,e=b.sigBytes,k=this.blockSize,m=e/(4*k),m=n?a.ceil(m):a.max((m|0)-this._minBufferSize,0);n=m*k;e=a.min(4*n,e);if(n){for(var c=0;cy;y++)v[y]=a();j=j.SHA512=d.extend({_doReset:function(){this._hash=new m.init([new f.init(1779033703,4089235720),new f.init(3144134277,2227873595),new f.init(1013904242,4271175723),new f.init(2773480762,1595750129),new f.init(1359893119,2917565137),new f.init(2600822924,725511199),new f.init(528734635,4215389547),new f.init(1541459225,327033209)])},_doProcessBlock:function(a,c){for(var d=this._hash.words,\nf=d[0],j=d[1],b=d[2],g=d[3],e=d[4],k=d[5],m=d[6],d=d[7],y=f.high,M=f.low,$=j.high,N=j.low,aa=b.high,O=b.low,ba=g.high,P=g.low,ca=e.high,Q=e.low,da=k.high,R=k.low,ea=m.high,S=m.low,fa=d.high,T=d.low,s=y,p=M,G=$,D=N,H=aa,E=O,W=ba,I=P,t=ca,q=Q,U=da,J=R,V=ea,K=S,X=fa,L=T,u=0;80>u;u++){var z=v[u];if(16>u)var r=z.high=a[c+2*u]|0,h=z.low=a[c+2*u+1]|0;else{var r=v[u-15],h=r.high,w=r.low,r=(h>>>1|w<<31)^(h>>>8|w<<24)^h>>>7,w=(w>>>1|h<<31)^(w>>>8|h<<24)^(w>>>7|h<<25),C=v[u-2],h=C.high,l=C.low,C=(h>>>19|l<<\n13)^(h<<3|l>>>29)^h>>>6,l=(l>>>19|h<<13)^(l<<3|h>>>29)^(l>>>6|h<<26),h=v[u-7],Y=h.high,A=v[u-16],x=A.high,A=A.low,h=w+h.low,r=r+Y+(h>>>0>>0?1:0),h=h+l,r=r+C+(h>>>0>>0?1:0),h=h+A,r=r+x+(h>>>0>>0?1:0);z.high=r;z.low=h}var Y=t&U^~t&V,A=q&J^~q&K,z=s&G^s&H^G&H,ja=p&D^p&E^D&E,w=(s>>>28|p<<4)^(s<<30|p>>>2)^(s<<25|p>>>7),C=(p>>>28|s<<4)^(p<<30|s>>>2)^(p<<25|s>>>7),l=B[u],ka=l.high,ga=l.low,l=L+((q>>>14|t<<18)^(q>>>18|t<<14)^(q<<23|t>>>9)),x=X+((t>>>14|q<<18)^(t>>>18|q<<14)^(t<<23|q>>>9))+(l>>>0<\nL>>>0?1:0),l=l+A,x=x+Y+(l>>>0>>0?1:0),l=l+ga,x=x+ka+(l>>>0>>0?1:0),l=l+h,x=x+r+(l>>>0>>0?1:0),h=C+ja,z=w+z+(h>>>0>>0?1:0),X=V,L=K,V=U,K=J,U=t,J=q,q=I+l|0,t=W+x+(q>>>0>>0?1:0)|0,W=H,I=E,H=G,E=D,G=s,D=p,p=l+h|0,s=x+z+(p>>>0>>0?1:0)|0}M=f.low=M+p;f.high=y+s+(M>>>0

>>0?1:0);N=j.low=N+D;j.high=$+G+(N>>>0>>0?1:0);O=b.low=O+E;b.high=aa+H+(O>>>0>>0?1:0);P=g.low=P+I;g.high=ba+W+(P>>>0>>0?1:0);Q=e.low=Q+q;e.high=ca+t+(Q>>>0>>0?1:0);R=k.low=R+J;k.high=da+U+(R>>>0>>0?1:0);\nS=m.low=S+K;m.high=ea+V+(S>>>0>>0?1:0);T=d.low=T+L;d.high=fa+X+(T>>>0>>0?1:0)},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,f=8*a.sigBytes;c[f>>>5]|=128<<24-f%32;c[(f+128>>>10<<5)+30]=Math.floor(d/4294967296);c[(f+128>>>10<<5)+31]=d;a.sigBytes=4*c.length;this._process();return this._hash.toX32()},clone:function(){var a=d.clone.call(this);a._hash=this._hash.clone();return a},blockSize:32});c.SHA512=d._createHelper(j);c.HmacSHA512=d._createHmacHelper(j)})();\n(function(){var a=CryptoJS,c=a.x64,d=c.Word,j=c.WordArray,c=a.algo,f=c.SHA512,c=c.SHA384=f.extend({_doReset:function(){this._hash=new j.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=f._doFinalize.call(this);a.sigBytes-=16;return a}});a.SHA384=\nf._createHelper(c);a.HmacSHA384=f._createHmacHelper(c)})();\n"], "crypto_js.rollups.sha512": [".js", "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto-js/wiki/License\n*/\nvar CryptoJS=CryptoJS||function(a,m){var r={},f=r.lib={},g=function(){},l=f.Base={extend:function(a){g.prototype=this;var b=new g;a&&b.mixIn(a);b.hasOwnProperty(\"init\")||(b.init=function(){b.$super.init.apply(this,arguments)});b.init.prototype=b;b.$super=this;return b},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty(\"toString\")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},\np=f.WordArray=l.extend({init:function(a,b){a=this.words=a||[];this.sigBytes=b!=m?b:4*a.length},toString:function(a){return(a||q).stringify(this)},concat:function(a){var b=this.words,d=a.words,c=this.sigBytes;a=a.sigBytes;this.clamp();if(c%4)for(var j=0;j>>2]|=(d[j>>>2]>>>24-8*(j%4)&255)<<24-8*((c+j)%4);else if(65535>>2]=d[j>>>2];else b.push.apply(b,d);this.sigBytes+=a;return this},clamp:function(){var n=this.words,b=this.sigBytes;n[b>>>2]&=4294967295<<\n32-8*(b%4);n.length=a.ceil(b/4)},clone:function(){var a=l.clone.call(this);a.words=this.words.slice(0);return a},random:function(n){for(var b=[],d=0;d>>2]>>>24-8*(c%4)&255;d.push((j>>>4).toString(16));d.push((j&15).toString(16))}return d.join(\"\")},parse:function(a){for(var b=a.length,d=[],c=0;c>>3]|=parseInt(a.substr(c,\n2),16)<<24-4*(c%8);return new p.init(d,b/2)}},G=y.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var d=[],c=0;c>>2]>>>24-8*(c%4)&255));return d.join(\"\")},parse:function(a){for(var b=a.length,d=[],c=0;c>>2]|=(a.charCodeAt(c)&255)<<24-8*(c%4);return new p.init(d,b)}},fa=y.Utf8={stringify:function(a){try{return decodeURIComponent(escape(G.stringify(a)))}catch(b){throw Error(\"Malformed UTF-8 data\");}},parse:function(a){return G.parse(unescape(encodeURIComponent(a)))}},\nh=f.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new p.init;this._nDataBytes=0},_append:function(a){\"string\"==typeof a&&(a=fa.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(n){var b=this._data,d=b.words,c=b.sigBytes,j=this.blockSize,l=c/(4*j),l=n?a.ceil(l):a.max((l|0)-this._minBufferSize,0);n=l*j;c=a.min(4*n,c);if(n){for(var h=0;hq;q++)y[q]=a();f=f.SHA512=r.extend({_doReset:function(){this._hash=new l.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,f){for(var h=this._hash.words,\ng=h[0],n=h[1],b=h[2],d=h[3],c=h[4],j=h[5],l=h[6],h=h[7],q=g.high,m=g.low,r=n.high,N=n.low,Z=b.high,O=b.low,$=d.high,P=d.low,aa=c.high,Q=c.low,ba=j.high,R=j.low,ca=l.high,S=l.low,da=h.high,T=h.low,v=q,s=m,H=r,E=N,I=Z,F=O,W=$,J=P,w=aa,t=Q,U=ba,K=R,V=ca,L=S,X=da,M=T,x=0;80>x;x++){var B=y[x];if(16>x)var u=B.high=a[f+2*x]|0,e=B.low=a[f+2*x+1]|0;else{var u=y[x-15],e=u.high,z=u.low,u=(e>>>1|z<<31)^(e>>>8|z<<24)^e>>>7,z=(z>>>1|e<<31)^(z>>>8|e<<24)^(z>>>7|e<<25),D=y[x-2],e=D.high,k=D.low,D=(e>>>19|k<<13)^\n(e<<3|k>>>29)^e>>>6,k=(k>>>19|e<<13)^(k<<3|e>>>29)^(k>>>6|e<<26),e=y[x-7],Y=e.high,C=y[x-16],A=C.high,C=C.low,e=z+e.low,u=u+Y+(e>>>0>>0?1:0),e=e+k,u=u+D+(e>>>0>>0?1:0),e=e+C,u=u+A+(e>>>0>>0?1:0);B.high=u;B.low=e}var Y=w&U^~w&V,C=t&K^~t&L,B=v&H^v&I^H&I,ha=s&E^s&F^E&F,z=(v>>>28|s<<4)^(v<<30|s>>>2)^(v<<25|s>>>7),D=(s>>>28|v<<4)^(s<<30|v>>>2)^(s<<25|v>>>7),k=p[x],ia=k.high,ea=k.low,k=M+((t>>>14|w<<18)^(t>>>18|w<<14)^(t<<23|w>>>9)),A=X+((w>>>14|t<<18)^(w>>>18|t<<14)^(w<<23|t>>>9))+(k>>>0>>\n0?1:0),k=k+C,A=A+Y+(k>>>0>>0?1:0),k=k+ea,A=A+ia+(k>>>0>>0?1:0),k=k+e,A=A+u+(k>>>0>>0?1:0),e=D+ha,B=z+B+(e>>>0>>0?1:0),X=V,M=L,V=U,L=K,U=w,K=t,t=J+k|0,w=W+A+(t>>>0>>0?1:0)|0,W=I,J=F,I=H,F=E,H=v,E=s,s=k+e|0,v=A+B+(s>>>0>>0?1:0)|0}m=g.low=m+s;g.high=q+v+(m>>>0>>0?1:0);N=n.low=N+E;n.high=r+H+(N>>>0>>0?1:0);O=b.low=O+F;b.high=Z+I+(O>>>0>>0?1:0);P=d.low=P+J;d.high=$+W+(P>>>0>>0?1:0);Q=c.low=Q+t;c.high=aa+w+(Q>>>0>>0?1:0);R=j.low=R+K;j.high=ba+U+(R>>>0>>0?1:0);S=l.low=\nS+L;l.high=ca+V+(S>>>0>>0?1:0);T=h.low=T+M;h.high=da+X+(T>>>0>>0?1:0)},_doFinalize:function(){var a=this._data,f=a.words,h=8*this._nDataBytes,g=8*a.sigBytes;f[g>>>5]|=128<<24-g%32;f[(g+128>>>10<<5)+30]=Math.floor(h/4294967296);f[(g+128>>>10<<5)+31]=h;a.sigBytes=4*f.length;this._process();return this._hash.toX32()},clone:function(){var a=r.clone.call(this);a._hash=this._hash.clone();return a},blockSize:32});m.SHA512=r._createHelper(f);m.HmacSHA512=r._createHmacHelper(f)})();\n"], "abc": [".py", "\n\n\n\"\"\"Abstract Base Classes (ABCs) according to PEP 3119.\"\"\"\n\n\ndef abstractmethod(funcobj):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n funcobj.__isabstractmethod__=True\n return funcobj\n \n \nclass abstractclassmethod(classmethod):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n def __init__(self,callable):\n callable.__isabstractmethod__=True\n super().__init__(callable)\n \n \nclass abstractstaticmethod(staticmethod):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n def __init__(self,callable):\n callable.__isabstractmethod__=True\n super().__init__(callable)\n \n \nclass abstractproperty(property):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n \ntry:\n from _abc import(get_cache_token,_abc_init,_abc_register,\n _abc_instancecheck,_abc_subclasscheck,_get_dump,\n _reset_registry,_reset_caches)\nexcept ImportError:\n from _py_abc import ABCMeta,get_cache_token\n ABCMeta.__module__='abc'\nelse:\n class ABCMeta(type):\n ''\n\n\n\n\n\n\n\n\n\n\n \n def __new__(mcls,name,bases,namespace,/,**kwargs):\n cls=super().__new__(mcls,name,bases,namespace,**kwargs)\n _abc_init(cls)\n return cls\n \n def register(cls,subclass):\n ''\n\n\n \n return _abc_register(cls,subclass)\n \n def __instancecheck__(cls,instance):\n ''\n return _abc_instancecheck(cls,instance)\n \n def __subclasscheck__(cls,subclass):\n ''\n return _abc_subclasscheck(cls,subclass)\n \n def _dump_registry(cls,file=None):\n ''\n print(f\"Class: {cls.__module__}.{cls.__qualname__}\",file=file)\n print(f\"Inv. counter: {get_cache_token()}\",file=file)\n (_abc_registry,_abc_cache,_abc_negative_cache,\n _abc_negative_cache_version)=_get_dump(cls)\n print(f\"_abc_registry: {_abc_registry !r}\",file=file)\n print(f\"_abc_cache: {_abc_cache !r}\",file=file)\n print(f\"_abc_negative_cache: {_abc_negative_cache !r}\",file=file)\n print(f\"_abc_negative_cache_version: {_abc_negative_cache_version !r}\",\n file=file)\n \n def _abc_registry_clear(cls):\n ''\n _reset_registry(cls)\n \n def _abc_caches_clear(cls):\n ''\n _reset_caches(cls)\n \n \ndef update_abstractmethods(cls):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not hasattr(cls,'__abstractmethods__'):\n \n \n \n return cls\n \n abstracts=set()\n \n \n for scls in cls.__bases__:\n for name in getattr(scls,'__abstractmethods__',()):\n value=getattr(cls,name,None)\n if getattr(value,\"__isabstractmethod__\",False):\n abstracts.add(name)\n \n for name,value in cls.__dict__.items():\n if getattr(value,\"__isabstractmethod__\",False):\n abstracts.add(name)\n cls.__abstractmethods__=frozenset(abstracts)\n return cls\n \n \nclass ABC(metaclass=ABCMeta):\n ''\n\n \n __slots__=()\n", ["_abc", "_py_abc"]], "antigravity": [".py", "\nimport webbrowser\nimport hashlib\n\nwebbrowser.open(\"https://xkcd.com/353/\")\n\ndef geohash(latitude,longitude,datedow):\n ''\n\n\n\n\n \n \n h=hashlib.md5(datedow,usedforsecurity=False).hexdigest()\n p,q=[('%f'%float.fromhex('0.'+x))for x in(h[:16],h[16:32])]\n print('%d%s %d%s'%(latitude,p[1:],longitude,q[1:]))\n", ["hashlib", "webbrowser"]], "argparse": [".py", "\n\n\n\"\"\"Command-line parsing library\n\nThis module is an optparse-inspired command-line parsing library that:\n\n - handles both optional and positional arguments\n - produces highly informative usage messages\n - supports parsers that dispatch to sub-parsers\n\nThe following is a simple usage example that sums integers from the\ncommand-line and writes the result to a file::\n\n parser = argparse.ArgumentParser(\n description='sum the integers at the command line')\n parser.add_argument(\n 'integers', metavar='int', nargs='+', type=int,\n help='an integer to be summed')\n parser.add_argument(\n '--log', default=sys.stdout, type=argparse.FileType('w'),\n help='the file where the sum should be written')\n args = parser.parse_args()\n args.log.write('%s' % sum(args.integers))\n args.log.close()\n\nThe module contains the following public classes:\n\n - ArgumentParser -- The main entry point for command-line parsing. As the\n example above shows, the add_argument() method is used to populate\n the parser with actions for optional and positional arguments. Then\n the parse_args() method is invoked to convert the args at the\n command-line into an object with attributes.\n\n - ArgumentError -- The exception raised by ArgumentParser objects when\n there are errors with the parser's actions. Errors raised while\n parsing the command-line are caught by ArgumentParser and emitted\n as command-line messages.\n\n - FileType -- A factory for defining types of files to be created. As the\n example above shows, instances of FileType are typically passed as\n the type= argument of add_argument() calls.\n\n - Action -- The base class for parser actions. Typically actions are\n selected by passing strings like 'store_true' or 'append_const' to\n the action= argument of add_argument(). However, for greater\n customization of ArgumentParser actions, subclasses of Action may\n be defined and passed as the action= argument.\n\n - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,\n ArgumentDefaultsHelpFormatter -- Formatter classes which\n may be passed as the formatter_class= argument to the\n ArgumentParser constructor. HelpFormatter is the default,\n RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser\n not to change the formatting for help text, and\n ArgumentDefaultsHelpFormatter adds information about argument defaults\n to the help.\n\nAll other classes in this module are considered implementation details.\n(Also note that HelpFormatter and RawDescriptionHelpFormatter are only\nconsidered public as object names -- the API of the formatter objects is\nstill considered an implementation detail.)\n\"\"\"\n\n__version__='1.1'\n__all__=[\n'ArgumentParser',\n'ArgumentError',\n'ArgumentTypeError',\n'BooleanOptionalAction',\n'FileType',\n'HelpFormatter',\n'ArgumentDefaultsHelpFormatter',\n'RawDescriptionHelpFormatter',\n'RawTextHelpFormatter',\n'MetavarTypeHelpFormatter',\n'Namespace',\n'Action',\n'ONE_OR_MORE',\n'OPTIONAL',\n'PARSER',\n'REMAINDER',\n'SUPPRESS',\n'ZERO_OR_MORE',\n]\n\n\nimport os as _os\nimport re as _re\nimport sys as _sys\n\nfrom gettext import gettext as _,ngettext\n\nSUPPRESS='==SUPPRESS=='\n\nOPTIONAL='?'\nZERO_OR_MORE='*'\nONE_OR_MORE='+'\nPARSER='A...'\nREMAINDER='...'\n_UNRECOGNIZED_ARGS_ATTR='_unrecognized_args'\n\n\n\n\n\nclass _AttributeHolder(object):\n ''\n\n\n\n\n\n \n \n def __repr__(self):\n type_name=type(self).__name__\n arg_strings=[]\n star_args={}\n for arg in self._get_args():\n arg_strings.append(repr(arg))\n for name,value in self._get_kwargs():\n if name.isidentifier():\n arg_strings.append('%s=%r'%(name,value))\n else:\n star_args[name]=value\n if star_args:\n arg_strings.append('**%s'%repr(star_args))\n return '%s(%s)'%(type_name,', '.join(arg_strings))\n \n def _get_kwargs(self):\n return list(self.__dict__.items())\n \n def _get_args(self):\n return[]\n \n \ndef _copy_items(items):\n if items is None:\n return[]\n \n \n \n if type(items)is list:\n return items[:]\n import copy\n return copy.copy(items)\n \n \n \n \n \n \n \nclass HelpFormatter(object):\n ''\n\n\n\n \n \n def __init__(self,\n prog,\n indent_increment=2,\n max_help_position=24,\n width=None):\n \n \n if width is None:\n import shutil\n width=shutil.get_terminal_size().columns\n width -=2\n \n self._prog=prog\n self._indent_increment=indent_increment\n self._max_help_position=min(max_help_position,\n max(width -20,indent_increment *2))\n self._width=width\n \n self._current_indent=0\n self._level=0\n self._action_max_length=0\n \n self._root_section=self._Section(self,None)\n self._current_section=self._root_section\n \n self._whitespace_matcher=_re.compile(r'\\s+',_re.ASCII)\n self._long_break_matcher=_re.compile(r'\\n\\n\\n+')\n \n \n \n \n def _indent(self):\n self._current_indent +=self._indent_increment\n self._level +=1\n \n def _dedent(self):\n self._current_indent -=self._indent_increment\n assert self._current_indent >=0,'Indent decreased below 0.'\n self._level -=1\n \n class _Section(object):\n \n def __init__(self,formatter,parent,heading=None):\n self.formatter=formatter\n self.parent=parent\n self.heading=heading\n self.items=[]\n \n def format_help(self):\n \n if self.parent is not None:\n self.formatter._indent()\n join=self.formatter._join_parts\n item_help=join([func(*args)for func,args in self.items])\n if self.parent is not None:\n self.formatter._dedent()\n \n \n if not item_help:\n return ''\n \n \n if self.heading is not SUPPRESS and self.heading is not None:\n current_indent=self.formatter._current_indent\n heading_text=_('%(heading)s:')%dict(heading=self.heading)\n heading='%*s%s\\n'%(current_indent,'',heading_text)\n else:\n heading=''\n \n \n return join(['\\n',heading,item_help,'\\n'])\n \n def _add_item(self,func,args):\n self._current_section.items.append((func,args))\n \n \n \n \n def start_section(self,heading):\n self._indent()\n section=self._Section(self,self._current_section,heading)\n self._add_item(section.format_help,[])\n self._current_section=section\n \n def end_section(self):\n self._current_section=self._current_section.parent\n self._dedent()\n \n def add_text(self,text):\n if text is not SUPPRESS and text is not None:\n self._add_item(self._format_text,[text])\n \n def add_usage(self,usage,actions,groups,prefix=None):\n if usage is not SUPPRESS:\n args=usage,actions,groups,prefix\n self._add_item(self._format_usage,args)\n \n def add_argument(self,action):\n if action.help is not SUPPRESS:\n \n \n get_invocation=self._format_action_invocation\n invocations=[get_invocation(action)]\n for subaction in self._iter_indented_subactions(action):\n invocations.append(get_invocation(subaction))\n \n \n invocation_length=max(map(len,invocations))\n action_length=invocation_length+self._current_indent\n self._action_max_length=max(self._action_max_length,\n action_length)\n \n \n self._add_item(self._format_action,[action])\n \n def add_arguments(self,actions):\n for action in actions:\n self.add_argument(action)\n \n \n \n \n def format_help(self):\n help=self._root_section.format_help()\n if help:\n help=self._long_break_matcher.sub('\\n\\n',help)\n help=help.strip('\\n')+'\\n'\n return help\n \n def _join_parts(self,part_strings):\n return ''.join([part\n for part in part_strings\n if part and part is not SUPPRESS])\n \n def _format_usage(self,usage,actions,groups,prefix):\n if prefix is None:\n prefix=_('usage: ')\n \n \n if usage is not None:\n usage=usage %dict(prog=self._prog)\n \n \n elif usage is None and not actions:\n usage='%(prog)s'%dict(prog=self._prog)\n \n \n elif usage is None:\n prog='%(prog)s'%dict(prog=self._prog)\n \n \n optionals=[]\n positionals=[]\n for action in actions:\n if action.option_strings:\n optionals.append(action)\n else:\n positionals.append(action)\n \n \n format=self._format_actions_usage\n action_usage=format(optionals+positionals,groups)\n usage=' '.join([s for s in[prog,action_usage]if s])\n \n \n text_width=self._width -self._current_indent\n if len(prefix)+len(usage)>text_width:\n \n \n opt_parts=self._get_actions_usage_parts(optionals,groups)\n pos_parts=self._get_actions_usage_parts(positionals,groups)\n \n \n def get_lines(parts,indent,prefix=None):\n lines=[]\n line=[]\n indent_length=len(indent)\n if prefix is not None:\n line_len=len(prefix)-1\n else:\n line_len=indent_length -1\n for part in parts:\n if line_len+1+len(part)>text_width and line:\n lines.append(indent+' '.join(line))\n line=[]\n line_len=indent_length -1\n line.append(part)\n line_len +=len(part)+1\n if line:\n lines.append(indent+' '.join(line))\n if prefix is not None:\n lines[0]=lines[0][indent_length:]\n return lines\n \n \n if len(prefix)+len(prog)<=0.75 *text_width:\n indent=' '*(len(prefix)+len(prog)+1)\n if opt_parts:\n lines=get_lines([prog]+opt_parts,indent,prefix)\n lines.extend(get_lines(pos_parts,indent))\n elif pos_parts:\n lines=get_lines([prog]+pos_parts,indent,prefix)\n else:\n lines=[prog]\n \n \n else:\n indent=' '*len(prefix)\n parts=opt_parts+pos_parts\n lines=get_lines(parts,indent)\n if len(lines)>1:\n lines=[]\n lines.extend(get_lines(opt_parts,indent))\n lines.extend(get_lines(pos_parts,indent))\n lines=[prog]+lines\n \n \n usage='\\n'.join(lines)\n \n \n return '%s%s\\n\\n'%(prefix,usage)\n \n def _format_actions_usage(self,actions,groups):\n return ' '.join(self._get_actions_usage_parts(actions,groups))\n \n def _get_actions_usage_parts(self,actions,groups):\n \n group_actions=set()\n inserts={}\n for group in groups:\n if not group._group_actions:\n raise ValueError(f'empty group {group}')\n \n if all(action.help is SUPPRESS for action in group._group_actions):\n continue\n \n try:\n start=actions.index(group._group_actions[0])\n except ValueError:\n continue\n else:\n end=start+len(group._group_actions)\n if actions[start:end]==group._group_actions:\n group_actions.update(group._group_actions)\n inserts[start,end]=group\n \n \n parts=[]\n for action in actions:\n \n \n if action.help is SUPPRESS:\n part=None\n \n \n elif not action.option_strings:\n default=self._get_default_metavar_for_positional(action)\n part=self._format_args(action,default)\n \n \n if action in group_actions:\n if part[0]=='['and part[-1]==']':\n part=part[1:-1]\n \n \n else:\n option_string=action.option_strings[0]\n \n \n \n if action.nargs ==0:\n part=action.format_usage()\n \n \n \n else:\n default=self._get_default_metavar_for_optional(action)\n args_string=self._format_args(action,default)\n part='%s %s'%(option_string,args_string)\n \n \n if not action.required and action not in group_actions:\n part='[%s]'%part\n \n \n parts.append(part)\n \n \n for start,end in sorted(inserts,reverse=True):\n group=inserts[start,end]\n group_parts=[item for item in parts[start:end]if item is not None]\n if group.required:\n open,close=\"()\"if len(group_parts)>1 else(\"\",\"\")\n else:\n open,close=\"[]\"\n parts[start]=open+\" | \".join(group_parts)+close\n for i in range(start+1,end):\n parts[i]=None\n \n \n return[item for item in parts if item is not None]\n \n def _format_text(self,text):\n if '%(prog)'in text:\n text=text %dict(prog=self._prog)\n text_width=max(self._width -self._current_indent,11)\n indent=' '*self._current_indent\n return self._fill_text(text,text_width,indent)+'\\n\\n'\n \n def _format_action(self,action):\n \n help_position=min(self._action_max_length+2,\n self._max_help_position)\n help_width=max(self._width -help_position,11)\n action_width=help_position -self._current_indent -2\n action_header=self._format_action_invocation(action)\n \n \n if not action.help:\n tup=self._current_indent,'',action_header\n action_header='%*s%s\\n'%tup\n \n \n elif len(action_header)<=action_width:\n tup=self._current_indent,'',action_width,action_header\n action_header='%*s%-*s '%tup\n indent_first=0\n \n \n else:\n tup=self._current_indent,'',action_header\n action_header='%*s%s\\n'%tup\n indent_first=help_position\n \n \n parts=[action_header]\n \n \n if action.help and action.help.strip():\n help_text=self._expand_help(action)\n if help_text:\n help_lines=self._split_lines(help_text,help_width)\n parts.append('%*s%s\\n'%(indent_first,'',help_lines[0]))\n for line in help_lines[1:]:\n parts.append('%*s%s\\n'%(help_position,'',line))\n \n \n elif not action_header.endswith('\\n'):\n parts.append('\\n')\n \n \n for subaction in self._iter_indented_subactions(action):\n parts.append(self._format_action(subaction))\n \n \n return self._join_parts(parts)\n \n def _format_action_invocation(self,action):\n if not action.option_strings:\n default=self._get_default_metavar_for_positional(action)\n metavar,=self._metavar_formatter(action,default)(1)\n return metavar\n \n else:\n \n \n \n if action.nargs ==0:\n return ', '.join(action.option_strings)\n \n \n \n else:\n default=self._get_default_metavar_for_optional(action)\n args_string=self._format_args(action,default)\n return ', '.join(action.option_strings)+' '+args_string\n \n def _metavar_formatter(self,action,default_metavar):\n if action.metavar is not None:\n result=action.metavar\n elif action.choices is not None:\n choice_strs=[str(choice)for choice in action.choices]\n result='{%s}'%','.join(choice_strs)\n else:\n result=default_metavar\n \n def format(tuple_size):\n if isinstance(result,tuple):\n return result\n else:\n return(result,)*tuple_size\n return format\n \n def _format_args(self,action,default_metavar):\n get_metavar=self._metavar_formatter(action,default_metavar)\n if action.nargs is None:\n result='%s'%get_metavar(1)\n elif action.nargs ==OPTIONAL:\n result='[%s]'%get_metavar(1)\n elif action.nargs ==ZERO_OR_MORE:\n metavar=get_metavar(1)\n if len(metavar)==2:\n result='[%s [%s ...]]'%metavar\n else:\n result='[%s ...]'%metavar\n elif action.nargs ==ONE_OR_MORE:\n result='%s [%s ...]'%get_metavar(2)\n elif action.nargs ==REMAINDER:\n result='...'\n elif action.nargs ==PARSER:\n result='%s ...'%get_metavar(1)\n elif action.nargs ==SUPPRESS:\n result=''\n else:\n try:\n formats=['%s'for _ in range(action.nargs)]\n except TypeError:\n raise ValueError(\"invalid nargs value\")from None\n result=' '.join(formats)%get_metavar(action.nargs)\n return result\n \n def _expand_help(self,action):\n params=dict(vars(action),prog=self._prog)\n for name in list(params):\n if params[name]is SUPPRESS:\n del params[name]\n for name in list(params):\n if hasattr(params[name],'__name__'):\n params[name]=params[name].__name__\n if params.get('choices')is not None:\n choices_str=', '.join([str(c)for c in params['choices']])\n params['choices']=choices_str\n return self._get_help_string(action)%params\n \n def _iter_indented_subactions(self,action):\n try:\n get_subactions=action._get_subactions\n except AttributeError:\n pass\n else:\n self._indent()\n yield from get_subactions()\n self._dedent()\n \n def _split_lines(self,text,width):\n text=self._whitespace_matcher.sub(' ',text).strip()\n \n \n import textwrap\n return textwrap.wrap(text,width)\n \n def _fill_text(self,text,width,indent):\n text=self._whitespace_matcher.sub(' ',text).strip()\n import textwrap\n return textwrap.fill(text,width,\n initial_indent=indent,\n subsequent_indent=indent)\n \n def _get_help_string(self,action):\n return action.help\n \n def _get_default_metavar_for_optional(self,action):\n return action.dest.upper()\n \n def _get_default_metavar_for_positional(self,action):\n return action.dest\n \n \nclass RawDescriptionHelpFormatter(HelpFormatter):\n ''\n\n\n\n \n \n def _fill_text(self,text,width,indent):\n return ''.join(indent+line for line in text.splitlines(keepends=True))\n \n \nclass RawTextHelpFormatter(RawDescriptionHelpFormatter):\n ''\n\n\n\n \n \n def _split_lines(self,text,width):\n return text.splitlines()\n \n \nclass ArgumentDefaultsHelpFormatter(HelpFormatter):\n ''\n\n\n\n \n \n def _get_help_string(self,action):\n help=action.help\n if help is None:\n help=''\n \n if '%(default)'not in help:\n if action.default is not SUPPRESS:\n defaulting_nargs=[OPTIONAL,ZERO_OR_MORE]\n if action.option_strings or action.nargs in defaulting_nargs:\n help +=_(' (default: %(default)s)')\n return help\n \n \n \nclass MetavarTypeHelpFormatter(HelpFormatter):\n ''\n\n\n\n\n \n \n def _get_default_metavar_for_optional(self,action):\n return action.type.__name__\n \n def _get_default_metavar_for_positional(self,action):\n return action.type.__name__\n \n \n \n \n \n \ndef _get_action_name(argument):\n if argument is None:\n return None\n elif argument.option_strings:\n return '/'.join(argument.option_strings)\n elif argument.metavar not in(None,SUPPRESS):\n return argument.metavar\n elif argument.dest not in(None,SUPPRESS):\n return argument.dest\n elif argument.choices:\n return '{'+','.join(argument.choices)+'}'\n else:\n return None\n \n \nclass ArgumentError(Exception):\n ''\n\n\n\n \n \n def __init__(self,argument,message):\n self.argument_name=_get_action_name(argument)\n self.message=message\n \n def __str__(self):\n if self.argument_name is None:\n format='%(message)s'\n else:\n format=_('argument %(argument_name)s: %(message)s')\n return format %dict(message=self.message,\n argument_name=self.argument_name)\n \n \nclass ArgumentTypeError(Exception):\n ''\n pass\n \n \n \n \n \n \nclass Action(_AttributeHolder):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,\n option_strings,\n dest,\n nargs=None,\n const=None,\n default=None,\n type=None,\n choices=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n self.option_strings=option_strings\n self.dest=dest\n self.nargs=nargs\n self.const=const\n self.default=default\n self.type=type\n self.choices=choices\n self.required=required\n self.help=help\n self.metavar=metavar\n self.deprecated=deprecated\n \n def _get_kwargs(self):\n names=[\n 'option_strings',\n 'dest',\n 'nargs',\n 'const',\n 'default',\n 'type',\n 'choices',\n 'required',\n 'help',\n 'metavar',\n 'deprecated',\n ]\n return[(name,getattr(self,name))for name in names]\n \n def format_usage(self):\n return self.option_strings[0]\n \n def __call__(self,parser,namespace,values,option_string=None):\n raise NotImplementedError(_('.__call__() not defined'))\n \n \n \n_deprecated_default=object()\n\nclass BooleanOptionalAction(Action):\n def __init__(self,\n option_strings,\n dest,\n default=None,\n type=_deprecated_default,\n choices=_deprecated_default,\n required=False,\n help=None,\n metavar=_deprecated_default,\n deprecated=False):\n \n _option_strings=[]\n for option_string in option_strings:\n _option_strings.append(option_string)\n \n if option_string.startswith('--'):\n option_string='--no-'+option_string[2:]\n _option_strings.append(option_string)\n \n \n \n \n for field_name in('type','choices','metavar'):\n if locals()[field_name]is not _deprecated_default:\n import warnings\n warnings._deprecated(\n field_name,\n \"{name!r} is deprecated as of Python 3.12 and will be \"\n \"removed in Python {remove}.\",\n remove=(3,14))\n \n if type is _deprecated_default:\n type=None\n if choices is _deprecated_default:\n choices=None\n if metavar is _deprecated_default:\n metavar=None\n \n super().__init__(\n option_strings=_option_strings,\n dest=dest,\n nargs=0,\n default=default,\n type=type,\n choices=choices,\n required=required,\n help=help,\n metavar=metavar,\n deprecated=deprecated)\n \n \n def __call__(self,parser,namespace,values,option_string=None):\n if option_string in self.option_strings:\n setattr(namespace,self.dest,not option_string.startswith('--no-'))\n \n def format_usage(self):\n return ' | '.join(self.option_strings)\n \n \nclass _StoreAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n nargs=None,\n const=None,\n default=None,\n type=None,\n choices=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n if nargs ==0:\n raise ValueError('nargs for store actions must be != 0; if you '\n 'have nothing to store, actions such as store '\n 'true or store const may be more appropriate')\n if const is not None and nargs !=OPTIONAL:\n raise ValueError('nargs must be %r to supply const'%OPTIONAL)\n super(_StoreAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=nargs,\n const=const,\n default=default,\n type=type,\n choices=choices,\n required=required,\n help=help,\n metavar=metavar,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n setattr(namespace,self.dest,values)\n \n \nclass _StoreConstAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n const=None,\n default=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n super(_StoreConstAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n const=const,\n default=default,\n required=required,\n help=help,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n setattr(namespace,self.dest,self.const)\n \n \nclass _StoreTrueAction(_StoreConstAction):\n\n def __init__(self,\n option_strings,\n dest,\n default=False,\n required=False,\n help=None,\n deprecated=False):\n super(_StoreTrueAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=True,\n deprecated=deprecated,\n required=required,\n help=help,\n default=default)\n \n \nclass _StoreFalseAction(_StoreConstAction):\n\n def __init__(self,\n option_strings,\n dest,\n default=True,\n required=False,\n help=None,\n deprecated=False):\n super(_StoreFalseAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=False,\n default=default,\n required=required,\n help=help,\n deprecated=deprecated)\n \n \nclass _AppendAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n nargs=None,\n const=None,\n default=None,\n type=None,\n choices=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n if nargs ==0:\n raise ValueError('nargs for append actions must be != 0; if arg '\n 'strings are not supplying the value to append, '\n 'the append const action may be more appropriate')\n if const is not None and nargs !=OPTIONAL:\n raise ValueError('nargs must be %r to supply const'%OPTIONAL)\n super(_AppendAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=nargs,\n const=const,\n default=default,\n type=type,\n choices=choices,\n required=required,\n help=help,\n metavar=metavar,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n items=getattr(namespace,self.dest,None)\n items=_copy_items(items)\n items.append(values)\n setattr(namespace,self.dest,items)\n \n \nclass _AppendConstAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n const=None,\n default=None,\n required=False,\n help=None,\n metavar=None,\n deprecated=False):\n super(_AppendConstAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n const=const,\n default=default,\n required=required,\n help=help,\n metavar=metavar,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n items=getattr(namespace,self.dest,None)\n items=_copy_items(items)\n items.append(self.const)\n setattr(namespace,self.dest,items)\n \n \nclass _CountAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n default=None,\n required=False,\n help=None,\n deprecated=False):\n super(_CountAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n default=default,\n required=required,\n help=help,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n count=getattr(namespace,self.dest,None)\n if count is None:\n count=0\n setattr(namespace,self.dest,count+1)\n \n \nclass _HelpAction(Action):\n\n def __init__(self,\n option_strings,\n dest=SUPPRESS,\n default=SUPPRESS,\n help=None,\n deprecated=False):\n super(_HelpAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n default=default,\n nargs=0,\n help=help,\n deprecated=deprecated)\n \n def __call__(self,parser,namespace,values,option_string=None):\n parser.print_help()\n parser.exit()\n \n \nclass _VersionAction(Action):\n\n def __init__(self,\n option_strings,\n version=None,\n dest=SUPPRESS,\n default=SUPPRESS,\n help=None,\n deprecated=False):\n if help is None:\n help=_(\"show program's version number and exit\")\n super(_VersionAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n default=default,\n nargs=0,\n help=help)\n self.version=version\n \n def __call__(self,parser,namespace,values,option_string=None):\n version=self.version\n if version is None:\n version=parser.version\n formatter=parser._get_formatter()\n formatter.add_text(version)\n parser._print_message(formatter.format_help(),_sys.stdout)\n parser.exit()\n \n \nclass _SubParsersAction(Action):\n\n class _ChoicesPseudoAction(Action):\n \n def __init__(self,name,aliases,help):\n metavar=dest=name\n if aliases:\n metavar +=' (%s)'%', '.join(aliases)\n sup=super(_SubParsersAction._ChoicesPseudoAction,self)\n sup.__init__(option_strings=[],dest=dest,help=help,\n metavar=metavar)\n \n def __init__(self,\n option_strings,\n prog,\n parser_class,\n dest=SUPPRESS,\n required=False,\n help=None,\n metavar=None):\n \n self._prog_prefix=prog\n self._parser_class=parser_class\n self._name_parser_map={}\n self._choices_actions=[]\n self._deprecated=set()\n \n super(_SubParsersAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=PARSER,\n choices=self._name_parser_map,\n required=required,\n help=help,\n metavar=metavar)\n \n def add_parser(self,name,*,deprecated=False,**kwargs):\n \n if kwargs.get('prog')is None:\n kwargs['prog']='%s %s'%(self._prog_prefix,name)\n \n aliases=kwargs.pop('aliases',())\n \n if name in self._name_parser_map:\n raise ArgumentError(self,_('conflicting subparser: %s')%name)\n for alias in aliases:\n if alias in self._name_parser_map:\n raise ArgumentError(\n self,_('conflicting subparser alias: %s')%alias)\n \n \n if 'help'in kwargs:\n help=kwargs.pop('help')\n choice_action=self._ChoicesPseudoAction(name,aliases,help)\n self._choices_actions.append(choice_action)\n \n \n parser=self._parser_class(**kwargs)\n self._name_parser_map[name]=parser\n \n \n for alias in aliases:\n self._name_parser_map[alias]=parser\n \n if deprecated:\n self._deprecated.add(name)\n self._deprecated.update(aliases)\n \n return parser\n \n def _get_subactions(self):\n return self._choices_actions\n \n def __call__(self,parser,namespace,values,option_string=None):\n parser_name=values[0]\n arg_strings=values[1:]\n \n \n if self.dest is not SUPPRESS:\n setattr(namespace,self.dest,parser_name)\n \n \n try:\n subparser=self._name_parser_map[parser_name]\n except KeyError:\n args={'parser_name':parser_name,\n 'choices':', '.join(self._name_parser_map)}\n msg=_('unknown parser %(parser_name)r (choices: %(choices)s)')%args\n raise ArgumentError(self,msg)\n \n if parser_name in self._deprecated:\n parser._warning(_(\"command '%(parser_name)s' is deprecated\")%\n {'parser_name':parser_name})\n \n \n \n \n \n \n \n \n subnamespace,arg_strings=subparser.parse_known_args(arg_strings,None)\n for key,value in vars(subnamespace).items():\n setattr(namespace,key,value)\n \n if arg_strings:\n vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR,[])\n getattr(namespace,_UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)\n \nclass _ExtendAction(_AppendAction):\n def __call__(self,parser,namespace,values,option_string=None):\n items=getattr(namespace,self.dest,None)\n items=_copy_items(items)\n items.extend(values)\n setattr(namespace,self.dest,items)\n \n \n \n \n \nclass FileType(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,mode='r',bufsize=-1,encoding=None,errors=None):\n self._mode=mode\n self._bufsize=bufsize\n self._encoding=encoding\n self._errors=errors\n \n def __call__(self,string):\n \n if string =='-':\n if 'r'in self._mode:\n return _sys.stdin.buffer if 'b'in self._mode else _sys.stdin\n elif any(c in self._mode for c in 'wax'):\n return _sys.stdout.buffer if 'b'in self._mode else _sys.stdout\n else:\n msg=_('argument \"-\" with mode %r')%self._mode\n raise ValueError(msg)\n \n \n try:\n return open(string,self._mode,self._bufsize,self._encoding,\n self._errors)\n except OSError as e:\n args={'filename':string,'error':e}\n message=_(\"can't open '%(filename)s': %(error)s\")\n raise ArgumentTypeError(message %args)\n \n def __repr__(self):\n args=self._mode,self._bufsize\n kwargs=[('encoding',self._encoding),('errors',self._errors)]\n args_str=', '.join([repr(arg)for arg in args if arg !=-1]+\n ['%s=%r'%(kw,arg)for kw,arg in kwargs\n if arg is not None])\n return '%s(%s)'%(type(self).__name__,args_str)\n \n \n \n \n \nclass Namespace(_AttributeHolder):\n ''\n\n\n\n \n \n def __init__(self,**kwargs):\n for name in kwargs:\n setattr(self,name,kwargs[name])\n \n def __eq__(self,other):\n if not isinstance(other,Namespace):\n return NotImplemented\n return vars(self)==vars(other)\n \n def __contains__(self,key):\n return key in self.__dict__\n \n \nclass _ActionsContainer(object):\n\n def __init__(self,\n description,\n prefix_chars,\n argument_default,\n conflict_handler):\n super(_ActionsContainer,self).__init__()\n \n self.description=description\n self.argument_default=argument_default\n self.prefix_chars=prefix_chars\n self.conflict_handler=conflict_handler\n \n \n self._registries={}\n \n \n self.register('action',None,_StoreAction)\n self.register('action','store',_StoreAction)\n self.register('action','store_const',_StoreConstAction)\n self.register('action','store_true',_StoreTrueAction)\n self.register('action','store_false',_StoreFalseAction)\n self.register('action','append',_AppendAction)\n self.register('action','append_const',_AppendConstAction)\n self.register('action','count',_CountAction)\n self.register('action','help',_HelpAction)\n self.register('action','version',_VersionAction)\n self.register('action','parsers',_SubParsersAction)\n self.register('action','extend',_ExtendAction)\n \n \n self._get_handler()\n \n \n self._actions=[]\n self._option_string_actions={}\n \n \n self._action_groups=[]\n self._mutually_exclusive_groups=[]\n \n \n self._defaults={}\n \n \n self._negative_number_matcher=_re.compile(r'^-\\d+$|^-\\d*\\.\\d+$')\n \n \n \n self._has_negative_number_optionals=[]\n \n \n \n \n def register(self,registry_name,value,object):\n registry=self._registries.setdefault(registry_name,{})\n registry[value]=object\n \n def _registry_get(self,registry_name,value,default=None):\n return self._registries[registry_name].get(value,default)\n \n \n \n \n def set_defaults(self,**kwargs):\n self._defaults.update(kwargs)\n \n \n \n for action in self._actions:\n if action.dest in kwargs:\n action.default=kwargs[action.dest]\n \n def get_default(self,dest):\n for action in self._actions:\n if action.dest ==dest and action.default is not None:\n return action.default\n return self._defaults.get(dest,None)\n \n \n \n \n \n def add_argument(self,*args,**kwargs):\n ''\n\n\n \n \n \n \n \n chars=self.prefix_chars\n if not args or len(args)==1 and args[0][0]not in chars:\n if args and 'dest'in kwargs:\n raise ValueError('dest supplied twice for positional argument')\n kwargs=self._get_positional_kwargs(*args,**kwargs)\n \n \n else:\n kwargs=self._get_optional_kwargs(*args,**kwargs)\n \n \n if 'default'not in kwargs:\n dest=kwargs['dest']\n if dest in self._defaults:\n kwargs['default']=self._defaults[dest]\n elif self.argument_default is not None:\n kwargs['default']=self.argument_default\n \n \n action_class=self._pop_action_class(kwargs)\n if not callable(action_class):\n raise ValueError('unknown action \"%s\"'%(action_class,))\n action=action_class(**kwargs)\n \n \n type_func=self._registry_get('type',action.type,action.type)\n if not callable(type_func):\n raise ValueError('%r is not callable'%(type_func,))\n \n if type_func is FileType:\n raise ValueError('%r is a FileType class object, instance of it'\n ' must be passed'%(type_func,))\n \n \n if hasattr(self,\"_get_formatter\"):\n try:\n self._get_formatter()._format_args(action,None)\n except TypeError:\n raise ValueError(\"length of metavar tuple does not match nargs\")\n \n return self._add_action(action)\n \n def add_argument_group(self,*args,**kwargs):\n group=_ArgumentGroup(self,*args,**kwargs)\n self._action_groups.append(group)\n return group\n \n def add_mutually_exclusive_group(self,**kwargs):\n group=_MutuallyExclusiveGroup(self,**kwargs)\n self._mutually_exclusive_groups.append(group)\n return group\n \n def _add_action(self,action):\n \n self._check_conflict(action)\n \n \n self._actions.append(action)\n action.container=self\n \n \n for option_string in action.option_strings:\n self._option_string_actions[option_string]=action\n \n \n for option_string in action.option_strings:\n if self._negative_number_matcher.match(option_string):\n if not self._has_negative_number_optionals:\n self._has_negative_number_optionals.append(True)\n \n \n return action\n \n def _remove_action(self,action):\n self._actions.remove(action)\n \n def _add_container_actions(self,container):\n \n title_group_map={}\n for group in self._action_groups:\n if group.title in title_group_map:\n \n \n msg=_('cannot merge actions - two groups are named %r')\n raise ValueError(msg %(group.title))\n title_group_map[group.title]=group\n \n \n group_map={}\n for group in container._action_groups:\n \n \n \n if group.title not in title_group_map:\n title_group_map[group.title]=self.add_argument_group(\n title=group.title,\n description=group.description,\n conflict_handler=group.conflict_handler)\n \n \n for action in group._group_actions:\n group_map[action]=title_group_map[group.title]\n \n \n \n \n for group in container._mutually_exclusive_groups:\n mutex_group=self.add_mutually_exclusive_group(\n required=group.required)\n \n \n for action in group._group_actions:\n group_map[action]=mutex_group\n \n \n for action in container._actions:\n group_map.get(action,self)._add_action(action)\n \n def _get_positional_kwargs(self,dest,**kwargs):\n \n if 'required'in kwargs:\n msg=_(\"'required' is an invalid argument for positionals\")\n raise TypeError(msg)\n \n \n \n if kwargs.get('nargs')not in[OPTIONAL,ZERO_OR_MORE]:\n kwargs['required']=True\n if kwargs.get('nargs')==ZERO_OR_MORE and 'default'not in kwargs:\n kwargs['required']=True\n \n \n return dict(kwargs,dest=dest,option_strings=[])\n \n def _get_optional_kwargs(self,*args,**kwargs):\n \n option_strings=[]\n long_option_strings=[]\n for option_string in args:\n \n if not option_string[0]in self.prefix_chars:\n args={'option':option_string,\n 'prefix_chars':self.prefix_chars}\n msg=_('invalid option string %(option)r: '\n 'must start with a character %(prefix_chars)r')\n raise ValueError(msg %args)\n \n \n option_strings.append(option_string)\n if len(option_string)>1 and option_string[1]in self.prefix_chars:\n long_option_strings.append(option_string)\n \n \n dest=kwargs.pop('dest',None)\n if dest is None:\n if long_option_strings:\n dest_option_string=long_option_strings[0]\n else:\n dest_option_string=option_strings[0]\n dest=dest_option_string.lstrip(self.prefix_chars)\n if not dest:\n msg=_('dest= is required for options like %r')\n raise ValueError(msg %option_string)\n dest=dest.replace('-','_')\n \n \n return dict(kwargs,dest=dest,option_strings=option_strings)\n \n def _pop_action_class(self,kwargs,default=None):\n action=kwargs.pop('action',default)\n return self._registry_get('action',action,action)\n \n def _get_handler(self):\n \n handler_func_name='_handle_conflict_%s'%self.conflict_handler\n try:\n return getattr(self,handler_func_name)\n except AttributeError:\n msg=_('invalid conflict_resolution value: %r')\n raise ValueError(msg %self.conflict_handler)\n \n def _check_conflict(self,action):\n \n \n confl_optionals=[]\n for option_string in action.option_strings:\n if option_string in self._option_string_actions:\n confl_optional=self._option_string_actions[option_string]\n confl_optionals.append((option_string,confl_optional))\n \n \n if confl_optionals:\n conflict_handler=self._get_handler()\n conflict_handler(action,confl_optionals)\n \n def _handle_conflict_error(self,action,conflicting_actions):\n message=ngettext('conflicting option string: %s',\n 'conflicting option strings: %s',\n len(conflicting_actions))\n conflict_string=', '.join([option_string\n for option_string,action\n in conflicting_actions])\n raise ArgumentError(action,message %conflict_string)\n \n def _handle_conflict_resolve(self,action,conflicting_actions):\n \n \n for option_string,action in conflicting_actions:\n \n \n action.option_strings.remove(option_string)\n self._option_string_actions.pop(option_string,None)\n \n \n \n if not action.option_strings:\n action.container._remove_action(action)\n \n \nclass _ArgumentGroup(_ActionsContainer):\n\n def __init__(self,container,title=None,description=None,**kwargs):\n \n update=kwargs.setdefault\n update('conflict_handler',container.conflict_handler)\n update('prefix_chars',container.prefix_chars)\n update('argument_default',container.argument_default)\n super_init=super(_ArgumentGroup,self).__init__\n super_init(description=description,**kwargs)\n \n \n self.title=title\n self._group_actions=[]\n \n \n self._registries=container._registries\n self._actions=container._actions\n self._option_string_actions=container._option_string_actions\n self._defaults=container._defaults\n self._has_negative_number_optionals=\\\n container._has_negative_number_optionals\n self._mutually_exclusive_groups=container._mutually_exclusive_groups\n \n def _add_action(self,action):\n action=super(_ArgumentGroup,self)._add_action(action)\n self._group_actions.append(action)\n return action\n \n def _remove_action(self,action):\n super(_ArgumentGroup,self)._remove_action(action)\n self._group_actions.remove(action)\n \n def add_argument_group(self,*args,**kwargs):\n import warnings\n warnings.warn(\n \"Nesting argument groups is deprecated.\",\n category=DeprecationWarning,\n stacklevel=2\n )\n return super().add_argument_group(*args,**kwargs)\n \n \nclass _MutuallyExclusiveGroup(_ArgumentGroup):\n\n def __init__(self,container,required=False):\n super(_MutuallyExclusiveGroup,self).__init__(container)\n self.required=required\n self._container=container\n \n def _add_action(self,action):\n if action.required:\n msg=_('mutually exclusive arguments must be optional')\n raise ValueError(msg)\n action=self._container._add_action(action)\n self._group_actions.append(action)\n return action\n \n def _remove_action(self,action):\n self._container._remove_action(action)\n self._group_actions.remove(action)\n \n def add_mutually_exclusive_group(self,*args,**kwargs):\n import warnings\n warnings.warn(\n \"Nesting mutually exclusive groups is deprecated.\",\n category=DeprecationWarning,\n stacklevel=2\n )\n return super().add_mutually_exclusive_group(*args,**kwargs)\n \n \nclass ArgumentParser(_AttributeHolder,_ActionsContainer):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,\n prog=None,\n usage=None,\n description=None,\n epilog=None,\n parents=[],\n formatter_class=HelpFormatter,\n prefix_chars='-',\n fromfile_prefix_chars=None,\n argument_default=None,\n conflict_handler='error',\n add_help=True,\n allow_abbrev=True,\n exit_on_error=True):\n \n superinit=super(ArgumentParser,self).__init__\n superinit(description=description,\n prefix_chars=prefix_chars,\n argument_default=argument_default,\n conflict_handler=conflict_handler)\n \n \n if prog is None:\n prog=_os.path.basename(_sys.argv[0])\n \n self.prog=prog\n self.usage=usage\n self.epilog=epilog\n self.formatter_class=formatter_class\n self.fromfile_prefix_chars=fromfile_prefix_chars\n self.add_help=add_help\n self.allow_abbrev=allow_abbrev\n self.exit_on_error=exit_on_error\n \n add_group=self.add_argument_group\n self._positionals=add_group(_('positional arguments'))\n self._optionals=add_group(_('options'))\n self._subparsers=None\n \n \n def identity(string):\n return string\n self.register('type',None,identity)\n \n \n \n default_prefix='-'if '-'in prefix_chars else prefix_chars[0]\n if self.add_help:\n self.add_argument(\n default_prefix+'h',default_prefix *2+'help',\n action='help',default=SUPPRESS,\n help=_('show this help message and exit'))\n \n \n for parent in parents:\n if not isinstance(parent,ArgumentParser):\n raise TypeError('parents must be a list of ArgumentParser')\n self._add_container_actions(parent)\n defaults=parent._defaults\n self._defaults.update(defaults)\n \n \n \n \n def _get_kwargs(self):\n names=[\n 'prog',\n 'usage',\n 'description',\n 'formatter_class',\n 'conflict_handler',\n 'add_help',\n ]\n return[(name,getattr(self,name))for name in names]\n \n \n \n \n def add_subparsers(self,**kwargs):\n if self._subparsers is not None:\n raise ArgumentError(None,_('cannot have multiple subparser arguments'))\n \n \n kwargs.setdefault('parser_class',type(self))\n \n if 'title'in kwargs or 'description'in kwargs:\n title=_(kwargs.pop('title','subcommands'))\n description=_(kwargs.pop('description',None))\n self._subparsers=self.add_argument_group(title,description)\n else:\n self._subparsers=self._positionals\n \n \n \n if kwargs.get('prog')is None:\n formatter=self._get_formatter()\n positionals=self._get_positional_actions()\n groups=self._mutually_exclusive_groups\n formatter.add_usage(self.usage,positionals,groups,'')\n kwargs['prog']=formatter.format_help().strip()\n \n \n parsers_class=self._pop_action_class(kwargs,'parsers')\n action=parsers_class(option_strings=[],**kwargs)\n self._subparsers._add_action(action)\n \n \n return action\n \n def _add_action(self,action):\n if action.option_strings:\n self._optionals._add_action(action)\n else:\n self._positionals._add_action(action)\n return action\n \n def _get_optional_actions(self):\n return[action\n for action in self._actions\n if action.option_strings]\n \n def _get_positional_actions(self):\n return[action\n for action in self._actions\n if not action.option_strings]\n \n \n \n \n def parse_args(self,args=None,namespace=None):\n args,argv=self.parse_known_args(args,namespace)\n if argv:\n msg=_('unrecognized arguments: %s')%' '.join(argv)\n if self.exit_on_error:\n self.error(msg)\n else:\n raise ArgumentError(None,msg)\n return args\n \n def parse_known_args(self,args=None,namespace=None):\n if args is None:\n \n args=_sys.argv[1:]\n else:\n \n args=list(args)\n \n \n if namespace is None:\n namespace=Namespace()\n \n \n for action in self._actions:\n if action.dest is not SUPPRESS:\n if not hasattr(namespace,action.dest):\n if action.default is not SUPPRESS:\n setattr(namespace,action.dest,action.default)\n \n \n for dest in self._defaults:\n if not hasattr(namespace,dest):\n setattr(namespace,dest,self._defaults[dest])\n \n \n if self.exit_on_error:\n try:\n namespace,args=self._parse_known_args(args,namespace)\n except ArgumentError as err:\n self.error(str(err))\n else:\n namespace,args=self._parse_known_args(args,namespace)\n \n if hasattr(namespace,_UNRECOGNIZED_ARGS_ATTR):\n args.extend(getattr(namespace,_UNRECOGNIZED_ARGS_ATTR))\n delattr(namespace,_UNRECOGNIZED_ARGS_ATTR)\n return namespace,args\n \n def _parse_known_args(self,arg_strings,namespace):\n \n if self.fromfile_prefix_chars is not None:\n arg_strings=self._read_args_from_files(arg_strings)\n \n \n \n action_conflicts={}\n for mutex_group in self._mutually_exclusive_groups:\n group_actions=mutex_group._group_actions\n for i,mutex_action in enumerate(mutex_group._group_actions):\n conflicts=action_conflicts.setdefault(mutex_action,[])\n conflicts.extend(group_actions[:i])\n conflicts.extend(group_actions[i+1:])\n \n \n \n \n option_string_indices={}\n arg_string_pattern_parts=[]\n arg_strings_iter=iter(arg_strings)\n for i,arg_string in enumerate(arg_strings_iter):\n \n \n if arg_string =='--':\n arg_string_pattern_parts.append('-')\n for arg_string in arg_strings_iter:\n arg_string_pattern_parts.append('A')\n \n \n \n else:\n option_tuple=self._parse_optional(arg_string)\n if option_tuple is None:\n pattern='A'\n else:\n option_string_indices[i]=option_tuple\n pattern='O'\n arg_string_pattern_parts.append(pattern)\n \n \n arg_strings_pattern=''.join(arg_string_pattern_parts)\n \n \n seen_actions=set()\n seen_non_default_actions=set()\n warned=set()\n \n def take_action(action,argument_strings,option_string=None):\n seen_actions.add(action)\n argument_values=self._get_values(action,argument_strings)\n \n \n \n \n if argument_values is not action.default:\n seen_non_default_actions.add(action)\n for conflict_action in action_conflicts.get(action,[]):\n if conflict_action in seen_non_default_actions:\n msg=_('not allowed with argument %s')\n action_name=_get_action_name(conflict_action)\n raise ArgumentError(action,msg %action_name)\n \n \n \n if argument_values is not SUPPRESS:\n action(self,namespace,argument_values,option_string)\n \n \n def consume_optional(start_index):\n \n \n option_tuple=option_string_indices[start_index]\n action,option_string,sep,explicit_arg=option_tuple\n \n \n \n match_argument=self._match_argument\n action_tuples=[]\n while True:\n \n \n if action is None:\n extras.append(arg_strings[start_index])\n return start_index+1\n \n \n \n if explicit_arg is not None:\n arg_count=match_argument(action,'A')\n \n \n \n \n chars=self.prefix_chars\n if(\n arg_count ==0\n and option_string[1]not in chars\n and explicit_arg !=''\n ):\n if sep or explicit_arg[0]in chars:\n msg=_('ignored explicit argument %r')\n raise ArgumentError(action,msg %explicit_arg)\n action_tuples.append((action,[],option_string))\n char=option_string[0]\n option_string=char+explicit_arg[0]\n optionals_map=self._option_string_actions\n if option_string in optionals_map:\n action=optionals_map[option_string]\n explicit_arg=explicit_arg[1:]\n if not explicit_arg:\n sep=explicit_arg=None\n elif explicit_arg[0]=='=':\n sep='='\n explicit_arg=explicit_arg[1:]\n else:\n sep=''\n else:\n extras.append(char+explicit_arg)\n stop=start_index+1\n break\n \n \n elif arg_count ==1:\n stop=start_index+1\n args=[explicit_arg]\n action_tuples.append((action,args,option_string))\n break\n \n \n \n else:\n msg=_('ignored explicit argument %r')\n raise ArgumentError(action,msg %explicit_arg)\n \n \n \n \n else:\n start=start_index+1\n selected_patterns=arg_strings_pattern[start:]\n arg_count=match_argument(action,selected_patterns)\n stop=start+arg_count\n args=arg_strings[start:stop]\n action_tuples.append((action,args,option_string))\n break\n \n \n \n assert action_tuples\n for action,args,option_string in action_tuples:\n if action.deprecated and option_string not in warned:\n self._warning(_(\"option '%(option)s' is deprecated\")%\n {'option':option_string})\n warned.add(option_string)\n take_action(action,args,option_string)\n return stop\n \n \n \n positionals=self._get_positional_actions()\n \n \n def consume_positionals(start_index):\n \n match_partial=self._match_arguments_partial\n selected_pattern=arg_strings_pattern[start_index:]\n arg_counts=match_partial(positionals,selected_pattern)\n \n \n \n for action,arg_count in zip(positionals,arg_counts):\n args=arg_strings[start_index:start_index+arg_count]\n start_index +=arg_count\n if args and action.deprecated and action.dest not in warned:\n self._warning(_(\"argument '%(argument_name)s' is deprecated\")%\n {'argument_name':action.dest})\n warned.add(action.dest)\n take_action(action,args)\n \n \n \n positionals[:]=positionals[len(arg_counts):]\n return start_index\n \n \n \n extras=[]\n start_index=0\n if option_string_indices:\n max_option_string_index=max(option_string_indices)\n else:\n max_option_string_index=-1\n while start_index <=max_option_string_index:\n \n \n next_option_string_index=start_index\n while next_option_string_index <=max_option_string_index:\n if next_option_string_index in option_string_indices:\n break\n next_option_string_index +=1\n if start_index !=next_option_string_index:\n positionals_end_index=consume_positionals(start_index)\n \n \n \n if positionals_end_index >start_index:\n start_index=positionals_end_index\n continue\n else:\n start_index=positionals_end_index\n \n \n \n if start_index not in option_string_indices:\n strings=arg_strings[start_index:next_option_string_index]\n extras.extend(strings)\n start_index=next_option_string_index\n \n \n start_index=consume_optional(start_index)\n \n \n stop_index=consume_positionals(start_index)\n \n \n extras.extend(arg_strings[stop_index:])\n \n \n \n required_actions=[]\n for action in self._actions:\n if action not in seen_actions:\n if action.required:\n required_actions.append(_get_action_name(action))\n else:\n \n \n \n \n if(action.default is not None and\n isinstance(action.default,str)and\n hasattr(namespace,action.dest)and\n action.default is getattr(namespace,action.dest)):\n setattr(namespace,action.dest,\n self._get_value(action,action.default))\n \n if required_actions:\n raise ArgumentError(None,_('the following arguments are required: %s')%\n ', '.join(required_actions))\n \n \n for group in self._mutually_exclusive_groups:\n if group.required:\n for action in group._group_actions:\n if action in seen_non_default_actions:\n break\n \n \n else:\n names=[_get_action_name(action)\n for action in group._group_actions\n if action.help is not SUPPRESS]\n msg=_('one of the arguments %s is required')\n raise ArgumentError(None,msg %' '.join(names))\n \n \n return namespace,extras\n \n def _read_args_from_files(self,arg_strings):\n \n new_arg_strings=[]\n for arg_string in arg_strings:\n \n \n if not arg_string or arg_string[0]not in self.fromfile_prefix_chars:\n new_arg_strings.append(arg_string)\n \n \n else:\n try:\n with open(arg_string[1:],\n encoding=_sys.getfilesystemencoding(),\n errors=_sys.getfilesystemencodeerrors())as args_file:\n arg_strings=[]\n for arg_line in args_file.read().splitlines():\n for arg in self.convert_arg_line_to_args(arg_line):\n arg_strings.append(arg)\n arg_strings=self._read_args_from_files(arg_strings)\n new_arg_strings.extend(arg_strings)\n except OSError as err:\n raise ArgumentError(None,str(err))\n \n \n return new_arg_strings\n \n def convert_arg_line_to_args(self,arg_line):\n return[arg_line]\n \n def _match_argument(self,action,arg_strings_pattern):\n \n nargs_pattern=self._get_nargs_pattern(action)\n match=_re.match(nargs_pattern,arg_strings_pattern)\n \n \n if match is None:\n nargs_errors={\n None:_('expected one argument'),\n OPTIONAL:_('expected at most one argument'),\n ONE_OR_MORE:_('expected at least one argument'),\n }\n msg=nargs_errors.get(action.nargs)\n if msg is None:\n msg=ngettext('expected %s argument',\n 'expected %s arguments',\n action.nargs)%action.nargs\n raise ArgumentError(action,msg)\n \n \n return len(match.group(1))\n \n def _match_arguments_partial(self,actions,arg_strings_pattern):\n \n \n result=[]\n for i in range(len(actions),0,-1):\n actions_slice=actions[:i]\n pattern=''.join([self._get_nargs_pattern(action)\n for action in actions_slice])\n match=_re.match(pattern,arg_strings_pattern)\n if match is not None:\n result.extend([len(string)for string in match.groups()])\n break\n \n \n return result\n \n def _parse_optional(self,arg_string):\n \n if not arg_string:\n return None\n \n \n if not arg_string[0]in self.prefix_chars:\n return None\n \n \n if arg_string in self._option_string_actions:\n action=self._option_string_actions[arg_string]\n return action,arg_string,None,None\n \n \n if len(arg_string)==1:\n return None\n \n \n option_string,sep,explicit_arg=arg_string.partition('=')\n if sep and option_string in self._option_string_actions:\n action=self._option_string_actions[option_string]\n return action,option_string,sep,explicit_arg\n \n \n \n option_tuples=self._get_option_tuples(arg_string)\n \n \n if len(option_tuples)>1:\n options=', '.join([option_string\n for action,option_string,sep,explicit_arg in option_tuples])\n args={'option':arg_string,'matches':options}\n msg=_('ambiguous option: %(option)s could match %(matches)s')\n raise ArgumentError(None,msg %args)\n \n \n \n elif len(option_tuples)==1:\n option_tuple,=option_tuples\n return option_tuple\n \n \n \n \n if self._negative_number_matcher.match(arg_string):\n if not self._has_negative_number_optionals:\n return None\n \n \n if ' 'in arg_string:\n return None\n \n \n \n return None,arg_string,None,None\n \n def _get_option_tuples(self,option_string):\n result=[]\n \n \n \n chars=self.prefix_chars\n if option_string[0]in chars and option_string[1]in chars:\n if self.allow_abbrev:\n option_prefix,sep,explicit_arg=option_string.partition('=')\n if not sep:\n sep=explicit_arg=None\n for option_string in self._option_string_actions:\n if option_string.startswith(option_prefix):\n action=self._option_string_actions[option_string]\n tup=action,option_string,sep,explicit_arg\n result.append(tup)\n \n \n \n \n elif option_string[0]in chars and option_string[1]not in chars:\n option_prefix=option_string\n short_option_prefix=option_string[:2]\n short_explicit_arg=option_string[2:]\n \n for option_string in self._option_string_actions:\n if option_string ==short_option_prefix:\n action=self._option_string_actions[option_string]\n tup=action,option_string,'',short_explicit_arg\n result.append(tup)\n elif option_string.startswith(option_prefix):\n action=self._option_string_actions[option_string]\n tup=action,option_string,None,None\n result.append(tup)\n \n \n else:\n raise ArgumentError(None,_('unexpected option string: %s')%option_string)\n \n \n return result\n \n def _get_nargs_pattern(self,action):\n \n \n nargs=action.nargs\n \n \n if nargs is None:\n nargs_pattern='(-*A-*)'\n \n \n elif nargs ==OPTIONAL:\n nargs_pattern='(-*A?-*)'\n \n \n elif nargs ==ZERO_OR_MORE:\n nargs_pattern='(-*[A-]*)'\n \n \n elif nargs ==ONE_OR_MORE:\n nargs_pattern='(-*A[A-]*)'\n \n \n elif nargs ==REMAINDER:\n nargs_pattern='([-AO]*)'\n \n \n elif nargs ==PARSER:\n nargs_pattern='(-*A[-AO]*)'\n \n \n elif nargs ==SUPPRESS:\n nargs_pattern='(-*-*)'\n \n \n else:\n nargs_pattern='(-*%s-*)'%'-*'.join('A'*nargs)\n \n \n if action.option_strings:\n nargs_pattern=nargs_pattern.replace('-*','')\n nargs_pattern=nargs_pattern.replace('-','')\n \n \n return nargs_pattern\n \n \n \n \n \n def parse_intermixed_args(self,args=None,namespace=None):\n args,argv=self.parse_known_intermixed_args(args,namespace)\n if argv:\n msg=_('unrecognized arguments: %s')%' '.join(argv)\n if self.exit_on_error:\n self.error(msg)\n else:\n raise ArgumentError(None,msg)\n return args\n \n def parse_known_intermixed_args(self,args=None,namespace=None):\n \n \n \n \n \n \n \n \n \n \n \n \n positionals=self._get_positional_actions()\n a=[action for action in positionals\n if action.nargs in[PARSER,REMAINDER]]\n if a:\n raise TypeError('parse_intermixed_args: positional arg'\n ' with nargs=%s'%a[0].nargs)\n \n if[action.dest for group in self._mutually_exclusive_groups\n for action in group._group_actions if action in positionals]:\n raise TypeError('parse_intermixed_args: positional in'\n ' mutuallyExclusiveGroup')\n \n try:\n save_usage=self.usage\n try:\n if self.usage is None:\n \n self.usage=self.format_usage()[7:]\n for action in positionals:\n \n action.save_nargs=action.nargs\n \n action.nargs=SUPPRESS\n action.save_default=action.default\n action.default=SUPPRESS\n namespace,remaining_args=self.parse_known_args(args,\n namespace)\n for action in positionals:\n \n if(hasattr(namespace,action.dest)\n and getattr(namespace,action.dest)==[]):\n from warnings import warn\n warn('Do not expect %s in %s'%(action.dest,namespace))\n delattr(namespace,action.dest)\n finally:\n \n for action in positionals:\n action.nargs=action.save_nargs\n action.default=action.save_default\n optionals=self._get_optional_actions()\n try:\n \n \n for action in optionals:\n action.save_required=action.required\n action.required=False\n for group in self._mutually_exclusive_groups:\n group.save_required=group.required\n group.required=False\n namespace,extras=self.parse_known_args(remaining_args,\n namespace)\n finally:\n \n for action in optionals:\n action.required=action.save_required\n for group in self._mutually_exclusive_groups:\n group.required=group.save_required\n finally:\n self.usage=save_usage\n return namespace,extras\n \n \n \n \n def _get_values(self,action,arg_strings):\n \n if not action.option_strings and action.nargs not in[PARSER,REMAINDER]:\n try:\n arg_strings.remove('--')\n except ValueError:\n pass\n \n \n if not arg_strings and action.nargs ==OPTIONAL:\n if action.option_strings:\n value=action.const\n else:\n value=action.default\n if isinstance(value,str):\n value=self._get_value(action,value)\n self._check_value(action,value)\n \n \n \n elif(not arg_strings and action.nargs ==ZERO_OR_MORE and\n not action.option_strings):\n if action.default is not None:\n value=action.default\n self._check_value(action,value)\n else:\n \n \n value=arg_strings\n \n \n elif len(arg_strings)==1 and action.nargs in[None,OPTIONAL]:\n arg_string,=arg_strings\n value=self._get_value(action,arg_string)\n self._check_value(action,value)\n \n \n elif action.nargs ==REMAINDER:\n value=[self._get_value(action,v)for v in arg_strings]\n \n \n elif action.nargs ==PARSER:\n value=[self._get_value(action,v)for v in arg_strings]\n self._check_value(action,value[0])\n \n \n elif action.nargs ==SUPPRESS:\n value=SUPPRESS\n \n \n else:\n value=[self._get_value(action,v)for v in arg_strings]\n for v in value:\n self._check_value(action,v)\n \n \n return value\n \n def _get_value(self,action,arg_string):\n type_func=self._registry_get('type',action.type,action.type)\n if not callable(type_func):\n msg=_('%r is not callable')\n raise ArgumentError(action,msg %type_func)\n \n \n try:\n result=type_func(arg_string)\n \n \n except ArgumentTypeError as err:\n msg=str(err)\n raise ArgumentError(action,msg)\n \n \n except(TypeError,ValueError):\n name=getattr(action.type,'__name__',repr(action.type))\n args={'type':name,'value':arg_string}\n msg=_('invalid %(type)s value: %(value)r')\n raise ArgumentError(action,msg %args)\n \n \n return result\n \n def _check_value(self,action,value):\n \n if action.choices is not None and value not in action.choices:\n args={'value':value,\n 'choices':', '.join(map(repr,action.choices))}\n msg=_('invalid choice: %(value)r (choose from %(choices)s)')\n raise ArgumentError(action,msg %args)\n \n \n \n \n def format_usage(self):\n formatter=self._get_formatter()\n formatter.add_usage(self.usage,self._actions,\n self._mutually_exclusive_groups)\n return formatter.format_help()\n \n def format_help(self):\n formatter=self._get_formatter()\n \n \n formatter.add_usage(self.usage,self._actions,\n self._mutually_exclusive_groups)\n \n \n formatter.add_text(self.description)\n \n \n for action_group in self._action_groups:\n formatter.start_section(action_group.title)\n formatter.add_text(action_group.description)\n formatter.add_arguments(action_group._group_actions)\n formatter.end_section()\n \n \n formatter.add_text(self.epilog)\n \n \n return formatter.format_help()\n \n def _get_formatter(self):\n return self.formatter_class(prog=self.prog)\n \n \n \n \n def print_usage(self,file=None):\n if file is None:\n file=_sys.stdout\n self._print_message(self.format_usage(),file)\n \n def print_help(self,file=None):\n if file is None:\n file=_sys.stdout\n self._print_message(self.format_help(),file)\n \n def _print_message(self,message,file=None):\n if message:\n file=file or _sys.stderr\n try:\n file.write(message)\n except(AttributeError,OSError):\n pass\n \n \n \n \n def exit(self,status=0,message=None):\n if message:\n self._print_message(message,_sys.stderr)\n _sys.exit(status)\n \n def error(self,message):\n ''\n\n\n\n\n\n\n \n self.print_usage(_sys.stderr)\n args={'prog':self.prog,'message':message}\n self.exit(2,_('%(prog)s: error: %(message)s\\n')%args)\n \n def _warning(self,message):\n args={'prog':self.prog,'message':message}\n self._print_message(_('%(prog)s: warning: %(message)s\\n')%args,_sys.stderr)\n", ["copy", "gettext", "os", "re", "shutil", "sys", "textwrap", "warnings"]], "ast": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport re\nfrom _ast import *\nfrom contextlib import contextmanager,nullcontext\nfrom enum import IntEnum,auto,_simple_enum\n\n\ndef parse(source,filename='',mode='exec',*,\ntype_comments=False,feature_version=None,optimize=-1):\n ''\n\n\n\n \n flags=PyCF_ONLY_AST\n if optimize >0:\n flags |=PyCF_OPTIMIZED_AST\n if type_comments:\n flags |=PyCF_TYPE_COMMENTS\n if feature_version is None:\n feature_version=-1\n elif isinstance(feature_version,tuple):\n major,minor=feature_version\n if major !=3:\n raise ValueError(f\"Unsupported major version: {major}\")\n feature_version=minor\n \n return compile(source,filename,mode,flags,\n _feature_version=feature_version,optimize=optimize)\n \n \ndef literal_eval(node_or_string):\n ''\n\n\n\n\n\n\n \n if isinstance(node_or_string,str):\n node_or_string=parse(node_or_string.lstrip(\" \\t\"),mode='eval')\n if isinstance(node_or_string,Expression):\n node_or_string=node_or_string.body\n def _raise_malformed_node(node):\n msg=\"malformed node or string\"\n if lno :=getattr(node,'lineno',None):\n msg +=f' on line {lno}'\n raise ValueError(msg+f': {node !r}')\n def _convert_num(node):\n if not isinstance(node,Constant)or type(node.value)not in(int,float,complex):\n _raise_malformed_node(node)\n return node.value\n def _convert_signed_num(node):\n if isinstance(node,UnaryOp)and isinstance(node.op,(UAdd,USub)):\n operand=_convert_num(node.operand)\n if isinstance(node.op,UAdd):\n return+operand\n else:\n return -operand\n return _convert_num(node)\n def _convert(node):\n if isinstance(node,Constant):\n return node.value\n elif isinstance(node,Tuple):\n return tuple(map(_convert,node.elts))\n elif isinstance(node,List):\n return list(map(_convert,node.elts))\n elif isinstance(node,Set):\n return set(map(_convert,node.elts))\n elif(isinstance(node,Call)and isinstance(node.func,Name)and\n node.func.id =='set'and node.args ==node.keywords ==[]):\n return set()\n elif isinstance(node,Dict):\n if len(node.keys)!=len(node.values):\n _raise_malformed_node(node)\n return dict(zip(map(_convert,node.keys),\n map(_convert,node.values)))\n elif isinstance(node,BinOp)and isinstance(node.op,(Add,Sub)):\n left=_convert_signed_num(node.left)\n right=_convert_num(node.right)\n if isinstance(left,(int,float))and isinstance(right,complex):\n if isinstance(node.op,Add):\n return left+right\n else:\n return left -right\n return _convert_signed_num(node)\n return _convert(node_or_string)\n \n \ndef dump(\nnode,annotate_fields=True,include_attributes=False,\n*,\nindent=None,show_empty=False,\n):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n def _format(node,level=0):\n if indent is not None:\n level +=1\n prefix='\\n'+indent *level\n sep=',\\n'+indent *level\n else:\n prefix=''\n sep=', '\n if isinstance(node,AST):\n cls=type(node)\n args=[]\n args_buffer=[]\n allsimple=True\n keywords=annotate_fields\n for name in node._fields:\n try:\n value=getattr(node,name)\n except AttributeError:\n keywords=True\n continue\n if value is None and getattr(cls,name,...)is None:\n keywords=True\n continue\n if(\n not show_empty\n and(value is None or value ==[])\n \n \n and not isinstance(node,(Constant,MatchSingleton))\n ):\n args_buffer.append(repr(value))\n continue\n elif not keywords:\n args.extend(args_buffer)\n args_buffer=[]\n value,simple=_format(value,level)\n allsimple=allsimple and simple\n if keywords:\n args.append('%s=%s'%(name,value))\n else:\n args.append(value)\n if include_attributes and node._attributes:\n for name in node._attributes:\n try:\n value=getattr(node,name)\n except AttributeError:\n continue\n if value is None and getattr(cls,name,...)is None:\n continue\n value,simple=_format(value,level)\n allsimple=allsimple and simple\n args.append('%s=%s'%(name,value))\n if allsimple and len(args)<=3:\n return '%s(%s)'%(node.__class__.__name__,', '.join(args)),not args\n return '%s(%s%s)'%(node.__class__.__name__,prefix,sep.join(args)),False\n elif isinstance(node,list):\n if not node:\n return '[]',True\n return '[%s%s]'%(prefix,sep.join(_format(x,level)[0]for x in node)),False\n return repr(node),True\n \n if not isinstance(node,AST):\n raise TypeError('expected AST, got %r'%node.__class__.__name__)\n if indent is not None and not isinstance(indent,str):\n indent=' '*indent\n return _format(node)[0]\n \n \ndef copy_location(new_node,old_node):\n ''\n\n\n \n for attr in 'lineno','col_offset','end_lineno','end_col_offset':\n if attr in old_node._attributes and attr in new_node._attributes:\n value=getattr(old_node,attr,None)\n \n \n if value is not None or(\n hasattr(old_node,attr)and attr.startswith(\"end_\")\n ):\n setattr(new_node,attr,value)\n return new_node\n \n \ndef fix_missing_locations(node):\n ''\n\n\n\n\n\n \n def _fix(node,lineno,col_offset,end_lineno,end_col_offset):\n if 'lineno'in node._attributes:\n if not hasattr(node,'lineno'):\n node.lineno=lineno\n else:\n lineno=node.lineno\n if 'end_lineno'in node._attributes:\n if getattr(node,'end_lineno',None)is None:\n node.end_lineno=end_lineno\n else:\n end_lineno=node.end_lineno\n if 'col_offset'in node._attributes:\n if not hasattr(node,'col_offset'):\n node.col_offset=col_offset\n else:\n col_offset=node.col_offset\n if 'end_col_offset'in node._attributes:\n if getattr(node,'end_col_offset',None)is None:\n node.end_col_offset=end_col_offset\n else:\n end_col_offset=node.end_col_offset\n for child in iter_child_nodes(node):\n _fix(child,lineno,col_offset,end_lineno,end_col_offset)\n _fix(node,1,0,1,0)\n return node\n \n \ndef increment_lineno(node,n=1):\n ''\n\n\n\n \n for child in walk(node):\n \n \n if isinstance(child,TypeIgnore):\n child.lineno=getattr(child,'lineno',0)+n\n continue\n \n if 'lineno'in child._attributes:\n child.lineno=getattr(child,'lineno',0)+n\n if(\n \"end_lineno\"in child._attributes\n and(end_lineno :=getattr(child,\"end_lineno\",0))is not None\n ):\n child.end_lineno=end_lineno+n\n return node\n \n \ndef iter_fields(node):\n ''\n\n\n \n for field in node._fields:\n try:\n yield field,getattr(node,field)\n except AttributeError:\n pass\n \n \ndef iter_child_nodes(node):\n ''\n\n\n \n for name,field in iter_fields(node):\n if isinstance(field,AST):\n yield field\n elif isinstance(field,list):\n for item in field:\n if isinstance(item,AST):\n yield item\n \n \ndef get_docstring(node,clean=True):\n ''\n\n\n\n\n\n\n \n if not isinstance(node,(AsyncFunctionDef,FunctionDef,ClassDef,Module)):\n raise TypeError(\"%r can't have docstrings\"%node.__class__.__name__)\n if not(node.body and isinstance(node.body[0],Expr)):\n return None\n node=node.body[0].value\n if isinstance(node,Constant)and isinstance(node.value,str):\n text=node.value\n else:\n return None\n if clean:\n import inspect\n text=inspect.cleandoc(text)\n return text\n \n \n_line_pattern=re.compile(r\"(.*?(?:\\r\\n|\\n|\\r|$))\")\ndef _splitlines_no_ff(source,maxlines=None):\n ''\n\n\n \n lines=[]\n for lineno,match in enumerate(_line_pattern.finditer(source),1):\n if maxlines is not None and lineno >maxlines:\n break\n lines.append(match[0])\n return lines\n \n \ndef _pad_whitespace(source):\n ''\n result=''\n for c in source:\n if c in '\\f\\t':\n result +=c\n else:\n result +=' '\n return result\n \n \ndef get_source_segment(source,node,*,padded=False):\n ''\n\n\n\n\n\n\n \n try:\n if node.end_lineno is None or node.end_col_offset is None:\n return None\n lineno=node.lineno -1\n end_lineno=node.end_lineno -1\n col_offset=node.col_offset\n end_col_offset=node.end_col_offset\n except AttributeError:\n return None\n \n lines=_splitlines_no_ff(source,maxlines=end_lineno+1)\n if end_lineno ==lineno:\n return lines[lineno].encode()[col_offset:end_col_offset].decode()\n \n if padded:\n padding=_pad_whitespace(lines[lineno].encode()[:col_offset].decode())\n else:\n padding=''\n \n first=padding+lines[lineno].encode()[col_offset:].decode()\n last=lines[end_lineno].encode()[:end_col_offset].decode()\n lines=lines[lineno+1:end_lineno]\n \n lines.insert(0,first)\n lines.append(last)\n return ''.join(lines)\n \n \ndef walk(node):\n ''\n\n\n\n \n from collections import deque\n todo=deque([node])\n while todo:\n node=todo.popleft()\n todo.extend(iter_child_nodes(node))\n yield node\n \n \nclass NodeVisitor(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def visit(self,node):\n ''\n method='visit_'+node.__class__.__name__\n visitor=getattr(self,method,self.generic_visit)\n return visitor(node)\n \n def generic_visit(self,node):\n ''\n for field,value in iter_fields(node):\n if isinstance(value,list):\n for item in value:\n if isinstance(item,AST):\n self.visit(item)\n elif isinstance(value,AST):\n self.visit(value)\n \n def visit_Constant(self,node):\n value=node.value\n type_name=_const_node_type_names.get(type(value))\n if type_name is None:\n for cls,name in _const_node_type_names.items():\n if isinstance(value,cls):\n type_name=name\n break\n if type_name is not None:\n method='visit_'+type_name\n try:\n visitor=getattr(self,method)\n except AttributeError:\n pass\n else:\n import warnings\n warnings.warn(f\"{method} is deprecated; add visit_Constant\",\n DeprecationWarning,2)\n return visitor(node)\n return self.generic_visit(node)\n \n \nclass NodeTransformer(NodeVisitor):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def generic_visit(self,node):\n for field,old_value in iter_fields(node):\n if isinstance(old_value,list):\n new_values=[]\n for value in old_value:\n if isinstance(value,AST):\n value=self.visit(value)\n if value is None:\n continue\n elif not isinstance(value,AST):\n new_values.extend(value)\n continue\n new_values.append(value)\n old_value[:]=new_values\n elif isinstance(old_value,AST):\n new_node=self.visit(old_value)\n if new_node is None:\n delattr(node,field)\n else:\n setattr(node,field,new_node)\n return node\n \n \n_DEPRECATED_VALUE_ALIAS_MESSAGE=(\n\"{name} is deprecated and will be removed in Python {remove}; use value instead\"\n)\n_DEPRECATED_CLASS_MESSAGE=(\n\"{name} is deprecated and will be removed in Python {remove}; \"\n\"use ast.Constant instead\"\n)\n\n\n\nif not hasattr(Constant,'n'):\n\n\n\n def _n_getter(self):\n ''\n import warnings\n warnings._deprecated(\n \"Attribute n\",message=_DEPRECATED_VALUE_ALIAS_MESSAGE,remove=(3,14)\n )\n return self.value\n \n def _n_setter(self,value):\n import warnings\n warnings._deprecated(\n \"Attribute n\",message=_DEPRECATED_VALUE_ALIAS_MESSAGE,remove=(3,14)\n )\n self.value=value\n \n def _s_getter(self):\n ''\n import warnings\n warnings._deprecated(\n \"Attribute s\",message=_DEPRECATED_VALUE_ALIAS_MESSAGE,remove=(3,14)\n )\n return self.value\n \n def _s_setter(self,value):\n import warnings\n warnings._deprecated(\n \"Attribute s\",message=_DEPRECATED_VALUE_ALIAS_MESSAGE,remove=(3,14)\n )\n self.value=value\n \n Constant.n=property(_n_getter,_n_setter)\n Constant.s=property(_s_getter,_s_setter)\n \nclass _ABC(type):\n\n def __init__(cls,*args):\n cls.__doc__=\"\"\"Deprecated AST node class. Use ast.Constant instead\"\"\"\n \n def __instancecheck__(cls,inst):\n if cls in _const_types:\n import warnings\n warnings._deprecated(\n f\"ast.{cls.__qualname__}\",\n message=_DEPRECATED_CLASS_MESSAGE,\n remove=(3,14)\n )\n if not isinstance(inst,Constant):\n return False\n if cls in _const_types:\n try:\n value=inst.value\n except AttributeError:\n return False\n else:\n return(\n isinstance(value,_const_types[cls])and\n not isinstance(value,_const_types_not.get(cls,()))\n )\n return type.__instancecheck__(cls,inst)\n \ndef _new(cls,*args,**kwargs):\n for key in kwargs:\n if key not in cls._fields:\n \n continue\n pos=cls._fields.index(key)\n if pos precedence)\n \n def get_precedence(self,node):\n return self._precedences.get(node,_Precedence.TEST)\n \n def set_precedence(self,precedence,*nodes):\n for node in nodes:\n self._precedences[node]=precedence\n \n def get_raw_docstring(self,node):\n ''\n\n\n \n if not isinstance(\n node,(AsyncFunctionDef,FunctionDef,ClassDef,Module)\n )or len(node.body)<1:\n return None\n node=node.body[0]\n if not isinstance(node,Expr):\n return None\n node=node.value\n if isinstance(node,Constant)and isinstance(node.value,str):\n return node\n \n def get_type_comment(self,node):\n comment=self._type_ignores.get(node.lineno)or node.type_comment\n if comment is not None:\n return f\" # type: {comment}\"\n \n def traverse(self,node):\n if isinstance(node,list):\n for item in node:\n self.traverse(item)\n else:\n super().visit(node)\n \n \n \n \n def visit(self,node):\n ''\n \n self._source=[]\n self.traverse(node)\n return \"\".join(self._source)\n \n def _write_docstring_and_traverse_body(self,node):\n if(docstring :=self.get_raw_docstring(node)):\n self._write_docstring(docstring)\n self.traverse(node.body[1:])\n else:\n self.traverse(node.body)\n \n def visit_Module(self,node):\n self._type_ignores={\n ignore.lineno:f\"ignore{ignore.tag}\"\n for ignore in node.type_ignores\n }\n self._write_docstring_and_traverse_body(node)\n self._type_ignores.clear()\n \n def visit_FunctionType(self,node):\n with self.delimit(\"(\",\")\"):\n self.interleave(\n lambda:self.write(\", \"),self.traverse,node.argtypes\n )\n \n self.write(\" -> \")\n self.traverse(node.returns)\n \n def visit_Expr(self,node):\n self.fill()\n self.set_precedence(_Precedence.YIELD,node.value)\n self.traverse(node.value)\n \n def visit_NamedExpr(self,node):\n with self.require_parens(_Precedence.NAMED_EXPR,node):\n self.set_precedence(_Precedence.ATOM,node.target,node.value)\n self.traverse(node.target)\n self.write(\" := \")\n self.traverse(node.value)\n \n def visit_Import(self,node):\n self.fill(\"import \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.names)\n \n def visit_ImportFrom(self,node):\n self.fill(\"from \")\n self.write(\".\"*(node.level or 0))\n if node.module:\n self.write(node.module)\n self.write(\" import \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.names)\n \n def visit_Assign(self,node):\n self.fill()\n for target in node.targets:\n self.set_precedence(_Precedence.TUPLE,target)\n self.traverse(target)\n self.write(\" = \")\n self.traverse(node.value)\n if type_comment :=self.get_type_comment(node):\n self.write(type_comment)\n \n def visit_AugAssign(self,node):\n self.fill()\n self.traverse(node.target)\n self.write(\" \"+self.binop[node.op.__class__.__name__]+\"= \")\n self.traverse(node.value)\n \n def visit_AnnAssign(self,node):\n self.fill()\n with self.delimit_if(\"(\",\")\",not node.simple and isinstance(node.target,Name)):\n self.traverse(node.target)\n self.write(\": \")\n self.traverse(node.annotation)\n if node.value:\n self.write(\" = \")\n self.traverse(node.value)\n \n def visit_Return(self,node):\n self.fill(\"return\")\n if node.value:\n self.write(\" \")\n self.traverse(node.value)\n \n def visit_Pass(self,node):\n self.fill(\"pass\")\n \n def visit_Break(self,node):\n self.fill(\"break\")\n \n def visit_Continue(self,node):\n self.fill(\"continue\")\n \n def visit_Delete(self,node):\n self.fill(\"del \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.targets)\n \n def visit_Assert(self,node):\n self.fill(\"assert \")\n self.traverse(node.test)\n if node.msg:\n self.write(\", \")\n self.traverse(node.msg)\n \n def visit_Global(self,node):\n self.fill(\"global \")\n self.interleave(lambda:self.write(\", \"),self.write,node.names)\n \n def visit_Nonlocal(self,node):\n self.fill(\"nonlocal \")\n self.interleave(lambda:self.write(\", \"),self.write,node.names)\n \n def visit_Await(self,node):\n with self.require_parens(_Precedence.AWAIT,node):\n self.write(\"await\")\n if node.value:\n self.write(\" \")\n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n \n def visit_Yield(self,node):\n with self.require_parens(_Precedence.YIELD,node):\n self.write(\"yield\")\n if node.value:\n self.write(\" \")\n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n \n def visit_YieldFrom(self,node):\n with self.require_parens(_Precedence.YIELD,node):\n self.write(\"yield from \")\n if not node.value:\n raise ValueError(\"Node can't be used without a value attribute.\")\n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n \n def visit_Raise(self,node):\n self.fill(\"raise\")\n if not node.exc:\n if node.cause:\n raise ValueError(f\"Node can't use cause without an exception.\")\n return\n self.write(\" \")\n self.traverse(node.exc)\n if node.cause:\n self.write(\" from \")\n self.traverse(node.cause)\n \n def do_visit_try(self,node):\n self.fill(\"try\")\n with self.block():\n self.traverse(node.body)\n for ex in node.handlers:\n self.traverse(ex)\n if node.orelse:\n self.fill(\"else\")\n with self.block():\n self.traverse(node.orelse)\n if node.finalbody:\n self.fill(\"finally\")\n with self.block():\n self.traverse(node.finalbody)\n \n def visit_Try(self,node):\n prev_in_try_star=self._in_try_star\n try:\n self._in_try_star=False\n self.do_visit_try(node)\n finally:\n self._in_try_star=prev_in_try_star\n \n def visit_TryStar(self,node):\n prev_in_try_star=self._in_try_star\n try:\n self._in_try_star=True\n self.do_visit_try(node)\n finally:\n self._in_try_star=prev_in_try_star\n \n def visit_ExceptHandler(self,node):\n self.fill(\"except*\"if self._in_try_star else \"except\")\n if node.type:\n self.write(\" \")\n self.traverse(node.type)\n if node.name:\n self.write(\" as \")\n self.write(node.name)\n with self.block():\n self.traverse(node.body)\n \n def visit_ClassDef(self,node):\n self.maybe_newline()\n for deco in node.decorator_list:\n self.fill(\"@\")\n self.traverse(deco)\n self.fill(\"class \"+node.name)\n if hasattr(node,\"type_params\"):\n self._type_params_helper(node.type_params)\n with self.delimit_if(\"(\",\")\",condition=node.bases or node.keywords):\n comma=False\n for e in node.bases:\n if comma:\n self.write(\", \")\n else:\n comma=True\n self.traverse(e)\n for e in node.keywords:\n if comma:\n self.write(\", \")\n else:\n comma=True\n self.traverse(e)\n \n with self.block():\n self._write_docstring_and_traverse_body(node)\n \n def visit_FunctionDef(self,node):\n self._function_helper(node,\"def\")\n \n def visit_AsyncFunctionDef(self,node):\n self._function_helper(node,\"async def\")\n \n def _function_helper(self,node,fill_suffix):\n self.maybe_newline()\n for deco in node.decorator_list:\n self.fill(\"@\")\n self.traverse(deco)\n def_str=fill_suffix+\" \"+node.name\n self.fill(def_str)\n if hasattr(node,\"type_params\"):\n self._type_params_helper(node.type_params)\n with self.delimit(\"(\",\")\"):\n self.traverse(node.args)\n if node.returns:\n self.write(\" -> \")\n self.traverse(node.returns)\n with self.block(extra=self.get_type_comment(node)):\n self._write_docstring_and_traverse_body(node)\n \n def _type_params_helper(self,type_params):\n if type_params is not None and len(type_params)>0:\n with self.delimit(\"[\",\"]\"):\n self.interleave(lambda:self.write(\", \"),self.traverse,type_params)\n \n def visit_TypeVar(self,node):\n self.write(node.name)\n if node.bound:\n self.write(\": \")\n self.traverse(node.bound)\n if node.default_value:\n self.write(\" = \")\n self.traverse(node.default_value)\n \n def visit_TypeVarTuple(self,node):\n self.write(\"*\"+node.name)\n if node.default_value:\n self.write(\" = \")\n self.traverse(node.default_value)\n \n def visit_ParamSpec(self,node):\n self.write(\"**\"+node.name)\n if node.default_value:\n self.write(\" = \")\n self.traverse(node.default_value)\n \n def visit_TypeAlias(self,node):\n self.fill(\"type \")\n self.traverse(node.name)\n self._type_params_helper(node.type_params)\n self.write(\" = \")\n self.traverse(node.value)\n \n def visit_For(self,node):\n self._for_helper(\"for \",node)\n \n def visit_AsyncFor(self,node):\n self._for_helper(\"async for \",node)\n \n def _for_helper(self,fill,node):\n self.fill(fill)\n self.set_precedence(_Precedence.TUPLE,node.target)\n self.traverse(node.target)\n self.write(\" in \")\n self.traverse(node.iter)\n with self.block(extra=self.get_type_comment(node)):\n self.traverse(node.body)\n if node.orelse:\n self.fill(\"else\")\n with self.block():\n self.traverse(node.orelse)\n \n def visit_If(self,node):\n self.fill(\"if \")\n self.traverse(node.test)\n with self.block():\n self.traverse(node.body)\n \n while node.orelse and len(node.orelse)==1 and isinstance(node.orelse[0],If):\n node=node.orelse[0]\n self.fill(\"elif \")\n self.traverse(node.test)\n with self.block():\n self.traverse(node.body)\n \n if node.orelse:\n self.fill(\"else\")\n with self.block():\n self.traverse(node.orelse)\n \n def visit_While(self,node):\n self.fill(\"while \")\n self.traverse(node.test)\n with self.block():\n self.traverse(node.body)\n if node.orelse:\n self.fill(\"else\")\n with self.block():\n self.traverse(node.orelse)\n \n def visit_With(self,node):\n self.fill(\"with \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.items)\n with self.block(extra=self.get_type_comment(node)):\n self.traverse(node.body)\n \n def visit_AsyncWith(self,node):\n self.fill(\"async with \")\n self.interleave(lambda:self.write(\", \"),self.traverse,node.items)\n with self.block(extra=self.get_type_comment(node)):\n self.traverse(node.body)\n \n def _str_literal_helper(\n self,string,*,quote_types=_ALL_QUOTES,escape_special_whitespace=False\n ):\n ''\n\n \n def escape_char(c):\n \n \n if not escape_special_whitespace and c in \"\\n\\t\":\n return c\n \n if c ==\"\\\\\"or not c.isprintable():\n return c.encode(\"unicode_escape\").decode(\"ascii\")\n return c\n \n escaped_string=\"\".join(map(escape_char,string))\n possible_quotes=quote_types\n if \"\\n\"in escaped_string:\n possible_quotes=[q for q in possible_quotes if q in _MULTI_QUOTES]\n possible_quotes=[q for q in possible_quotes if q not in escaped_string]\n if not possible_quotes:\n \n \n \n string=repr(string)\n quote=next((q for q in quote_types if string[0]in q),string[0])\n return string[1:-1],[quote]\n if escaped_string:\n \n possible_quotes.sort(key=lambda q:q[0]==escaped_string[-1])\n \n \n if possible_quotes[0][0]==escaped_string[-1]:\n assert len(possible_quotes[0])==3\n escaped_string=escaped_string[:-1]+\"\\\\\"+escaped_string[-1]\n return escaped_string,possible_quotes\n \n def _write_str_avoiding_backslashes(self,string,*,quote_types=_ALL_QUOTES):\n ''\n string,quote_types=self._str_literal_helper(string,quote_types=quote_types)\n quote_type=quote_types[0]\n self.write(f\"{quote_type}{string}{quote_type}\")\n \n def visit_JoinedStr(self,node):\n self.write(\"f\")\n \n fstring_parts=[]\n for value in node.values:\n with self.buffered()as buffer:\n self._write_fstring_inner(value)\n fstring_parts.append(\n (\"\".join(buffer),isinstance(value,Constant))\n )\n \n new_fstring_parts=[]\n quote_types=list(_ALL_QUOTES)\n fallback_to_repr=False\n for value,is_constant in fstring_parts:\n if is_constant:\n value,new_quote_types=self._str_literal_helper(\n value,\n quote_types=quote_types,\n escape_special_whitespace=True,\n )\n if set(new_quote_types).isdisjoint(quote_types):\n fallback_to_repr=True\n break\n quote_types=new_quote_types\n elif \"\\n\"in value:\n quote_types=[q for q in quote_types if q in _MULTI_QUOTES]\n assert quote_types\n new_fstring_parts.append(value)\n \n if fallback_to_repr:\n \n \n quote_types=[\"'''\"]\n new_fstring_parts.clear()\n for value,is_constant in fstring_parts:\n if is_constant:\n value=repr('\"'+value)\n expected_prefix=\"'\\\"\"\n assert value.startswith(expected_prefix),repr(value)\n value=value[len(expected_prefix):-1]\n new_fstring_parts.append(value)\n \n value=\"\".join(new_fstring_parts)\n quote_type=quote_types[0]\n self.write(f\"{quote_type}{value}{quote_type}\")\n \n def _write_fstring_inner(self,node,is_format_spec=False):\n if isinstance(node,JoinedStr):\n \n for value in node.values:\n self._write_fstring_inner(value,is_format_spec=is_format_spec)\n elif isinstance(node,Constant)and isinstance(node.value,str):\n value=node.value.replace(\"{\",\"{{\").replace(\"}\",\"}}\")\n \n if is_format_spec:\n value=value.replace(\"\\\\\",\"\\\\\\\\\")\n value=value.replace(\"'\",\"\\\\'\")\n value=value.replace('\"','\\\\\"')\n value=value.replace(\"\\n\",\"\\\\n\")\n self.write(value)\n elif isinstance(node,FormattedValue):\n self.visit_FormattedValue(node)\n else:\n raise ValueError(f\"Unexpected node inside JoinedStr, {node !r}\")\n \n def visit_FormattedValue(self,node):\n def unparse_inner(inner):\n unparser=type(self)()\n unparser.set_precedence(_Precedence.TEST.next(),inner)\n return unparser.visit(inner)\n \n with self.delimit(\"{\",\"}\"):\n expr=unparse_inner(node.value)\n if expr.startswith(\"{\"):\n \n self.write(\" \")\n self.write(expr)\n if node.conversion !=-1:\n self.write(f\"!{chr(node.conversion)}\")\n if node.format_spec:\n self.write(\":\")\n self._write_fstring_inner(node.format_spec,is_format_spec=True)\n \n def visit_Name(self,node):\n self.write(node.id)\n \n def _write_docstring(self,node):\n self.fill()\n if node.kind ==\"u\":\n self.write(\"u\")\n self._write_str_avoiding_backslashes(node.value,quote_types=_MULTI_QUOTES)\n \n def _write_constant(self,value):\n if isinstance(value,(float,complex)):\n \n \n self.write(\n repr(value)\n .replace(\"inf\",_INFSTR)\n .replace(\"nan\",f\"({_INFSTR}-{_INFSTR})\")\n )\n else:\n self.write(repr(value))\n \n def visit_Constant(self,node):\n value=node.value\n if isinstance(value,tuple):\n with self.delimit(\"(\",\")\"):\n self.items_view(self._write_constant,value)\n elif value is ...:\n self.write(\"...\")\n else:\n if node.kind ==\"u\":\n self.write(\"u\")\n self._write_constant(node.value)\n \n def visit_List(self,node):\n with self.delimit(\"[\",\"]\"):\n self.interleave(lambda:self.write(\", \"),self.traverse,node.elts)\n \n def visit_ListComp(self,node):\n with self.delimit(\"[\",\"]\"):\n self.traverse(node.elt)\n for gen in node.generators:\n self.traverse(gen)\n \n def visit_GeneratorExp(self,node):\n with self.delimit(\"(\",\")\"):\n self.traverse(node.elt)\n for gen in node.generators:\n self.traverse(gen)\n \n def visit_SetComp(self,node):\n with self.delimit(\"{\",\"}\"):\n self.traverse(node.elt)\n for gen in node.generators:\n self.traverse(gen)\n \n def visit_DictComp(self,node):\n with self.delimit(\"{\",\"}\"):\n self.traverse(node.key)\n self.write(\": \")\n self.traverse(node.value)\n for gen in node.generators:\n self.traverse(gen)\n \n def visit_comprehension(self,node):\n if node.is_async:\n self.write(\" async for \")\n else:\n self.write(\" for \")\n self.set_precedence(_Precedence.TUPLE,node.target)\n self.traverse(node.target)\n self.write(\" in \")\n self.set_precedence(_Precedence.TEST.next(),node.iter,*node.ifs)\n self.traverse(node.iter)\n for if_clause in node.ifs:\n self.write(\" if \")\n self.traverse(if_clause)\n \n def visit_IfExp(self,node):\n with self.require_parens(_Precedence.TEST,node):\n self.set_precedence(_Precedence.TEST.next(),node.body,node.test)\n self.traverse(node.body)\n self.write(\" if \")\n self.traverse(node.test)\n self.write(\" else \")\n self.set_precedence(_Precedence.TEST,node.orelse)\n self.traverse(node.orelse)\n \n def visit_Set(self,node):\n if node.elts:\n with self.delimit(\"{\",\"}\"):\n self.interleave(lambda:self.write(\", \"),self.traverse,node.elts)\n else:\n \n \n self.write('{*()}')\n \n def visit_Dict(self,node):\n def write_key_value_pair(k,v):\n self.traverse(k)\n self.write(\": \")\n self.traverse(v)\n \n def write_item(item):\n k,v=item\n if k is None:\n \n \n self.write(\"**\")\n self.set_precedence(_Precedence.EXPR,v)\n self.traverse(v)\n else:\n write_key_value_pair(k,v)\n \n with self.delimit(\"{\",\"}\"):\n self.interleave(\n lambda:self.write(\", \"),write_item,zip(node.keys,node.values)\n )\n \n def visit_Tuple(self,node):\n with self.delimit_if(\n \"(\",\n \")\",\n len(node.elts)==0 or self.get_precedence(node)>_Precedence.TUPLE\n ):\n self.items_view(self.traverse,node.elts)\n \n unop={\"Invert\":\"~\",\"Not\":\"not\",\"UAdd\":\"+\",\"USub\":\"-\"}\n unop_precedence={\n \"not\":_Precedence.NOT,\n \"~\":_Precedence.FACTOR,\n \"+\":_Precedence.FACTOR,\n \"-\":_Precedence.FACTOR,\n }\n \n def visit_UnaryOp(self,node):\n operator=self.unop[node.op.__class__.__name__]\n operator_precedence=self.unop_precedence[operator]\n with self.require_parens(operator_precedence,node):\n self.write(operator)\n \n \n if operator_precedence is not _Precedence.FACTOR:\n self.write(\" \")\n self.set_precedence(operator_precedence,node.operand)\n self.traverse(node.operand)\n \n binop={\n \"Add\":\"+\",\n \"Sub\":\"-\",\n \"Mult\":\"*\",\n \"MatMult\":\"@\",\n \"Div\":\"/\",\n \"Mod\":\"%\",\n \"LShift\":\"<<\",\n \"RShift\":\">>\",\n \"BitOr\":\"|\",\n \"BitXor\":\"^\",\n \"BitAnd\":\"&\",\n \"FloorDiv\":\"//\",\n \"Pow\":\"**\",\n }\n \n binop_precedence={\n \"+\":_Precedence.ARITH,\n \"-\":_Precedence.ARITH,\n \"*\":_Precedence.TERM,\n \"@\":_Precedence.TERM,\n \"/\":_Precedence.TERM,\n \"%\":_Precedence.TERM,\n \"<<\":_Precedence.SHIFT,\n \">>\":_Precedence.SHIFT,\n \"|\":_Precedence.BOR,\n \"^\":_Precedence.BXOR,\n \"&\":_Precedence.BAND,\n \"//\":_Precedence.TERM,\n \"**\":_Precedence.POWER,\n }\n \n binop_rassoc=frozenset((\"**\",))\n def visit_BinOp(self,node):\n operator=self.binop[node.op.__class__.__name__]\n operator_precedence=self.binop_precedence[operator]\n with self.require_parens(operator_precedence,node):\n if operator in self.binop_rassoc:\n left_precedence=operator_precedence.next()\n right_precedence=operator_precedence\n else:\n left_precedence=operator_precedence\n right_precedence=operator_precedence.next()\n \n self.set_precedence(left_precedence,node.left)\n self.traverse(node.left)\n self.write(f\" {operator} \")\n self.set_precedence(right_precedence,node.right)\n self.traverse(node.right)\n \n cmpops={\n \"Eq\":\"==\",\n \"NotEq\":\"!=\",\n \"Lt\":\"<\",\n \"LtE\":\"<=\",\n \"Gt\":\">\",\n \"GtE\":\">=\",\n \"Is\":\"is\",\n \"IsNot\":\"is not\",\n \"In\":\"in\",\n \"NotIn\":\"not in\",\n }\n \n def visit_Compare(self,node):\n with self.require_parens(_Precedence.CMP,node):\n self.set_precedence(_Precedence.CMP.next(),node.left,*node.comparators)\n self.traverse(node.left)\n for o,e in zip(node.ops,node.comparators):\n self.write(\" \"+self.cmpops[o.__class__.__name__]+\" \")\n self.traverse(e)\n \n boolops={\"And\":\"and\",\"Or\":\"or\"}\n boolop_precedence={\"and\":_Precedence.AND,\"or\":_Precedence.OR}\n \n def visit_BoolOp(self,node):\n operator=self.boolops[node.op.__class__.__name__]\n operator_precedence=self.boolop_precedence[operator]\n \n def increasing_level_traverse(node):\n nonlocal operator_precedence\n operator_precedence=operator_precedence.next()\n self.set_precedence(operator_precedence,node)\n self.traverse(node)\n \n with self.require_parens(operator_precedence,node):\n s=f\" {operator} \"\n self.interleave(lambda:self.write(s),increasing_level_traverse,node.values)\n \n def visit_Attribute(self,node):\n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n \n \n \n if isinstance(node.value,Constant)and isinstance(node.value.value,int):\n self.write(\" \")\n self.write(\".\")\n self.write(node.attr)\n \n def visit_Call(self,node):\n self.set_precedence(_Precedence.ATOM,node.func)\n self.traverse(node.func)\n with self.delimit(\"(\",\")\"):\n comma=False\n for e in node.args:\n if comma:\n self.write(\", \")\n else:\n comma=True\n self.traverse(e)\n for e in node.keywords:\n if comma:\n self.write(\", \")\n else:\n comma=True\n self.traverse(e)\n \n def visit_Subscript(self,node):\n def is_non_empty_tuple(slice_value):\n return(\n isinstance(slice_value,Tuple)\n and slice_value.elts\n )\n \n self.set_precedence(_Precedence.ATOM,node.value)\n self.traverse(node.value)\n with self.delimit(\"[\",\"]\"):\n if is_non_empty_tuple(node.slice):\n \n self.items_view(self.traverse,node.slice.elts)\n else:\n self.traverse(node.slice)\n \n def visit_Starred(self,node):\n self.write(\"*\")\n self.set_precedence(_Precedence.EXPR,node.value)\n self.traverse(node.value)\n \n def visit_Ellipsis(self,node):\n self.write(\"...\")\n \n def visit_Slice(self,node):\n if node.lower:\n self.traverse(node.lower)\n self.write(\":\")\n if node.upper:\n self.traverse(node.upper)\n if node.step:\n self.write(\":\")\n self.traverse(node.step)\n \n def visit_Match(self,node):\n self.fill(\"match \")\n self.traverse(node.subject)\n with self.block():\n for case in node.cases:\n self.traverse(case)\n \n def visit_arg(self,node):\n self.write(node.arg)\n if node.annotation:\n self.write(\": \")\n self.traverse(node.annotation)\n \n def visit_arguments(self,node):\n first=True\n \n all_args=node.posonlyargs+node.args\n defaults=[None]*(len(all_args)-len(node.defaults))+node.defaults\n for index,elements in enumerate(zip(all_args,defaults),1):\n a,d=elements\n if first:\n first=False\n else:\n self.write(\", \")\n self.traverse(a)\n if d:\n self.write(\"=\")\n self.traverse(d)\n if index ==len(node.posonlyargs):\n self.write(\", /\")\n \n \n if node.vararg or node.kwonlyargs:\n if first:\n first=False\n else:\n self.write(\", \")\n self.write(\"*\")\n if node.vararg:\n self.write(node.vararg.arg)\n if node.vararg.annotation:\n self.write(\": \")\n self.traverse(node.vararg.annotation)\n \n \n if node.kwonlyargs:\n for a,d in zip(node.kwonlyargs,node.kw_defaults):\n self.write(\", \")\n self.traverse(a)\n if d:\n self.write(\"=\")\n self.traverse(d)\n \n \n if node.kwarg:\n if first:\n first=False\n else:\n self.write(\", \")\n self.write(\"**\"+node.kwarg.arg)\n if node.kwarg.annotation:\n self.write(\": \")\n self.traverse(node.kwarg.annotation)\n \n def visit_keyword(self,node):\n if node.arg is None:\n self.write(\"**\")\n else:\n self.write(node.arg)\n self.write(\"=\")\n self.traverse(node.value)\n \n def visit_Lambda(self,node):\n with self.require_parens(_Precedence.TEST,node):\n self.write(\"lambda\")\n with self.buffered()as buffer:\n self.traverse(node.args)\n if buffer:\n self.write(\" \",*buffer)\n self.write(\": \")\n self.set_precedence(_Precedence.TEST,node.body)\n self.traverse(node.body)\n \n def visit_alias(self,node):\n self.write(node.name)\n if node.asname:\n self.write(\" as \"+node.asname)\n \n def visit_withitem(self,node):\n self.traverse(node.context_expr)\n if node.optional_vars:\n self.write(\" as \")\n self.traverse(node.optional_vars)\n \n def visit_match_case(self,node):\n self.fill(\"case \")\n self.traverse(node.pattern)\n if node.guard:\n self.write(\" if \")\n self.traverse(node.guard)\n with self.block():\n self.traverse(node.body)\n \n def visit_MatchValue(self,node):\n self.traverse(node.value)\n \n def visit_MatchSingleton(self,node):\n self._write_constant(node.value)\n \n def visit_MatchSequence(self,node):\n with self.delimit(\"[\",\"]\"):\n self.interleave(\n lambda:self.write(\", \"),self.traverse,node.patterns\n )\n \n def visit_MatchStar(self,node):\n name=node.name\n if name is None:\n name=\"_\"\n self.write(f\"*{name}\")\n \n def visit_MatchMapping(self,node):\n def write_key_pattern_pair(pair):\n k,p=pair\n self.traverse(k)\n self.write(\": \")\n self.traverse(p)\n \n with self.delimit(\"{\",\"}\"):\n keys=node.keys\n self.interleave(\n lambda:self.write(\", \"),\n write_key_pattern_pair,\n zip(keys,node.patterns,strict=True),\n )\n rest=node.rest\n if rest is not None:\n if keys:\n self.write(\", \")\n self.write(f\"**{rest}\")\n \n def visit_MatchClass(self,node):\n self.set_precedence(_Precedence.ATOM,node.cls)\n self.traverse(node.cls)\n with self.delimit(\"(\",\")\"):\n patterns=node.patterns\n self.interleave(\n lambda:self.write(\", \"),self.traverse,patterns\n )\n attrs=node.kwd_attrs\n if attrs:\n def write_attr_pattern(pair):\n attr,pattern=pair\n self.write(f\"{attr}=\")\n self.traverse(pattern)\n \n if patterns:\n self.write(\", \")\n self.interleave(\n lambda:self.write(\", \"),\n write_attr_pattern,\n zip(attrs,node.kwd_patterns,strict=True),\n )\n \n def visit_MatchAs(self,node):\n name=node.name\n pattern=node.pattern\n if name is None:\n self.write(\"_\")\n elif pattern is None:\n self.write(node.name)\n else:\n with self.require_parens(_Precedence.TEST,node):\n self.set_precedence(_Precedence.BOR,node.pattern)\n self.traverse(node.pattern)\n self.write(f\" as {node.name}\")\n \n def visit_MatchOr(self,node):\n with self.require_parens(_Precedence.BOR,node):\n self.set_precedence(_Precedence.BOR.next(),*node.patterns)\n self.interleave(lambda:self.write(\" | \"),self.traverse,node.patterns)\n \ndef unparse(ast_obj):\n unparser=_Unparser()\n return unparser.visit(ast_obj)\n \n \n_deprecated_globals={\nname:globals().pop(name)\nfor name in('Num','Str','Bytes','NameConstant','Ellipsis')\n}\n\ndef __getattr__(name):\n if name in _deprecated_globals:\n globals()[name]=value=_deprecated_globals[name]\n import warnings\n warnings._deprecated(\n f\"ast.{name}\",message=_DEPRECATED_CLASS_MESSAGE,remove=(3,14)\n )\n return value\n raise AttributeError(f\"module 'ast' has no attribute '{name}'\")\n \n \ndef main():\n import argparse\n \n parser=argparse.ArgumentParser(prog='python -m ast')\n parser.add_argument('infile',nargs='?',default='-',\n help='the file to parse; defaults to stdin')\n parser.add_argument('-m','--mode',default='exec',\n choices=('exec','single','eval','func_type'),\n help='specify what kind of code must be parsed')\n parser.add_argument('--no-type-comments',default=True,action='store_false',\n help=\"don't add information about type comments\")\n parser.add_argument('-a','--include-attributes',action='store_true',\n help='include attributes such as line numbers and '\n 'column offsets')\n parser.add_argument('-i','--indent',type=int,default=3,\n help='indentation of nodes (number of spaces)')\n args=parser.parse_args()\n \n if args.infile =='-':\n name=''\n source=sys.stdin.buffer.read()\n else:\n name=args.infile\n with open(args.infile,'rb')as infile:\n source=infile.read()\n tree=parse(source,name,args.mode,type_comments=args.no_type_comments)\n print(dump(tree,include_attributes=args.include_attributes,indent=args.indent))\n \nif __name__ =='__main__':\n main()\n", ["_ast", "argparse", "collections", "contextlib", "enum", "inspect", "re", "sys", "warnings"]], "asyncio": [".py", "print('Brython implementation of asyncio is present to avoid ImportError '+\n'in some modules, but does not implement the asyncio features '+\n'because of browser limitations.\\nFor asynchronous programming, use '+\n'browser.aio instead')\n\nALL_COMPLETED=\"\"\"ALL_COMPLETED\"\"\"\n\n\nclass AbstractEventLoop:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n \nclass AbstractEventLoopPolicy:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n def get_child_watcher(*args,**kw):\n pass\n \n def get_event_loop(*args,**kw):\n pass\n \n def new_event_loop(*args,**kw):\n pass\n \n def set_child_watcher(*args,**kw):\n pass\n \n def set_event_loop(*args,**kw):\n pass\n \nclass AbstractServer:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n def close(*args,**kw):\n pass\n \n def get_loop(*args,**kw):\n pass\n \n def is_serving(*args,**kw):\n pass\n \n def serve_forever(*args,**kw):\n pass\n \n def start_serving(*args,**kw):\n pass\n \n def wait_closed(*args,**kw):\n pass\n \nclass Barrier:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _block(*args,**kw):\n pass\n \n def _exit(*args,**kw):\n pass\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def _release(*args,**kw):\n pass\n \n def _wait(*args,**kw):\n pass\n \n def abort(*args,**kw):\n pass\n \n broken=\"\"\n \n n_waiting=\"\"\n \n parties=\"\"\n \n def reset(*args,**kw):\n pass\n \n def wait(*args,**kw):\n pass\n \nclass BaseEventLoop:\n\n __module__=\"\"\"asyncio.base_events\"\"\"\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n \nclass BaseProtocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass BaseTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \nclass BoundedSemaphore:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def _wake_up_next(*args,**kw):\n pass\n \n def acquire(*args,**kw):\n pass\n \n def locked(*args,**kw):\n pass\n \n def release(*args,**kw):\n pass\n \nclass BrokenBarrierError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass BufferedProtocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def buffer_updated(*args,**kw):\n pass\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def eof_received(*args,**kw):\n pass\n \n def get_buffer(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass CancelledError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass Condition:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def notify(*args,**kw):\n pass\n \n def notify_all(*args,**kw):\n pass\n \n def wait(*args,**kw):\n pass\n \n def wait_for(*args,**kw):\n pass\n \nclass DatagramProtocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def datagram_received(*args,**kw):\n pass\n \n def error_received(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass DatagramTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def abort(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def sendto(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \nclass DefaultEventLoopPolicy:\n\n\n class _Local:\n \n __module__=\"\"\"asyncio.events\"\"\"\n \n _loop=None\n \n _set_called=False\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n \n class _loop_factory:\n \n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _loop_self_reading(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_duplex_pipe_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_accept_futures(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_pipe_connection(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_serving_pipe(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n def get_child_watcher(*args,**kw):\n pass\n \n def get_event_loop(*args,**kw):\n pass\n \n def new_event_loop(*args,**kw):\n pass\n \n def set_child_watcher(*args,**kw):\n pass\n \n def set_event_loop(*args,**kw):\n pass\n \nclass Event:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def clear(*args,**kw):\n pass\n \n def is_set(*args,**kw):\n pass\n \n def set(*args,**kw):\n pass\n \n def wait(*args,**kw):\n pass\nFIRST_COMPLETED=\"\"\"FIRST_COMPLETED\"\"\"\n\nFIRST_EXCEPTION=\"\"\"FIRST_EXCEPTION\"\"\"\n\n\nclass Future:\n\n _asyncio_future_blocking=\"\"\n \n _callbacks=\"\"\n \n _cancel_message=\"\"\n \n _exception=\"\"\n \n _log_traceback=\"\"\n \n _loop=\"\"\n \n _make_cancelled_error=\"\"\n \n _result=\"\"\n \n _source_traceback=\"\"\n \n _state=\"\"\n \n add_done_callback=\"\"\n \n cancel=\"\"\n \n cancelled=\"\"\n \n done=\"\"\n \n exception=\"\"\n \n get_loop=\"\"\n \n remove_done_callback=\"\"\n \n result=\"\"\n \n set_exception=\"\"\n \n set_result=\"\"\n \nclass Handle:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n _args=\"\"\n \n _callback=\"\"\n \n _cancelled=\"\"\n \n _context=\"\"\n \n _loop=\"\"\n \n _repr=\"\"\n \n def _repr_info(*args,**kw):\n pass\n \n def _run(*args,**kw):\n pass\n \n _source_traceback=\"\"\n \n def cancel(*args,**kw):\n pass\n \n def cancelled(*args,**kw):\n pass\n \nclass IncompleteReadError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass InvalidStateError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass IocpProactor:\n\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _check_closed(*args,**kw):\n pass\n \n def _get_accept_socket(*args,**kw):\n pass\n \n def _poll(*args,**kw):\n pass\n \n def _register(*args,**kw):\n pass\n \n def _register_with_iocp(*args,**kw):\n pass\n \n def _result(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _unregister(*args,**kw):\n pass\n \n def _wait_cancel(*args,**kw):\n pass\n \n def _wait_for_handle(*args,**kw):\n pass\n \n def accept(*args,**kw):\n pass\n \n def accept_pipe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect(*args,**kw):\n pass\n \n def connect_pipe(*args,**kw):\n pass\n \n def recv(*args,**kw):\n pass\n \n def recv_into(*args,**kw):\n pass\n \n def recvfrom(*args,**kw):\n pass\n \n def recvfrom_into(*args,**kw):\n pass\n \n def select(*args,**kw):\n pass\n \n def send(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def sendto(*args,**kw):\n pass\n \n def set_loop(*args,**kw):\n pass\n \n def wait_for_handle(*args,**kw):\n pass\n \nclass LifoQueue:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n def _format(*args,**kw):\n pass\n \n def _get(*args,**kw):\n pass\n \n def _get_loop(*args,**kw):\n pass\n \n def _init(*args,**kw):\n pass\n \n _loop=None\n \n def _put(*args,**kw):\n pass\n \n def _wakeup_next(*args,**kw):\n pass\n \n def empty(*args,**kw):\n pass\n \n def full(*args,**kw):\n pass\n \n def get(*args,**kw):\n pass\n \n def get_nowait(*args,**kw):\n pass\n \n def join(*args,**kw):\n pass\n \n maxsize=\"\"\n \n def put(*args,**kw):\n pass\n \n def put_nowait(*args,**kw):\n pass\n \n def qsize(*args,**kw):\n pass\n \n def task_done(*args,**kw):\n pass\n \nclass LimitOverrunError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass Lock:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def _wake_up_first(*args,**kw):\n pass\n \n def acquire(*args,**kw):\n pass\n \n def locked(*args,**kw):\n pass\n \n def release(*args,**kw):\n pass\n \nclass PriorityQueue:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n def _format(*args,**kw):\n pass\n \n def _get(*args,**kw):\n pass\n \n def _get_loop(*args,**kw):\n pass\n \n def _init(*args,**kw):\n pass\n \n _loop=None\n \n def _put(*args,**kw):\n pass\n \n def _wakeup_next(*args,**kw):\n pass\n \n def empty(*args,**kw):\n pass\n \n def full(*args,**kw):\n pass\n \n def get(*args,**kw):\n pass\n \n def get_nowait(*args,**kw):\n pass\n \n def join(*args,**kw):\n pass\n \n maxsize=\"\"\n \n def put(*args,**kw):\n pass\n \n def put_nowait(*args,**kw):\n pass\n \n def qsize(*args,**kw):\n pass\n \n def task_done(*args,**kw):\n pass\n \nclass ProactorEventLoop:\n\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _loop_self_reading(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_duplex_pipe_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_accept_futures(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_pipe_connection(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_serving_pipe(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n \nclass Protocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def data_received(*args,**kw):\n pass\n \n def eof_received(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass Queue:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n def _format(*args,**kw):\n pass\n \n def _get(*args,**kw):\n pass\n \n def _get_loop(*args,**kw):\n pass\n \n def _init(*args,**kw):\n pass\n \n _loop=None\n \n def _put(*args,**kw):\n pass\n \n def _wakeup_next(*args,**kw):\n pass\n \n def empty(*args,**kw):\n pass\n \n def full(*args,**kw):\n pass\n \n def get(*args,**kw):\n pass\n \n def get_nowait(*args,**kw):\n pass\n \n def join(*args,**kw):\n pass\n \n maxsize=\"\"\n \n def put(*args,**kw):\n pass\n \n def put_nowait(*args,**kw):\n pass\n \n def qsize(*args,**kw):\n pass\n \n def task_done(*args,**kw):\n pass\n \nclass QueueEmpty:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass QueueFull:\n\n __module__=\"\"\"asyncio.queues\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass ReadTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def is_reading(*args,**kw):\n pass\n \n def pause_reading(*args,**kw):\n pass\n \n def resume_reading(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \nclass Runner:\n\n __module__=\"\"\"asyncio.runners\"\"\"\n \n def _lazy_init(*args,**kw):\n pass\n \n def _on_sigint(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_loop(*args,**kw):\n pass\n \n def run(*args,**kw):\n pass\n \nclass SelectorEventLoop:\n\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _accept_connection(*args,**kw):\n pass\n \n def _accept_connection2(*args,**kw):\n pass\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _add_reader(*args,**kw):\n pass\n \n def _add_writer(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_fd_no_transport(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _process_self_data(*args,**kw):\n pass\n \n def _read_from_self(*args,**kw):\n pass\n \n def _remove_reader(*args,**kw):\n pass\n \n def _remove_writer(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_accept(*args,**kw):\n pass\n \n def _sock_connect(*args,**kw):\n pass\n \n def _sock_connect_cb(*args,**kw):\n pass\n \n def _sock_read_done(*args,**kw):\n pass\n \n def _sock_recv(*args,**kw):\n pass\n \n def _sock_recv_into(*args,**kw):\n pass\n \n def _sock_recvfrom(*args,**kw):\n pass\n \n def _sock_recvfrom_into(*args,**kw):\n pass\n \n def _sock_sendall(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _sock_sendto(*args,**kw):\n pass\n \n def _sock_write_done(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n \nclass Semaphore:\n\n __module__=\"\"\"asyncio.locks\"\"\"\n \n def _get_loop(*args,**kw):\n pass\n \n _loop=None\n \n def _wake_up_next(*args,**kw):\n pass\n \n def acquire(*args,**kw):\n pass\n \n def locked(*args,**kw):\n pass\n \n def release(*args,**kw):\n pass\n \nclass SendfileNotAvailableError:\n\n __module__=\"\"\"asyncio.exceptions\"\"\"\n \n add_note=\"\"\n \n args=\"\"\n \n with_traceback=\"\"\n \nclass Server:\n\n __module__=\"\"\"asyncio.base_events\"\"\"\n \n def _attach(*args,**kw):\n pass\n \n def _detach(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _wakeup(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_loop(*args,**kw):\n pass\n \n def is_serving(*args,**kw):\n pass\n \n def serve_forever(*args,**kw):\n pass\n \n sockets=\"\"\n \n def start_serving(*args,**kw):\n pass\n \n def wait_closed(*args,**kw):\n pass\n \nclass StreamReader:\n\n __module__=\"\"\"asyncio.streams\"\"\"\n \n def _maybe_resume_transport(*args,**kw):\n pass\n \n _source_traceback=None\n \n def _wait_for_data(*args,**kw):\n pass\n \n def _wakeup_waiter(*args,**kw):\n pass\n \n def at_eof(*args,**kw):\n pass\n \n def exception(*args,**kw):\n pass\n \n def feed_data(*args,**kw):\n pass\n \n def feed_eof(*args,**kw):\n pass\n \n def read(*args,**kw):\n pass\n \n def readexactly(*args,**kw):\n pass\n \n def readline(*args,**kw):\n pass\n \n def readuntil(*args,**kw):\n pass\n \n def set_exception(*args,**kw):\n pass\n \n def set_transport(*args,**kw):\n pass\n \nclass StreamReaderProtocol:\n\n __module__=\"\"\"asyncio.streams\"\"\"\n \n def _drain_helper(*args,**kw):\n pass\n \n def _get_close_waiter(*args,**kw):\n pass\n \n def _replace_writer(*args,**kw):\n pass\n \n _source_traceback=None\n \n _stream_reader=\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def data_received(*args,**kw):\n pass\n \n def eof_received(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass StreamWriter:\n\n __module__=\"\"\"asyncio.streams\"\"\"\n \n def can_write_eof(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def drain(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n transport=\"\"\n \n def wait_closed(*args,**kw):\n pass\n \n def write(*args,**kw):\n pass\n \n def write_eof(*args,**kw):\n pass\n \n def writelines(*args,**kw):\n pass\n \nclass SubprocessProtocol:\n\n __module__=\"\"\"asyncio.protocols\"\"\"\n \n def connection_lost(*args,**kw):\n pass\n \n def connection_made(*args,**kw):\n pass\n \n def pause_writing(*args,**kw):\n pass\n \n def pipe_connection_lost(*args,**kw):\n pass\n \n def pipe_data_received(*args,**kw):\n pass\n \n def process_exited(*args,**kw):\n pass\n \n def resume_writing(*args,**kw):\n pass\n \nclass SubprocessTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_pid(*args,**kw):\n pass\n \n def get_pipe_transport(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def get_returncode(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def kill(*args,**kw):\n pass\n \n def send_signal(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \n def terminate(*args,**kw):\n pass\n \nclass Task:\n\n _asyncio_future_blocking=\"\"\n \n _callbacks=\"\"\n \n _cancel_message=\"\"\n \n _check_future=\"\"\n \n _coro=\"\"\n \n _exception=\"\"\n \n _fut_waiter=\"\"\n \n _log_destroy_pending=\"\"\n \n _log_traceback=\"\"\n \n _loop=\"\"\n \n _make_cancelled_error=\"\"\n \n _must_cancel=\"\"\n \n _result=\"\"\n \n _source_traceback=\"\"\n \n _state=\"\"\n \n add_done_callback=\"\"\n \n cancel=\"\"\n \n cancelled=\"\"\n \n cancelling=\"\"\n \n done=\"\"\n \n exception=\"\"\n \n get_coro=\"\"\n \n get_loop=\"\"\n \n get_name=\"\"\n \n get_stack=\"\"\n \n print_stack=\"\"\n \n remove_done_callback=\"\"\n \n result=\"\"\n \n set_exception=\"\"\n \n set_name=\"\"\n \n set_result=\"\"\n \n uncancel=\"\"\n \nclass TaskGroup:\n\n __module__=\"\"\"asyncio.taskgroups\"\"\"\n \n def _abort(*args,**kw):\n pass\n \n def _is_base_error(*args,**kw):\n pass\n \n def _on_task_done(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \nclass Timeout:\n\n __module__=\"\"\"asyncio.timeouts\"\"\"\n \n def _on_timeout(*args,**kw):\n pass\n \n def expired(*args,**kw):\n pass\n \n def reschedule(*args,**kw):\n pass\n \n def when(*args,**kw):\n pass\n \nclass TimeoutError:\n\n add_note=\"\"\n \n args=\"\"\n \n characters_written=\"\"\n \n errno=\"\"\n \n filename=\"\"\n \n filename2=\"\"\n \n strerror=\"\"\n \n winerror=\"\"\n \n with_traceback=\"\"\n \nclass TimerHandle:\n\n __module__=\"\"\"asyncio.events\"\"\"\n \n _args=\"\"\n \n _callback=\"\"\n \n _cancelled=\"\"\n \n _context=\"\"\n \n _loop=\"\"\n \n _repr=\"\"\n \n def _repr_info(*args,**kw):\n pass\n \n def _run(*args,**kw):\n pass\n \n _scheduled=\"\"\n \n _source_traceback=\"\"\n \n _when=\"\"\n \n def cancel(*args,**kw):\n pass\n \n def cancelled(*args,**kw):\n pass\n \n def when(*args,**kw):\n pass\n \nclass Transport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def abort(*args,**kw):\n pass\n \n def can_write_eof(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def get_write_buffer_limits(*args,**kw):\n pass\n \n def get_write_buffer_size(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def is_reading(*args,**kw):\n pass\n \n def pause_reading(*args,**kw):\n pass\n \n def resume_reading(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \n def set_write_buffer_limits(*args,**kw):\n pass\n \n def write(*args,**kw):\n pass\n \n def write_eof(*args,**kw):\n pass\n \n def writelines(*args,**kw):\n pass\n \nclass WindowsProactorEventLoopPolicy:\n\n\n class _Local:\n \n __module__=\"\"\"asyncio.events\"\"\"\n \n _loop=None\n \n _set_called=False\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n \n class _loop_factory:\n \n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _loop_self_reading(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_duplex_pipe_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_accept_futures(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_pipe_connection(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_serving_pipe(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n def get_child_watcher(*args,**kw):\n pass\n \n def get_event_loop(*args,**kw):\n pass\n \n def new_event_loop(*args,**kw):\n pass\n \n def set_child_watcher(*args,**kw):\n pass\n \n def set_event_loop(*args,**kw):\n pass\n \nclass WindowsSelectorEventLoopPolicy:\n\n\n class _Local:\n \n __module__=\"\"\"asyncio.events\"\"\"\n \n _loop=None\n \n _set_called=False\n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n \n class _loop_factory:\n \n __module__=\"\"\"asyncio.windows_events\"\"\"\n \n def _accept_connection(*args,**kw):\n pass\n \n def _accept_connection2(*args,**kw):\n pass\n \n def _add_callback(*args,**kw):\n pass\n \n def _add_callback_signalsafe(*args,**kw):\n pass\n \n def _add_reader(*args,**kw):\n pass\n \n def _add_writer(*args,**kw):\n pass\n \n def _asyncgen_finalizer_hook(*args,**kw):\n pass\n \n def _asyncgen_firstiter_hook(*args,**kw):\n pass\n \n def _call_soon(*args,**kw):\n pass\n \n def _check_callback(*args,**kw):\n pass\n \n def _check_closed(*args,**kw):\n pass\n \n def _check_default_executor(*args,**kw):\n pass\n \n def _check_running(*args,**kw):\n pass\n \n def _check_sendfile_params(*args,**kw):\n pass\n \n def _check_thread(*args,**kw):\n pass\n \n def _close_self_pipe(*args,**kw):\n pass\n \n def _connect_sock(*args,**kw):\n pass\n \n def _create_connection_transport(*args,**kw):\n pass\n \n def _create_server_getaddrinfo(*args,**kw):\n pass\n \n def _do_shutdown(*args,**kw):\n pass\n \n def _ensure_fd_no_transport(*args,**kw):\n pass\n \n def _ensure_resolved(*args,**kw):\n pass\n \n def _getaddrinfo_debug(*args,**kw):\n pass\n \n def _log_subprocess(*args,**kw):\n pass\n \n def _make_datagram_transport(*args,**kw):\n pass\n \n def _make_read_pipe_transport(*args,**kw):\n pass\n \n def _make_self_pipe(*args,**kw):\n pass\n \n def _make_socket_transport(*args,**kw):\n pass\n \n def _make_ssl_transport(*args,**kw):\n pass\n \n def _make_subprocess_transport(*args,**kw):\n pass\n \n def _make_write_pipe_transport(*args,**kw):\n pass\n \n def _process_events(*args,**kw):\n pass\n \n def _process_self_data(*args,**kw):\n pass\n \n def _read_from_self(*args,**kw):\n pass\n \n def _remove_reader(*args,**kw):\n pass\n \n def _remove_writer(*args,**kw):\n pass\n \n def _run_once(*args,**kw):\n pass\n \n def _sendfile_fallback(*args,**kw):\n pass\n \n def _sendfile_native(*args,**kw):\n pass\n \n def _set_coroutine_origin_tracking(*args,**kw):\n pass\n \n def _sock_accept(*args,**kw):\n pass\n \n def _sock_connect(*args,**kw):\n pass\n \n def _sock_connect_cb(*args,**kw):\n pass\n \n def _sock_read_done(*args,**kw):\n pass\n \n def _sock_recv(*args,**kw):\n pass\n \n def _sock_recv_into(*args,**kw):\n pass\n \n def _sock_recvfrom(*args,**kw):\n pass\n \n def _sock_recvfrom_into(*args,**kw):\n pass\n \n def _sock_sendall(*args,**kw):\n pass\n \n def _sock_sendfile_fallback(*args,**kw):\n pass\n \n def _sock_sendfile_native(*args,**kw):\n pass\n \n def _sock_sendto(*args,**kw):\n pass\n \n def _sock_write_done(*args,**kw):\n pass\n \n def _start_serving(*args,**kw):\n pass\n \n def _stop_serving(*args,**kw):\n pass\n \n def _timer_handle_cancelled(*args,**kw):\n pass\n \n def _write_to_self(*args,**kw):\n pass\n \n def add_reader(*args,**kw):\n pass\n \n def add_signal_handler(*args,**kw):\n pass\n \n def add_writer(*args,**kw):\n pass\n \n def call_at(*args,**kw):\n pass\n \n def call_exception_handler(*args,**kw):\n pass\n \n def call_later(*args,**kw):\n pass\n \n def call_soon(*args,**kw):\n pass\n \n def call_soon_threadsafe(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def connect_accepted_socket(*args,**kw):\n pass\n \n def connect_read_pipe(*args,**kw):\n pass\n \n def connect_write_pipe(*args,**kw):\n pass\n \n def create_connection(*args,**kw):\n pass\n \n def create_datagram_endpoint(*args,**kw):\n pass\n \n def create_future(*args,**kw):\n pass\n \n def create_server(*args,**kw):\n pass\n \n def create_task(*args,**kw):\n pass\n \n def create_unix_connection(*args,**kw):\n pass\n \n def create_unix_server(*args,**kw):\n pass\n \n def default_exception_handler(*args,**kw):\n pass\n \n def get_debug(*args,**kw):\n pass\n \n def get_exception_handler(*args,**kw):\n pass\n \n def get_task_factory(*args,**kw):\n pass\n \n def getaddrinfo(*args,**kw):\n pass\n \n def getnameinfo(*args,**kw):\n pass\n \n def is_closed(*args,**kw):\n pass\n \n def is_running(*args,**kw):\n pass\n \n def remove_reader(*args,**kw):\n pass\n \n def remove_signal_handler(*args,**kw):\n pass\n \n def remove_writer(*args,**kw):\n pass\n \n def run_forever(*args,**kw):\n pass\n \n def run_in_executor(*args,**kw):\n pass\n \n def run_until_complete(*args,**kw):\n pass\n \n def sendfile(*args,**kw):\n pass\n \n def set_debug(*args,**kw):\n pass\n \n def set_default_executor(*args,**kw):\n pass\n \n def set_exception_handler(*args,**kw):\n pass\n \n def set_task_factory(*args,**kw):\n pass\n \n def shutdown_asyncgens(*args,**kw):\n pass\n \n def shutdown_default_executor(*args,**kw):\n pass\n \n def sock_accept(*args,**kw):\n pass\n \n def sock_connect(*args,**kw):\n pass\n \n def sock_recv(*args,**kw):\n pass\n \n def sock_recv_into(*args,**kw):\n pass\n \n def sock_recvfrom(*args,**kw):\n pass\n \n def sock_recvfrom_into(*args,**kw):\n pass\n \n def sock_sendall(*args,**kw):\n pass\n \n def sock_sendfile(*args,**kw):\n pass\n \n def sock_sendto(*args,**kw):\n pass\n \n def start_tls(*args,**kw):\n pass\n \n def stop(*args,**kw):\n pass\n \n def subprocess_exec(*args,**kw):\n pass\n \n def subprocess_shell(*args,**kw):\n pass\n \n def time(*args,**kw):\n pass\n def get_child_watcher(*args,**kw):\n pass\n \n def get_event_loop(*args,**kw):\n pass\n \n def new_event_loop(*args,**kw):\n pass\n \n def set_child_watcher(*args,**kw):\n pass\n \n def set_event_loop(*args,**kw):\n pass\n \nclass WriteTransport:\n\n __module__=\"\"\"asyncio.transports\"\"\"\n \n _extra=\"\"\n \n def abort(*args,**kw):\n pass\n \n def can_write_eof(*args,**kw):\n pass\n \n def close(*args,**kw):\n pass\n \n def get_extra_info(*args,**kw):\n pass\n \n def get_protocol(*args,**kw):\n pass\n \n def get_write_buffer_limits(*args,**kw):\n pass\n \n def get_write_buffer_size(*args,**kw):\n pass\n \n def is_closing(*args,**kw):\n pass\n \n def set_protocol(*args,**kw):\n pass\n \n def set_write_buffer_limits(*args,**kw):\n pass\n \n def write(*args,**kw):\n pass\n \n def write_eof(*args,**kw):\n pass\n \n def writelines(*args,**kw):\n pass\ndef _enter_task(*args,**kw):\n pass\n \ndef _get_running_loop(*args,**kw):\n pass\n \ndef _leave_task(*args,**kw):\n pass\n \ndef _register_task(*args,**kw):\n pass\n \ndef _set_running_loop(*args,**kw):\n pass\n \ndef _unregister_task(*args,**kw):\n pass\n \ndef all_tasks(*args,**kw):\n pass\n \ndef as_completed(*args,**kw):\n pass\n \nbase_events=\"\"\n\nbase_futures=\"\"\n\nbase_subprocess=\"\"\n\nbase_tasks=\"\"\n\nconstants=\"\"\n\ncoroutines=\"\"\n\ndef create_subprocess_exec(*args,**kw):\n pass\n \ndef create_subprocess_shell(*args,**kw):\n pass\n \ndef create_task(*args,**kw):\n pass\n \ndef current_task(*args,**kw):\n pass\n \ndef ensure_future(*args,**kw):\n pass\n \nevents=\"\"\n\nexceptions=\"\"\n\nformat_helpers=\"\"\n\nfutures=\"\"\n\ndef gather(*args,**kw):\n pass\n \ndef get_child_watcher(*args,**kw):\n pass\n \ndef get_event_loop(*args,**kw):\n pass\n \ndef get_event_loop_policy(*args,**kw):\n pass\n \ndef get_running_loop(*args,**kw):\n pass\n \ndef iscoroutine(*args,**kw):\n pass\n \ndef iscoroutinefunction(*args,**kw):\n pass\n \ndef isfuture(*args,**kw):\n pass\n \nlocks=\"\"\n\nlog=\"\"\n\nmixins=\"\"\n\ndef new_event_loop(*args,**kw):\n pass\n \ndef open_connection(*args,**kw):\n pass\n \nproactor_events=\"\"\n\nprotocols=\"\"\n\nqueues=\"\"\n\ndef run(*args,**kw):\n pass\n \ndef run_coroutine_threadsafe(*args,**kw):\n pass\n \nrunners=\"\"\n\nselector_events=\"\"\n\ndef set_child_watcher(*args,**kw):\n pass\n \ndef set_event_loop(*args,**kw):\n pass\n \ndef set_event_loop_policy(*args,**kw):\n pass\n \ndef shield(*args,**kw):\n pass\n \ndef sleep(*args,**kw):\n pass\n \nsslproto=\"\"\n\nstaggered=\"\"\n\ndef start_server(*args,**kw):\n pass\n \nstreams=\"\"\n\nsubprocess=\"\"\n\nsys=\"\"\n\ntaskgroups=\"\"\n\ntasks=\"\"\n\nthreads=\"\"\n\ndef timeout(*args,**kw):\n pass\n \ndef timeout_at(*args,**kw):\n pass\n \ntimeouts=\"\"\n\ndef to_thread(*args,**kw):\n pass\n \ntransports=\"\"\n\ntrsock=\"\"\n\ndef wait(*args,**kw):\n pass\n \ndef wait_for(*args,**kw):\n pass\n \nwindows_events=\"\"\n\nwindows_utils=\"\"\n\ndef wrap_future(*args,**kw):\n pass\n \n", []], "atexit": [".py", "''\n\n\n\n\n\nclass __loader__(object):\n pass\n \ndef _clear(*args,**kw):\n ''\n \n pass\n \ndef _run_exitfuncs(*args,**kw):\n ''\n \n pass\n \ndef register(*args,**kw):\n ''\n\n\n\n\n\n\n \n pass\n \ndef unregister(*args,**kw):\n ''\n\n\n\n \n pass\n", []], "base64": [".py", "#! /usr/bin/env python3\n\n\"\"\"Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings\"\"\"\n\n\n\n\n\nimport re\nimport struct\nimport binascii\n\n\n__all__=[\n\n'encode','decode','encodebytes','decodebytes',\n\n'b64encode','b64decode','b32encode','b32decode',\n'b32hexencode','b32hexdecode','b16encode','b16decode',\n\n'b85encode','b85decode','a85encode','a85decode','z85encode','z85decode',\n\n'standard_b64encode','standard_b64decode',\n\n\n\n\n'urlsafe_b64encode','urlsafe_b64decode',\n]\n\n\nbytes_types=(bytes,bytearray)\n\ndef _bytes_from_decode_data(s):\n if isinstance(s,str):\n try:\n return s.encode('ascii')\n except UnicodeEncodeError:\n raise ValueError('string argument should contain only ASCII characters')\n if isinstance(s,bytes_types):\n return s\n try:\n return memoryview(s).tobytes()\n except TypeError:\n raise TypeError(\"argument should be a bytes-like object or ASCII \"\n \"string, not %r\"%s.__class__.__name__)from None\n \n \n \n \ndef b64encode(s,altchars=None):\n ''\n\n\n\n\n \n encoded=binascii.b2a_base64(s,newline=False)\n if altchars is not None:\n assert len(altchars)==2,repr(altchars)\n return encoded.translate(bytes.maketrans(b'+/',altchars))\n return encoded\n \n \ndef b64decode(s,altchars=None,validate=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n if altchars is not None:\n altchars=_bytes_from_decode_data(altchars)\n assert len(altchars)==2,repr(altchars)\n s=s.translate(bytes.maketrans(altchars,b'+/'))\n return binascii.a2b_base64(s,strict_mode=validate)\n \n \ndef standard_b64encode(s):\n ''\n\n\n \n return b64encode(s)\n \ndef standard_b64decode(s):\n ''\n\n\n\n\n\n \n return b64decode(s)\n \n \n_urlsafe_encode_translation=bytes.maketrans(b'+/',b'-_')\n_urlsafe_decode_translation=bytes.maketrans(b'-_',b'+/')\n\ndef urlsafe_b64encode(s):\n ''\n\n\n\n\n \n return b64encode(s).translate(_urlsafe_encode_translation)\n \ndef urlsafe_b64decode(s):\n ''\n\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n s=s.translate(_urlsafe_decode_translation)\n return b64decode(s)\n \n \n \n \n_B32_ENCODE_DOCSTRING='''\nEncode the bytes-like objects using {encoding} and return a bytes object.\n'''\n_B32_DECODE_DOCSTRING='''\nDecode the {encoding} encoded bytes-like object or ASCII string s.\n\nOptional casefold is a flag specifying whether a lowercase alphabet is\nacceptable as input. For security purposes, the default is False.\n{extra_args}\nThe result is returned as a bytes object. A binascii.Error is raised if\nthe input is incorrectly padded or if there are non-alphabet\ncharacters present in the input.\n'''\n_B32_DECODE_MAP01_DOCSTRING='''\nRFC 3548 allows for optional mapping of the digit 0 (zero) to the\nletter O (oh), and for optional mapping of the digit 1 (one) to\neither the letter I (eye) or letter L (el). The optional argument\nmap01 when not None, specifies which letter the digit 1 should be\nmapped to (when map01 is not None, the digit 0 is always mapped to\nthe letter O). For security purposes the default is None, so that\n0 and 1 are not allowed in the input.\n'''\n_b32alphabet=b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\n_b32hexalphabet=b'0123456789ABCDEFGHIJKLMNOPQRSTUV'\n_b32tab2={}\n_b32rev={}\n\ndef _b32encode(alphabet,s):\n\n\n if alphabet not in _b32tab2:\n b32tab=[bytes((i,))for i in alphabet]\n _b32tab2[alphabet]=[a+b for a in b32tab for b in b32tab]\n b32tab=None\n \n if not isinstance(s,bytes_types):\n s=memoryview(s).tobytes()\n leftover=len(s)%5\n \n if leftover:\n s=s+b'\\0'*(5 -leftover)\n encoded=bytearray()\n from_bytes=int.from_bytes\n b32tab2=_b32tab2[alphabet]\n for i in range(0,len(s),5):\n c=from_bytes(s[i:i+5])\n encoded +=(b32tab2[c >>30]+\n b32tab2[(c >>20)&0x3ff]+\n b32tab2[(c >>10)&0x3ff]+\n b32tab2[c&0x3ff]\n )\n \n if leftover ==1:\n encoded[-6:]=b'======'\n elif leftover ==2:\n encoded[-4:]=b'===='\n elif leftover ==3:\n encoded[-3:]=b'==='\n elif leftover ==4:\n encoded[-1:]=b'='\n return bytes(encoded)\n \ndef _b32decode(alphabet,s,casefold=False,map01=None):\n\n\n if alphabet not in _b32rev:\n _b32rev[alphabet]={v:k for k,v in enumerate(alphabet)}\n s=_bytes_from_decode_data(s)\n if len(s)%8:\n raise binascii.Error('Incorrect padding')\n \n \n \n if map01 is not None:\n map01=_bytes_from_decode_data(map01)\n assert len(map01)==1,repr(map01)\n s=s.translate(bytes.maketrans(b'01',b'O'+map01))\n if casefold:\n s=s.upper()\n \n \n \n l=len(s)\n s=s.rstrip(b'=')\n padchars=l -len(s)\n \n decoded=bytearray()\n b32rev=_b32rev[alphabet]\n for i in range(0,len(s),8):\n quanta=s[i:i+8]\n acc=0\n try:\n for c in quanta:\n acc=(acc <<5)+b32rev[c]\n except KeyError:\n raise binascii.Error('Non-base32 digit found')from None\n decoded +=acc.to_bytes(5)\n \n if l %8 or padchars not in{0,1,3,4,6}:\n raise binascii.Error('Incorrect padding')\n if padchars and decoded:\n acc <<=5 *padchars\n last=acc.to_bytes(5)\n leftover=(43 -5 *padchars)//8\n decoded[-5:]=last[:leftover]\n return bytes(decoded)\n \n \ndef b32encode(s):\n return _b32encode(_b32alphabet,s)\nb32encode.__doc__=_B32_ENCODE_DOCSTRING.format(encoding='base32')\n\ndef b32decode(s,casefold=False,map01=None):\n return _b32decode(_b32alphabet,s,casefold,map01)\nb32decode.__doc__=_B32_DECODE_DOCSTRING.format(encoding='base32',\nextra_args=_B32_DECODE_MAP01_DOCSTRING)\n\ndef b32hexencode(s):\n return _b32encode(_b32hexalphabet,s)\nb32hexencode.__doc__=_B32_ENCODE_DOCSTRING.format(encoding='base32hex')\n\ndef b32hexdecode(s,casefold=False):\n\n return _b32decode(_b32hexalphabet,s,casefold)\nb32hexdecode.__doc__=_B32_DECODE_DOCSTRING.format(encoding='base32hex',\nextra_args='')\n\n\n\n\n\ndef b16encode(s):\n ''\n \n return binascii.hexlify(s).upper()\n \n \ndef b16decode(s,casefold=False):\n ''\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n if casefold:\n s=s.upper()\n if re.search(b'[^0-9A-F]',s):\n raise binascii.Error('Non-base16 digit found')\n return binascii.unhexlify(s)\n \n \n \n \n \n_a85chars=None\n_a85chars2=None\n_A85START=b\"<~\"\n_A85END=b\"~>\"\n\ndef _85encode(b,chars,chars2,pad=False,foldnuls=False,foldspaces=False):\n\n if not isinstance(b,bytes_types):\n b=memoryview(b).tobytes()\n \n padding=(-len(b))%4\n if padding:\n b=b+b'\\0'*padding\n words=struct.Struct('!%dI'%(len(b)//4)).unpack(b)\n \n chunks=[b'z'if foldnuls and not word else\n b'y'if foldspaces and word ==0x20202020 else\n (chars2[word //614125]+\n chars2[word //85 %7225]+\n chars[word %85])\n for word in words]\n \n if padding and not pad:\n if chunks[-1]==b'z':\n chunks[-1]=chars[0]*5\n chunks[-1]=chunks[-1][:-padding]\n \n return b''.join(chunks)\n \ndef a85encode(b,*,foldspaces=False,wrapcol=0,pad=False,adobe=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _a85chars,_a85chars2\n \n \n if _a85chars2 is None:\n _a85chars=[bytes((i,))for i in range(33,118)]\n _a85chars2=[(a+b)for a in _a85chars for b in _a85chars]\n \n result=_85encode(b,_a85chars,_a85chars2,pad,True,foldspaces)\n \n if adobe:\n result=_A85START+result\n if wrapcol:\n wrapcol=max(2 if adobe else 1,wrapcol)\n chunks=[result[i:i+wrapcol]\n for i in range(0,len(result),wrapcol)]\n if adobe:\n if len(chunks[-1])+2 >wrapcol:\n chunks.append(b'')\n result=b'\\n'.join(chunks)\n if adobe:\n result +=_A85END\n \n return result\n \ndef a85decode(b,*,foldspaces=False,adobe=False,ignorechars=b' \\t\\n\\r\\v'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n b=_bytes_from_decode_data(b)\n if adobe:\n if not b.endswith(_A85END):\n raise ValueError(\n \"Ascii85 encoded byte sequences must end \"\n \"with {!r}\".format(_A85END)\n )\n if b.startswith(_A85START):\n b=b[2:-2]\n else:\n b=b[:-2]\n \n \n \n \n packI=struct.Struct('!I').pack\n decoded=[]\n decoded_append=decoded.append\n curr=[]\n curr_append=curr.append\n curr_clear=curr.clear\n for x in b+b'u'*4:\n if b'!'[0]<=x <=b'u'[0]:\n curr_append(x)\n if len(curr)==5:\n acc=0\n for x in curr:\n acc=85 *acc+(x -33)\n try:\n decoded_append(packI(acc))\n except struct.error:\n raise ValueError('Ascii85 overflow')from None\n curr_clear()\n elif x ==b'z'[0]:\n if curr:\n raise ValueError('z inside Ascii85 5-tuple')\n decoded_append(b'\\0\\0\\0\\0')\n elif foldspaces and x ==b'y'[0]:\n if curr:\n raise ValueError('y inside Ascii85 5-tuple')\n decoded_append(b'\\x20\\x20\\x20\\x20')\n elif x in ignorechars:\n \n continue\n else:\n raise ValueError('Non-Ascii85 digit found: %c'%x)\n \n result=b''.join(decoded)\n padding=4 -len(curr)\n if padding:\n \n result=result[:-padding]\n return result\n \n \n \n_b85alphabet=(b\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nb\"abcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~\")\n_b85chars=None\n_b85chars2=None\n_b85dec=None\n\ndef b85encode(b,pad=False):\n ''\n\n\n\n \n global _b85chars,_b85chars2\n \n \n if _b85chars2 is None:\n _b85chars=[bytes((i,))for i in _b85alphabet]\n _b85chars2=[(a+b)for a in _b85chars for b in _b85chars]\n return _85encode(b,_b85chars,_b85chars2,pad)\n \ndef b85decode(b):\n ''\n\n\n \n global _b85dec\n \n \n if _b85dec is None:\n _b85dec=[None]*256\n for i,c in enumerate(_b85alphabet):\n _b85dec[c]=i\n \n b=_bytes_from_decode_data(b)\n padding=(-len(b))%5\n b=b+b'~'*padding\n out=[]\n packI=struct.Struct('!I').pack\n for i in range(0,len(b),5):\n chunk=b[i:i+5]\n acc=0\n try:\n for c in chunk:\n acc=acc *85+_b85dec[c]\n except TypeError:\n for j,c in enumerate(chunk):\n if _b85dec[c]is None:\n raise ValueError('bad base85 character at position %d'\n %(i+j))from None\n raise\n try:\n out.append(packI(acc))\n except struct.error:\n raise ValueError('base85 overflow in hunk starting at byte %d'\n %i)from None\n \n result=b''.join(out)\n if padding:\n result=result[:-padding]\n return result\n \n_z85alphabet=(b'0123456789abcdefghijklmnopqrstuvwxyz'\nb'ABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#')\n\n\n_z85_b85_decode_diff=b';_`|~'\n_z85_decode_translation=bytes.maketrans(\n_z85alphabet+_z85_b85_decode_diff,\n_b85alphabet+b'\\x00'*len(_z85_b85_decode_diff)\n)\n_z85_encode_translation=bytes.maketrans(_b85alphabet,_z85alphabet)\n\ndef z85encode(s):\n ''\n return b85encode(s).translate(_z85_encode_translation)\n \ndef z85decode(s):\n ''\n\n\n \n s=_bytes_from_decode_data(s)\n s=s.translate(_z85_decode_translation)\n try:\n return b85decode(s)\n except ValueError as e:\n raise ValueError(e.args[0].replace('base85','z85'))from None\n \n \n \n \n \nMAXLINESIZE=76\nMAXBINSIZE=(MAXLINESIZE //4)*3\n\ndef encode(input,output):\n ''\n while s :=input.read(MAXBINSIZE):\n while len(s)\":\n return filename\n canonic=self.fncache.get(filename)\n if not canonic:\n canonic=os.path.abspath(filename)\n canonic=os.path.normcase(canonic)\n self.fncache[filename]=canonic\n return canonic\n \n def reset(self):\n ''\n import linecache\n linecache.checkcache()\n self.botframe=None\n self._set_stopinfo(None,None)\n \n def trace_dispatch(self,frame,event,arg):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.enterframe=frame\n \n if self.quitting:\n return\n if event =='line':\n return self.dispatch_line(frame)\n if event =='call':\n return self.dispatch_call(frame,arg)\n if event =='return':\n return self.dispatch_return(frame,arg)\n if event =='exception':\n return self.dispatch_exception(frame,arg)\n if event =='c_call':\n return self.trace_dispatch\n if event =='c_exception':\n return self.trace_dispatch\n if event =='c_return':\n return self.trace_dispatch\n if event =='opcode':\n return self.dispatch_opcode(frame,arg)\n print('bdb.Bdb.dispatch: unknown debugging event:',repr(event))\n return self.trace_dispatch\n \n def dispatch_line(self,frame):\n ''\n\n\n\n\n \n if self.stop_here(frame)or self.break_here(frame):\n self.user_line(frame)\n if self.quitting:raise BdbQuit\n return self.trace_dispatch\n \n def dispatch_call(self,frame,arg):\n ''\n\n\n\n\n \n \n if self.botframe is None:\n \n self.botframe=frame.f_back\n return self.trace_dispatch\n if not(self.stop_here(frame)or self.break_anywhere(frame)):\n \n return\n \n if self.stopframe and frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n return self.trace_dispatch\n self.user_call(frame,arg)\n if self.quitting:raise BdbQuit\n return self.trace_dispatch\n \n def dispatch_return(self,frame,arg):\n ''\n\n\n\n\n \n if self.stop_here(frame)or frame ==self.returnframe:\n \n if self.stopframe and frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n return self.trace_dispatch\n try:\n self.frame_returning=frame\n self.user_return(frame,arg)\n finally:\n self.frame_returning=None\n if self.quitting:raise BdbQuit\n \n if self.stopframe is frame and self.stoplineno !=-1:\n self._set_stopinfo(None,None)\n \n \n \n if self.stoplineno !=-1:\n self._set_caller_tracefunc(frame)\n return self.trace_dispatch\n \n def dispatch_exception(self,frame,arg):\n ''\n\n\n\n\n \n if self.stop_here(frame):\n \n \n \n if not(frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS\n and arg[0]is StopIteration and arg[2]is None):\n self.user_exception(frame,arg)\n if self.quitting:raise BdbQuit\n \n \n \n \n elif(self.stopframe and frame is not self.stopframe\n and self.stopframe.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS\n and arg[0]in(StopIteration,GeneratorExit)):\n self.user_exception(frame,arg)\n if self.quitting:raise BdbQuit\n \n return self.trace_dispatch\n \n def dispatch_opcode(self,frame,arg):\n ''\n\n\n\n \n if self.stop_here(frame)or self.break_here(frame):\n self.user_opcode(frame)\n if self.quitting:raise BdbQuit\n return self.trace_dispatch\n \n \n \n \n \n def is_skipped_module(self,module_name):\n ''\n if module_name is None:\n return False\n for pattern in self.skip:\n if fnmatch.fnmatch(module_name,pattern):\n return True\n return False\n \n def stop_here(self,frame):\n ''\n \n \n if self.skip and\\\n self.is_skipped_module(frame.f_globals.get('__name__')):\n return False\n if frame is self.stopframe:\n if self.stoplineno ==-1:\n return False\n return frame.f_lineno >=self.stoplineno\n if not self.stopframe:\n return True\n return False\n \n def break_here(self,frame):\n ''\n\n\n\n \n filename=self.canonic(frame.f_code.co_filename)\n if filename not in self.breaks:\n return False\n lineno=frame.f_lineno\n if lineno not in self.breaks[filename]:\n \n \n lineno=frame.f_code.co_firstlineno\n if lineno not in self.breaks[filename]:\n return False\n \n \n (bp,flag)=effective(filename,lineno,frame)\n if bp:\n self.currentbp=bp.number\n if(flag and bp.temporary):\n self.do_clear(str(bp.number))\n return True\n else:\n return False\n \n def do_clear(self,arg):\n ''\n\n\n \n raise NotImplementedError(\"subclass of bdb must implement do_clear()\")\n \n def break_anywhere(self,frame):\n ''\n \n return self.canonic(frame.f_code.co_filename)in self.breaks\n \n \n \n \n def user_call(self,frame,argument_list):\n ''\n pass\n \n def user_line(self,frame):\n ''\n pass\n \n def user_return(self,frame,return_value):\n ''\n pass\n \n def user_exception(self,frame,exc_info):\n ''\n pass\n \n def user_opcode(self,frame):\n ''\n pass\n \n def _set_trace_opcodes(self,trace_opcodes):\n if trace_opcodes !=self.trace_opcodes:\n self.trace_opcodes=trace_opcodes\n frame=self.enterframe\n while frame is not None:\n frame.f_trace_opcodes=trace_opcodes\n if frame is self.botframe:\n break\n frame=frame.f_back\n \n def _set_stopinfo(self,stopframe,returnframe,stoplineno=0,opcode=False):\n ''\n\n\n\n\n \n self.stopframe=stopframe\n self.returnframe=returnframe\n self.quitting=False\n \n \n self.stoplineno=stoplineno\n self._set_trace_opcodes(opcode)\n \n def _set_caller_tracefunc(self,current_frame):\n \n \n \n \n caller_frame=current_frame.f_back\n if caller_frame and not caller_frame.f_trace:\n caller_frame.f_trace=self.trace_dispatch\n \n \n \n \n def set_until(self,frame,lineno=None):\n ''\n \n \n if lineno is None:\n lineno=frame.f_lineno+1\n self._set_stopinfo(frame,frame,lineno)\n \n def set_step(self):\n ''\n self._set_stopinfo(None,None)\n \n def set_stepinstr(self):\n ''\n self._set_stopinfo(None,None,opcode=True)\n \n def set_next(self,frame):\n ''\n self._set_stopinfo(frame,None)\n \n def set_return(self,frame):\n ''\n if frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n self._set_stopinfo(frame,None,-1)\n else:\n self._set_stopinfo(frame.f_back,frame)\n \n def set_trace(self,frame=None):\n ''\n\n\n \n if frame is None:\n frame=sys._getframe().f_back\n self.reset()\n self.enterframe=frame\n while frame:\n frame.f_trace=self.trace_dispatch\n self.botframe=frame\n self.frame_trace_lines_opcodes[frame]=(frame.f_trace_lines,frame.f_trace_opcodes)\n \n frame.f_trace_lines=True\n frame=frame.f_back\n self.set_stepinstr()\n sys.settrace(self.trace_dispatch)\n \n def set_continue(self):\n ''\n\n\n \n \n self._set_stopinfo(self.botframe,None,-1)\n if not self.breaks:\n \n sys.settrace(None)\n frame=sys._getframe().f_back\n while frame and frame is not self.botframe:\n del frame.f_trace\n frame=frame.f_back\n for frame,(trace_lines,trace_opcodes)in self.frame_trace_lines_opcodes.items():\n frame.f_trace_lines,frame.f_trace_opcodes=trace_lines,trace_opcodes\n self.frame_trace_lines_opcodes={}\n \n def set_quit(self):\n ''\n\n\n \n self.stopframe=self.botframe\n self.returnframe=None\n self.quitting=True\n sys.settrace(None)\n \n \n \n \n \n \n \n \n def _add_to_breaks(self,filename,lineno):\n ''\n bp_linenos=self.breaks.setdefault(filename,[])\n if lineno not in bp_linenos:\n bp_linenos.append(lineno)\n \n def set_break(self,filename,lineno,temporary=False,cond=None,\n funcname=None):\n ''\n\n\n\n \n filename=self.canonic(filename)\n import linecache\n line=linecache.getline(filename,lineno)\n if not line:\n return 'Line %s:%d does not exist'%(filename,lineno)\n self._add_to_breaks(filename,lineno)\n bp=Breakpoint(filename,lineno,temporary,cond,funcname)\n return None\n \n def _load_breaks(self):\n ''\n\n\n\n\n\n \n for(filename,lineno)in Breakpoint.bplist.keys():\n self._add_to_breaks(filename,lineno)\n \n def _prune_breaks(self,filename,lineno):\n ''\n\n\n\n\n\n \n if(filename,lineno)not in Breakpoint.bplist:\n self.breaks[filename].remove(lineno)\n if not self.breaks[filename]:\n del self.breaks[filename]\n \n def clear_break(self,filename,lineno):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename not in self.breaks:\n return 'There are no breakpoints in %s'%filename\n if lineno not in self.breaks[filename]:\n return 'There is no breakpoint at %s:%d'%(filename,lineno)\n \n \n for bp in Breakpoint.bplist[filename,lineno][:]:\n bp.deleteMe()\n self._prune_breaks(filename,lineno)\n return None\n \n def clear_bpbynumber(self,arg):\n ''\n\n\n \n try:\n bp=self.get_bpbynumber(arg)\n except ValueError as err:\n return str(err)\n bp.deleteMe()\n self._prune_breaks(bp.file,bp.line)\n return None\n \n def clear_all_file_breaks(self,filename):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename not in self.breaks:\n return 'There are no breakpoints in %s'%filename\n for line in self.breaks[filename]:\n blist=Breakpoint.bplist[filename,line]\n for bp in blist:\n bp.deleteMe()\n del self.breaks[filename]\n return None\n \n def clear_all_breaks(self):\n ''\n\n\n \n if not self.breaks:\n return 'There are no breakpoints'\n for bp in Breakpoint.bpbynumber:\n if bp:\n bp.deleteMe()\n self.breaks={}\n return None\n \n def get_bpbynumber(self,arg):\n ''\n\n\n\n \n if not arg:\n raise ValueError('Breakpoint number expected')\n try:\n number=int(arg)\n except ValueError:\n raise ValueError('Non-numeric breakpoint number %s'%arg)from None\n try:\n bp=Breakpoint.bpbynumber[number]\n except IndexError:\n raise ValueError('Breakpoint number %d out of range'%number)from None\n if bp is None:\n raise ValueError('Breakpoint %d already deleted'%number)\n return bp\n \n def get_break(self,filename,lineno):\n ''\n filename=self.canonic(filename)\n return filename in self.breaks and\\\n lineno in self.breaks[filename]\n \n def get_breaks(self,filename,lineno):\n ''\n\n\n \n filename=self.canonic(filename)\n return filename in self.breaks and\\\n lineno in self.breaks[filename]and\\\n Breakpoint.bplist[filename,lineno]or[]\n \n def get_file_breaks(self,filename):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename in self.breaks:\n return self.breaks[filename]\n else:\n return[]\n \n def get_all_breaks(self):\n ''\n return self.breaks\n \n \n \n \n def get_stack(self,f,t):\n ''\n\n\n\n \n stack=[]\n if t and t.tb_frame is f:\n t=t.tb_next\n while f is not None:\n stack.append((f,f.f_lineno))\n if f is self.botframe:\n break\n f=f.f_back\n stack.reverse()\n i=max(0,len(stack)-1)\n while t is not None:\n stack.append((t.tb_frame,t.tb_lineno))\n t=t.tb_next\n if f is None:\n i=max(0,len(stack)-1)\n return stack,i\n \n def format_stack_entry(self,frame_lineno,lprefix=': '):\n ''\n\n\n\n\n\n\n \n import linecache,reprlib\n frame,lineno=frame_lineno\n filename=self.canonic(frame.f_code.co_filename)\n s='%s(%r)'%(filename,lineno)\n if frame.f_code.co_name:\n s +=frame.f_code.co_name\n else:\n s +=\"\"\n s +='()'\n if '__return__'in frame.f_locals:\n rv=frame.f_locals['__return__']\n s +='->'\n s +=reprlib.repr(rv)\n if lineno is not None:\n line=linecache.getline(filename,lineno,frame.f_globals)\n if line:\n s +=lprefix+line.strip()\n else:\n s +=f'{lprefix}Warning: lineno is None'\n return s\n \n \n \n \n \n def run(self,cmd,globals=None,locals=None):\n ''\n\n\n \n if globals is None:\n import __main__\n globals=__main__.__dict__\n if locals is None:\n locals=globals\n self.reset()\n if isinstance(cmd,str):\n cmd=compile(cmd,\"\",\"exec\")\n sys.settrace(self.trace_dispatch)\n try:\n exec(cmd,globals,locals)\n except BdbQuit:\n pass\n finally:\n self.quitting=True\n sys.settrace(None)\n \n def runeval(self,expr,globals=None,locals=None):\n ''\n\n\n \n if globals is None:\n import __main__\n globals=__main__.__dict__\n if locals is None:\n locals=globals\n self.reset()\n sys.settrace(self.trace_dispatch)\n try:\n return eval(expr,globals,locals)\n except BdbQuit:\n pass\n finally:\n self.quitting=True\n sys.settrace(None)\n \n def runctx(self,cmd,globals,locals):\n ''\n \n self.run(cmd,globals,locals)\n \n \n \n def runcall(self,func,/,*args,**kwds):\n ''\n\n\n \n self.reset()\n sys.settrace(self.trace_dispatch)\n res=None\n try:\n res=func(*args,**kwds)\n except BdbQuit:\n pass\n finally:\n self.quitting=True\n sys.settrace(None)\n return res\n \n \ndef set_trace():\n ''\n Bdb().set_trace()\n \n \nclass Breakpoint:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n next=1\n bplist={}\n bpbynumber=[None]\n \n \n \n def __init__(self,file,line,temporary=False,cond=None,funcname=None):\n self.funcname=funcname\n \n self.func_first_executable_line=None\n self.file=file\n self.line=line\n self.temporary=temporary\n self.cond=cond\n self.enabled=True\n self.ignore=0\n self.hits=0\n self.number=Breakpoint.next\n Breakpoint.next +=1\n \n self.bpbynumber.append(self)\n if(file,line)in self.bplist:\n self.bplist[file,line].append(self)\n else:\n self.bplist[file,line]=[self]\n \n @staticmethod\n def clearBreakpoints():\n Breakpoint.next=1\n Breakpoint.bplist={}\n Breakpoint.bpbynumber=[None]\n \n def deleteMe(self):\n ''\n\n\n\n \n \n index=(self.file,self.line)\n self.bpbynumber[self.number]=None\n self.bplist[index].remove(self)\n if not self.bplist[index]:\n \n del self.bplist[index]\n \n def enable(self):\n ''\n self.enabled=True\n \n def disable(self):\n ''\n self.enabled=False\n \n def bpprint(self,out=None):\n ''\n\n\n\n \n if out is None:\n out=sys.stdout\n print(self.bpformat(),file=out)\n \n def bpformat(self):\n ''\n\n\n\n\n\n \n if self.temporary:\n disp='del '\n else:\n disp='keep '\n if self.enabled:\n disp=disp+'yes '\n else:\n disp=disp+'no '\n ret='%-4dbreakpoint %s at %s:%d'%(self.number,disp,\n self.file,self.line)\n if self.cond:\n ret +='\\n\\tstop only if %s'%(self.cond,)\n if self.ignore:\n ret +='\\n\\tignore next %d hits'%(self.ignore,)\n if self.hits:\n if self.hits >1:\n ss='s'\n else:\n ss=''\n ret +='\\n\\tbreakpoint already hit %d time%s'%(self.hits,ss)\n return ret\n \n def __str__(self):\n ''\n return 'breakpoint %s at %s:%s'%(self.number,self.file,self.line)\n \n \n \n \ndef checkfuncname(b,frame):\n ''\n\n\n\n\n\n \n if not b.funcname:\n \n if b.line !=frame.f_lineno:\n \n \n return False\n return True\n \n \n if frame.f_code.co_name !=b.funcname:\n \n return False\n \n \n if not b.func_first_executable_line:\n \n b.func_first_executable_line=frame.f_lineno\n \n if b.func_first_executable_line !=frame.f_lineno:\n \n return False\n return True\n \n \ndef effective(file,line,frame):\n ''\n\n\n\n\n\n\n\n\n\n\n \n possibles=Breakpoint.bplist[file,line]\n for b in possibles:\n if not b.enabled:\n continue\n if not checkfuncname(b,frame):\n continue\n \n b.hits +=1\n if not b.cond:\n \n if b.ignore >0:\n b.ignore -=1\n continue\n else:\n \n return(b,True)\n else:\n \n \n \n try:\n val=eval(b.cond,frame.f_globals,frame.f_locals)\n if val:\n if b.ignore >0:\n b.ignore -=1\n \n else:\n return(b,True)\n \n \n except:\n \n \n \n return(b,False)\n return(None,None)\n \n \n \n \nclass Tdb(Bdb):\n def user_call(self,frame,args):\n name=frame.f_code.co_name\n if not name:name='???'\n print('+++ call',name,args)\n def user_line(self,frame):\n import linecache\n name=frame.f_code.co_name\n if not name:name='???'\n fn=self.canonic(frame.f_code.co_filename)\n line=linecache.getline(fn,frame.f_lineno,frame.f_globals)\n print('+++',fn,frame.f_lineno,name,':',line.strip())\n def user_return(self,frame,retval):\n print('+++ return',retval)\n def user_exception(self,frame,exc_stuff):\n print('+++ exception',exc_stuff)\n self.set_continue()\n \ndef foo(n):\n print('foo(',n,')')\n x=bar(n *10)\n print('bar returned',x)\n \ndef bar(a):\n print('bar(',a,')')\n return a /2\n \ndef test():\n t=Tdb()\n t.run('import bdb; bdb.foo(10)')\n", ["__main__", "fnmatch", "inspect", "linecache", "os", "reprlib", "sys"]], "binascii": [".py", "''\n\n\n\n\n\n\n\nimport _base64\n\nfrom _binascii import *\n\nclass Error(ValueError):\n def __init__(self,msg=''):\n self._msg=msg\n \n def __str__(self):\n return \" binascii.Error: \"+self._msg\n \n \nclass Done(Exception):\n pass\n \nclass Incomplete(Error):\n pass\n \ndef a2b_uu(s):\n if not s:\n return ''\n \n length=(ord(s[0])-0x20)%64\n \n def quadruplets_gen(s):\n while s:\n try:\n yield ord(s[0]),ord(s[1]),ord(s[2]),ord(s[3])\n except IndexError:\n s +=' '\n yield ord(s[0]),ord(s[1]),ord(s[2]),ord(s[3])\n return\n s=s[4:]\n \n try:\n result=[''.join(\n [chr((A -0x20)<<2 |(((B -0x20)>>4)&0x3)),\n chr(((B -0x20)&0xf)<<4 |(((C -0x20)>>2)&0xf)),\n chr(((C -0x20)&0x3)<<6 |((D -0x20)&0x3f))\n ])for A,B,C,D in quadruplets_gen(s[1:].rstrip())]\n except ValueError:\n raise Error('Illegal char')\n result=''.join(result)\n trailingdata=result[length:]\n if trailingdata.strip('\\x00'):\n raise Error('Trailing garbage')\n result=result[:length]\n if len(result)>2)&0x3F],\n table_b2a_base64[((A <<4)|((B >>4)&0xF))&0x3F],\n table_b2a_base64[((B <<2)|((C >>6)&0x3))&0x3F],\n table_b2a_base64[(C)&0x3F]])\n for A,B,C in a]\n \n final=s[length -final_length:]\n if final_length ==0:\n snippet=''\n elif final_length ==1:\n a=final[0]\n snippet=table_b2a_base64[(a >>2)&0x3F]+\\\n table_b2a_base64[(a <<4)&0x3F]+'=='\n else:\n a=final[0]\n b=final[1]\n snippet=table_b2a_base64[(a >>2)&0x3F]+\\\n table_b2a_base64[((a <<4)|(b >>4)&0xF)&0x3F]+\\\n table_b2a_base64[(b <<2)&0x3F]+'='\n \n result=''.join(result)+snippet\n if newline:\n result +='\\n'\n return bytes(result,__BRYTHON__.charset)\n \ndef a2b_qp(s,header=False):\n inp=0\n odata=[]\n while inp =len(s):\n break\n \n if(s[inp]=='\\n')or(s[inp]=='\\r'):\n if s[inp]!='\\n':\n while inp 0 and data[lf -1]=='\\r'\n \n inp=0\n linelen=0\n odata=[]\n while inp '~'or\n c =='='or\n (header and c =='_')or\n (c =='.'and linelen ==0 and(inp+1 ==len(data)or\n data[inp+1]=='\\n'or\n data[inp+1]=='\\r'))or\n (not istext and(c =='\\r'or c =='\\n'))or\n ((c =='\\t'or c ==' ')and(inp+1 ==len(data)))or\n (c <=' 'and c !='\\r'and c !='\\n'and\n (quotetabs or(not quotetabs and(c !='\\t'and c !=' '))))):\n linelen +=3\n if linelen >=MAXLINESIZE:\n odata.append('=')\n if crlf:odata.append('\\r')\n odata.append('\\n')\n linelen=3\n odata.append('='+two_hex_digits(ord(c)))\n inp +=1\n else:\n if(istext and\n (c =='\\n'or(inp+1 0 and\n (odata[-1]==' 'or odata[-1]=='\\t')):\n ch=ord(odata[-1])\n odata[-1]='='\n odata.append(two_hex_digits(ch))\n \n if crlf:odata.append('\\r')\n odata.append('\\n')\n if c =='\\r':\n inp +=2\n else:\n inp +=1\n else:\n if(inp+1 =MAXLINESIZE):\n odata.append('=')\n if crlf:odata.append('\\r')\n odata.append('\\n')\n linelen=0\n \n linelen +=1\n if header and c ==' ':\n c='_'\n odata.append(c)\n inp +=1\n return ''.join(odata)\n \nhex_numbers='0123456789ABCDEF'\ndef hex(n):\n if n ==0:\n return '0'\n \n if n <0:\n n=-n\n sign='-'\n else:\n sign=''\n arr=[]\n \n def hex_gen(n):\n ''\n while n:\n yield n %0x10\n n=n /0x10\n \n for nibble in hex_gen(n):\n arr=[hex_numbers[nibble]]+arr\n return sign+''.join(arr)\n \ndef two_hex_digits(n):\n return hex_numbers[n /0x10]+hex_numbers[n %0x10]\n \n \ndef strhex_to_int(s):\n i=0\n for c in s:\n i=i *0x10+hex_numbers.index(c)\n return i\n \nhqx_encoding='!\"#$%&\\'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr'\n\nDONE=0x7f\nSKIP=0x7e\nFAIL=0x7d\n\ntable_a2b_hqx=[\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,SKIP,FAIL,FAIL,SKIP,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,0x00,0x01,0x02,0x03,0x04,0x05,0x06,\n\n0x07,0x08,0x09,0x0A,0x0B,0x0C,FAIL,FAIL,\n\n0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,FAIL,\n\n0x14,0x15,DONE,FAIL,FAIL,FAIL,FAIL,FAIL,\n\n0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,\n\n0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,FAIL,\n\n0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,FAIL,\n\n0x2C,0x2D,0x2E,0x2F,FAIL,FAIL,FAIL,FAIL,\n\n0x30,0x31,0x32,0x33,0x34,0x35,0x36,FAIL,\n\n0x37,0x38,0x39,0x3A,0x3B,0x3C,FAIL,FAIL,\n\n0x3D,0x3E,0x3F,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n]\n\ndef a2b_hqx(s):\n result=[]\n \n def quadruples_gen(s):\n t=[]\n for c in s:\n res=table_a2b_hqx[ord(c)]\n if res ==SKIP:\n continue\n elif res ==FAIL:\n raise Error('Illegal character')\n elif res ==DONE:\n yield t\n raise Done\n else:\n t.append(res)\n if len(t)==4:\n yield t\n t=[]\n yield t\n \n done=0\n try:\n for snippet in quadruples_gen(s):\n length=len(snippet)\n if length ==4:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n result.append(chr(((snippet[1]&0x0f)<<4)|(snippet[2]>>2)))\n result.append(chr(((snippet[2]&0x03)<<6)|(snippet[3])))\n elif length ==3:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n result.append(chr(((snippet[1]&0x0f)<<4)|(snippet[2]>>2)))\n elif length ==2:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n except Done:\n done=1\n except Error:\n raise\n return(''.join(result),done)\n \n \n \ndef b2a_hqx(s):\n result=[]\n \n def triples_gen(s):\n while s:\n try:\n yield ord(s[0]),ord(s[1]),ord(s[2])\n except IndexError:\n yield tuple([ord(c)for c in s])\n s=s[3:]\n \n for snippet in triples_gen(s):\n length=len(snippet)\n if length ==3:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)|((snippet[1]&0xf0)>>4)])\n result.append(hqx_encoding[\n (snippet[1]&0x0f)<<2 |((snippet[2]&0xc0)>>6)])\n result.append(hqx_encoding[snippet[2]&0x3f])\n elif length ==2:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)|((snippet[1]&0xf0)>>4)])\n result.append(hqx_encoding[\n (snippet[1]&0x0f)<<2])\n elif length ==1:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)])\n return ''.join(result)\n \ncrctab_hqx=[\n0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,\n0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,\n0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,\n0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,\n0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,\n0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,\n0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,\n0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,\n0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,\n0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,\n0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,\n0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,\n0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,\n0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,\n0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,\n0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,\n0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,\n0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,\n0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,\n0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,\n0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,\n0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,\n0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,\n0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,\n0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,\n0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,\n0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,\n0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,\n0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,\n0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,\n0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,\n0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0,\n]\n\ndef crc_hqx(s,crc):\n for c in s:\n crc=((crc <<8)&0xff00)^crctab_hqx[((crc >>8)&0xff)^ord(c)]\n \n return crc\n \ndef rlecode_hqx(s):\n ''\n\n\n\n \n if not s:\n return ''\n result=[]\n prev=s[0]\n count=1\n \n \n \n \n if s[-1]=='!':\n s=s[1:]+'?'\n else:\n s=s[1:]+'!'\n \n for c in s:\n if c ==prev and count <255:\n count +=1\n else:\n if count ==1:\n if prev !='\\x90':\n result.append(prev)\n else:\n result.extend(['\\x90','\\x00'])\n elif count <4:\n if prev !='\\x90':\n result.extend([prev]*count)\n else:\n result.extend(['\\x90','\\x00']*count)\n else:\n if prev !='\\x90':\n result.extend([prev,'\\x90',chr(count)])\n else:\n result.extend(['\\x90','\\x00','\\x90',chr(count)])\n count=1\n prev=c\n \n return ''.join(result)\n \ndef rledecode_hqx(s):\n s=s.split('\\x90')\n result=[s[0]]\n prev=s[0]\n for snippet in s[1:]:\n count=ord(snippet[0])\n if count >0:\n result.append(prev[-1]*(count -1))\n prev=snippet\n else:\n result.append('\\x90')\n prev='\\x90'\n result.append(snippet[1:])\n \n return ''.join(result)\n \ncrc_32_tab=[\n0x00000000,0x77073096,0xee0e612c,0x990951ba,0x076dc419,\n0x706af48f,0xe963a535,0x9e6495a3,0x0edb8832,0x79dcb8a4,\n0xe0d5e91e,0x97d2d988,0x09b64c2b,0x7eb17cbd,0xe7b82d07,\n0x90bf1d91,0x1db71064,0x6ab020f2,0xf3b97148,0x84be41de,\n0x1adad47d,0x6ddde4eb,0xf4d4b551,0x83d385c7,0x136c9856,\n0x646ba8c0,0xfd62f97a,0x8a65c9ec,0x14015c4f,0x63066cd9,\n0xfa0f3d63,0x8d080df5,0x3b6e20c8,0x4c69105e,0xd56041e4,\n0xa2677172,0x3c03e4d1,0x4b04d447,0xd20d85fd,0xa50ab56b,\n0x35b5a8fa,0x42b2986c,0xdbbbc9d6,0xacbcf940,0x32d86ce3,\n0x45df5c75,0xdcd60dcf,0xabd13d59,0x26d930ac,0x51de003a,\n0xc8d75180,0xbfd06116,0x21b4f4b5,0x56b3c423,0xcfba9599,\n0xb8bda50f,0x2802b89e,0x5f058808,0xc60cd9b2,0xb10be924,\n0x2f6f7c87,0x58684c11,0xc1611dab,0xb6662d3d,0x76dc4190,\n0x01db7106,0x98d220bc,0xefd5102a,0x71b18589,0x06b6b51f,\n0x9fbfe4a5,0xe8b8d433,0x7807c9a2,0x0f00f934,0x9609a88e,\n0xe10e9818,0x7f6a0dbb,0x086d3d2d,0x91646c97,0xe6635c01,\n0x6b6b51f4,0x1c6c6162,0x856530d8,0xf262004e,0x6c0695ed,\n0x1b01a57b,0x8208f4c1,0xf50fc457,0x65b0d9c6,0x12b7e950,\n0x8bbeb8ea,0xfcb9887c,0x62dd1ddf,0x15da2d49,0x8cd37cf3,\n0xfbd44c65,0x4db26158,0x3ab551ce,0xa3bc0074,0xd4bb30e2,\n0x4adfa541,0x3dd895d7,0xa4d1c46d,0xd3d6f4fb,0x4369e96a,\n0x346ed9fc,0xad678846,0xda60b8d0,0x44042d73,0x33031de5,\n0xaa0a4c5f,0xdd0d7cc9,0x5005713c,0x270241aa,0xbe0b1010,\n0xc90c2086,0x5768b525,0x206f85b3,0xb966d409,0xce61e49f,\n0x5edef90e,0x29d9c998,0xb0d09822,0xc7d7a8b4,0x59b33d17,\n0x2eb40d81,0xb7bd5c3b,0xc0ba6cad,0xedb88320,0x9abfb3b6,\n0x03b6e20c,0x74b1d29a,0xead54739,0x9dd277af,0x04db2615,\n0x73dc1683,0xe3630b12,0x94643b84,0x0d6d6a3e,0x7a6a5aa8,\n0xe40ecf0b,0x9309ff9d,0x0a00ae27,0x7d079eb1,0xf00f9344,\n0x8708a3d2,0x1e01f268,0x6906c2fe,0xf762575d,0x806567cb,\n0x196c3671,0x6e6b06e7,0xfed41b76,0x89d32be0,0x10da7a5a,\n0x67dd4acc,0xf9b9df6f,0x8ebeeff9,0x17b7be43,0x60b08ed5,\n0xd6d6a3e8,0xa1d1937e,0x38d8c2c4,0x4fdff252,0xd1bb67f1,\n0xa6bc5767,0x3fb506dd,0x48b2364b,0xd80d2bda,0xaf0a1b4c,\n0x36034af6,0x41047a60,0xdf60efc3,0xa867df55,0x316e8eef,\n0x4669be79,0xcb61b38c,0xbc66831a,0x256fd2a0,0x5268e236,\n0xcc0c7795,0xbb0b4703,0x220216b9,0x5505262f,0xc5ba3bbe,\n0xb2bd0b28,0x2bb45a92,0x5cb36a04,0xc2d7ffa7,0xb5d0cf31,\n0x2cd99e8b,0x5bdeae1d,0x9b64c2b0,0xec63f226,0x756aa39c,\n0x026d930a,0x9c0906a9,0xeb0e363f,0x72076785,0x05005713,\n0x95bf4a82,0xe2b87a14,0x7bb12bae,0x0cb61b38,0x92d28e9b,\n0xe5d5be0d,0x7cdcefb7,0x0bdbdf21,0x86d3d2d4,0xf1d4e242,\n0x68ddb3f8,0x1fda836e,0x81be16cd,0xf6b9265b,0x6fb077e1,\n0x18b74777,0x88085ae6,0xff0f6a70,0x66063bca,0x11010b5c,\n0x8f659eff,0xf862ae69,0x616bffd3,0x166ccf45,0xa00ae278,\n0xd70dd2ee,0x4e048354,0x3903b3c2,0xa7672661,0xd06016f7,\n0x4969474d,0x3e6e77db,0xaed16a4a,0xd9d65adc,0x40df0b66,\n0x37d83bf0,0xa9bcae53,0xdebb9ec5,0x47b2cf7f,0x30b5ffe9,\n0xbdbdf21c,0xcabac28a,0x53b39330,0x24b4a3a6,0xbad03605,\n0xcdd70693,0x54de5729,0x23d967bf,0xb3667a2e,0xc4614ab8,\n0x5d681b02,0x2a6f2b94,0xb40bbe37,0xc30c8ea1,0x5a05df1b,\n0x2d02ef8d\n]\n\ndef crc32(s,crc=0):\n result=0\n crc=~int(crc)&0xffffffff\n \n for c in s:\n crc=crc_32_tab[(crc ^int(ord(c)))&0xff]^(crc >>8)\n \n \n \n result=crc ^0xffffffff\n \n if result >2 **31:\n result=((result+2 **31)%2 **32)-2 **31\n \n return result\n", ["_base64", "_binascii"]], "bisect": [".py", "''\n\n\ndef insort_right(a,x,lo=0,hi=None,*,key=None):\n ''\n\n\n\n\n\n\n\n \n if key is None:\n lo=bisect_right(a,x,lo,hi)\n else:\n lo=bisect_right(a,key(x),lo,hi,key=key)\n a.insert(lo,x)\n \n \ndef bisect_right(a,x,lo=0,hi=None,*,key=None):\n ''\n\n\n\n\n\n\n\n\n\n \n \n if lo <0:\n raise ValueError('lo must be non-negative')\n if hi is None:\n hi=len(a)\n \n \n if key is None:\n while lo =9:\n names=day_name\n else:\n names=day_abbr\n return names[day][:width].center(width)\n \n def formatweekheader(self,width):\n ''\n\n \n return ' '.join(self.formatweekday(i,width)for i in self.iterweekdays())\n \n def formatmonthname(self,theyear,themonth,width,withyear=True):\n ''\n\n \n s=month_name[themonth]\n if withyear:\n s=\"%s %r\"%(s,theyear)\n return s.center(width)\n \n def prmonth(self,theyear,themonth,w=0,l=0):\n ''\n\n \n print(self.formatmonth(theyear,themonth,w,l),end='')\n \n def formatmonth(self,theyear,themonth,w=0,l=0):\n ''\n\n \n w=max(2,w)\n l=max(1,l)\n s=self.formatmonthname(theyear,themonth,7 *(w+1)-1)\n s=s.rstrip()\n s +='\\n'*l\n s +=self.formatweekheader(w).rstrip()\n s +='\\n'*l\n for week in self.monthdays2calendar(theyear,themonth):\n s +=self.formatweek(week,w).rstrip()\n s +='\\n'*l\n return s\n \n def formatyear(self,theyear,w=2,l=1,c=6,m=3):\n ''\n\n \n w=max(2,w)\n l=max(1,l)\n c=max(2,c)\n colwidth=(w+1)*7 -1\n v=[]\n a=v.append\n a(repr(theyear).center(colwidth *m+c *(m -1)).rstrip())\n a('\\n'*l)\n header=self.formatweekheader(w)\n for(i,row)in enumerate(self.yeardays2calendar(theyear,m)):\n \n months=range(m *i+1,min(m *(i+1)+1,13))\n a('\\n'*l)\n names=(self.formatmonthname(theyear,k,colwidth,False)\n for k in months)\n a(formatstring(names,colwidth,c).rstrip())\n a('\\n'*l)\n headers=(header for k in months)\n a(formatstring(headers,colwidth,c).rstrip())\n a('\\n'*l)\n \n height=max(len(cal)for cal in row)\n for j in range(height):\n weeks=[]\n for cal in row:\n if j >=len(cal):\n weeks.append('')\n else:\n weeks.append(self.formatweek(cal[j],w))\n a(formatstring(weeks,colwidth,c).rstrip())\n a('\\n'*l)\n return ''.join(v)\n \n def pryear(self,theyear,w=0,l=0,c=6,m=3):\n ''\n print(self.formatyear(theyear,w,l,c,m),end='')\n \n \nclass HTMLCalendar(Calendar):\n ''\n\n \n \n \n cssclasses=[\"mon\",\"tue\",\"wed\",\"thu\",\"fri\",\"sat\",\"sun\"]\n \n \n cssclasses_weekday_head=cssclasses\n \n \n cssclass_noday=\"noday\"\n \n \n cssclass_month_head=\"month\"\n \n \n cssclass_month=\"month\"\n \n \n cssclass_year_head=\"year\"\n \n \n cssclass_year=\"year\"\n \n def formatday(self,day,weekday):\n ''\n\n \n if day ==0:\n \n return ' '%self.cssclass_noday\n else:\n return '%d'%(self.cssclasses[weekday],day)\n \n def formatweek(self,theweek):\n ''\n\n \n s=''.join(self.formatday(d,wd)for(d,wd)in theweek)\n return '%s'%s\n \n def formatweekday(self,day):\n ''\n\n \n return '%s'%(\n self.cssclasses_weekday_head[day],day_abbr[day])\n \n def formatweekheader(self):\n ''\n\n \n s=''.join(self.formatweekday(i)for i in self.iterweekdays())\n return '%s'%s\n \n def formatmonthname(self,theyear,themonth,withyear=True):\n ''\n\n \n if withyear:\n s='%s %s'%(month_name[themonth],theyear)\n else:\n s='%s'%month_name[themonth]\n return '%s'%(\n self.cssclass_month_head,s)\n \n def formatmonth(self,theyear,themonth,withyear=True):\n ''\n\n \n v=[]\n a=v.append\n a(''%(\n self.cssclass_month))\n a('\\n')\n a(self.formatmonthname(theyear,themonth,withyear=withyear))\n a('\\n')\n a(self.formatweekheader())\n a('\\n')\n for week in self.monthdays2calendar(theyear,themonth):\n a(self.formatweek(week))\n a('\\n')\n a('
')\n a('\\n')\n return ''.join(v)\n \n def formatyear(self,theyear,width=3):\n ''\n\n \n v=[]\n a=v.append\n width=max(width,1)\n a(''%\n self.cssclass_year)\n a('\\n')\n a(''%(\n width,self.cssclass_year_head,theyear))\n for i in range(JANUARY,JANUARY+12,width):\n \n months=range(i,min(i+width,13))\n a('')\n for m in months:\n a('')\n a('')\n a('
%s
')\n a(self.formatmonth(theyear,m,withyear=False))\n a('
')\n return ''.join(v)\n \n def formatyearpage(self,theyear,width=3,css='calendar.css',encoding=None):\n ''\n\n \n if encoding is None:\n encoding=sys.getdefaultencoding()\n v=[]\n a=v.append\n a('\\n'%encoding)\n a('\\n')\n a('\\n')\n a('\\n')\n a('\\n'%encoding)\n if css is not None:\n a('\\n'%css)\n a('Calendar for %d\\n'%theyear)\n a('\\n')\n a('\\n')\n a(self.formatyear(theyear,width))\n a('\\n')\n a('\\n')\n return ''.join(v).encode(encoding,\"xmlcharrefreplace\")\n \n \nclass different_locale:\n def __init__(self,locale):\n self.locale=locale\n self.oldlocale=None\n \n def __enter__(self):\n self.oldlocale=_locale.setlocale(_locale.LC_TIME,None)\n _locale.setlocale(_locale.LC_TIME,self.locale)\n \n def __exit__(self,*args):\n _locale.setlocale(_locale.LC_TIME,self.oldlocale)\n \n \ndef _get_default_locale():\n locale=_locale.setlocale(_locale.LC_TIME,None)\n if locale ==\"C\":\n with different_locale(\"\"):\n \n \n locale=_locale.setlocale(_locale.LC_TIME,None)\n return locale\n \n \nclass LocaleTextCalendar(TextCalendar):\n ''\n\n\n \n \n def __init__(self,firstweekday=0,locale=None):\n TextCalendar.__init__(self,firstweekday)\n if locale is None:\n locale=_get_default_locale()\n self.locale=locale\n \n def formatweekday(self,day,width):\n with different_locale(self.locale):\n return super().formatweekday(day,width)\n \n def formatmonthname(self,theyear,themonth,width,withyear=True):\n with different_locale(self.locale):\n return super().formatmonthname(theyear,themonth,width,withyear)\n \n \nclass LocaleHTMLCalendar(HTMLCalendar):\n ''\n\n\n \n def __init__(self,firstweekday=0,locale=None):\n HTMLCalendar.__init__(self,firstweekday)\n if locale is None:\n locale=_get_default_locale()\n self.locale=locale\n \n def formatweekday(self,day):\n with different_locale(self.locale):\n return super().formatweekday(day)\n \n def formatmonthname(self,theyear,themonth,withyear=True):\n with different_locale(self.locale):\n return super().formatmonthname(theyear,themonth,withyear)\n \n \nc=TextCalendar()\n\nfirstweekday=c.getfirstweekday\n\ndef setfirstweekday(firstweekday):\n if not MONDAY <=firstweekday <=SUNDAY:\n raise IllegalWeekdayError(firstweekday)\n c.firstweekday=firstweekday\n \nmonthcalendar=c.monthdayscalendar\nprweek=c.prweek\nweek=c.formatweek\nweekheader=c.formatweekheader\nprmonth=c.prmonth\nmonth=c.formatmonth\ncalendar=c.formatyear\nprcal=c.pryear\n\n\n\n_colwidth=7 *3 -1\n_spacing=6\n\n\ndef format(cols,colwidth=_colwidth,spacing=_spacing):\n ''\n print(formatstring(cols,colwidth,spacing))\n \n \ndef formatstring(cols,colwidth=_colwidth,spacing=_spacing):\n ''\n spacing *=' '\n return spacing.join(c.center(colwidth)for c in cols)\n \n \nEPOCH=1970\n_EPOCH_ORD=datetime.date(EPOCH,1,1).toordinal()\n\n\ndef timegm(tuple):\n ''\n year,month,day,hour,minute,second=tuple[:6]\n days=datetime.date(year,month,1).toordinal()-_EPOCH_ORD+day -1\n hours=days *24+hour\n minutes=hours *60+minute\n seconds=minutes *60+second\n return seconds\n \n \ndef main(args=None):\n import argparse\n parser=argparse.ArgumentParser()\n textgroup=parser.add_argument_group('text only arguments')\n htmlgroup=parser.add_argument_group('html only arguments')\n textgroup.add_argument(\n \"-w\",\"--width\",\n type=int,default=2,\n help=\"width of date column (default 2)\"\n )\n textgroup.add_argument(\n \"-l\",\"--lines\",\n type=int,default=1,\n help=\"number of lines for each week (default 1)\"\n )\n textgroup.add_argument(\n \"-s\",\"--spacing\",\n type=int,default=6,\n help=\"spacing between months (default 6)\"\n )\n textgroup.add_argument(\n \"-m\",\"--months\",\n type=int,default=3,\n help=\"months per row (default 3)\"\n )\n htmlgroup.add_argument(\n \"-c\",\"--css\",\n default=\"calendar.css\",\n help=\"CSS to use for page\"\n )\n parser.add_argument(\n \"-L\",\"--locale\",\n default=None,\n help=\"locale to use for month and weekday names\"\n )\n parser.add_argument(\n \"-e\",\"--encoding\",\n default=None,\n help=\"encoding to use for output\"\n )\n parser.add_argument(\n \"-t\",\"--type\",\n default=\"text\",\n choices=(\"text\",\"html\"),\n help=\"output type (text or html)\"\n )\n parser.add_argument(\n \"-f\",\"--first-weekday\",\n type=int,default=0,\n help=\"weekday (0 is Monday, 6 is Sunday) to start each week (default 0)\"\n )\n parser.add_argument(\n \"year\",\n nargs='?',type=int,\n help=\"year number\"\n )\n parser.add_argument(\n \"month\",\n nargs='?',type=int,\n help=\"month number (1-12, text only)\"\n )\n \n options=parser.parse_args(args)\n \n if options.locale and not options.encoding:\n parser.error(\"if --locale is specified --encoding is required\")\n sys.exit(1)\n \n locale=options.locale,options.encoding\n \n if options.type ==\"html\":\n if options.month:\n parser.error(\"incorrect number of arguments\")\n sys.exit(1)\n if options.locale:\n cal=LocaleHTMLCalendar(locale=locale)\n else:\n cal=HTMLCalendar()\n cal.setfirstweekday(options.first_weekday)\n encoding=options.encoding\n if encoding is None:\n encoding=sys.getdefaultencoding()\n optdict=dict(encoding=encoding,css=options.css)\n write=sys.stdout.buffer.write\n if options.year is None:\n write(cal.formatyearpage(datetime.date.today().year,**optdict))\n else:\n write(cal.formatyearpage(options.year,**optdict))\n else:\n if options.locale:\n cal=LocaleTextCalendar(locale=locale)\n else:\n cal=TextCalendar()\n cal.setfirstweekday(options.first_weekday)\n optdict=dict(w=options.width,l=options.lines)\n if options.month is None:\n optdict[\"c\"]=options.spacing\n optdict[\"m\"]=options.months\n if options.year is None:\n result=cal.formatyear(datetime.date.today().year,**optdict)\n elif options.month is None:\n result=cal.formatyear(options.year,**optdict)\n else:\n result=cal.formatmonth(options.year,options.month,**optdict)\n write=sys.stdout.write\n if options.encoding:\n result=result.encode(options.encoding)\n write=sys.stdout.buffer.write\n write(result)\n \n \nif __name__ ==\"__main__\":\n main()\n", ["argparse", "datetime", "enum", "itertools", "locale", "sys", "warnings"]], "cmath": [".py", "\n\n\n\n\n\n\n\n\n\nimport math\nimport sys\n\ndef _takes_complex(func):\n def decorated(x):\n if isinstance(x,complex):\n return func(x)\n elif type(x)in[int,float]:\n return func(complex(x))\n elif hasattr(x,'__complex__'):\n c=x.__complex__()\n if not isinstance(c,complex):\n raise TypeError(\"A complex number is required\")\n else:\n return func(c)\n elif hasattr(x,'__float__'):\n try:\n c=complex(x.__float__(),0)\n except:\n raise TypeError(\"A complex number is required\")\n return func(c)\n elif hasattr(x,'__index__'):\n try:\n c=complex(x.__index__(),0)\n except:\n raise TypeError(\"A complex number is required\")\n return func(c)\n else:\n raise TypeError(\"A complex number is required\")\n if hasattr(func,'__doc__'):\n decorated.__doc__=func.__doc__\n if hasattr(func,'__name__'):\n decorated.__name__=func.__name__\n return decorated\n \n@_takes_complex\ndef isfinite(x):\n return math.isfinite(x.imag)and math.isfinite(x.real)\n \n@_takes_complex\ndef phase(x):\n ''\n return math.atan2(x.imag,x.real)\n \n@_takes_complex\ndef polar(x):\n ''\n\n\n\n\n \n phi=math.atan2(x.imag,x.real)\n if math.isnan(x.imag):\n if math.isinf(x.real):\n return abs(x.real),nan\n return nan,nan\n elif math.isinf(x.imag):\n r=inf\n elif math.isinf(x.real):\n r=inf\n else:\n r=math.sqrt(x.real **2+x.imag **2)\n if math.isinf(r):\n raise OverflowError(\"math range error\")\n return r,phi\n \ndef rect(r,phi):\n ''\n\n \n if math.isnan(r):\n if not math.isnan(phi)and not phi:\n return complex(nan,0)\n return complex(nan,nan)\n elif math.isnan(phi):\n if not r:\n return complex(0,0)\n elif math.isinf(r):\n return complex(inf,nan)\n return complex(nan,nan)\n if math.isinf(r)or math.isinf(phi):\n \n \n if math.isinf(phi)and r !=.0 and not math.isnan(r):\n raise ValueError(\"math domain error\")\n \n \n \n \n if -inf 0:\n _real=math.copysign(inf,math.cos(phi))\n _imag=math.copysign(inf,math.sin(phi))\n else:\n _real=-math.copysign(inf,math.cos(phi));\n _imag=-math.copysign(inf,math.sin(phi));\n return complex(_real,_imag)\n return _SPECIAL_VALUE(complex(r,phi),_rect_special_values)\n \n else:\n if phi ==.0:\n \n \n \n return complex(r,phi *r)\n else:\n return complex(r *math.cos(phi),r *math.sin(phi))\n \n@_takes_complex\ndef sqrt(x):\n ''\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n s,d,ax,ay=.0,.0,math.fabs(x.real),math.fabs(x.imag)\n \n ret=_SPECIAL_VALUE(x,_sqrt_special_values)\n if ret is not None:\n return ret\n \n if math.isinf(x.imag):\n return complex(inf,x.imag)\n \n if x.real ==.0 and x.imag ==.0:\n _real=.0\n _imag=x.imag\n return complex(_real,_imag)\n \n if ay ==0:\n s=math.sqrt(ax)\n d=0\n elif ax 0. or ay >0.):\n \n AX=math.ldexp(ax,_CM_SCALE_UP)\n AY=math.ldexp(ay,_CM_SCALE_UP)\n S=math.sqrt((AX+math.hypot(AX,AY))/2.0)\n D=AY /(2 *S)\n s=math.ldexp(S,_CM_SCALE_DOWN)\n d=math.ldexp(D,_CM_SCALE_DOWN)\n else:\n ax /=8.0 ;\n s=2.0 *math.sqrt(ax+math.hypot(ax,ay /8.0));\n d=ay /(2.0 *s)\n \n if x.real >=.0:\n _real=s ;\n _imag=math.copysign(d,x.imag)\n else:\n _real=d ;\n _imag=math.copysign(s,x.imag)\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef acos(x):\n ''\n\n\n\n\n \n \n ret=_SPECIAL_VALUE(x,_acos_special_values)\n if ret is not None:\n if isinstance(ret,Exception):\n raise ret\n return ret\n \n if math.fabs(x.real)>_CM_LARGE_DOUBLE or math.fabs(x.imag)>_CM_LARGE_DOUBLE:\n \n _real=math.atan2(math.fabs(x.imag),x.real)\n \n \n \n if x.real <0:\n _imag=-math.copysign(math.log(math.hypot(x.real /2.,x.imag /2.))+_M_LN2 *2.,x.imag);\n else:\n _imag=math.copysign(math.log(math.hypot(x.real /2.,x.imag /2.))+_M_LN2 *2.,-x.imag);\n elif math.isnan(x.real):\n return complex(nan,nan)\n elif math.isnan(x.imag):\n if x.real ==0:\n return complex(pi /2,nan)\n return complex(nan,nan)\n else:\n s1=complex(float(1 -x.real),-x.imag)\n s1=sqrt(s1)\n s2=complex(1.0+x.real,x.imag)\n s2=sqrt(s2)\n _real=2.0 *math.atan2(s1.real,s2.real)\n _imag=math.asinh(s2.real *s1.imag -s2.imag *s1.real)\n if not x.imag:\n if x.real >1:\n _real=0\n elif x.real <-1:\n _real=math.pi\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef acosh(x):\n ''\n\n\n\n \n ret=_SPECIAL_VALUE(x,_acosh_special_values)\n if ret is not None:\n return ret\n \n if math.fabs(x.real)>_CM_LARGE_DOUBLE or math.fabs(x.imag)>_CM_LARGE_DOUBLE:\n \n _real=math.log(math.hypot(x.real /2.0,x.imag /2.0))+_M_LN2 *2.0\n _imag=math.atan2(x.imag,x.real);\n else:\n s1=sqrt(complex(x.real -1.0,x.imag))\n s2=sqrt(complex(x.real+1.0,x.imag))\n _real=math.asinh(s1.real *s2.real+s1.imag *s2.imag)\n _imag=2. *math.atan2(s1.imag,s2.real)\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef asin(x):\n ''\n\n\n\n \n \n s=complex(-x.imag,x.real)\n s=asinh(s)\n return complex(s.imag,-s.real)\n \n@_takes_complex\ndef asinh(x):\n ''\n\n\n\n\n \n ret=_SPECIAL_VALUE(x,_asinh_special_values)\n if ret is not None:\n return ret\n \n if math.fabs(x.real)>_CM_LARGE_DOUBLE or math.fabs(x.imag)>_CM_LARGE_DOUBLE:\n if x.imag >=.0:\n _real=math.copysign(math.log(math.hypot(x.real /2.,x.imag /2.))+_M_LN2 *2.,x.real)\n else:\n _real=-math.copysign(math.log(math.hypot(x.real /2.,x.imag /2.))+_M_LN2 *2.,-x.real)\n _imag=math.atan2(x.imag,math.fabs(x.real))\n else:\n s1=sqrt(complex(1.0+x.imag,-x.real))\n s2=sqrt(complex(1.0 -x.imag,x.real))\n _real=math.asinh(s1.real *s2.imag -s2.real *s1.imag)\n _imag=math.atan2(x.imag,s1.real *s2.real -s1.imag *s2.imag)\n return complex(_real,_imag)\n \n@_takes_complex\ndef atan(x):\n ''\n\n\n\n\n \n ret=_SPECIAL_VALUE(x,_atan_special_values)\n if ret is not None:\n return ret\n \n if isinf(x):\n return complex(math.copysign(1,x.real)*pi /2,\n math.copysign(0,x.imag))\n s=atanh(complex(-x.imag,x.real))\n return complex(s.imag,-s.real)\n \n@_takes_complex\ndef atanh(x):\n ''\n\n\n\n\n \n \n ret=_SPECIAL_VALUE(x,_atanh_special_values)\n if ret is not None:\n return ret\n \n if isinf(x):\n return complex(math.copysign(0,x.real),\n math.copysign(1,x.imag)*pi /2)\n \n \n if x.real <.0:\n return -(atanh(-x))\n \n ay=math.fabs(x.imag)\n \n if x.real >_CM_SQRT_LARGE_DOUBLE or ay >_CM_SQRT_LARGE_DOUBLE:\n \n \n \n \n \n h=math.hypot(x.real /2.,x.imag /2.)\n _real=x.real /4. /h /h\n \n \n \n \n \n \n _imag=-math.copysign(math.pi /2.,-x.imag)\n \n elif x.real ==1.0 and ay <_CM_SQRT_DBL_MIN:\n \n \n if(ay ==.0):\n raise ValueError(\"math domain error\")\n else:\n _real=-math.log(math.sqrt(ay)/math.sqrt(math.hypot(ay,2.)))\n _imag=math.copysign(math.atan2(2.0,-ay)/2,x.imag)\n \n else:\n \n _real=math.log1p(4. *x.real /((1 -x.real)*(1 -x.real)+ay *ay))/4.\n _imag=-math.atan2(-2. *x.imag,(1 -x.real)*(1+x.real)-ay *ay)/2.\n errno=0\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef cos(x):\n ''\n return cosh(complex(-x.imag,x.real))\n \n@_takes_complex\ndef cosh(x):\n ''\n \n ret=_SPECIAL_VALUE(x,_cosh_special_values)\n if ret is not None:\n if isinstance(ret,Exception):\n raise ret\n return ret\n \n if not math.isinf(x.real)and math.fabs(x.real)>_CM_LOG_LARGE_DOUBLE:\n \n \n x_minus_one=x.real -math.copysign(1.0,x.real)\n _real=cos(x.imag)*math.cosh(x_minus_one)*math.e\n _imag=sin(x.imag)*math.sinh(x_minus_one)*math.e\n elif math.isinf(x.real)and x.imag ==0:\n if x.real >0:\n return x\n else:\n return complex(inf,-x.imag)\n elif math.isinf(x.imag):\n raise ValueError(\"math domain error\")\n else:\n _real=math.cos(x.imag)*math.cosh(x.real)\n _imag=math.sin(x.imag)*math.sinh(x.real)\n \n ret=complex(_real,_imag)\n return ret\n \n@_takes_complex\ndef exp(x):\n ''\n if math.isinf(x.real)or math.isinf(x.imag):\n \n if math.isinf(x.imag)and(-inf 0):\n raise ValueError(\"math domain error\")\n \n if math.isinf(x.real)and -inf 0:\n _real=math.copysign(inf,math.cos(x.imag))\n _imag=math.copysign(inf,math.sin(x.imag))\n else:\n _real=math.copysign(.0,math.cos(x.imag))\n _imag=math.copysign(.0,math.sin(x.imag))\n return complex(_real,_imag)\n \n return _SPECIAL_VALUE(x,_exp_special_values)\n \n if math.isnan(x.real)and x.imag ==0:\n return x\n \n if x.real >_CM_LOG_LARGE_DOUBLE:\n l=math.exp(x.real -1.);\n _real=l *math.cos(x.imag)*math.e\n _imag=l *math.sin(x.imag)*math.e\n else:\n l=math.exp(x.real);\n _real=l *math.cos(x.imag)\n _imag=l *math.sin(x.imag)\n \n if math.isinf(_real)or math.isinf(_imag):\n raise OverflowError()\n \n return complex(_real,_imag)\n \ndef isclose(x,y,*,rel_tol=1e-09,abs_tol=0.0):\n try:\n complex(x)\n except ValueError:\n raise TypeError(f\"must be a number, not {x.__class__.__name__}\")\n try:\n complex(y)\n except ValueError:\n raise TypeError(f\"must be a number, not {y.__class__.__name__}\")\n rel_tol=float(rel_tol)\n abs_tol=float(abs_tol)\n if rel_tol <0.0 or abs_tol <0.0:\n raise ValueError('tolerances must be non-negative')\n if x is inf or x is _NINF or y is inf or y is _NINF:\n return y is x\n if x is nan or y is nan:\n return False\n return abs(x -y)<=max(rel_tol *float(max(abs(x),abs(y))),abs_tol)\n \n@_takes_complex\ndef isinf(x):\n ''\n return math.isinf(x.real)or math.isinf(x.imag)\n \n@_takes_complex\ndef isnan(x):\n ''\n return math.isnan(x.real)or math.isnan(x.imag)\n \n \n@_takes_complex\ndef _to_complex(x):\n return x\n \ndef log(x,base=None):\n ''\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n x=_to_complex(x)\n \n \n \n \n \n \n denom=1 if base is None else log(base)\n ''\n\n\n\n \n \n ret=_SPECIAL_VALUE(x,_log_special_values)\n if ret is not None:\n return ret\n \n if math.isnan(x.real):\n return complex(inf if math.isinf(x.imag)else nan,nan)\n elif math.isnan(x.imag):\n return complex(inf if math.isinf(x.real)else nan,nan)\n \n ax=math.fabs(x.real)\n ay=math.fabs(x.imag)\n \n if ax >_CM_LARGE_DOUBLE or ay >_CM_LARGE_DOUBLE:\n _real=math.log(math.hypot(ax /2.0,ay /2.0))+_M_LN2\n elif ax .0 or ay >.0:\n \n _real=math.log(math.hypot(math.ldexp(ax,sys.float_info.mant_dig),math.ldexp(ay,sys.float_info.mant_dig)))-sys.float_info.mant_dig *_M_LN2\n else:\n \n raise ValueError(\"math domain error\")\n _real=-inf\n _imag=math.atan2(x.imag,x.real)\n else:\n h=math.hypot(ax,ay)\n _real=math.log(h)/denom\n if not ay:\n if type(_real)==complex:\n return _real\n if x.real <0:\n return complex(_real,math.copysign(math.pi,x.imag))\n return complex(_real,x.imag)\n _imag=math.atan2(x.imag,x.real)\n return complex(_real,_imag)\n \n@_takes_complex\ndef log10(x):\n ''\n\n\n\n \n ret=log(x)\n _real=ret.real /_M_LN10\n _imag=ret.imag /_M_LN10\n return complex(_real,_imag)\n \n@_takes_complex\ndef sin(x):\n ''\n \n s=complex(-x.imag,x.real)\n s=sinh(s)\n return complex(s.imag,-s.real)\n \n@_takes_complex\ndef sinh(x):\n ''\n \n ret=_SPECIAL_VALUE(x,_sinh_special_values)\n if ret is not None:\n if isinstance(ret,Exception):\n raise ret\n return ret\n \n if math.isinf(x.real)or math.isinf(x.imag):\n \n \n if math.isinf(x.imag)and not math.isnan(x.real):\n raise ValueError(\"math domain error\")\n \n if math.isinf(x.real)and -inf 0:\n _real=math.copysign(inf,math.cos(x.imag))\n _imag=math.copysign(inf,math.sin(x.imag))\n else:\n _real=-math.copysign(inf,math.cos(x.imag))\n _imag=math.copysign(inf,math.sin(x.imag))\n return complex(_real,_imag)\n \n return _SPECIAL_VALUE(x,_sinh_special_values)\n \n if math.fabs(x.real)>_CM_LOG_LARGE_DOUBLE:\n x_minus_one=x.real -math.copysign(1.0,x.real)\n z=complex(x_minus_one,x.imag)\n _real=math.cos(z.imag)*math.sinh(z.real)*math.e\n _imag=math.sin(z.imag)*math.cosh(z.real)*math.e\n else:\n _real=math.cos(x.imag)*math.sinh(x.real)\n _imag=math.sin(x.imag)*math.cosh(x.real)\n \n if math.isinf(_real)or math.isinf(_imag):\n raise OverflowError()\n \n return complex(_real,_imag)\n \n@_takes_complex\ndef tan(x):\n ''\n if math.isnan(x.real):\n if math.isinf(x.imag):\n return complex(0,math.copysign(1,x.imag))\n return complex(nan,nan)\n elif math.isnan(x.imag):\n if not x.real:\n return complex(math.copysign(0,x.real),nan)\n return complex(nan,nan)\n s=tanh(complex(-x.imag,x.real))\n return complex(s.imag,-s.real)\n \n@_takes_complex\ndef tanh(x):\n ''\n ''\n\n\n \n \n \n \n \n \n \n \n \n \n if math.isnan(x.real):\n if x.imag ==0:\n return complex(nan,math.copysign(0,x.imag))\n return complex(nan,nan)\n elif math.isnan(x.imag):\n if math.isinf(x.real):\n return complex(math.copysign(1,x.real),0)\n return complex(nan,nan)\n \n if isinf(x):\n if math.isinf(x.imag)and -inf 0:\n _real=1.0\n _imag=math.copysign(.0,2.0 *math.sin(x.imag)*math.cos(x.imag))\n else:\n _real=-1.0\n _imag=math.copysign(.0,2. *math.sin(x.imag)*math.cos(x.imag))\n return complex(_real,_imag)\n return _SPECIAL_VALUE(x,_tanh_special_values)\n \n \n if math.fabs(x.real)>_CM_LOG_LARGE_DOUBLE:\n _real=math.copysign(1.,x.real)\n _imag=4. *math.sin(x.imag)*math.cos(x.imag)*math.exp(-2. *math.fabs(x.real))\n else:\n tx=math.tanh(x.real)\n ty=math.tan(x.imag)\n cx=1.0 /math.cosh(x.real)\n txty=tx *ty\n denom=1.+txty *txty\n _real=tx *(1.+ty *ty)/denom\n _imag=((ty /denom)*cx)*cx\n return complex(_real,_imag)\n \n \nFunctionType=type(_takes_complex)\nlocs=locals()\nkeys=list(locs.keys())\nfor f in keys:\n if type(locs[f])is FunctionType and not f.startswith(\"_\"):\n locals()[f]=type(abs)(locals()[f])\n \npi=math.pi\ne=math.e\ntau=math.tau\n\n_CM_LARGE_DOUBLE=sys.float_info.max /4\n_CM_SQRT_LARGE_DOUBLE=math.sqrt(_CM_LARGE_DOUBLE)\n_CM_LOG_LARGE_DOUBLE=math.log(_CM_LARGE_DOUBLE)\n_CM_SQRT_DBL_MIN=math.sqrt(sys.float_info.min)\n_M_LN2=0.6931471805599453094\n_M_LN10=2.302585092994045684\n\nif sys.float_info.radix ==2:\n _CM_SCALE_UP=int((2 *(sys.float_info.mant_dig /2)+1))\nelif sys.float_info.radix ==16:\n _CM_SCALE_UP=int((4 *sys.float_info.mant_dig+1))\nelse:\n raise(\"cmath implementation expects the float base to be either 2 or 16, got \"+str(sys.float_info.radix)+\" instead.\")\n_CM_SCALE_DOWN=int((-(_CM_SCALE_UP+1)/2))\n\ninf=float('inf')\ninfj=complex(0.0,inf)\n_NINF=float('-inf')\nnan=float('nan')\nnanj=complex(0.0,float('nan'))\n\n_P14=0.25 *pi\n_P12=0.5 *pi\n_P34=0.75 *pi\n_U=-9.5426319407711027e33\n\n\n_ST_NINF=0\n_ST_NEG=1\n_ST_NZERO=2\n_ST_PZERO=3\n_ST_POS=4\n_ST_PINF=5\n_ST_NAN=6\n\n\ndef _SPECIAL_VALUE(z,table):\n if not math.isfinite(z.real)or not math.isfinite(z.imag):\n return table[_special_type(z.real)][_special_type(z.imag)]\n else:\n return None\n \ndef _special_type(x):\n if -inf ):\"\n misc_header=\"Miscellaneous help topics:\"\n undoc_header=\"Undocumented commands:\"\n nohelp=\"*** No help on %s\"\n use_rawinput=1\n \n def __init__(self,completekey='tab',stdin=None,stdout=None):\n ''\n\n\n\n\n\n\n\n\n \n if stdin is not None:\n self.stdin=stdin\n else:\n self.stdin=sys.stdin\n if stdout is not None:\n self.stdout=stdout\n else:\n self.stdout=sys.stdout\n self.cmdqueue=[]\n self.completekey=completekey\n \n def cmdloop(self,intro=None):\n ''\n\n\n\n \n \n self.preloop()\n if self.use_rawinput and self.completekey:\n try:\n import readline\n self.old_completer=readline.get_completer()\n readline.set_completer(self.complete)\n if readline.backend ==\"editline\":\n if self.completekey =='tab':\n \n command_string=\"bind ^I rl_complete\"\n else:\n command_string=f\"bind {self.completekey} rl_complete\"\n else:\n command_string=f\"{self.completekey}: complete\"\n readline.parse_and_bind(command_string)\n except ImportError:\n pass\n try:\n if intro is not None:\n self.intro=intro\n if self.intro:\n self.stdout.write(str(self.intro)+\"\\n\")\n stop=None\n while not stop:\n if self.cmdqueue:\n line=self.cmdqueue.pop(0)\n else:\n if self.use_rawinput:\n try:\n line=input(self.prompt)\n except EOFError:\n line='EOF'\n else:\n self.stdout.write(self.prompt)\n self.stdout.flush()\n line=self.stdin.readline()\n if not len(line):\n line='EOF'\n else:\n line=line.rstrip('\\r\\n')\n line=self.precmd(line)\n stop=self.onecmd(line)\n stop=self.postcmd(stop,line)\n self.postloop()\n finally:\n if self.use_rawinput and self.completekey:\n try:\n import readline\n readline.set_completer(self.old_completer)\n except ImportError:\n pass\n \n \n def precmd(self,line):\n ''\n\n\n \n return line\n \n def postcmd(self,stop,line):\n ''\n return stop\n \n def preloop(self):\n ''\n pass\n \n def postloop(self):\n ''\n\n\n \n pass\n \n def parseline(self,line):\n ''\n\n\n \n line=line.strip()\n if not line:\n return None,None,line\n elif line[0]=='?':\n line='help '+line[1:]\n elif line[0]=='!':\n if hasattr(self,'do_shell'):\n line='shell '+line[1:]\n else:\n return None,None,line\n i,n=0,len(line)\n while i 0:\n cmd,args,foo=self.parseline(line)\n if cmd =='':\n compfunc=self.completedefault\n else:\n try:\n compfunc=getattr(self,'complete_'+cmd)\n except AttributeError:\n compfunc=self.completedefault\n else:\n compfunc=self.completenames\n self.completion_matches=compfunc(text,line,begidx,endidx)\n try:\n return self.completion_matches[state]\n except IndexError:\n return None\n \n def get_names(self):\n \n \n return dir(self.__class__)\n \n def complete_help(self,*args):\n commands=set(self.completenames(*args))\n topics=set(a[5:]for a in self.get_names()\n if a.startswith('help_'+args[0]))\n return list(commands |topics)\n \n def do_help(self,arg):\n ''\n if arg:\n \n try:\n func=getattr(self,'help_'+arg)\n except AttributeError:\n try:\n doc=getattr(self,'do_'+arg).__doc__\n doc=inspect.cleandoc(doc)\n if doc:\n self.stdout.write(\"%s\\n\"%str(doc))\n return\n except AttributeError:\n pass\n self.stdout.write(\"%s\\n\"%str(self.nohelp %(arg,)))\n return\n func()\n else:\n names=self.get_names()\n cmds_doc=[]\n cmds_undoc=[]\n topics=set()\n for name in names:\n if name[:5]=='help_':\n topics.add(name[5:])\n names.sort()\n \n prevname=''\n for name in names:\n if name[:3]=='do_':\n if name ==prevname:\n continue\n prevname=name\n cmd=name[3:]\n if cmd in topics:\n cmds_doc.append(cmd)\n topics.remove(cmd)\n elif getattr(self,name).__doc__:\n cmds_doc.append(cmd)\n else:\n cmds_undoc.append(cmd)\n self.stdout.write(\"%s\\n\"%str(self.doc_leader))\n self.print_topics(self.doc_header,cmds_doc,15,80)\n self.print_topics(self.misc_header,sorted(topics),15,80)\n self.print_topics(self.undoc_header,cmds_undoc,15,80)\n \n def print_topics(self,header,cmds,cmdlen,maxcol):\n if cmds:\n self.stdout.write(\"%s\\n\"%str(header))\n if self.ruler:\n self.stdout.write(\"%s\\n\"%str(self.ruler *len(header)))\n self.columnize(cmds,maxcol -1)\n self.stdout.write(\"\\n\")\n \n def columnize(self,list,displaywidth=80):\n ''\n\n\n\n \n if not list:\n self.stdout.write(\"\\n\")\n return\n \n nonstrings=[i for i in range(len(list))\n if not isinstance(list[i],str)]\n if nonstrings:\n raise TypeError(\"list[i] not a string for i in %s\"\n %\", \".join(map(str,nonstrings)))\n size=len(list)\n if size ==1:\n self.stdout.write('%s\\n'%str(list[0]))\n return\n \n for nrows in range(1,len(list)):\n ncols=(size+nrows -1)//nrows\n colwidths=[]\n totwidth=-2\n for col in range(ncols):\n colwidth=0\n for row in range(nrows):\n i=row+nrows *col\n if i >=size:\n break\n x=list[i]\n colwidth=max(colwidth,len(x))\n colwidths.append(colwidth)\n totwidth +=colwidth+2\n if totwidth >displaywidth:\n break\n if totwidth <=displaywidth:\n break\n else:\n nrows=len(list)\n ncols=1\n colwidths=[0]\n for row in range(nrows):\n texts=[]\n for col in range(ncols):\n i=row+nrows *col\n if i >=size:\n x=\"\"\n else:\n x=list[i]\n texts.append(x)\n while texts and not texts[-1]:\n del texts[-1]\n for col in range(len(texts)):\n texts[col]=texts[col].ljust(colwidths[col])\n self.stdout.write(\"%s\\n\"%str(\" \".join(texts)))\n", ["inspect", "readline", "string", "sys"]], "code": [".py", "''\n\n\n\n\n\n\nimport builtins\nimport sys\nimport traceback\nfrom codeop import CommandCompiler,compile_command\n\n__all__=[\"InteractiveInterpreter\",\"InteractiveConsole\",\"interact\",\n\"compile_command\"]\n\nclass InteractiveInterpreter:\n ''\n\n\n\n\n\n \n \n def __init__(self,locals=None):\n ''\n\n\n\n\n\n\n \n if locals is None:\n locals={\"__name__\":\"__console__\",\"__doc__\":None}\n self.locals=locals\n self.compile=CommandCompiler()\n \n def runsource(self,source,filename=\"\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n code=self.compile(source,filename,symbol)\n except(OverflowError,SyntaxError,ValueError):\n \n self.showsyntaxerror(filename)\n return False\n \n if code is None:\n \n return True\n \n \n self.runcode(code)\n return False\n \n def runcode(self,code):\n ''\n\n\n\n\n\n\n\n\n\n \n try:\n exec(code,self.locals)\n except SystemExit:\n raise\n except:\n self.showtraceback()\n \n def showsyntaxerror(self,filename=None,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.pop('colorize',False)\n type,value,tb=sys.exc_info()\n sys.last_exc=value\n sys.last_type=type\n sys.last_value=value\n sys.last_traceback=tb\n if filename and type is SyntaxError:\n \n try:\n msg,(dummy_filename,lineno,offset,line)=value.args\n except ValueError:\n \n pass\n else:\n \n value=SyntaxError(msg,(filename,lineno,offset,line))\n sys.last_exc=sys.last_value=value\n if sys.excepthook is sys.__excepthook__:\n lines=traceback.format_exception_only(type,value,colorize=colorize)\n self.write(''.join(lines))\n else:\n \n \n sys.excepthook(type,value,tb)\n \n def showtraceback(self,**kwargs):\n ''\n\n\n\n\n\n \n colorize=kwargs.pop('colorize',False)\n sys.last_type,sys.last_value,last_tb=ei=sys.exc_info()\n sys.last_traceback=last_tb\n sys.last_exc=ei[1]\n try:\n lines=traceback.format_exception(ei[0],ei[1],last_tb.tb_next,colorize=colorize)\n if sys.excepthook is sys.__excepthook__:\n self.write(''.join(lines))\n else:\n \n \n sys.excepthook(ei[0],ei[1],last_tb)\n finally:\n last_tb=ei=None\n \n def write(self,data):\n ''\n\n\n\n\n \n sys.stderr.write(data)\n \n \nclass InteractiveConsole(InteractiveInterpreter):\n ''\n\n\n\n\n \n \n def __init__(self,locals=None,filename=\"\",*,local_exit=False):\n ''\n\n\n\n\n\n\n\n \n InteractiveInterpreter.__init__(self,locals)\n self.filename=filename\n self.local_exit=local_exit\n self.resetbuffer()\n \n def resetbuffer(self):\n ''\n self.buffer=[]\n \n def interact(self,banner=None,exitmsg=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n sys.ps1\n except AttributeError:\n sys.ps1=\">>> \"\n try:\n sys.ps2\n except AttributeError:\n sys.ps2=\"... \"\n cprt='Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.'\n if banner is None:\n self.write(\"Python %s on %s\\n%s\\n(%s)\\n\"%\n (sys.version,sys.platform,cprt,\n self.__class__.__name__))\n elif banner:\n self.write(\"%s\\n\"%str(banner))\n more=0\n \n \n \n \n \n \n \n \n \n \n _exit=None\n _quit=None\n \n if self.local_exit:\n if hasattr(builtins,\"exit\"):\n _exit=builtins.exit\n builtins.exit=Quitter(\"exit\")\n \n if hasattr(builtins,\"quit\"):\n _quit=builtins.quit\n builtins.quit=Quitter(\"quit\")\n \n try:\n while True:\n try:\n if more:\n prompt=sys.ps2\n else:\n prompt=sys.ps1\n try:\n line=self.raw_input(prompt)\n except EOFError:\n self.write(\"\\n\")\n break\n else:\n more=self.push(line)\n except KeyboardInterrupt:\n self.write(\"\\nKeyboardInterrupt\\n\")\n self.resetbuffer()\n more=0\n except SystemExit as e:\n if self.local_exit:\n self.write(\"\\n\")\n break\n else:\n raise e\n finally:\n \n if _exit is not None:\n builtins.exit=_exit\n \n if _quit is not None:\n builtins.quit=_quit\n \n if exitmsg is None:\n self.write('now exiting %s...\\n'%self.__class__.__name__)\n elif exitmsg !='':\n self.write('%s\\n'%exitmsg)\n \n def push(self,line,filename=None,_symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self.buffer.append(line)\n source=\"\\n\".join(self.buffer)\n if filename is None:\n filename=self.filename\n more=self.runsource(source,filename,symbol=_symbol)\n if not more:\n self.resetbuffer()\n return more\n \n def raw_input(self,prompt=\"\"):\n ''\n\n\n\n\n\n\n\n\n \n return input(prompt)\n \n \nclass Quitter:\n def __init__(self,name):\n self.name=name\n if sys.platform ==\"win32\":\n self.eof='Ctrl-Z plus Return'\n else:\n self.eof='Ctrl-D (i.e. EOF)'\n \n def __repr__(self):\n return f'Use {self.name} or {self.eof} to exit'\n \n def __call__(self,code=None):\n raise SystemExit(code)\n \n \ndef interact(banner=None,readfunc=None,local=None,exitmsg=None,local_exit=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n console=InteractiveConsole(local,local_exit=local_exit)\n if readfunc is not None:\n console.raw_input=readfunc\n else:\n try:\n import readline\n except ImportError:\n pass\n console.interact(banner,exitmsg)\n \n \nif __name__ ==\"__main__\":\n import argparse\n \n parser=argparse.ArgumentParser()\n parser.add_argument('-q',action='store_true',\n help=\"don't print version and copyright messages\")\n args=parser.parse_args()\n if args.q or sys.flags.quiet:\n banner=''\n else:\n banner=None\n interact(banner)\n", ["argparse", "builtins", "codeop", "readline", "sys", "traceback"]], "codecs": [".py", "''\n\n\n\n\n\n\n\n\nimport builtins\nimport sys\n\n\n\ntry:\n from _codecs import *\nexcept ImportError as why:\n raise SystemError('Failed to load the builtin codecs: %s'%why)\n \n__all__=[\"register\",\"lookup\",\"open\",\"EncodedFile\",\"BOM\",\"BOM_BE\",\n\"BOM_LE\",\"BOM32_BE\",\"BOM32_LE\",\"BOM64_BE\",\"BOM64_LE\",\n\"BOM_UTF8\",\"BOM_UTF16\",\"BOM_UTF16_LE\",\"BOM_UTF16_BE\",\n\"BOM_UTF32\",\"BOM_UTF32_LE\",\"BOM_UTF32_BE\",\n\"CodecInfo\",\"Codec\",\"IncrementalEncoder\",\"IncrementalDecoder\",\n\"StreamReader\",\"StreamWriter\",\n\"StreamReaderWriter\",\"StreamRecoder\",\n\"getencoder\",\"getdecoder\",\"getincrementalencoder\",\n\"getincrementaldecoder\",\"getreader\",\"getwriter\",\n\"encode\",\"decode\",\"iterencode\",\"iterdecode\",\n\"strict_errors\",\"ignore_errors\",\"replace_errors\",\n\"xmlcharrefreplace_errors\",\n\"backslashreplace_errors\",\"namereplace_errors\",\n\"register_error\",\"lookup_error\"]\n\n\n\n\n\n\n\n\n\n\nBOM_UTF8=b'\\xef\\xbb\\xbf'\n\n\nBOM_LE=BOM_UTF16_LE=b'\\xff\\xfe'\n\n\nBOM_BE=BOM_UTF16_BE=b'\\xfe\\xff'\n\n\nBOM_UTF32_LE=b'\\xff\\xfe\\x00\\x00'\n\n\nBOM_UTF32_BE=b'\\x00\\x00\\xfe\\xff'\n\nif sys.byteorder =='little':\n\n\n BOM=BOM_UTF16=BOM_UTF16_LE\n \n \n BOM_UTF32=BOM_UTF32_LE\n \nelse:\n\n\n BOM=BOM_UTF16=BOM_UTF16_BE\n \n \n BOM_UTF32=BOM_UTF32_BE\n \n \nBOM32_LE=BOM_UTF16_LE\nBOM32_BE=BOM_UTF16_BE\nBOM64_LE=BOM_UTF32_LE\nBOM64_BE=BOM_UTF32_BE\n\n\n\n\nclass CodecInfo(tuple):\n ''\n \n \n \n \n \n \n \n _is_text_encoding=True\n \n def __new__(cls,encode,decode,streamreader=None,streamwriter=None,\n incrementalencoder=None,incrementaldecoder=None,name=None,\n *,_is_text_encoding=None):\n self=tuple.__new__(cls,(encode,decode,streamreader,streamwriter))\n self.name=name\n self.encode=encode\n self.decode=decode\n self.incrementalencoder=incrementalencoder\n self.incrementaldecoder=incrementaldecoder\n self.streamwriter=streamwriter\n self.streamreader=streamreader\n if _is_text_encoding is not None:\n self._is_text_encoding=_is_text_encoding\n return self\n \n def __repr__(self):\n return \"<%s.%s object for encoding %s at %#x>\"%\\\n (self.__class__.__module__,self.__class__.__qualname__,\n self.name,id(self))\n \n def __getnewargs__(self):\n return tuple(self)\n \nclass Codec:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def encode(self,input,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def decode(self,input,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \nclass IncrementalEncoder(object):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n ''\n\n\n\n\n\n \n self.errors=errors\n self.buffer=\"\"\n \n def encode(self,input,final=False):\n ''\n\n \n raise NotImplementedError\n \n def reset(self):\n ''\n\n \n \n def getstate(self):\n ''\n\n \n return 0\n \n def setstate(self,state):\n ''\n\n\n \n \nclass BufferedIncrementalEncoder(IncrementalEncoder):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n IncrementalEncoder.__init__(self,errors)\n \n self.buffer=\"\"\n \n def _buffer_encode(self,input,errors,final):\n \n \n raise NotImplementedError\n \n def encode(self,input,final=False):\n \n data=self.buffer+input\n (result,consumed)=self._buffer_encode(data,self.errors,final)\n \n self.buffer=data[consumed:]\n return result\n \n def reset(self):\n IncrementalEncoder.reset(self)\n self.buffer=\"\"\n \n def getstate(self):\n return self.buffer or 0\n \n def setstate(self,state):\n self.buffer=state or \"\"\n \nclass IncrementalDecoder(object):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n ''\n\n\n\n\n\n \n self.errors=errors\n \n def decode(self,input,final=False):\n ''\n\n \n raise NotImplementedError\n \n def reset(self):\n ''\n\n \n \n def getstate(self):\n ''\n\n\n\n\n\n\n\n\n\n \n return(b\"\",0)\n \n def setstate(self,state):\n ''\n\n\n\n\n \n \nclass BufferedIncrementalDecoder(IncrementalDecoder):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n IncrementalDecoder.__init__(self,errors)\n \n self.buffer=b\"\"\n \n def _buffer_decode(self,input,errors,final):\n \n \n raise NotImplementedError\n \n def decode(self,input,final=False):\n \n data=self.buffer+input\n (result,consumed)=self._buffer_decode(data,self.errors,final)\n \n self.buffer=data[consumed:]\n return result\n \n def reset(self):\n IncrementalDecoder.reset(self)\n self.buffer=b\"\"\n \n def getstate(self):\n \n return(self.buffer,0)\n \n def setstate(self,state):\n \n self.buffer=state[0]\n \n \n \n \n \n \n \n \nclass StreamWriter(Codec):\n\n def __init__(self,stream,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.errors=errors\n \n def write(self,object):\n \n ''\n \n data,consumed=self.encode(object,self.errors)\n self.stream.write(data)\n \n def writelines(self,list):\n \n ''\n\n \n self.write(''.join(list))\n \n def reset(self):\n \n ''\n\n\n\n\n\n\n \n pass\n \n def seek(self,offset,whence=0):\n self.stream.seek(offset,whence)\n if whence ==0 and offset ==0:\n self.reset()\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n def __reduce_ex__(self,proto):\n raise TypeError(\"can't serialize %s\"%self.__class__.__name__)\n \n \n \nclass StreamReader(Codec):\n\n charbuffertype=str\n \n def __init__(self,stream,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.errors=errors\n self.bytebuffer=b\"\"\n self._empty_charbuffer=self.charbuffertype()\n self.charbuffer=self._empty_charbuffer\n self.linebuffer=None\n \n def decode(self,input,errors='strict'):\n raise NotImplementedError\n \n def read(self,size=-1,chars=-1,firstline=False):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if self.linebuffer:\n self.charbuffer=self._empty_charbuffer.join(self.linebuffer)\n self.linebuffer=None\n \n if chars <0:\n \n \n chars=size\n \n \n while True:\n \n if chars >=0:\n if len(self.charbuffer)>=chars:\n break\n \n if size <0:\n newdata=self.stream.read()\n else:\n newdata=self.stream.read(size)\n \n data=self.bytebuffer+newdata\n if not data:\n break\n try:\n newchars,decodedbytes=self.decode(data,self.errors)\n except UnicodeDecodeError as exc:\n if firstline:\n newchars,decodedbytes=\\\n self.decode(data[:exc.start],self.errors)\n lines=newchars.splitlines(keepends=True)\n if len(lines)<=1:\n raise\n else:\n raise\n \n self.bytebuffer=data[decodedbytes:]\n \n self.charbuffer +=newchars\n \n if not newdata:\n break\n if chars <0:\n \n result=self.charbuffer\n self.charbuffer=self._empty_charbuffer\n else:\n \n result=self.charbuffer[:chars]\n self.charbuffer=self.charbuffer[chars:]\n return result\n \n def readline(self,size=None,keepends=True):\n \n ''\n\n\n\n\n\n \n \n \n if self.linebuffer:\n line=self.linebuffer[0]\n del self.linebuffer[0]\n if len(self.linebuffer)==1:\n \n \n self.charbuffer=self.linebuffer[0]\n self.linebuffer=None\n if not keepends:\n line=line.splitlines(keepends=False)[0]\n return line\n \n readsize=size or 72\n line=self._empty_charbuffer\n \n while True:\n data=self.read(readsize,firstline=True)\n if data:\n \n \n \n if(isinstance(data,str)and data.endswith(\"\\r\"))or\\\n (isinstance(data,bytes)and data.endswith(b\"\\r\")):\n data +=self.read(size=1,chars=1)\n \n line +=data\n lines=line.splitlines(keepends=True)\n if lines:\n if len(lines)>1:\n \n \n line=lines[0]\n del lines[0]\n if len(lines)>1:\n \n lines[-1]+=self.charbuffer\n self.linebuffer=lines\n self.charbuffer=None\n else:\n \n self.charbuffer=lines[0]+self.charbuffer\n if not keepends:\n line=line.splitlines(keepends=False)[0]\n break\n line0withend=lines[0]\n line0withoutend=lines[0].splitlines(keepends=False)[0]\n if line0withend !=line0withoutend:\n \n self.charbuffer=self._empty_charbuffer.join(lines[1:])+\\\n self.charbuffer\n if keepends:\n line=line0withend\n else:\n line=line0withoutend\n break\n \n if not data or size is not None:\n if line and not keepends:\n line=line.splitlines(keepends=False)[0]\n break\n if readsize <8000:\n readsize *=2\n return line\n \n def readlines(self,sizehint=None,keepends=True):\n \n ''\n\n\n\n\n\n\n\n\n \n data=self.read()\n return data.splitlines(keepends)\n \n def reset(self):\n \n ''\n\n\n\n\n\n \n self.bytebuffer=b\"\"\n self.charbuffer=self._empty_charbuffer\n self.linebuffer=None\n \n def seek(self,offset,whence=0):\n ''\n\n\n \n self.stream.seek(offset,whence)\n self.reset()\n \n def __next__(self):\n \n ''\n line=self.readline()\n if line:\n return line\n raise StopIteration\n \n def __iter__(self):\n return self\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n def __reduce_ex__(self,proto):\n raise TypeError(\"can't serialize %s\"%self.__class__.__name__)\n \n \n \nclass StreamReaderWriter:\n\n ''\n\n\n\n\n\n\n \n \n encoding='unknown'\n \n def __init__(self,stream,Reader,Writer,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.reader=Reader(stream,errors)\n self.writer=Writer(stream,errors)\n self.errors=errors\n \n def read(self,size=-1):\n \n return self.reader.read(size)\n \n def readline(self,size=None):\n \n return self.reader.readline(size)\n \n def readlines(self,sizehint=None):\n \n return self.reader.readlines(sizehint)\n \n def __next__(self):\n \n ''\n return next(self.reader)\n \n def __iter__(self):\n return self\n \n def write(self,data):\n \n return self.writer.write(data)\n \n def writelines(self,list):\n \n return self.writer.writelines(list)\n \n def reset(self):\n \n self.reader.reset()\n self.writer.reset()\n \n def seek(self,offset,whence=0):\n self.stream.seek(offset,whence)\n self.reader.reset()\n if whence ==0 and offset ==0:\n self.writer.reset()\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n \n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n def __reduce_ex__(self,proto):\n raise TypeError(\"can't serialize %s\"%self.__class__.__name__)\n \n \n \nclass StreamRecoder:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n data_encoding='unknown'\n file_encoding='unknown'\n \n def __init__(self,stream,encode,decode,Reader,Writer,\n errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.encode=encode\n self.decode=decode\n self.reader=Reader(stream,errors)\n self.writer=Writer(stream,errors)\n self.errors=errors\n \n def read(self,size=-1):\n \n data=self.reader.read(size)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def readline(self,size=None):\n \n if size is None:\n data=self.reader.readline()\n else:\n data=self.reader.readline(size)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def readlines(self,sizehint=None):\n \n data=self.reader.read()\n data,bytesencoded=self.encode(data,self.errors)\n return data.splitlines(keepends=True)\n \n def __next__(self):\n \n ''\n data=next(self.reader)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def __iter__(self):\n return self\n \n def write(self,data):\n \n data,bytesdecoded=self.decode(data,self.errors)\n return self.writer.write(data)\n \n def writelines(self,list):\n \n data=b''.join(list)\n data,bytesdecoded=self.decode(data,self.errors)\n return self.writer.write(data)\n \n def reset(self):\n \n self.reader.reset()\n self.writer.reset()\n \n def seek(self,offset,whence=0):\n \n \n self.reader.seek(offset,whence)\n self.writer.seek(offset,whence)\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n def __reduce_ex__(self,proto):\n raise TypeError(\"can't serialize %s\"%self.__class__.__name__)\n \n \n \ndef open(filename,mode='r',encoding=None,errors='strict',buffering=-1):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if encoding is not None and\\\n 'b'not in mode:\n \n mode=mode+'b'\n file=builtins.open(filename,mode,buffering)\n if encoding is None:\n return file\n \n try:\n info=lookup(encoding)\n srw=StreamReaderWriter(file,info.streamreader,info.streamwriter,errors)\n \n srw.encoding=encoding\n return srw\n except:\n file.close()\n raise\n \ndef EncodedFile(file,data_encoding,file_encoding=None,errors='strict'):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if file_encoding is None:\n file_encoding=data_encoding\n data_info=lookup(data_encoding)\n file_info=lookup(file_encoding)\n sr=StreamRecoder(file,data_info.encode,data_info.decode,\n file_info.streamreader,file_info.streamwriter,errors)\n \n sr.data_encoding=data_encoding\n sr.file_encoding=file_encoding\n return sr\n \n \n \ndef getencoder(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).encode\n \ndef getdecoder(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).decode\n \ndef getincrementalencoder(encoding):\n\n ''\n\n\n\n\n\n \n encoder=lookup(encoding).incrementalencoder\n if encoder is None:\n raise LookupError(encoding)\n return encoder\n \ndef getincrementaldecoder(encoding):\n\n ''\n\n\n\n\n\n \n decoder=lookup(encoding).incrementaldecoder\n if decoder is None:\n raise LookupError(encoding)\n return decoder\n \ndef getreader(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).streamreader\n \ndef getwriter(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).streamwriter\n \ndef iterencode(iterator,encoding,errors='strict',**kwargs):\n ''\n\n\n\n\n\n\n \n encoder=getincrementalencoder(encoding)(errors,**kwargs)\n for input in iterator:\n output=encoder.encode(input)\n if output:\n yield output\n output=encoder.encode(\"\",True)\n if output:\n yield output\n \ndef iterdecode(iterator,encoding,errors='strict',**kwargs):\n ''\n\n\n\n\n\n\n \n decoder=getincrementaldecoder(encoding)(errors,**kwargs)\n for input in iterator:\n output=decoder.decode(input)\n if output:\n yield output\n output=decoder.decode(b\"\",True)\n if output:\n yield output\n \n \n \ndef make_identity_dict(rng):\n\n ''\n\n\n\n\n \n return{i:i for i in rng}\n \ndef make_encoding_map(decoding_map):\n\n ''\n\n\n\n\n\n\n\n\n\n \n m={}\n for k,v in decoding_map.items():\n if not v in m:\n m[v]=k\n else:\n m[v]=None\n return m\n \n \n \ntry:\n strict_errors=lookup_error(\"strict\")\n ignore_errors=lookup_error(\"ignore\")\n replace_errors=lookup_error(\"replace\")\n xmlcharrefreplace_errors=lookup_error(\"xmlcharrefreplace\")\n backslashreplace_errors=lookup_error(\"backslashreplace\")\n namereplace_errors=lookup_error(\"namereplace\")\nexcept LookupError:\n\n strict_errors=None\n ignore_errors=None\n replace_errors=None\n xmlcharrefreplace_errors=None\n backslashreplace_errors=None\n namereplace_errors=None\n \n \n \n_false=0\nif _false:\n import encodings\n", ["_codecs", "builtins", "encodings", "sys"]], "codeop": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport __future__\nimport warnings\n\n_features=[getattr(__future__,fname)\nfor fname in __future__.all_feature_names]\n\n__all__=[\"compile_command\",\"Compile\",\"CommandCompiler\"]\n\n\n\n\nPyCF_DONT_IMPLY_DEDENT=0x200\nPyCF_ALLOW_INCOMPLETE_INPUT=0x4000\n\ndef _maybe_compile(compiler,source,filename,symbol):\n\n for line in source.split(\"\\n\"):\n line=line.strip()\n if line and line[0]!='#':\n break\n else:\n if symbol !=\"eval\":\n source=\"pass\"\n \n \n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\",(SyntaxWarning,DeprecationWarning))\n try:\n compiler(source,filename,symbol)\n except SyntaxError:\n try:\n compiler(source+\"\\n\",filename,symbol)\n return None\n except _IncompleteInputError as e:\n return None\n except SyntaxError as e:\n pass\n \n \n return compiler(source,filename,symbol,incomplete_input=False)\n \ndef _compile(source,filename,symbol,incomplete_input=True):\n flags=0\n if incomplete_input:\n flags |=PyCF_ALLOW_INCOMPLETE_INPUT\n flags |=PyCF_DONT_IMPLY_DEDENT\n return compile(source,filename,symbol,flags)\n \ndef compile_command(source,filename=\"\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _maybe_compile(_compile,source,filename,symbol)\n \nclass Compile:\n ''\n\n\n \n def __init__(self):\n self.flags=PyCF_DONT_IMPLY_DEDENT |PyCF_ALLOW_INCOMPLETE_INPUT\n \n def __call__(self,source,filename,symbol,**kwargs):\n flags=self.flags\n if kwargs.get('incomplete_input',True)is False:\n flags &=~PyCF_DONT_IMPLY_DEDENT\n flags &=~PyCF_ALLOW_INCOMPLETE_INPUT\n codeob=compile(source,filename,symbol,flags,True)\n for feature in _features:\n if codeob.co_flags&feature.compiler_flag:\n self.flags |=feature.compiler_flag\n return codeob\n \nclass CommandCompiler:\n ''\n\n\n\n \n \n def __init__(self,):\n self.compiler=Compile()\n \n def __call__(self,source,filename=\"\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _maybe_compile(self.compiler,source,filename,symbol)\n", ["__future__", "warnings"]], "colorsys": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\"rgb_to_yiq\",\"yiq_to_rgb\",\"rgb_to_hls\",\"hls_to_rgb\",\n\"rgb_to_hsv\",\"hsv_to_rgb\"]\n\n\n\nONE_THIRD=1.0 /3.0\nONE_SIXTH=1.0 /6.0\nTWO_THIRD=2.0 /3.0\n\n\n\n\n\n\n\n\ndef rgb_to_yiq(r,g,b):\n y=0.30 *r+0.59 *g+0.11 *b\n i=0.74 *(r -y)-0.27 *(b -y)\n q=0.48 *(r -y)+0.41 *(b -y)\n return(y,i,q)\n \ndef yiq_to_rgb(y,i,q):\n\n\n\n\n r=y+0.9468822170900693 *i+0.6235565819861433 *q\n g=y -0.27478764629897834 *i -0.6356910791873801 *q\n b=y -1.1085450346420322 *i+1.7090069284064666 *q\n \n if r <0.0:\n r=0.0\n if g <0.0:\n g=0.0\n if b <0.0:\n b=0.0\n if r >1.0:\n r=1.0\n if g >1.0:\n g=1.0\n if b >1.0:\n b=1.0\n return(r,g,b)\n \n \n \n \n \n \n \ndef rgb_to_hls(r,g,b):\n maxc=max(r,g,b)\n minc=min(r,g,b)\n sumc=(maxc+minc)\n rangec=(maxc -minc)\n l=sumc /2.0\n if minc ==maxc:\n return 0.0,l,0.0\n if l <=0.5:\n s=rangec /sumc\n else:\n s=rangec /(2.0 -maxc -minc)\n rc=(maxc -r)/rangec\n gc=(maxc -g)/rangec\n bc=(maxc -b)/rangec\n if r ==maxc:\n h=bc -gc\n elif g ==maxc:\n h=2.0+rc -bc\n else:\n h=4.0+gc -rc\n h=(h /6.0)%1.0\n return h,l,s\n \ndef hls_to_rgb(h,l,s):\n if s ==0.0:\n return l,l,l\n if l <=0.5:\n m2=l *(1.0+s)\n else:\n m2=l+s -(l *s)\n m1=2.0 *l -m2\n return(_v(m1,m2,h+ONE_THIRD),_v(m1,m2,h),_v(m1,m2,h -ONE_THIRD))\n \ndef _v(m1,m2,hue):\n hue=hue %1.0\n if hue \"\n \n \nUNNAMED_SECTION=_UnnamedSection()\n\n\n\n\n\n_UNSET=object()\n\n\nclass Interpolation:\n ''\n \n def before_get(self,parser,section,option,value,defaults):\n return value\n \n def before_set(self,parser,section,option,value):\n return value\n \n def before_read(self,parser,section,option,value):\n return value\n \n def before_write(self,parser,section,option,value):\n return value\n \n \nclass BasicInterpolation(Interpolation):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n _KEYCRE=re.compile(r\"%\\(([^)]+)\\)s\")\n \n def before_get(self,parser,section,option,value,defaults):\n L=[]\n self._interpolate_some(parser,option,L,value,section,defaults,1)\n return ''.join(L)\n \n def before_set(self,parser,section,option,value):\n tmp_value=value.replace('%%','')\n tmp_value=self._KEYCRE.sub('',tmp_value)\n if '%'in tmp_value:\n raise ValueError(\"invalid interpolation syntax in %r at \"\n \"position %d\"%(value,tmp_value.find('%')))\n return value\n \n def _interpolate_some(self,parser,option,accum,rest,section,map,\n depth):\n rawval=parser.get(section,option,raw=True,fallback=rest)\n if depth >MAX_INTERPOLATION_DEPTH:\n raise InterpolationDepthError(option,section,rawval)\n while rest:\n p=rest.find(\"%\")\n if p <0:\n accum.append(rest)\n return\n if p >0:\n accum.append(rest[:p])\n rest=rest[p:]\n \n c=rest[1:2]\n if c ==\"%\":\n accum.append(\"%\")\n rest=rest[2:]\n elif c ==\"(\":\n m=self._KEYCRE.match(rest)\n if m is None:\n raise InterpolationSyntaxError(option,section,\n \"bad interpolation variable reference %r\"%rest)\n var=parser.optionxform(m.group(1))\n rest=rest[m.end():]\n try:\n v=map[var]\n except KeyError:\n raise InterpolationMissingOptionError(\n option,section,rawval,var)from None\n if \"%\"in v:\n self._interpolate_some(parser,option,accum,v,\n section,map,depth+1)\n else:\n accum.append(v)\n else:\n raise InterpolationSyntaxError(\n option,section,\n \"'%%' must be followed by '%%' or '(', \"\n \"found: %r\"%(rest,))\n \n \nclass ExtendedInterpolation(Interpolation):\n ''\n \n \n _KEYCRE=re.compile(r\"\\$\\{([^}]+)\\}\")\n \n def before_get(self,parser,section,option,value,defaults):\n L=[]\n self._interpolate_some(parser,option,L,value,section,defaults,1)\n return ''.join(L)\n \n def before_set(self,parser,section,option,value):\n tmp_value=value.replace('$$','')\n tmp_value=self._KEYCRE.sub('',tmp_value)\n if '$'in tmp_value:\n raise ValueError(\"invalid interpolation syntax in %r at \"\n \"position %d\"%(value,tmp_value.find('$')))\n return value\n \n def _interpolate_some(self,parser,option,accum,rest,section,map,\n depth):\n rawval=parser.get(section,option,raw=True,fallback=rest)\n if depth >MAX_INTERPOLATION_DEPTH:\n raise InterpolationDepthError(option,section,rawval)\n while rest:\n p=rest.find(\"$\")\n if p <0:\n accum.append(rest)\n return\n if p >0:\n accum.append(rest[:p])\n rest=rest[p:]\n \n c=rest[1:2]\n if c ==\"$\":\n accum.append(\"$\")\n rest=rest[2:]\n elif c ==\"{\":\n m=self._KEYCRE.match(rest)\n if m is None:\n raise InterpolationSyntaxError(option,section,\n \"bad interpolation variable reference %r\"%rest)\n path=m.group(1).split(':')\n rest=rest[m.end():]\n sect=section\n opt=option\n try:\n if len(path)==1:\n opt=parser.optionxform(path[0])\n v=map[opt]\n elif len(path)==2:\n sect=path[0]\n opt=parser.optionxform(path[1])\n v=parser.get(sect,opt,raw=True)\n else:\n raise InterpolationSyntaxError(\n option,section,\n \"More than one ':' found: %r\"%(rest,))\n except(KeyError,NoSectionError,NoOptionError):\n raise InterpolationMissingOptionError(\n option,section,rawval,\":\".join(path))from None\n if \"$\"in v:\n self._interpolate_some(parser,opt,accum,v,sect,\n dict(parser.items(sect,raw=True)),\n depth+1)\n else:\n accum.append(v)\n else:\n raise InterpolationSyntaxError(\n option,section,\n \"'$' must be followed by '$' or '{', \"\n \"found: %r\"%(rest,))\n \n \nclass _ReadState:\n elements_added:set[str]\n cursect:dict[str,str]|None=None\n sectname:str |None=None\n optname:str |None=None\n lineno:int=0\n indent_level:int=0\n errors:list[ParsingError]\n \n def __init__(self):\n self.elements_added=set()\n self.errors=list()\n \n \nclass _Line(str):\n\n def __new__(cls,val,*args,**kwargs):\n return super().__new__(cls,val)\n \n def __init__(self,val,prefixes):\n self.prefixes=prefixes\n \n @functools.cached_property\n def clean(self):\n return self._strip_full()and self._strip_inline()\n \n @property\n def has_comments(self):\n return self.strip()!=self.clean\n \n def _strip_inline(self):\n ''\n\n \n matcher=re.compile(\n '|'.join(fr'(^|\\s)({re.escape(prefix)})'for prefix in self.prefixes.inline)\n \n or '(?!)'\n )\n match=matcher.search(self)\n return self[:match.start()if match else None].strip()\n \n def _strip_full(self):\n return ''if any(map(self.strip().startswith,self.prefixes.full))else True\n \n \nclass RawConfigParser(MutableMapping):\n ''\n \n \n _SECT_TMPL=r\"\"\"\n \\[ # [\n (?P

.+) # very permissive!\n \\] # ]\n \"\"\"\n _OPT_TMPL=r\"\"\"\n (?Pn'%(\n toprefix,num_chg)\n else:\n in_change=False\n \n if not flaglist:\n flaglist=[False]\n next_id=['']\n next_href=['']\n last=0\n if context:\n fromlist=[' No Differences Found ']\n tolist=fromlist\n else:\n fromlist=tolist=[' Empty File ']\n \n if not flaglist[0]:\n next_href[0]='f'%toprefix\n \n next_href[last]='t'%(toprefix)\n \n return fromlist,tolist,flaglist,next_href,next_id\n \n def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,\n numlines=5):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n self._make_prefix()\n \n \n \n fromlines,tolines=self._tab_newline_replace(fromlines,tolines)\n \n \n if context:\n context_lines=numlines\n else:\n context_lines=None\n diffs=_mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,\n charjunk=self._charjunk)\n \n \n if self._wrapcolumn:\n diffs=self._line_wrapper(diffs)\n \n \n fromlist,tolist,flaglist=self._collect_lines(diffs)\n \n \n fromlist,tolist,flaglist,next_href,next_id=self._convert_flags(\n fromlist,tolist,flaglist,context,numlines)\n \n s=[]\n fmt=' %s%s'+\\\n '%s%s\\n'\n for i in range(len(flaglist)):\n if flaglist[i]is None:\n \n \n if i >0:\n s.append(' \\n \\n')\n else:\n s.append(fmt %(next_id[i],next_href[i],fromlist[i],\n next_href[i],tolist[i]))\n if fromdesc or todesc:\n header_row='%s%s%s%s'%(\n '
',\n '%s'%fromdesc,\n '
',\n '%s'%todesc)\n else:\n header_row=''\n \n table=self._table_template %dict(\n data_rows=''.join(s),\n header_row=header_row,\n prefix=self._prefix[1])\n \n return table.replace('\\0+','').\\\n replace('\\0-','').\\\n replace('\\0^','').\\\n replace('\\1','').\\\n replace('\\t',' ')\n \ndel re\n\ndef restore(delta,which):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n tag={1:\"- \",2:\"+ \"}[int(which)]\n except KeyError:\n raise ValueError('unknown delta choice (must be 1 or 2): %r'\n %which)from None\n prefixes=(\" \",tag)\n for line in delta:\n if line[:2]in prefixes:\n yield line[2:]\n \ndef _test():\n import doctest,difflib\n return doctest.testmod(difflib)\n \nif __name__ ==\"__main__\":\n _test()\n", ["collections", "difflib", "doctest", "heapq", "re", "types"]], "doctest": [".py", "\n\n\n\n\n\n\n\nr\"\"\"Module doctest -- a framework for running examples in docstrings.\n\nIn simplest use, end each module M to be tested with:\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n _test()\n\nThen running the module as a script will cause the examples in the\ndocstrings to get executed and verified:\n\npython M.py\n\nThis won't display anything unless an example fails, in which case the\nfailing example(s) and the cause(s) of the failure(s) are printed to stdout\n(why not stderr? because stderr is a lame hack <0.2 wink>), and the final\nline of output is \"Test failed.\".\n\nRun it with the -v switch instead:\n\npython M.py -v\n\nand a detailed report of all examples tried is printed to stdout, along\nwith assorted summaries at the end.\n\nYou can force verbose mode by passing \"verbose=True\" to testmod, or prohibit\nit by passing \"verbose=False\". In either of those cases, sys.argv is not\nexamined by testmod.\n\nThere are a variety of other ways to run doctests, including integration\nwith the unittest framework, and support for running non-Python text\nfiles containing doctests. There are also many ways to override parts\nof doctest's default behaviors. See the Library Reference Manual for\ndetails.\n\"\"\"\n\n__docformat__='reStructuredText en'\n\n__all__=[\n\n'register_optionflag',\n'DONT_ACCEPT_TRUE_FOR_1',\n'DONT_ACCEPT_BLANKLINE',\n'NORMALIZE_WHITESPACE',\n'ELLIPSIS',\n'SKIP',\n'IGNORE_EXCEPTION_DETAIL',\n'COMPARISON_FLAGS',\n'REPORT_UDIFF',\n'REPORT_CDIFF',\n'REPORT_NDIFF',\n'REPORT_ONLY_FIRST_FAILURE',\n'REPORTING_FLAGS',\n'FAIL_FAST',\n\n\n'Example',\n'DocTest',\n\n'DocTestParser',\n\n'DocTestFinder',\n\n'DocTestRunner',\n'OutputChecker',\n'DocTestFailure',\n'UnexpectedException',\n'DebugRunner',\n\n'testmod',\n'testfile',\n'run_docstring_examples',\n\n'DocTestSuite',\n'DocFileSuite',\n'set_unittest_reportflags',\n\n'script_from_examples',\n'testsource',\n'debug_src',\n'debug',\n]\n\nimport __future__\nimport difflib\nimport inspect\nimport linecache\nimport os\nimport pdb\nimport re\nimport sys\nimport traceback\nimport unittest\nfrom io import StringIO,IncrementalNewlineDecoder\nfrom collections import namedtuple\nimport _colorize\nfrom _colorize import ANSIColors,can_colorize\n\n\nclass TestResults(namedtuple('TestResults','failed attempted')):\n def __new__(cls,failed,attempted,*,skipped=0):\n results=super().__new__(cls,failed,attempted)\n results.skipped=skipped\n return results\n \n def __repr__(self):\n if self.skipped:\n return(f'TestResults(failed={self.failed}, '\n f'attempted={self.attempted}, '\n f'skipped={self.skipped})')\n else:\n \n \n return super().__repr__()\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nOPTIONFLAGS_BY_NAME={}\ndef register_optionflag(name):\n\n return OPTIONFLAGS_BY_NAME.setdefault(name,1 <=2\n \n \n startpos,endpos=0,len(got)\n w=ws[0]\n if w:\n if got.startswith(w):\n startpos=len(w)\n del ws[0]\n else:\n return False\n w=ws[-1]\n if w:\n if got.endswith(w):\n endpos -=len(w)\n del ws[-1]\n else:\n return False\n \n if startpos >endpos:\n \n \n return False\n \n \n \n \n for w in ws:\n \n \n \n startpos=got.find(w,startpos,endpos)\n if startpos <0:\n return False\n startpos +=len(w)\n \n return True\n \ndef _comment_line(line):\n ''\n line=line.rstrip()\n if line:\n return '# '+line\n else:\n return '#'\n \ndef _strip_exception_details(msg):\n\n\n\n\n\n\n\n\n\n\n start,end=0,len(msg)\n \n i=msg.find(\"\\n\")\n if i >=0:\n end=i\n \n i=msg.find(':',0,end)\n if i >=0:\n end=i\n \n i=msg.rfind('.',0,end)\n if i >=0:\n start=i+1\n return msg[start:end]\n \nclass _OutputRedirectingPdb(pdb.Pdb):\n ''\n\n\n\n \n def __init__(self,out):\n self.__out=out\n self.__debugger_used=False\n \n pdb.Pdb.__init__(self,stdout=out,nosigint=True)\n \n self.use_rawinput=1\n \n def set_trace(self,frame=None):\n self.__debugger_used=True\n if frame is None:\n frame=sys._getframe().f_back\n pdb.Pdb.set_trace(self,frame)\n \n def set_continue(self):\n \n \n if self.__debugger_used:\n pdb.Pdb.set_continue(self)\n \n def trace_dispatch(self,*args):\n \n save_stdout=sys.stdout\n sys.stdout=self.__out\n \n try:\n return pdb.Pdb.trace_dispatch(self,*args)\n finally:\n sys.stdout=save_stdout\n \n \ndef _module_relative_path(module,test_path):\n if not inspect.ismodule(module):\n raise TypeError('Expected a module: %r'%module)\n if test_path.startswith('/'):\n raise ValueError('Module-relative files may not have absolute paths')\n \n \n test_path=os.path.join(*(test_path.split('/')))\n \n \n if hasattr(module,'__file__'):\n \n basedir=os.path.split(module.__file__)[0]\n elif module.__name__ =='__main__':\n \n if len(sys.argv)>0 and sys.argv[0]!='':\n basedir=os.path.split(sys.argv[0])[0]\n else:\n basedir=os.curdir\n else:\n if hasattr(module,'__path__'):\n for directory in module.__path__:\n fullpath=os.path.join(directory,test_path)\n if os.path.exists(fullpath):\n return fullpath\n \n \n raise ValueError(\"Can't resolve paths relative to the module \"\n \"%r (it has no __file__)\"\n %module.__name__)\n \n \n return os.path.join(basedir,test_path)\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass Example:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,source,want,exc_msg=None,lineno=0,indent=0,\n options=None):\n \n if not source.endswith('\\n'):\n source +='\\n'\n if want and not want.endswith('\\n'):\n want +='\\n'\n if exc_msg is not None and not exc_msg.endswith('\\n'):\n exc_msg +='\\n'\n \n self.source=source\n self.want=want\n self.lineno=lineno\n self.indent=indent\n if options is None:options={}\n self.options=options\n self.exc_msg=exc_msg\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self.source ==other.source and\\\n self.want ==other.want and\\\n self.lineno ==other.lineno and\\\n self.indent ==other.indent and\\\n self.options ==other.options and\\\n self.exc_msg ==other.exc_msg\n \n def __hash__(self):\n return hash((self.source,self.want,self.lineno,self.indent,\n self.exc_msg))\n \nclass DocTest:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,examples,globs,name,filename,lineno,docstring):\n ''\n\n\n \n assert not isinstance(examples,str),\\\n \"DocTest no longer accepts str; use DocTestParser instead\"\n self.examples=examples\n self.docstring=docstring\n self.globs=globs.copy()\n self.name=name\n self.filename=filename\n self.lineno=lineno\n \n def __repr__(self):\n if len(self.examples)==0:\n examples='no examples'\n elif len(self.examples)==1:\n examples='1 example'\n else:\n examples='%d examples'%len(self.examples)\n return('<%s %s from %s:%s (%s)>'%\n (self.__class__.__name__,\n self.name,self.filename,self.lineno,examples))\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self.examples ==other.examples and\\\n self.docstring ==other.docstring and\\\n self.globs ==other.globs and\\\n self.name ==other.name and\\\n self.filename ==other.filename and\\\n self.lineno ==other.lineno\n \n def __hash__(self):\n return hash((self.docstring,self.name,self.filename,self.lineno))\n \n \n def __lt__(self,other):\n if not isinstance(other,DocTest):\n return NotImplemented\n self_lno=self.lineno if self.lineno is not None else -1\n other_lno=other.lineno if other.lineno is not None else -1\n return((self.name,self.filename,self_lno,id(self))\n <\n (other.name,other.filename,other_lno,id(other)))\n \n \n \n \n \nclass DocTestParser:\n ''\n\n \n \n \n \n \n \n _EXAMPLE_RE=re.compile(r'''\n # Source consists of a PS1 line followed by zero or more PS2 lines.\n (?P\n (?:^(?P [ ]*) >>> .*) # PS1 line\n (?:\\n [ ]* \\.\\.\\. .*)*) # PS2 lines\n \\n?\n # Want consists of any non-blank lines that do not start with PS1.\n (?P (?:(?![ ]*$) # Not a blank line\n (?![ ]*>>>) # Not a line starting with PS1\n .+$\\n? # But any other line\n )*)\n ''',re.MULTILINE |re.VERBOSE)\n \n \n \n \n \n \n \n \n \n \n _EXCEPTION_RE=re.compile(r\"\"\"\n # Grab the traceback header. Different versions of Python have\n # said different things on the first traceback line.\n ^(?P Traceback\\ \\(\n (?: most\\ recent\\ call\\ last\n | innermost\\ last\n ) \\) :\n )\n \\s* $ # toss trailing whitespace on the header.\n (?P .*?) # don't blink: absorb stuff until...\n ^ (?P \\w+ .*) # a line *starts* with alphanum.\n \"\"\",re.VERBOSE |re.MULTILINE |re.DOTALL)\n \n \n \n _IS_BLANK_OR_COMMENT=re.compile(r'^[ ]*(#.*)?$').match\n \n def parse(self,string,name=''):\n ''\n\n\n\n\n\n \n string=string.expandtabs()\n \n min_indent=self._min_indent(string)\n if min_indent >0:\n string='\\n'.join([l[min_indent:]for l in string.split('\\n')])\n \n output=[]\n charno,lineno=0,0\n \n for m in self._EXAMPLE_RE.finditer(string):\n \n output.append(string[charno:m.start()])\n \n lineno +=string.count('\\n',charno,m.start())\n \n (source,options,want,exc_msg)=\\\n self._parse_example(m,name,lineno)\n \n if not self._IS_BLANK_OR_COMMENT(source):\n output.append(Example(source,want,exc_msg,\n lineno=lineno,\n indent=min_indent+len(m.group('indent')),\n options=options))\n \n lineno +=string.count('\\n',m.start(),m.end())\n \n charno=m.end()\n \n output.append(string[charno:])\n return output\n \n def get_doctest(self,string,globs,name,filename,lineno):\n ''\n\n\n\n\n\n\n \n return DocTest(self.get_examples(string,name),globs,\n name,filename,lineno,string)\n \n def get_examples(self,string,name=''):\n ''\n\n\n\n\n\n\n\n\n \n return[x for x in self.parse(string,name)\n if isinstance(x,Example)]\n \n def _parse_example(self,m,name,lineno):\n ''\n\n\n\n\n\n\n\n\n \n \n indent=len(m.group('indent'))\n \n \n \n source_lines=m.group('source').split('\\n')\n self._check_prompt_blank(source_lines,indent,name,lineno)\n self._check_prefix(source_lines[1:],' '*indent+'.',name,lineno)\n source='\\n'.join([sl[indent+4:]for sl in source_lines])\n \n \n \n \n want=m.group('want')\n want_lines=want.split('\\n')\n if len(want_lines)>1 and re.match(r' *$',want_lines[-1]):\n del want_lines[-1]\n self._check_prefix(want_lines,' '*indent,name,\n lineno+len(source_lines))\n want='\\n'.join([wl[indent:]for wl in want_lines])\n \n \n m=self._EXCEPTION_RE.match(want)\n if m:\n exc_msg=m.group('msg')\n else:\n exc_msg=None\n \n \n options=self._find_options(source,name,lineno)\n \n return source,options,want,exc_msg\n \n \n \n \n \n \n \n \n _OPTION_DIRECTIVE_RE=re.compile(r'#\\s*doctest:\\s*([^\\n\\'\"]*)$',\n re.MULTILINE)\n \n def _find_options(self,source,name,lineno):\n ''\n\n\n\n\n\n \n options={}\n \n for m in self._OPTION_DIRECTIVE_RE.finditer(source):\n option_strings=m.group(1).replace(',',' ').split()\n for option in option_strings:\n if(option[0]not in '+-'or\n option[1:]not in OPTIONFLAGS_BY_NAME):\n raise ValueError('line %r of the doctest for %s '\n 'has an invalid option: %r'%\n (lineno+1,name,option))\n flag=OPTIONFLAGS_BY_NAME[option[1:]]\n options[flag]=(option[0]=='+')\n if options and self._IS_BLANK_OR_COMMENT(source):\n raise ValueError('line %r of the doctest for %s has an option '\n 'directive on a line with no example: %r'%\n (lineno,name,source))\n return options\n \n \n \n _INDENT_RE=re.compile(r'^([ ]*)(?=\\S)',re.MULTILINE)\n \n def _min_indent(self,s):\n ''\n indents=[len(indent)for indent in self._INDENT_RE.findall(s)]\n if len(indents)>0:\n return min(indents)\n else:\n return 0\n \n def _check_prompt_blank(self,lines,indent,name,lineno):\n ''\n\n\n\n\n \n for i,line in enumerate(lines):\n if len(line)>=indent+4 and line[indent+3]!=' ':\n raise ValueError('line %r of the docstring for %s '\n 'lacks blank after %s: %r'%\n (lineno+i+1,name,\n line[indent:indent+3],line))\n \n def _check_prefix(self,lines,prefix,name,lineno):\n ''\n\n\n \n for i,line in enumerate(lines):\n if line and not line.startswith(prefix):\n raise ValueError('line %r of the docstring for %s has '\n 'inconsistent leading whitespace: %r'%\n (lineno+i+1,name,line))\n \n \n \n \n \n \nclass DocTestFinder:\n ''\n\n\n\n\n\n \n \n def __init__(self,verbose=False,parser=DocTestParser(),\n recurse=True,exclude_empty=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._parser=parser\n self._verbose=verbose\n self._recurse=recurse\n self._exclude_empty=exclude_empty\n \n def find(self,obj,name=None,module=None,globs=None,extraglobs=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if name is None:\n name=getattr(obj,'__name__',None)\n if name is None:\n raise ValueError(\"DocTestFinder.find: name must be given \"\n \"when obj.__name__ doesn't exist: %r\"%\n (type(obj),))\n \n \n \n \n if module is False:\n module=None\n elif module is None:\n module=inspect.getmodule(obj)\n \n \n \n \n try:\n file=inspect.getsourcefile(obj)\n except TypeError:\n source_lines=None\n else:\n if not file:\n \n \n file=inspect.getfile(obj)\n if not file[0]+file[-2:]=='<]>':file=None\n if file is None:\n source_lines=None\n else:\n if module is not None:\n \n \n \n source_lines=linecache.getlines(file,module.__dict__)\n else:\n \n \n source_lines=linecache.getlines(file)\n if not source_lines:\n source_lines=None\n \n \n if globs is None:\n if module is None:\n globs={}\n else:\n globs=module.__dict__.copy()\n else:\n globs=globs.copy()\n if extraglobs is not None:\n globs.update(extraglobs)\n if '__name__'not in globs:\n globs['__name__']='__main__'\n \n \n tests=[]\n self._find(tests,obj,name,module,source_lines,globs,{})\n \n \n \n \n tests.sort()\n return tests\n \n def _from_module(self,module,object):\n ''\n\n\n \n if module is None:\n return True\n elif inspect.getmodule(object)is not None:\n return module is inspect.getmodule(object)\n elif inspect.isfunction(object):\n return module.__dict__ is object.__globals__\n elif(inspect.ismethoddescriptor(object)or\n inspect.ismethodwrapper(object)):\n if hasattr(object,'__objclass__'):\n obj_mod=object.__objclass__.__module__\n elif hasattr(object,'__module__'):\n obj_mod=object.__module__\n else:\n return True\n return module.__name__ ==obj_mod\n elif inspect.isclass(object):\n return module.__name__ ==object.__module__\n elif hasattr(object,'__module__'):\n return module.__name__ ==object.__module__\n elif isinstance(object,property):\n return True\n else:\n raise ValueError(\"object must be a class or function\")\n \n def _is_routine(self,obj):\n ''\n\n \n maybe_routine=obj\n try:\n maybe_routine=inspect.unwrap(maybe_routine)\n except ValueError:\n pass\n return inspect.isroutine(maybe_routine)\n \n def _find(self,tests,obj,name,module,source_lines,globs,seen):\n ''\n\n\n \n if self._verbose:\n print('Finding tests in %s'%name)\n \n \n if id(obj)in seen:\n return\n seen[id(obj)]=1\n \n \n test=self._get_test(obj,name,module,globs,source_lines)\n if test is not None:\n tests.append(test)\n \n \n if inspect.ismodule(obj)and self._recurse:\n for valname,val in obj.__dict__.items():\n valname='%s.%s'%(name,valname)\n \n \n if((self._is_routine(val)or inspect.isclass(val))and\n self._from_module(module,val)):\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n \n if inspect.ismodule(obj)and self._recurse:\n for valname,val in getattr(obj,'__test__',{}).items():\n if not isinstance(valname,str):\n raise ValueError(\"DocTestFinder.find: __test__ keys \"\n \"must be strings: %r\"%\n (type(valname),))\n if not(inspect.isroutine(val)or inspect.isclass(val)or\n inspect.ismodule(val)or isinstance(val,str)):\n raise ValueError(\"DocTestFinder.find: __test__ values \"\n \"must be strings, functions, methods, \"\n \"classes, or modules: %r\"%\n (type(val),))\n valname='%s.__test__.%s'%(name,valname)\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n \n if inspect.isclass(obj)and self._recurse:\n for valname,val in obj.__dict__.items():\n \n if isinstance(val,(staticmethod,classmethod)):\n val=val.__func__\n \n \n if((inspect.isroutine(val)or inspect.isclass(val)or\n isinstance(val,property))and\n self._from_module(module,val)):\n valname='%s.%s'%(name,valname)\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n def _get_test(self,obj,name,module,globs,source_lines):\n ''\n\n\n \n \n \n if isinstance(obj,str):\n docstring=obj\n else:\n try:\n if obj.__doc__ is None:\n docstring=''\n else:\n docstring=obj.__doc__\n if not isinstance(docstring,str):\n docstring=str(docstring)\n except(TypeError,AttributeError):\n docstring=''\n \n \n lineno=self._find_lineno(obj,source_lines)\n \n \n if self._exclude_empty and not docstring:\n return None\n \n \n if module is None:\n filename=None\n else:\n \n filename=getattr(module,'__file__',None)or module.__name__\n if filename[-4:]==\".pyc\":\n filename=filename[:-1]\n return self._parser.get_doctest(docstring,globs,name,\n filename,lineno)\n \n def _find_lineno(self,obj,source_lines):\n ''\n\n\n\n \n lineno=None\n docstring=getattr(obj,'__doc__',None)\n \n \n if inspect.ismodule(obj)and docstring is not None:\n lineno=0\n \n \n \n \n if inspect.isclass(obj)and docstring is not None:\n if source_lines is None:\n return None\n pat=re.compile(r'^\\s*class\\s*%s\\b'%\n re.escape(getattr(obj,'__name__','-')))\n for i,line in enumerate(source_lines):\n if pat.match(line):\n lineno=i\n break\n \n \n if inspect.ismethod(obj):obj=obj.__func__\n if isinstance(obj,property):\n obj=obj.fget\n if inspect.isfunction(obj)and getattr(obj,'__doc__',None):\n \n obj=inspect.unwrap(obj)\n try:\n obj=obj.__code__\n except AttributeError:\n \n \n \n return None\n if inspect.istraceback(obj):obj=obj.tb_frame\n if inspect.isframe(obj):obj=obj.f_code\n if inspect.iscode(obj):\n lineno=obj.co_firstlineno -1\n \n \n \n \n \n \n if lineno is not None:\n if source_lines is None:\n return lineno+1\n pat=re.compile(r'(^|.*:)\\s*\\w*(\"|\\')')\n for lineno in range(lineno,len(source_lines)):\n if pat.match(source_lines[lineno]):\n return lineno\n \n \n return None\n \n \n \n \n \nclass DocTestRunner:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n DIVIDER=\"*\"*70\n \n def __init__(self,checker=None,verbose=None,optionflags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._checker=checker or OutputChecker()\n if verbose is None:\n verbose='-v'in sys.argv\n self._verbose=verbose\n self.optionflags=optionflags\n self.original_optionflags=optionflags\n \n \n self.tries=0\n self.failures=0\n self.skips=0\n self._stats={}\n \n \n self._fakeout=_SpoofOut()\n \n \n \n \n \n def report_start(self,out,test,example):\n ''\n\n\n \n if self._verbose:\n if example.want:\n out('Trying:\\n'+_indent(example.source)+\n 'Expecting:\\n'+_indent(example.want))\n else:\n out('Trying:\\n'+_indent(example.source)+\n 'Expecting nothing\\n')\n \n def report_success(self,out,test,example,got):\n ''\n\n\n \n if self._verbose:\n out(\"ok\\n\")\n \n def report_failure(self,out,test,example,got):\n ''\n\n \n out(self._failure_header(test,example)+\n self._checker.output_difference(example,got,self.optionflags))\n \n def report_unexpected_exception(self,out,test,example,exc_info):\n ''\n\n \n out(self._failure_header(test,example)+\n 'Exception raised:\\n'+_indent(_exception_traceback(exc_info)))\n \n def _failure_header(self,test,example):\n red,reset=(\n (ANSIColors.RED,ANSIColors.RESET)if can_colorize()else(\"\",\"\")\n )\n out=[f\"{red}{self.DIVIDER}{reset}\"]\n if test.filename:\n if test.lineno is not None and example.lineno is not None:\n lineno=test.lineno+example.lineno+1\n else:\n lineno='?'\n out.append('File \"%s\", line %s, in %s'%\n (test.filename,lineno,test.name))\n else:\n out.append('Line %s, in %s'%(example.lineno+1,test.name))\n out.append('Failed example:')\n source=example.source\n out.append(_indent(source))\n return '\\n'.join(out)\n \n \n \n \n \n def __run(self,test,compileflags,out):\n ''\n\n\n\n\n\n \n \n failures=attempted=skips=0\n \n \n \n original_optionflags=self.optionflags\n \n SUCCESS,FAILURE,BOOM=range(3)\n \n check=self._checker.check_output\n \n \n for examplenum,example in enumerate(test.examples):\n attempted +=1\n \n \n \n quiet=(self.optionflags&REPORT_ONLY_FIRST_FAILURE and\n failures >0)\n \n \n self.optionflags=original_optionflags\n if example.options:\n for(optionflag,val)in example.options.items():\n if val:\n self.optionflags |=optionflag\n else:\n self.optionflags &=~optionflag\n \n \n if self.optionflags&SKIP:\n skips +=1\n continue\n \n \n if not quiet:\n self.report_start(out,test,example)\n \n \n \n \n filename=''%(test.name,examplenum)\n \n \n \n \n try:\n \n exec(compile(example.source,filename,\"single\",\n compileflags,True),test.globs)\n self.debugger.set_continue()\n exception=None\n except KeyboardInterrupt:\n raise\n except:\n exception=sys.exc_info()\n self.debugger.set_continue()\n \n got=self._fakeout.getvalue()\n self._fakeout.truncate(0)\n outcome=FAILURE\n \n \n \n if exception is None:\n if check(example.want,got,self.optionflags):\n outcome=SUCCESS\n \n \n else:\n formatted_ex=traceback.format_exception_only(*exception[:2])\n if issubclass(exception[0],SyntaxError):\n \n \n \n \n exception_line_prefixes=(\n f\"{exception[0].__qualname__}:\",\n f\"{exception[0].__module__}.{exception[0].__qualname__}:\",\n )\n exc_msg_index=next(\n index\n for index,line in enumerate(formatted_ex)\n if line.startswith(exception_line_prefixes)\n )\n formatted_ex=formatted_ex[exc_msg_index:]\n \n exc_msg=\"\".join(formatted_ex)\n if not quiet:\n got +=_exception_traceback(exception)\n \n \n \n if example.exc_msg is None:\n outcome=BOOM\n \n \n elif check(example.exc_msg,exc_msg,self.optionflags):\n outcome=SUCCESS\n \n \n elif self.optionflags&IGNORE_EXCEPTION_DETAIL:\n if check(_strip_exception_details(example.exc_msg),\n _strip_exception_details(exc_msg),\n self.optionflags):\n outcome=SUCCESS\n \n \n if outcome is SUCCESS:\n if not quiet:\n self.report_success(out,test,example,got)\n elif outcome is FAILURE:\n if not quiet:\n self.report_failure(out,test,example,got)\n failures +=1\n elif outcome is BOOM:\n if not quiet:\n self.report_unexpected_exception(out,test,example,\n exception)\n failures +=1\n else:\n assert False,(\"unknown outcome\",outcome)\n \n if failures and self.optionflags&FAIL_FAST:\n break\n \n \n self.optionflags=original_optionflags\n \n \n self.__record_outcome(test,failures,attempted,skips)\n return TestResults(failures,attempted,skipped=skips)\n \n def __record_outcome(self,test,failures,tries,skips):\n ''\n\n\n \n failures2,tries2,skips2=self._stats.get(test.name,(0,0,0))\n self._stats[test.name]=(failures+failures2,\n tries+tries2,\n skips+skips2)\n self.failures +=failures\n self.tries +=tries\n self.skips +=skips\n \n __LINECACHE_FILENAME_RE=re.compile(r'.+)'\n r'\\[(?P\\d+)\\]>$')\n def __patched_linecache_getlines(self,filename,module_globals=None):\n m=self.__LINECACHE_FILENAME_RE.match(filename)\n if m and m.group('name')==self.test.name:\n example=self.test.examples[int(m.group('examplenum'))]\n return example.source.splitlines(keepends=True)\n else:\n return self.save_linecache_getlines(filename,module_globals)\n \n def run(self,test,compileflags=None,out=None,clear_globs=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.test=test\n \n if compileflags is None:\n compileflags=_extract_future_flags(test.globs)\n \n save_stdout=sys.stdout\n if out is None:\n encoding=save_stdout.encoding\n if encoding is None or encoding.lower()=='utf-8':\n out=save_stdout.write\n else:\n \n def out(s):\n s=str(s.encode(encoding,'backslashreplace'),encoding)\n save_stdout.write(s)\n sys.stdout=self._fakeout\n \n \n \n \n \n \n save_trace=sys.gettrace()\n save_set_trace=pdb.set_trace\n self.debugger=_OutputRedirectingPdb(save_stdout)\n self.debugger.reset()\n pdb.set_trace=self.debugger.set_trace\n \n \n \n self.save_linecache_getlines=linecache.getlines\n linecache.getlines=self.__patched_linecache_getlines\n \n \n save_displayhook=sys.displayhook\n sys.displayhook=sys.__displayhook__\n saved_can_colorize=_colorize.can_colorize\n _colorize.can_colorize=lambda:False\n color_variables={\"PYTHON_COLORS\":None,\"FORCE_COLOR\":None}\n for key in color_variables:\n color_variables[key]=os.environ.pop(key,None)\n try:\n return self.__run(test,compileflags,out)\n finally:\n sys.stdout=save_stdout\n pdb.set_trace=save_set_trace\n sys.settrace(save_trace)\n linecache.getlines=self.save_linecache_getlines\n sys.displayhook=save_displayhook\n _colorize.can_colorize=saved_can_colorize\n for key,value in color_variables.items():\n if value is not None:\n os.environ[key]=value\n if clear_globs:\n test.globs.clear()\n import builtins\n builtins._=None\n \n \n \n \n def summarize(self,verbose=None):\n ''\n\n\n\n\n\n\n \n if verbose is None:\n verbose=self._verbose\n \n notests,passed,failed=[],[],[]\n total_tries=total_failures=total_skips=0\n \n for name,(failures,tries,skips)in self._stats.items():\n assert failures <=tries\n total_tries +=tries\n total_failures +=failures\n total_skips +=skips\n \n if tries ==0:\n notests.append(name)\n elif failures ==0:\n passed.append((name,tries))\n else:\n failed.append((name,(failures,tries,skips)))\n \n ansi=_colorize.get_colors()\n bold_green=ansi.BOLD_GREEN\n bold_red=ansi.BOLD_RED\n green=ansi.GREEN\n red=ansi.RED\n reset=ansi.RESET\n yellow=ansi.YELLOW\n \n if verbose:\n if notests:\n print(f\"{_n_items(notests)} had no tests:\")\n notests.sort()\n for name in notests:\n print(f\" {name}\")\n \n if passed:\n print(f\"{green}{_n_items(passed)} passed all tests:{reset}\")\n for name,count in sorted(passed):\n s=\"\"if count ==1 else \"s\"\n print(f\" {green}{count:3d} test{s} in {name}{reset}\")\n \n if failed:\n print(f\"{red}{self.DIVIDER}{reset}\")\n print(f\"{_n_items(failed)} had failures:\")\n for name,(failures,tries,skips)in sorted(failed):\n print(f\" {failures:3d} of {tries:3d} in {name}\")\n \n if verbose:\n s=\"\"if total_tries ==1 else \"s\"\n print(f\"{total_tries} test{s} in {_n_items(self._stats)}.\")\n \n and_f=(\n f\" and {red}{total_failures} failed{reset}\"\n if total_failures else \"\"\n )\n print(f\"{green}{total_tries -total_failures} passed{reset}{and_f}.\")\n \n if total_failures:\n s=\"\"if total_failures ==1 else \"s\"\n msg=f\"{bold_red}***Test Failed*** {total_failures} failure{s}{reset}\"\n if total_skips:\n s=\"\"if total_skips ==1 else \"s\"\n msg=f\"{msg} and {yellow}{total_skips} skipped test{s}{reset}\"\n print(f\"{msg}.\")\n elif verbose:\n print(f\"{bold_green}Test passed.{reset}\")\n \n return TestResults(total_failures,total_tries,skipped=total_skips)\n \n \n \n \n def merge(self,other):\n d=self._stats\n for name,(failures,tries,skips)in other._stats.items():\n if name in d:\n failures2,tries2,skips2=d[name]\n failures=failures+failures2\n tries=tries+tries2\n skips=skips+skips2\n d[name]=(failures,tries,skips)\n \n \ndef _n_items(items:list |dict)->str:\n ''\n\n \n n=len(items)\n s=\"\"if n ==1 else \"s\"\n return f\"{n} item{s}\"\n \n \nclass OutputChecker:\n ''\n\n\n\n\n\n \n def _toAscii(self,s):\n ''\n\n \n return str(s.encode('ASCII','backslashreplace'),\"ASCII\")\n \n def check_output(self,want,got,optionflags):\n ''\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n got=self._toAscii(got)\n want=self._toAscii(want)\n \n \n \n if got ==want:\n return True\n \n \n \n if not(optionflags&DONT_ACCEPT_TRUE_FOR_1):\n if(got,want)==(\"True\\n\",\"1\\n\"):\n return True\n if(got,want)==(\"False\\n\",\"0\\n\"):\n return True\n \n \n \n if not(optionflags&DONT_ACCEPT_BLANKLINE):\n \n want=re.sub(r'(?m)^%s\\s*?$'%re.escape(BLANKLINE_MARKER),\n '',want)\n \n \n got=re.sub(r'(?m)^[^\\S\\n]+$','',got)\n if got ==want:\n return True\n \n \n \n \n if optionflags&NORMALIZE_WHITESPACE:\n got=' '.join(got.split())\n want=' '.join(want.split())\n if got ==want:\n return True\n \n \n \n if optionflags&ELLIPSIS:\n if _ellipsis_match(want,got):\n return True\n \n \n return False\n \n \n def _do_a_fancy_diff(self,want,got,optionflags):\n \n if not optionflags&(REPORT_UDIFF |\n REPORT_CDIFF |\n REPORT_NDIFF):\n return False\n \n \n \n \n \n \n \n \n \n \n \n if optionflags&REPORT_NDIFF:\n return True\n \n \n return want.count('\\n')>2 and got.count('\\n')>2\n \n def output_difference(self,example,got,optionflags):\n ''\n\n\n\n\n \n want=example.want\n \n \n if not(optionflags&DONT_ACCEPT_BLANKLINE):\n got=re.sub('(?m)^[ ]*(?=\\n)',BLANKLINE_MARKER,got)\n \n \n if self._do_a_fancy_diff(want,got,optionflags):\n \n want_lines=want.splitlines(keepends=True)\n got_lines=got.splitlines(keepends=True)\n \n if optionflags&REPORT_UDIFF:\n diff=difflib.unified_diff(want_lines,got_lines,n=2)\n diff=list(diff)[2:]\n kind='unified diff with -expected +actual'\n elif optionflags&REPORT_CDIFF:\n diff=difflib.context_diff(want_lines,got_lines,n=2)\n diff=list(diff)[2:]\n kind='context diff with expected followed by actual'\n elif optionflags&REPORT_NDIFF:\n engine=difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)\n diff=list(engine.compare(want_lines,got_lines))\n kind='ndiff with -expected +actual'\n else:\n assert 0,'Bad diff option'\n return 'Differences (%s):\\n'%kind+_indent(''.join(diff))\n \n \n \n if want and got:\n return 'Expected:\\n%sGot:\\n%s'%(_indent(want),_indent(got))\n elif want:\n return 'Expected:\\n%sGot nothing\\n'%_indent(want)\n elif got:\n return 'Expected nothing\\nGot:\\n%s'%_indent(got)\n else:\n return 'Expected nothing\\nGot nothing\\n'\n \nclass DocTestFailure(Exception):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,test,example,got):\n self.test=test\n self.example=example\n self.got=got\n \n def __str__(self):\n return str(self.test)\n \nclass UnexpectedException(Exception):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,test,example,exc_info):\n self.test=test\n self.example=example\n self.exc_info=exc_info\n \n def __str__(self):\n return str(self.test)\n \nclass DebugRunner(DocTestRunner):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def run(self,test,compileflags=None,out=None,clear_globs=True):\n r=DocTestRunner.run(self,test,compileflags,out,False)\n if clear_globs:\n test.globs.clear()\n return r\n \n def report_unexpected_exception(self,out,test,example,exc_info):\n raise UnexpectedException(test,example,exc_info)\n \n def report_failure(self,out,test,example,got):\n raise DocTestFailure(test,example,got)\n \n \n \n \n \n \n \n \nmaster=None\n\ndef testmod(m=None,name=None,globs=None,verbose=None,\nreport=True,optionflags=0,extraglobs=None,\nraise_on_error=False,exclude_empty=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global master\n \n \n if m is None:\n \n \n \n m=sys.modules.get('__main__')\n \n \n if not inspect.ismodule(m):\n raise TypeError(\"testmod: module required; %r\"%(m,))\n \n \n if name is None:\n name=m.__name__\n \n \n finder=DocTestFinder(exclude_empty=exclude_empty)\n \n if raise_on_error:\n runner=DebugRunner(verbose=verbose,optionflags=optionflags)\n else:\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n \n for test in finder.find(m,name,globs=globs,extraglobs=extraglobs):\n runner.run(test)\n \n if report:\n runner.summarize()\n \n if master is None:\n master=runner\n else:\n master.merge(runner)\n \n return TestResults(runner.failures,runner.tries,skipped=runner.skips)\n \n \ndef testfile(filename,module_relative=True,name=None,package=None,\nglobs=None,verbose=None,report=True,optionflags=0,\nextraglobs=None,raise_on_error=False,parser=DocTestParser(),\nencoding=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global master\n \n if package and not module_relative:\n raise ValueError(\"Package may only be specified for module-\"\n \"relative paths.\")\n \n \n text,filename=_load_testfile(filename,package,module_relative,\n encoding or \"utf-8\")\n \n \n if name is None:\n name=os.path.basename(filename)\n \n \n if globs is None:\n globs={}\n else:\n globs=globs.copy()\n if extraglobs is not None:\n globs.update(extraglobs)\n if '__name__'not in globs:\n globs['__name__']='__main__'\n \n if raise_on_error:\n runner=DebugRunner(verbose=verbose,optionflags=optionflags)\n else:\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n \n \n test=parser.get_doctest(text,globs,name,filename,0)\n runner.run(test)\n \n if report:\n runner.summarize()\n \n if master is None:\n master=runner\n else:\n master.merge(runner)\n \n return TestResults(runner.failures,runner.tries,skipped=runner.skips)\n \n \ndef run_docstring_examples(f,globs,verbose=False,name=\"NoName\",\ncompileflags=None,optionflags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n finder=DocTestFinder(verbose=verbose,recurse=False)\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n for test in finder.find(f,name,globs=globs):\n runner.run(test,compileflags=compileflags)\n \n \n \n \n \n_unittest_reportflags=0\n\ndef set_unittest_reportflags(flags):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _unittest_reportflags\n \n if(flags&REPORTING_FLAGS)!=flags:\n raise ValueError(\"Only reporting flags allowed\",flags)\n old=_unittest_reportflags\n _unittest_reportflags=flags\n return old\n \n \nclass DocTestCase(unittest.TestCase):\n\n def __init__(self,test,optionflags=0,setUp=None,tearDown=None,\n checker=None):\n \n unittest.TestCase.__init__(self)\n self._dt_optionflags=optionflags\n self._dt_checker=checker\n self._dt_test=test\n self._dt_setUp=setUp\n self._dt_tearDown=tearDown\n \n def setUp(self):\n test=self._dt_test\n self._dt_globs=test.globs.copy()\n \n if self._dt_setUp is not None:\n self._dt_setUp(test)\n \n def tearDown(self):\n test=self._dt_test\n \n if self._dt_tearDown is not None:\n self._dt_tearDown(test)\n \n \n test.globs.clear()\n test.globs.update(self._dt_globs)\n \n def runTest(self):\n test=self._dt_test\n old=sys.stdout\n new=StringIO()\n optionflags=self._dt_optionflags\n \n if not(optionflags&REPORTING_FLAGS):\n \n \n optionflags |=_unittest_reportflags\n \n runner=DocTestRunner(optionflags=optionflags,\n checker=self._dt_checker,verbose=False)\n \n try:\n runner.DIVIDER=\"-\"*70\n results=runner.run(test,out=new.write,clear_globs=False)\n if results.skipped ==results.attempted:\n raise unittest.SkipTest(\"all examples were skipped\")\n finally:\n sys.stdout=old\n \n if results.failed:\n raise self.failureException(self.format_failure(new.getvalue()))\n \n def format_failure(self,err):\n test=self._dt_test\n if test.lineno is None:\n lineno='unknown line number'\n else:\n lineno='%s'%test.lineno\n lname='.'.join(test.name.split('.')[-1:])\n return('Failed doctest test for %s\\n'\n ' File \"%s\", line %s, in %s\\n\\n%s'\n %(test.name,test.filename,lineno,lname,err)\n )\n \n def debug(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.setUp()\n runner=DebugRunner(optionflags=self._dt_optionflags,\n checker=self._dt_checker,verbose=False)\n runner.run(self._dt_test,clear_globs=False)\n self.tearDown()\n \n def id(self):\n return self._dt_test.name\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self._dt_test ==other._dt_test and\\\n self._dt_optionflags ==other._dt_optionflags and\\\n self._dt_setUp ==other._dt_setUp and\\\n self._dt_tearDown ==other._dt_tearDown and\\\n self._dt_checker ==other._dt_checker\n \n def __hash__(self):\n return hash((self._dt_optionflags,self._dt_setUp,self._dt_tearDown,\n self._dt_checker))\n \n def __repr__(self):\n name=self._dt_test.name.split('.')\n return \"%s (%s)\"%(name[-1],'.'.join(name[:-1]))\n \n __str__=object.__str__\n \n def shortDescription(self):\n return \"Doctest: \"+self._dt_test.name\n \nclass SkipDocTestCase(DocTestCase):\n def __init__(self,module):\n self.module=module\n DocTestCase.__init__(self,None)\n \n def setUp(self):\n self.skipTest(\"DocTestSuite will not work with -O2 and above\")\n \n def test_skip(self):\n pass\n \n def shortDescription(self):\n return \"Skipping tests from %s\"%self.module.__name__\n \n __str__=shortDescription\n \n \nclass _DocTestSuite(unittest.TestSuite):\n\n def _removeTestAtIndex(self,index):\n pass\n \n \ndef DocTestSuite(module=None,globs=None,extraglobs=None,test_finder=None,\n**options):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if test_finder is None:\n test_finder=DocTestFinder()\n \n module=_normalize_module(module)\n tests=test_finder.find(module,globs=globs,extraglobs=extraglobs)\n \n if not tests and sys.flags.optimize >=2:\n \n suite=_DocTestSuite()\n suite.addTest(SkipDocTestCase(module))\n return suite\n \n tests.sort()\n suite=_DocTestSuite()\n \n for test in tests:\n if len(test.examples)==0:\n continue\n if not test.filename:\n filename=module.__file__\n if filename[-4:]==\".pyc\":\n filename=filename[:-1]\n test.filename=filename\n suite.addTest(DocTestCase(test,**options))\n \n return suite\n \nclass DocFileCase(DocTestCase):\n\n def id(self):\n return '_'.join(self._dt_test.name.split('.'))\n \n def __repr__(self):\n return self._dt_test.filename\n \n def format_failure(self,err):\n return('Failed doctest test for %s\\n File \"%s\", line 0\\n\\n%s'\n %(self._dt_test.name,self._dt_test.filename,err)\n )\n \ndef DocFileTest(path,module_relative=True,package=None,\nglobs=None,parser=DocTestParser(),\nencoding=None,**options):\n if globs is None:\n globs={}\n else:\n globs=globs.copy()\n \n if package and not module_relative:\n raise ValueError(\"Package may only be specified for module-\"\n \"relative paths.\")\n \n \n doc,path=_load_testfile(path,package,module_relative,\n encoding or \"utf-8\")\n \n if \"__file__\"not in globs:\n globs[\"__file__\"]=path\n \n \n name=os.path.basename(path)\n \n \n test=parser.get_doctest(doc,globs,name,path,0)\n return DocFileCase(test,**options)\n \ndef DocFileSuite(*paths,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n suite=_DocTestSuite()\n \n \n \n \n if kw.get('module_relative',True):\n kw['package']=_normalize_module(kw.get('package'))\n \n for path in paths:\n suite.addTest(DocFileTest(path,**kw))\n \n return suite\n \n \n \n \n \ndef script_from_examples(s):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n output=[]\n for piece in DocTestParser().parse(s):\n if isinstance(piece,Example):\n \n output.append(piece.source[:-1])\n \n want=piece.want\n if want:\n output.append('# Expected:')\n output +=['## '+l for l in want.split('\\n')[:-1]]\n else:\n \n output +=[_comment_line(l)\n for l in piece.split('\\n')[:-1]]\n \n \n while output and output[-1]=='#':\n output.pop()\n while output and output[0]=='#':\n output.pop(0)\n \n \n return '\\n'.join(output)+'\\n'\n \ndef testsource(module,name):\n ''\n\n\n\n\n \n module=_normalize_module(module)\n tests=DocTestFinder().find(module)\n test=[t for t in tests if t.name ==name]\n if not test:\n raise ValueError(name,\"not found in tests\")\n test=test[0]\n testsrc=script_from_examples(test.docstring)\n return testsrc\n \ndef debug_src(src,pm=False,globs=None):\n ''\n testsrc=script_from_examples(src)\n debug_script(testsrc,pm,globs)\n \ndef debug_script(src,pm=False,globs=None):\n ''\n import pdb\n \n if globs:\n globs=globs.copy()\n else:\n globs={}\n \n if pm:\n try:\n exec(src,globs,globs)\n except:\n print(sys.exc_info()[1])\n p=pdb.Pdb(nosigint=True)\n p.reset()\n p.interaction(None,sys.exc_info()[2])\n else:\n pdb.Pdb(nosigint=True).run(\"exec(%r)\"%src,globs,globs)\n \ndef debug(module,name,pm=False):\n ''\n\n\n\n\n \n module=_normalize_module(module)\n testsrc=testsource(module,name)\n debug_script(testsrc,pm,module.__dict__)\n \n \n \n \nclass _TestClass:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,val):\n ''\n\n\n\n\n \n \n self.val=val\n \n def square(self):\n ''\n\n\n\n \n \n self.val=self.val **2\n return self\n \n def get(self):\n ''\n\n\n\n\n \n \n return self.val\n \n__test__={\"_TestClass\":_TestClass,\n\"string\":r\"\"\"\n Example of a string object, searched as-is.\n >>> x = 1; y = 2\n >>> x + y, x * y\n (3, 2)\n \"\"\",\n\n\"bool-int equivalence\":r\"\"\"\n In 2.2, boolean expressions displayed\n 0 or 1. By default, we still accept\n them. This can be disabled by passing\n DONT_ACCEPT_TRUE_FOR_1 to the new\n optionflags argument.\n >>> 4 == 4\n 1\n >>> 4 == 4\n True\n >>> 4 > 4\n 0\n >>> 4 > 4\n False\n \"\"\",\n\n\"blank lines\":r\"\"\"\n Blank lines can be marked with :\n >>> print('foo\\n\\nbar\\n')\n foo\n \n bar\n \n \"\"\",\n\n\"ellipsis\":r\"\"\"\n If the ellipsis flag is used, then '...' can be used to\n elide substrings in the desired output:\n >>> print(list(range(1000))) #doctest: +ELLIPSIS\n [0, 1, 2, ..., 999]\n \"\"\",\n\n\"whitespace normalization\":r\"\"\"\n If the whitespace normalization flag is used, then\n differences in whitespace are ignored.\n >>> print(list(range(30))) #doctest: +NORMALIZE_WHITESPACE\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n 27, 28, 29]\n \"\"\",\n}\n\n\ndef _test():\n import argparse\n \n parser=argparse.ArgumentParser(description=\"doctest runner\")\n parser.add_argument('-v','--verbose',action='store_true',default=False,\n help='print very verbose output for all tests')\n parser.add_argument('-o','--option',action='append',\n choices=OPTIONFLAGS_BY_NAME.keys(),default=[],\n help=('specify a doctest option flag to apply'\n ' to the test run; may be specified more'\n ' than once to apply multiple options'))\n parser.add_argument('-f','--fail-fast',action='store_true',\n help=('stop running tests after first failure (this'\n ' is a shorthand for -o FAIL_FAST, and is'\n ' in addition to any other -o options)'))\n parser.add_argument('file',nargs='+',\n help='file containing the tests to run')\n args=parser.parse_args()\n testfiles=args.file\n \n \n verbose=args.verbose\n options=0\n for option in args.option:\n options |=OPTIONFLAGS_BY_NAME[option]\n if args.fail_fast:\n options |=FAIL_FAST\n for filename in testfiles:\n if filename.endswith(\".py\"):\n \n \n \n dirname,filename=os.path.split(filename)\n sys.path.insert(0,dirname)\n m=__import__(filename[:-3])\n del sys.path[0]\n failures,_=testmod(m,verbose=verbose,optionflags=options)\n else:\n failures,_=testfile(filename,module_relative=False,\n verbose=verbose,optionflags=options)\n if failures:\n return 1\n return 0\n \n \nif __name__ ==\"__main__\":\n sys.exit(_test())\n", ["__future__", "_colorize", "argparse", "builtins", "collections", "difflib", "inspect", "io", "linecache", "os", "pdb", "re", "sys", "traceback", "unittest"]], "enum": [".py", "import sys\nimport builtins as bltns\nfrom types import MappingProxyType,DynamicClassAttribute\n\n\n__all__=[\n'EnumType','EnumMeta','EnumDict',\n'Enum','IntEnum','StrEnum','Flag','IntFlag','ReprEnum',\n'auto','unique','property','verify','member','nonmember',\n'FlagBoundary','STRICT','CONFORM','EJECT','KEEP',\n'global_flag_repr','global_enum_repr','global_str','global_enum',\n'EnumCheck','CONTINUOUS','NAMED_FLAGS','UNIQUE',\n'pickle_by_global_name','pickle_by_enum_name',\n]\n\n\n\n\n\nEnum=Flag=EJECT=_stdlib_enums=ReprEnum=None\n\nclass nonmember(object):\n ''\n\n \n def __init__(self,value):\n self.value=value\n \nclass member(object):\n ''\n\n \n def __init__(self,value):\n self.value=value\n \ndef _is_descriptor(obj):\n ''\n\n \n return(\n hasattr(obj,'__get__')or\n hasattr(obj,'__set__')or\n hasattr(obj,'__delete__')\n )\n \ndef _is_dunder(name):\n ''\n\n \n return(\n len(name)>4 and\n name[:2]==name[-2:]=='__'and\n name[2]!='_'and\n name[-3]!='_'\n )\n \ndef _is_sunder(name):\n ''\n\n \n return(\n len(name)>2 and\n name[0]==name[-1]=='_'and\n name[1]!='_'and\n name[-2]!='_'\n )\n \ndef _is_internal_class(cls_name,obj):\n\n if not isinstance(obj,type):\n return False\n qualname=getattr(obj,'__qualname__','')\n s_pattern=cls_name+'.'+getattr(obj,'__name__','')\n e_pattern='.'+s_pattern\n return qualname ==s_pattern or qualname.endswith(e_pattern)\n \ndef _is_private(cls_name,name):\n\n pattern='_%s__'%(cls_name,)\n pat_len=len(pattern)\n if(\n len(name)>pat_len\n and name.startswith(pattern)\n and(name[-1]!='_'or name[-2]!='_')\n ):\n return True\n else:\n return False\n \ndef _is_single_bit(num):\n ''\n\n \n if num ==0:\n return False\n num &=num -1\n return num ==0\n \ndef _make_class_unpicklable(obj):\n ''\n\n\n\n \n def _break_on_call_reduce(self,proto):\n raise TypeError('%r cannot be pickled'%self)\n if isinstance(obj,dict):\n obj['__reduce_ex__']=_break_on_call_reduce\n obj['__module__']=''\n else:\n setattr(obj,'__reduce_ex__',_break_on_call_reduce)\n setattr(obj,'__module__','')\n \ndef _iter_bits_lsb(num):\n\n original=num\n if isinstance(num,Enum):\n num=num.value\n if num <0:\n raise ValueError('%r is not a positive integer'%original)\n while num:\n b=num&(~num+1)\n yield b\n num ^=b\n \ndef show_flag_values(value):\n return list(_iter_bits_lsb(value))\n \ndef bin(num,max_bits=None):\n ''\n\n\n\n\n\n\n\n\n \n \n ceiling=2 **(num).bit_length()\n if num >=0:\n s=bltns.bin(num+ceiling).replace('1','0',1)\n else:\n s=bltns.bin(~num ^(ceiling -1)+ceiling)\n sign=s[:3]\n digits=s[3:]\n if max_bits is not None:\n if len(digits)')\n_not_given=_not_given()\n\nclass _auto_null:\n def __repr__(self):\n return '_auto_null'\n_auto_null=_auto_null()\n\nclass auto:\n ''\n\n \n def __init__(self,value=_auto_null):\n self.value=value\n \n def __repr__(self):\n return \"auto(%r)\"%self.value\n \nclass property(DynamicClassAttribute):\n ''\n\n\n\n\n\n \n \n member=None\n _attr_type=None\n _cls_type=None\n \n def __get__(self,instance,ownerclass=None):\n if instance is None:\n if self.member is not None:\n return self.member\n else:\n raise AttributeError(\n '%r has no attribute %r'%(ownerclass,self.name)\n )\n if self.fget is not None:\n \n return self.fget(instance)\n elif self._attr_type =='attr':\n \n return getattr(self._cls_type,self.name)\n elif self._attr_type =='desc':\n \n return getattr(instance._value_,self.name)\n \n try:\n return ownerclass._member_map_[self.name]\n except KeyError:\n raise AttributeError(\n '%r has no attribute %r'%(ownerclass,self.name)\n )from None\n \n def __set__(self,instance,value):\n if self.fset is not None:\n return self.fset(instance,value)\n raise AttributeError(\n \" cannot set attribute %r\"%(self.clsname,self.name)\n )\n \n def __delete__(self,instance):\n if self.fdel is not None:\n return self.fdel(instance)\n raise AttributeError(\n \" cannot delete attribute %r\"%(self.clsname,self.name)\n )\n \n def __set_name__(self,ownerclass,name):\n self.name=name\n self.clsname=ownerclass.__name__\n \n \nclass _proto_member:\n ''\n\n \n \n def __init__(self,value):\n self.value=value\n \n def __set_name__(self,enum_class,member_name):\n ''\n\n \n \n delattr(enum_class,member_name)\n \n value=self.value\n if not isinstance(value,tuple):\n args=(value,)\n else:\n args=value\n if enum_class._member_type_ is tuple:\n args=(args,)\n if not enum_class._use_args_:\n enum_member=enum_class._new_member_(enum_class)\n else:\n enum_member=enum_class._new_member_(enum_class,*args)\n if not hasattr(enum_member,'_value_'):\n if enum_class._member_type_ is object:\n enum_member._value_=value\n else:\n try:\n enum_member._value_=enum_class._member_type_(*args)\n except Exception as exc:\n new_exc=TypeError(\n '_value_ not set in __new__, unable to create it'\n )\n new_exc.__cause__=exc\n raise new_exc\n value=enum_member._value_\n enum_member._name_=member_name\n enum_member.__objclass__=enum_class\n enum_member.__init__(*args)\n enum_member._sort_order_=len(enum_class._member_names_)\n \n if Flag is not None and issubclass(enum_class,Flag):\n if isinstance(value,int):\n enum_class._flag_mask_ |=value\n if _is_single_bit(value):\n enum_class._singles_mask_ |=value\n enum_class._all_bits_=2 **((enum_class._flag_mask_).bit_length())-1\n \n \n \n try:\n try:\n \n enum_member=enum_class._value2member_map_[value]\n except TypeError:\n for name,canonical_member in enum_class._member_map_.items():\n if canonical_member._value_ ==value:\n enum_member=canonical_member\n break\n else:\n raise KeyError\n except KeyError:\n \n \n if(\n Flag is None\n or not issubclass(enum_class,Flag)\n ):\n \n enum_class._member_names_.append(member_name)\n elif(\n Flag is not None\n and issubclass(enum_class,Flag)\n and isinstance(value,int)\n and _is_single_bit(value)\n ):\n \n enum_class._member_names_.append(member_name)\n \n enum_class._add_member_(member_name,enum_member)\n try:\n \n \n \n enum_class._value2member_map_.setdefault(value,enum_member)\n except TypeError:\n \n enum_class._unhashable_values_.append(value)\n enum_class._unhashable_values_map_.setdefault(member_name,[]).append(value)\n \n \nclass EnumDict(dict):\n ''\n\n\n\n\n \n def __init__(self):\n super().__init__()\n self._member_names={}\n self._last_values=[]\n self._ignore=[]\n self._auto_called=False\n \n def __setitem__(self,key,value):\n ''\n\n\n\n\n\n\n \n if _is_private(self._cls_name,key):\n \n pass\n elif _is_sunder(key):\n if key not in(\n '_order_',\n '_generate_next_value_','_numeric_repr_','_missing_','_ignore_',\n '_iter_member_','_iter_member_by_value_','_iter_member_by_def_',\n '_add_alias_','_add_value_alias_',\n \n \n \n )and not key.startswith('_repr_'):\n raise ValueError(\n '_sunder_ names, such as %r, are reserved for future Enum use'\n %(key,)\n )\n if key =='_generate_next_value_':\n \n if self._auto_called:\n raise TypeError(\"_generate_next_value_ must be defined before members\")\n _gnv=value.__func__ if isinstance(value,staticmethod)else value\n setattr(self,'_generate_next_value',_gnv)\n elif key =='_ignore_':\n if isinstance(value,str):\n value=value.replace(',',' ').split()\n else:\n value=list(value)\n self._ignore=value\n already=set(value)&set(self._member_names)\n if already:\n raise ValueError(\n '_ignore_ cannot specify already set names: %r'\n %(already,)\n )\n elif _is_dunder(key):\n if key =='__order__':\n key='_order_'\n elif key in self._member_names:\n \n raise TypeError('%r already defined as %r'%(key,self[key]))\n elif key in self._ignore:\n pass\n elif isinstance(value,nonmember):\n \n value=value.value\n elif _is_descriptor(value):\n pass\n elif _is_internal_class(self._cls_name,value):\n \n pass\n else:\n if key in self:\n \n raise TypeError('%r already defined as %r'%(key,self[key]))\n elif isinstance(value,member):\n \n value=value.value\n non_auto_store=True\n single=False\n if isinstance(value,auto):\n single=True\n value=(value,)\n if isinstance(value,tuple)and any(isinstance(v,auto)for v in value):\n \n \n auto_valued=[]\n t=type(value)\n for v in value:\n if isinstance(v,auto):\n non_auto_store=False\n if v.value ==_auto_null:\n v.value=self._generate_next_value(\n key,1,len(self._member_names),self._last_values[:],\n )\n self._auto_called=True\n v=v.value\n self._last_values.append(v)\n auto_valued.append(v)\n if single:\n value=auto_valued[0]\n else:\n try:\n \n value=t(auto_valued)\n except TypeError:\n \n value=t(*auto_valued)\n self._member_names[key]=None\n if non_auto_store:\n self._last_values.append(value)\n super().__setitem__(key,value)\n \n @property\n def member_names(self):\n return list(self._member_names)\n \n def update(self,members,**more_members):\n try:\n for name in members.keys():\n self[name]=members[name]\n except AttributeError:\n for name,value in members:\n self[name]=value\n for name,value in more_members.items():\n self[name]=value\n \n_EnumDict=EnumDict\n\n\nclass EnumType(type):\n ''\n\n \n \n @classmethod\n def __prepare__(metacls,cls,bases,**kwds):\n \n metacls._check_for_existing_members_(cls,bases)\n \n enum_dict=EnumDict()\n enum_dict._cls_name=cls\n \n member_type,first_enum=metacls._get_mixins_(cls,bases)\n if first_enum is not None:\n enum_dict['_generate_next_value_']=getattr(\n first_enum,'_generate_next_value_',None,\n )\n return enum_dict\n \n def __new__(metacls,cls,bases,classdict,*,boundary=None,_simple=False,**kwds):\n \n \n \n \n \n if _simple:\n return super().__new__(metacls,cls,bases,classdict,**kwds)\n \n \n classdict.setdefault('_ignore_',[]).append('_ignore_')\n ignore=classdict['_ignore_']\n for key in ignore:\n classdict.pop(key,None)\n \n \n member_names=classdict._member_names\n \n \n invalid_names=set(member_names)&{'mro',''}\n if invalid_names:\n raise ValueError('invalid enum member name(s) %s'%(\n ','.join(repr(n)for n in invalid_names)\n ))\n \n \n _order_=classdict.pop('_order_',None)\n _gnv=classdict.get('_generate_next_value_')\n if _gnv is not None and type(_gnv)is not staticmethod:\n _gnv=staticmethod(_gnv)\n \n classdict=dict(classdict.items())\n if _gnv is not None:\n classdict['_generate_next_value_']=_gnv\n \n \n member_type,first_enum=metacls._get_mixins_(cls,bases)\n __new__,save_new,use_args=metacls._find_new_(\n classdict,member_type,first_enum,\n )\n classdict['_new_member_']=__new__\n classdict['_use_args_']=use_args\n \n \n for name in member_names:\n value=classdict[name]\n classdict[name]=_proto_member(value)\n \n \n classdict['_member_names_']=[]\n classdict['_member_map_']={}\n classdict['_value2member_map_']={}\n classdict['_unhashable_values_']=[]\n classdict['_unhashable_values_map_']={}\n classdict['_member_type_']=member_type\n \n classdict['_value_repr_']=metacls._find_data_repr_(cls,bases)\n \n \n classdict['_boundary_']=(\n boundary\n or getattr(first_enum,'_boundary_',None)\n )\n classdict['_flag_mask_']=0\n classdict['_singles_mask_']=0\n classdict['_all_bits_']=0\n classdict['_inverted_']=None\n try:\n exc=None\n classdict['_%s__in_progress'%cls]=True\n enum_class=super().__new__(metacls,cls,bases,classdict,**kwds)\n classdict['_%s__in_progress'%cls]=False\n delattr(enum_class,'_%s__in_progress'%cls)\n except Exception as e:\n \n \n \n exc=type(e)(str(e))\n exc.__cause__=e.__cause__\n exc.__context__=e.__context__\n tb=e.__traceback__\n if exc is not None:\n raise exc.with_traceback(tb)\n \n \n classdict.update(enum_class.__dict__)\n \n \n \n \n \n \n \n if ReprEnum is not None and ReprEnum in bases:\n if member_type is object:\n raise TypeError(\n 'ReprEnum subclasses must be mixed with a data type (i.e.'\n ' int, str, float, etc.)'\n )\n if '__format__'not in classdict:\n enum_class.__format__=member_type.__format__\n classdict['__format__']=enum_class.__format__\n if '__str__'not in classdict:\n method=member_type.__str__\n if method is object.__str__:\n \n \n method=member_type.__repr__\n enum_class.__str__=method\n classdict['__str__']=enum_class.__str__\n for name in('__repr__','__str__','__format__','__reduce_ex__'):\n if name not in classdict:\n \n enum_method=getattr(first_enum,name)\n found_method=getattr(enum_class,name)\n object_method=getattr(object,name)\n data_type_method=getattr(member_type,name)\n if found_method in(data_type_method,object_method):\n setattr(enum_class,name,enum_method)\n \n \n if Flag is not None and issubclass(enum_class,Flag):\n for name in(\n '__or__','__and__','__xor__',\n '__ror__','__rand__','__rxor__',\n '__invert__'\n ):\n if name not in classdict:\n enum_method=getattr(Flag,name)\n setattr(enum_class,name,enum_method)\n classdict[name]=enum_method\n \n \n \n if Enum is not None:\n \n \n if save_new:\n enum_class.__new_member__=__new__\n enum_class.__new__=Enum.__new__\n \n \n \n \n \n \n \n \n \n \n if _order_ is not None:\n if isinstance(_order_,str):\n _order_=_order_.replace(',',' ').split()\n \n \n if(\n Flag is None and cls !='Flag'\n or Flag is not None and not issubclass(enum_class,Flag)\n ):\n delattr(enum_class,'_boundary_')\n delattr(enum_class,'_flag_mask_')\n delattr(enum_class,'_singles_mask_')\n delattr(enum_class,'_all_bits_')\n delattr(enum_class,'_inverted_')\n elif Flag is not None and issubclass(enum_class,Flag):\n \n member_list=[m._value_ for m in enum_class]\n if member_list !=sorted(member_list):\n enum_class._iter_member_=enum_class._iter_member_by_def_\n if _order_:\n \n _order_=[\n o\n for o in _order_\n if o not in enum_class._member_map_ or _is_single_bit(enum_class[o]._value_)\n ]\n \n if _order_:\n \n _order_=[\n o\n for o in _order_\n if(\n o not in enum_class._member_map_\n or\n (o in enum_class._member_map_ and o in enum_class._member_names_)\n )]\n \n if _order_ !=enum_class._member_names_:\n raise TypeError(\n 'member order does not match _order_:\\n %r\\n %r'\n %(enum_class._member_names_,_order_)\n )\n \n return enum_class\n \n def __bool__(cls):\n ''\n\n \n return True\n \n def __call__(cls,value,names=_not_given,*values,module=None,qualname=None,type=None,start=1,boundary=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if cls._member_map_:\n \n if names is not _not_given:\n value=(value,names)+values\n return cls.__new__(cls,value)\n \n if names is _not_given and type is None:\n \n raise TypeError(\n f\"{cls} has no members; specify `names=()` if you meant to create a new, empty, enum\"\n )\n return cls._create_(\n class_name=value,\n names=None if names is _not_given else names,\n module=module,\n qualname=qualname,\n type=type,\n start=start,\n boundary=boundary,\n )\n \n def __contains__(cls,value):\n ''\n\n\n\n\n \n if isinstance(value,cls):\n return True\n try:\n return value in cls._value2member_map_\n except TypeError:\n return value in cls._unhashable_values_\n \n def __delattr__(cls,attr):\n \n \n if attr in cls._member_map_:\n raise AttributeError(\"%r cannot delete member %r.\"%(cls.__name__,attr))\n super().__delattr__(attr)\n \n def __dir__(cls):\n interesting=set([\n '__class__','__contains__','__doc__','__getitem__',\n '__iter__','__len__','__members__','__module__',\n '__name__','__qualname__',\n ]\n +cls._member_names_\n )\n if cls._new_member_ is not object.__new__:\n interesting.add('__new__')\n if cls.__init_subclass__ is not object.__init_subclass__:\n interesting.add('__init_subclass__')\n if cls._member_type_ is object:\n return sorted(interesting)\n else:\n \n return sorted(set(dir(cls._member_type_))|interesting)\n \n def __getitem__(cls,name):\n ''\n\n \n return cls._member_map_[name]\n \n def __iter__(cls):\n ''\n\n \n return(cls._member_map_[name]for name in cls._member_names_)\n \n def __len__(cls):\n ''\n\n \n return len(cls._member_names_)\n \n @bltns.property\n def __members__(cls):\n ''\n\n\n\n\n \n return MappingProxyType(cls._member_map_)\n \n def __repr__(cls):\n if Flag is not None and issubclass(cls,Flag):\n return \"\"%cls.__name__\n else:\n return \"\"%cls.__name__\n \n def __reversed__(cls):\n ''\n\n \n return(cls._member_map_[name]for name in reversed(cls._member_names_))\n \n def __setattr__(cls,name,value):\n ''\n\n\n\n\n\n \n member_map=cls.__dict__.get('_member_map_',{})\n if name in member_map:\n raise AttributeError('cannot reassign member %r'%(name,))\n super().__setattr__(name,value)\n \n def _create_(cls,class_name,names,*,module=None,qualname=None,type=None,start=1,boundary=None):\n ''\n\n\n\n\n\n\n\n\n\n \n metacls=cls.__class__\n bases=(cls,)if type is None else(type,cls)\n _,first_enum=cls._get_mixins_(class_name,bases)\n classdict=metacls.__prepare__(class_name,bases)\n \n \n if isinstance(names,str):\n names=names.replace(',',' ').split()\n if isinstance(names,(tuple,list))and names and isinstance(names[0],str):\n original_names,names=names,[]\n last_values=[]\n for count,name in enumerate(original_names):\n value=first_enum._generate_next_value_(name,start,count,last_values[:])\n last_values.append(value)\n names.append((name,value))\n if names is None:\n names=()\n \n \n for item in names:\n if isinstance(item,str):\n member_name,member_value=item,names[item]\n else:\n member_name,member_value=item\n classdict[member_name]=member_value\n \n if module is None:\n try:\n module=sys._getframemodulename(2)\n except AttributeError:\n \n try:\n module=sys._getframe(2).f_globals['__name__']\n except(AttributeError,ValueError,KeyError):\n pass\n if module is None:\n _make_class_unpicklable(classdict)\n else:\n classdict['__module__']=module\n if qualname is not None:\n classdict['__qualname__']=qualname\n \n return metacls.__new__(metacls,class_name,bases,classdict,boundary=boundary)\n \n def _convert_(cls,name,module,filter,source=None,*,boundary=None,as_global=False):\n ''\n\n \n \n \n \n \n \n module_globals=sys.modules[module].__dict__\n if source:\n source=source.__dict__\n else:\n source=module_globals\n \n \n \n members=[\n (name,value)\n for name,value in source.items()\n if filter(name)]\n try:\n \n members.sort(key=lambda t:(t[1],t[0]))\n except TypeError:\n \n members.sort(key=lambda t:t[0])\n body={t[0]:t[1]for t in members}\n body['__module__']=module\n tmp_cls=type(name,(object,),body)\n cls=_simple_enum(etype=cls,boundary=boundary or KEEP)(tmp_cls)\n if as_global:\n global_enum(cls)\n else:\n sys.modules[cls.__module__].__dict__.update(cls.__members__)\n module_globals[name]=cls\n return cls\n \n @classmethod\n def _check_for_existing_members_(mcls,class_name,bases):\n for chain in bases:\n for base in chain.__mro__:\n if isinstance(base,EnumType)and base._member_names_:\n raise TypeError(\n \" cannot extend %r\"\n %(class_name,base)\n )\n \n @classmethod\n def _get_mixins_(mcls,class_name,bases):\n ''\n\n\n\n\n \n if not bases:\n return object,Enum\n \n \n first_enum=bases[-1]\n if not isinstance(first_enum,EnumType):\n raise TypeError(\"new enumerations should be created as \"\n \"`EnumName([mixin_type, ...] [data_type,] enum_type)`\")\n member_type=mcls._find_data_type_(class_name,bases)or object\n return member_type,first_enum\n \n @classmethod\n def _find_data_repr_(mcls,class_name,bases):\n for chain in bases:\n for base in chain.__mro__:\n if base is object:\n continue\n elif isinstance(base,EnumType):\n \n return base._value_repr_\n elif '__repr__'in base.__dict__:\n \n \n if(\n '__dataclass_fields__'in base.__dict__\n and '__dataclass_params__'in base.__dict__\n and base.__dict__['__dataclass_params__'].repr\n ):\n return _dataclass_repr\n else:\n return base.__dict__['__repr__']\n return None\n \n @classmethod\n def _find_data_type_(mcls,class_name,bases):\n \n data_types=set()\n base_chain=set()\n for chain in bases:\n candidate=None\n for base in chain.__mro__:\n base_chain.add(base)\n if base is object:\n continue\n elif isinstance(base,EnumType):\n if base._member_type_ is not object:\n data_types.add(base._member_type_)\n break\n elif '__new__'in base.__dict__ or '__dataclass_fields__'in base.__dict__:\n data_types.add(candidate or base)\n break\n else:\n candidate=candidate or base\n if len(data_types)>1:\n raise TypeError('too many data types for %r: %r'%(class_name,data_types))\n elif data_types:\n return data_types.pop()\n else:\n return None\n \n @classmethod\n def _find_new_(mcls,classdict,member_type,first_enum):\n ''\n\n\n\n\n\n \n \n \n \n __new__=classdict.get('__new__',None)\n \n \n save_new=first_enum is not None and __new__ is not None\n \n if __new__ is None:\n \n \n for method in('__new_member__','__new__'):\n for possible in(member_type,first_enum):\n target=getattr(possible,method,None)\n if target not in{\n None,\n None.__new__,\n object.__new__,\n Enum.__new__,\n }:\n __new__=target\n break\n if __new__ is not None:\n break\n else:\n __new__=object.__new__\n \n \n \n \n if first_enum is None or __new__ in(Enum.__new__,object.__new__):\n use_args=False\n else:\n use_args=True\n return __new__,save_new,use_args\n \n def _add_member_(cls,name,member):\n \n if name in cls._member_map_:\n if cls._member_map_[name]is not member:\n raise NameError('%r is already bound: %r'%(name,cls._member_map_[name]))\n return\n \n \n found_descriptor=None\n descriptor_type=None\n class_type=None\n for base in cls.__mro__[1:]:\n attr=base.__dict__.get(name)\n if attr is not None:\n if isinstance(attr,(property,DynamicClassAttribute)):\n found_descriptor=attr\n class_type=base\n descriptor_type='enum'\n break\n elif _is_descriptor(attr):\n found_descriptor=attr\n descriptor_type=descriptor_type or 'desc'\n class_type=class_type or base\n continue\n else:\n descriptor_type='attr'\n class_type=base\n if found_descriptor:\n redirect=property()\n redirect.member=member\n redirect.__set_name__(cls,name)\n if descriptor_type in('enum','desc'):\n \n redirect.fget=getattr(found_descriptor,'fget',None)\n redirect._get=getattr(found_descriptor,'__get__',None)\n redirect.fset=getattr(found_descriptor,'fset',None)\n redirect._set=getattr(found_descriptor,'__set__',None)\n redirect.fdel=getattr(found_descriptor,'fdel',None)\n redirect._del=getattr(found_descriptor,'__delete__',None)\n redirect._attr_type=descriptor_type\n redirect._cls_type=class_type\n setattr(cls,name,redirect)\n else:\n setattr(cls,name,member)\n \n cls._member_map_[name]=member\n \nEnumMeta=EnumType\n\n\nclass Enum(metaclass=EnumType):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n @classmethod\n def __signature__(cls):\n if cls._member_names_:\n return '(*values)'\n else:\n return '(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)'\n \n def __new__(cls,value):\n \n \n \n if type(value)is cls:\n \n return value\n \n \n try:\n return cls._value2member_map_[value]\n except KeyError:\n \n pass\n except TypeError:\n \n for name,values in cls._unhashable_values_map_.items():\n if value in values:\n return cls[name]\n \n \n if not cls._member_map_:\n if getattr(cls,'_%s__in_progress'%cls.__name__,False):\n raise TypeError('do not use `super().__new__; call the appropriate __new__ directly')from None\n raise TypeError(\"%r has no members defined\"%cls)\n \n \n try:\n exc=None\n result=cls._missing_(value)\n except Exception as e:\n exc=e\n result=None\n try:\n if isinstance(result,cls):\n return result\n elif(\n Flag is not None and issubclass(cls,Flag)\n and cls._boundary_ is EJECT and isinstance(result,int)\n ):\n return result\n else:\n ve_exc=ValueError(\"%r is not a valid %s\"%(value,cls.__qualname__))\n if result is None and exc is None:\n raise ve_exc\n elif exc is None:\n exc=TypeError(\n 'error in %s._missing_: returned %r instead of None or a valid member'\n %(cls.__name__,result)\n )\n if not isinstance(exc,ValueError):\n exc.__context__=ve_exc\n raise exc\n finally:\n \n exc=None\n ve_exc=None\n \n def __init__(self,*args,**kwds):\n pass\n \n def _add_alias_(self,name):\n self.__class__._add_member_(name,self)\n \n def _add_value_alias_(self,value):\n cls=self.__class__\n try:\n if value in cls._value2member_map_:\n if cls._value2member_map_[value]is not self:\n raise ValueError('%r is already bound: %r'%(value,cls._value2member_map_[value]))\n return\n except TypeError:\n \n for m in cls._member_map_.values():\n if m._value_ ==value:\n if m is not self:\n raise ValueError('%r is already bound: %r'%(value,cls._value2member_map_[value]))\n return\n try:\n \n \n \n cls._value2member_map_.setdefault(value,self)\n except TypeError:\n \n cls._unhashable_values_.append(value)\n cls._unhashable_values_map_.setdefault(self.name,[]).append(value)\n \n @staticmethod\n def _generate_next_value_(name,start,count,last_values):\n ''\n\n\n\n\n\n\n \n if not last_values:\n return start\n try:\n last_value=sorted(last_values).pop()\n except TypeError:\n raise TypeError('unable to sort non-numeric values')from None\n try:\n return last_value+1\n except TypeError:\n raise TypeError('unable to increment %r'%(last_value,))from None\n \n @classmethod\n def _missing_(cls,value):\n return None\n \n def __repr__(self):\n v_repr=self.__class__._value_repr_ or repr\n return \"<%s.%s: %s>\"%(self.__class__.__name__,self._name_,v_repr(self._value_))\n \n def __str__(self):\n return \"%s.%s\"%(self.__class__.__name__,self._name_,)\n \n def __dir__(self):\n ''\n\n \n interesting=set()\n if self.__class__._member_type_ is not object:\n interesting=set(object.__dir__(self))\n for name in getattr(self,'__dict__',[]):\n if name[0]!='_'and name not in self._member_map_:\n interesting.add(name)\n for cls in self.__class__.mro():\n for name,obj in cls.__dict__.items():\n if name[0]=='_':\n continue\n if isinstance(obj,property):\n \n if obj.fget is not None or name not in self._member_map_:\n interesting.add(name)\n else:\n \n interesting.discard(name)\n elif name not in self._member_map_:\n interesting.add(name)\n names=sorted(\n set(['__class__','__doc__','__eq__','__hash__','__module__'])\n |interesting\n )\n return names\n \n def __format__(self,format_spec):\n return str.__format__(str(self),format_spec)\n \n def __hash__(self):\n return hash(self._name_)\n \n def __reduce_ex__(self,proto):\n return self.__class__,(self._value_,)\n \n def __deepcopy__(self,memo):\n return self\n \n def __copy__(self):\n return self\n \n \n \n \n \n \n \n \n \n @property\n def name(self):\n ''\n return self._name_\n \n @property\n def value(self):\n ''\n return self._value_\n \n \nclass ReprEnum(Enum):\n ''\n\n \n \n \nclass IntEnum(int,ReprEnum):\n ''\n\n \n \n \nclass StrEnum(str,ReprEnum):\n ''\n\n \n \n def __new__(cls,*values):\n ''\n if len(values)>3:\n raise TypeError('too many arguments for str(): %r'%(values,))\n if len(values)==1:\n \n if not isinstance(values[0],str):\n raise TypeError('%r is not a string'%(values[0],))\n if len(values)>=2:\n \n if not isinstance(values[1],str):\n raise TypeError('encoding must be a string, not %r'%(values[1],))\n if len(values)==3:\n \n if not isinstance(values[2],str):\n raise TypeError('errors must be a string, not %r'%(values[2]))\n value=str(*values)\n member=str.__new__(cls,value)\n member._value_=value\n return member\n \n @staticmethod\n def _generate_next_value_(name,start,count,last_values):\n ''\n\n \n return name.lower()\n \n \ndef pickle_by_global_name(self,proto):\n\n return self.name\n_reduce_ex_by_global_name=pickle_by_global_name\n\ndef pickle_by_enum_name(self,proto):\n\n return getattr,(self.__class__,self._name_)\n \nclass FlagBoundary(StrEnum):\n ''\n\n\n\n\n\n \n STRICT=auto()\n CONFORM=auto()\n EJECT=auto()\n KEEP=auto()\nSTRICT,CONFORM,EJECT,KEEP=FlagBoundary\n\n\nclass Flag(Enum,boundary=STRICT):\n ''\n\n \n \n _numeric_repr_=repr\n \n @staticmethod\n def _generate_next_value_(name,start,count,last_values):\n ''\n\n\n\n\n\n\n \n if not count:\n return start if start is not None else 1\n last_value=max(last_values)\n try:\n high_bit=_high_bit(last_value)\n except Exception:\n raise TypeError('invalid flag value %r'%last_value)from None\n return 2 **(high_bit+1)\n \n @classmethod\n def _iter_member_by_value_(cls,value):\n ''\n\n \n for val in _iter_bits_lsb(value&cls._flag_mask_):\n yield cls._value2member_map_.get(val)\n \n _iter_member_=_iter_member_by_value_\n \n @classmethod\n def _iter_member_by_def_(cls,value):\n ''\n\n \n yield from sorted(\n cls._iter_member_by_value_(value),\n key=lambda m:m._sort_order_,\n )\n \n @classmethod\n def _missing_(cls,value):\n ''\n\n\n\n \n if not isinstance(value,int):\n raise ValueError(\n \"%r is not a valid %s\"%(value,cls.__qualname__)\n )\n \n \n \n \n flag_mask=cls._flag_mask_\n singles_mask=cls._singles_mask_\n all_bits=cls._all_bits_\n neg_value=None\n if(\n not ~all_bits <=value <=all_bits\n or value&(all_bits ^flag_mask)\n ):\n if cls._boundary_ is STRICT:\n max_bits=max(value.bit_length(),flag_mask.bit_length())\n raise ValueError(\n \"%r invalid value %r\\n given %s\\n allowed %s\"%(\n cls,value,bin(value,max_bits),bin(flag_mask,max_bits),\n ))\n elif cls._boundary_ is CONFORM:\n value=value&flag_mask\n elif cls._boundary_ is EJECT:\n return value\n elif cls._boundary_ is KEEP:\n if value <0:\n value=(\n max(all_bits+1,2 **(value.bit_length()))\n +value\n )\n else:\n raise ValueError(\n '%r unknown flag boundary %r'%(cls,cls._boundary_,)\n )\n if value <0:\n neg_value=value\n value=all_bits+1+value\n \n unknown=value&~flag_mask\n aliases=value&~singles_mask\n member_value=value&singles_mask\n if unknown and cls._boundary_ is not KEEP:\n raise ValueError(\n '%s(%r) --> unknown values %r [%s]'\n %(cls.__name__,value,unknown,bin(unknown))\n )\n \n if cls._member_type_ is object:\n \n pseudo_member=object.__new__(cls)\n else:\n pseudo_member=cls._member_type_.__new__(cls,value)\n if not hasattr(pseudo_member,'_value_'):\n pseudo_member._value_=value\n if member_value or aliases:\n members=[]\n combined_value=0\n for m in cls._iter_member_(member_value):\n members.append(m)\n combined_value |=m._value_\n if aliases:\n value=member_value |aliases\n for n,pm in cls._member_map_.items():\n if pm not in members and pm._value_ and pm._value_&value ==pm._value_:\n members.append(pm)\n combined_value |=pm._value_\n unknown=value ^combined_value\n pseudo_member._name_='|'.join([m._name_ for m in members])\n if not combined_value:\n pseudo_member._name_=None\n elif unknown and cls._boundary_ is STRICT:\n raise ValueError('%r: no members with value %r'%(cls,unknown))\n elif unknown:\n pseudo_member._name_ +='|%s'%cls._numeric_repr_(unknown)\n else:\n pseudo_member._name_=None\n \n \n \n pseudo_member=cls._value2member_map_.setdefault(value,pseudo_member)\n if neg_value is not None:\n cls._value2member_map_[neg_value]=pseudo_member\n return pseudo_member\n \n def __contains__(self,other):\n ''\n\n \n if not isinstance(other,self.__class__):\n raise TypeError(\n \"unsupported operand type(s) for 'in': %r and %r\"%(\n type(other).__qualname__,self.__class__.__qualname__))\n return other._value_&self._value_ ==other._value_\n \n def __iter__(self):\n ''\n\n \n yield from self._iter_member_(self._value_)\n \n def __len__(self):\n return self._value_.bit_count()\n \n def __repr__(self):\n cls_name=self.__class__.__name__\n v_repr=self.__class__._value_repr_ or repr\n if self._name_ is None:\n return \"<%s: %s>\"%(cls_name,v_repr(self._value_))\n else:\n return \"<%s.%s: %s>\"%(cls_name,self._name_,v_repr(self._value_))\n \n def __str__(self):\n cls_name=self.__class__.__name__\n if self._name_ is None:\n return '%s(%r)'%(cls_name,self._value_)\n else:\n return \"%s.%s\"%(cls_name,self._name_)\n \n def __bool__(self):\n return bool(self._value_)\n \n def _get_value(self,flag):\n if isinstance(flag,self.__class__):\n return flag._value_\n elif self._member_type_ is not object and isinstance(flag,self._member_type_):\n return flag\n return NotImplemented\n \n def __or__(self,other):\n other_value=self._get_value(other)\n if other_value is NotImplemented:\n return NotImplemented\n \n for flag in self,other:\n if self._get_value(flag)is None:\n raise TypeError(f\"'{flag}' cannot be combined with other flags with |\")\n value=self._value_\n return self.__class__(value |other_value)\n \n def __and__(self,other):\n other_value=self._get_value(other)\n if other_value is NotImplemented:\n return NotImplemented\n \n for flag in self,other:\n if self._get_value(flag)is None:\n raise TypeError(f\"'{flag}' cannot be combined with other flags with &\")\n value=self._value_\n return self.__class__(value&other_value)\n \n def __xor__(self,other):\n other_value=self._get_value(other)\n if other_value is NotImplemented:\n return NotImplemented\n \n for flag in self,other:\n if self._get_value(flag)is None:\n raise TypeError(f\"'{flag}' cannot be combined with other flags with ^\")\n value=self._value_\n return self.__class__(value ^other_value)\n \n def __invert__(self):\n if self._get_value(self)is None:\n raise TypeError(f\"'{self}' cannot be inverted\")\n \n if self._inverted_ is None:\n if self._boundary_ in(EJECT,KEEP):\n self._inverted_=self.__class__(~self._value_)\n else:\n self._inverted_=self.__class__(self._singles_mask_&~self._value_)\n return self._inverted_\n \n __rand__=__and__\n __ror__=__or__\n __rxor__=__xor__\n \n \nclass IntFlag(int,ReprEnum,Flag,boundary=KEEP):\n ''\n\n \n \n \ndef _high_bit(value):\n ''\n\n \n return value.bit_length()-1\n \ndef unique(enumeration):\n ''\n\n \n duplicates=[]\n for name,member in enumeration.__members__.items():\n if name !=member.name:\n duplicates.append((name,member.name))\n if duplicates:\n alias_details=', '.join(\n [\"%s -> %s\"%(alias,name)for(alias,name)in duplicates])\n raise ValueError('duplicate values found in %r: %s'%\n (enumeration,alias_details))\n return enumeration\n \ndef _dataclass_repr(self):\n dcf=self.__dataclass_fields__\n return ', '.join(\n '%s=%r'%(k,getattr(self,k))\n for k in dcf.keys()\n if dcf[k].repr\n )\n \ndef global_enum_repr(self):\n ''\n\n\n\n \n module=self.__class__.__module__.split('.')[-1]\n return '%s.%s'%(module,self._name_)\n \ndef global_flag_repr(self):\n ''\n\n\n\n \n module=self.__class__.__module__.split('.')[-1]\n cls_name=self.__class__.__name__\n if self._name_ is None:\n return \"%s.%s(%r)\"%(module,cls_name,self._value_)\n if _is_single_bit(self._value_):\n return '%s.%s'%(module,self._name_)\n if self._boundary_ is not FlagBoundary.KEEP:\n return '|'.join(['%s.%s'%(module,name)for name in self.name.split('|')])\n else:\n name=[]\n for n in self._name_.split('|'):\n if n[0].isdigit():\n name.append(n)\n else:\n name.append('%s.%s'%(module,n))\n return '|'.join(name)\n \ndef global_str(self):\n ''\n\n \n if self._name_ is None:\n cls_name=self.__class__.__name__\n return \"%s(%r)\"%(cls_name,self._value_)\n else:\n return self._name_\n \ndef global_enum(cls,update_str=False):\n ''\n\n\n\n \n if issubclass(cls,Flag):\n cls.__repr__=global_flag_repr\n else:\n cls.__repr__=global_enum_repr\n if not issubclass(cls,ReprEnum)or update_str:\n cls.__str__=global_str\n sys.modules[cls.__module__].__dict__.update(cls.__members__)\n return cls\n \ndef _simple_enum(etype=Enum,*,boundary=None,use_args=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def convert_class(cls):\n nonlocal use_args\n cls_name=cls.__name__\n if use_args is None:\n use_args=etype._use_args_\n __new__=cls.__dict__.get('__new__')\n if __new__ is not None:\n new_member=__new__.__func__\n else:\n new_member=etype._member_type_.__new__\n attrs={}\n body={}\n if __new__ is not None:\n body['__new_member__']=new_member\n body['_new_member_']=new_member\n body['_use_args_']=use_args\n body['_generate_next_value_']=gnv=etype._generate_next_value_\n body['_member_names_']=member_names=[]\n body['_member_map_']=member_map={}\n body['_value2member_map_']=value2member_map={}\n body['_unhashable_values_']=unhashable_values=[]\n body['_unhashable_values_map_']={}\n body['_member_type_']=member_type=etype._member_type_\n body['_value_repr_']=etype._value_repr_\n if issubclass(etype,Flag):\n body['_boundary_']=boundary or etype._boundary_\n body['_flag_mask_']=None\n body['_all_bits_']=None\n body['_singles_mask_']=None\n body['_inverted_']=None\n body['__or__']=Flag.__or__\n body['__xor__']=Flag.__xor__\n body['__and__']=Flag.__and__\n body['__ror__']=Flag.__ror__\n body['__rxor__']=Flag.__rxor__\n body['__rand__']=Flag.__rand__\n body['__invert__']=Flag.__invert__\n for name,obj in cls.__dict__.items():\n if name in('__dict__','__weakref__'):\n continue\n if _is_dunder(name)or _is_private(cls_name,name)or _is_sunder(name)or _is_descriptor(obj):\n body[name]=obj\n else:\n attrs[name]=obj\n if cls.__dict__.get('__doc__')is None:\n body['__doc__']='An enumeration.'\n \n \n \n \n \n enum_class=type(cls_name,(etype,),body,boundary=boundary,_simple=True)\n for name in('__repr__','__str__','__format__','__reduce_ex__'):\n if name not in body:\n \n enum_method=getattr(etype,name)\n found_method=getattr(enum_class,name)\n object_method=getattr(object,name)\n data_type_method=getattr(member_type,name)\n if found_method in(data_type_method,object_method):\n setattr(enum_class,name,enum_method)\n gnv_last_values=[]\n if issubclass(enum_class,Flag):\n \n single_bits=multi_bits=0\n for name,value in attrs.items():\n if isinstance(value,auto)and auto.value is _auto_null:\n value=gnv(name,1,len(member_names),gnv_last_values)\n \n if use_args:\n if not isinstance(value,tuple):\n value=(value,)\n member=new_member(enum_class,*value)\n value=value[0]\n else:\n member=new_member(enum_class)\n if __new__ is None:\n member._value_=value\n \n try:\n contained=value2member_map.get(member._value_)\n except TypeError:\n contained=None\n if member._value_ in unhashable_values:\n for m in enum_class:\n if m._value_ ==member._value_:\n contained=m\n break\n if contained is not None:\n \n contained._add_alias_(name)\n else:\n \n member._name_=name\n member.__objclass__=enum_class\n member.__init__(value)\n member._sort_order_=len(member_names)\n if name not in('name','value'):\n setattr(enum_class,name,member)\n member_map[name]=member\n else:\n enum_class._add_member_(name,member)\n value2member_map[value]=member\n if _is_single_bit(value):\n \n member_names.append(name)\n single_bits |=value\n else:\n multi_bits |=value\n gnv_last_values.append(value)\n enum_class._flag_mask_=single_bits |multi_bits\n enum_class._singles_mask_=single_bits\n enum_class._all_bits_=2 **((single_bits |multi_bits).bit_length())-1\n \n member_list=[m._value_ for m in enum_class]\n if member_list !=sorted(member_list):\n enum_class._iter_member_=enum_class._iter_member_by_def_\n else:\n \n for name,value in attrs.items():\n if isinstance(value,auto):\n if value.value is _auto_null:\n value.value=gnv(name,1,len(member_names),gnv_last_values)\n value=value.value\n \n if use_args:\n if not isinstance(value,tuple):\n value=(value,)\n member=new_member(enum_class,*value)\n value=value[0]\n else:\n member=new_member(enum_class)\n if __new__ is None:\n member._value_=value\n \n try:\n contained=value2member_map.get(member._value_)\n except TypeError:\n contained=None\n if member._value_ in unhashable_values:\n for m in enum_class:\n if m._value_ ==member._value_:\n contained=m\n break\n if contained is not None:\n \n contained._add_alias_(name)\n else:\n \n member._name_=name\n member.__objclass__=enum_class\n member.__init__(value)\n member._sort_order_=len(member_names)\n if name not in('name','value'):\n setattr(enum_class,name,member)\n member_map[name]=member\n else:\n enum_class._add_member_(name,member)\n member_names.append(name)\n gnv_last_values.append(value)\n try:\n \n \n \n enum_class._value2member_map_.setdefault(value,member)\n except TypeError:\n \n enum_class._unhashable_values_.append(value)\n enum_class._unhashable_values_map_.setdefault(name,[]).append(value)\n if '__new__'in body:\n enum_class.__new_member__=enum_class.__new__\n enum_class.__new__=Enum.__new__\n return enum_class\n return convert_class\n \n@_simple_enum(StrEnum)\nclass EnumCheck:\n ''\n\n \n CONTINUOUS=\"no skipped integer values\"\n NAMED_FLAGS=\"multi-flag aliases may not contain unnamed flags\"\n UNIQUE=\"one name per value\"\nCONTINUOUS,NAMED_FLAGS,UNIQUE=EnumCheck\n\n\nclass verify:\n ''\n\n \n def __init__(self,*checks):\n self.checks=checks\n def __call__(self,enumeration):\n checks=self.checks\n cls_name=enumeration.__name__\n if Flag is not None and issubclass(enumeration,Flag):\n enum_type='flag'\n elif issubclass(enumeration,Enum):\n enum_type='enum'\n else:\n raise TypeError(\"the 'verify' decorator only works with Enum and Flag\")\n for check in checks:\n if check is UNIQUE:\n \n duplicates=[]\n for name,member in enumeration.__members__.items():\n if name !=member.name:\n duplicates.append((name,member.name))\n if duplicates:\n alias_details=', '.join(\n [\"%s -> %s\"%(alias,name)for(alias,name)in duplicates])\n raise ValueError('aliases found in %r: %s'%\n (enumeration,alias_details))\n elif check is CONTINUOUS:\n values=set(e.value for e in enumeration)\n if len(values)<2:\n continue\n low,high=min(values),max(values)\n missing=[]\n if enum_type =='flag':\n \n for i in range(_high_bit(low)+1,_high_bit(high)):\n if 2 **i not in values:\n missing.append(2 **i)\n elif enum_type =='enum':\n \n for i in range(low+1,high):\n if i not in values:\n missing.append(i)\n else:\n raise Exception('verify: unknown type %r'%enum_type)\n if missing:\n raise ValueError(('invalid %s %r: missing values %s'%(\n enum_type,cls_name,', '.join((str(m)for m in missing)))\n )[:256])\n \n elif check is NAMED_FLAGS:\n \n member_names=enumeration._member_names_\n member_values=[m.value for m in enumeration]\n missing_names=[]\n missing_value=0\n for name,alias in enumeration._member_map_.items():\n if name in member_names:\n \n continue\n if alias.value <0:\n \n continue\n values=list(_iter_bits_lsb(alias.value))\n missed=[v for v in values if v not in member_values]\n if missed:\n missing_names.append(name)\n for val in missed:\n missing_value |=val\n if missing_names:\n if len(missing_names)==1:\n alias='alias %s is missing'%missing_names[0]\n else:\n alias='aliases %s and %s are missing'%(\n ', '.join(missing_names[:-1]),missing_names[-1]\n )\n if _is_single_bit(missing_value):\n value='value 0x%x'%missing_value\n else:\n value='combined values of 0x%x'%missing_value\n raise ValueError(\n 'invalid Flag %r: %s %s [use enum.show_flag_values(value) for details]'\n %(cls_name,alias,value)\n )\n return enumeration\n \ndef _test_simple_enum(checked_enum,simple_enum):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n failed=[]\n if checked_enum.__dict__ !=simple_enum.__dict__:\n checked_dict=checked_enum.__dict__\n checked_keys=list(checked_dict.keys())\n simple_dict=simple_enum.__dict__\n simple_keys=list(simple_dict.keys())\n member_names=set(\n list(checked_enum._member_map_.keys())\n +list(simple_enum._member_map_.keys())\n )\n for key in set(checked_keys+simple_keys):\n if key in('__module__','_member_map_','_value2member_map_','__doc__',\n '__static_attributes__','__firstlineno__'):\n \n continue\n elif key in member_names:\n \n continue\n elif key not in simple_keys:\n failed.append(\"missing key: %r\"%(key,))\n elif key not in checked_keys:\n failed.append(\"extra key: %r\"%(key,))\n else:\n checked_value=checked_dict[key]\n simple_value=simple_dict[key]\n if callable(checked_value)or isinstance(checked_value,bltns.property):\n continue\n if key =='__doc__':\n \n compressed_checked_value=checked_value.replace(' ','').replace('\\t','')\n compressed_simple_value=simple_value.replace(' ','').replace('\\t','')\n if compressed_checked_value !=compressed_simple_value:\n failed.append(\"%r:\\n %s\\n %s\"%(\n key,\n \"checked -> %r\"%(checked_value,),\n \"simple -> %r\"%(simple_value,),\n ))\n elif checked_value !=simple_value:\n failed.append(\"%r:\\n %s\\n %s\"%(\n key,\n \"checked -> %r\"%(checked_value,),\n \"simple -> %r\"%(simple_value,),\n ))\n failed.sort()\n for name in member_names:\n failed_member=[]\n if name not in simple_keys:\n failed.append('missing member from simple enum: %r'%name)\n elif name not in checked_keys:\n failed.append('extra member in simple enum: %r'%name)\n else:\n checked_member_dict=checked_enum[name].__dict__\n checked_member_keys=list(checked_member_dict.keys())\n simple_member_dict=simple_enum[name].__dict__\n simple_member_keys=list(simple_member_dict.keys())\n for key in set(checked_member_keys+simple_member_keys):\n if key in('__module__','__objclass__','_inverted_'):\n \n continue\n elif key not in simple_member_keys:\n failed_member.append(\"missing key %r not in the simple enum member %r\"%(key,name))\n elif key not in checked_member_keys:\n failed_member.append(\"extra key %r in simple enum member %r\"%(key,name))\n else:\n checked_value=checked_member_dict[key]\n simple_value=simple_member_dict[key]\n if checked_value !=simple_value:\n failed_member.append(\"%r:\\n %s\\n %s\"%(\n key,\n \"checked member -> %r\"%(checked_value,),\n \"simple member -> %r\"%(simple_value,),\n ))\n if failed_member:\n failed.append('%r member mismatch:\\n %s'%(\n name,'\\n '.join(failed_member),\n ))\n for method in(\n '__str__','__repr__','__reduce_ex__','__format__',\n '__getnewargs_ex__','__getnewargs__','__reduce_ex__','__reduce__'\n ):\n if method in simple_keys and method in checked_keys:\n \n continue\n elif method not in simple_keys and method not in checked_keys:\n \n checked_method=getattr(checked_enum,method,None)\n simple_method=getattr(simple_enum,method,None)\n if hasattr(checked_method,'__func__'):\n checked_method=checked_method.__func__\n simple_method=simple_method.__func__\n if checked_method !=simple_method:\n failed.append(\"%r: %-30s %s\"%(\n method,\n \"checked -> %r\"%(checked_method,),\n \"simple -> %r\"%(simple_method,),\n ))\n else:\n \n \n pass\n if failed:\n raise TypeError('enum mismatch:\\n %s'%'\\n '.join(failed))\n \ndef _old_convert_(etype,name,module,filter,source=None,*,boundary=None):\n ''\n\n \n \n \n \n \n \n module_globals=sys.modules[module].__dict__\n if source:\n source=source.__dict__\n else:\n source=module_globals\n \n \n \n members=[\n (name,value)\n for name,value in source.items()\n if filter(name)]\n try:\n \n members.sort(key=lambda t:(t[1],t[0]))\n except TypeError:\n \n members.sort(key=lambda t:t[0])\n cls=etype(name,members,module=module,boundary=boundary or KEEP)\n return cls\n \n_stdlib_enums=IntEnum,StrEnum,IntFlag\n", ["builtins", "sys", "types"]], "errno": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\nE2BIG=7\n\nEACCES=13\n\nEADDRINUSE=10048\n\nEADDRNOTAVAIL=10049\n\nEAFNOSUPPORT=10047\n\nEAGAIN=11\n\nEALREADY=10037\n\nEBADF=9\n\nEBADMSG=104\n\nEBUSY=16\n\nECANCELED=105\n\nECHILD=10\n\nECONNABORTED=10053\n\nECONNREFUSED=10061\n\nECONNRESET=10054\n\nEDEADLK=36\n\nEDEADLOCK=36\n\nEDESTADDRREQ=10039\n\nEDOM=33\n\nEDQUOT=10069\n\nEEXIST=17\n\nEFAULT=14\n\nEFBIG=27\n\nEHOSTDOWN=10064\n\nEHOSTUNREACH=10065\n\nEIDRM=111\n\nEILSEQ=42\n\nEINPROGRESS=10036\n\nEINTR=4\n\nEINVAL=22\n\nEIO=5\n\nEISCONN=10056\n\nEISDIR=21\n\nELOOP=10062\n\nEMFILE=24\n\nEMLINK=31\n\nEMSGSIZE=10040\n\nENAMETOOLONG=38\n\nENETDOWN=10050\n\nENETRESET=10052\n\nENETUNREACH=10051\n\nENFILE=23\n\nENOBUFS=10055\n\nENODATA=120\n\nENODEV=19\n\nENOENT=2\n\nENOEXEC=8\n\nENOLCK=39\n\nENOLINK=121\n\nENOMEM=12\n\nENOMSG=122\n\nENOPROTOOPT=10042\n\nENOSPC=28\n\nENOSR=124\n\nENOSTR=125\n\nENOSYS=40\n\nENOTCONN=10057\n\nENOTDIR=20\n\nENOTEMPTY=41\n\nENOTRECOVERABLE=127\n\nENOTSOCK=10038\n\nENOTSUP=129\n\nENOTTY=25\n\nENXIO=6\n\nEOPNOTSUPP=10045\n\nEOVERFLOW=132\n\nEOWNERDEAD=133\n\nEPERM=1\n\nEPFNOSUPPORT=10046\n\nEPIPE=32\n\nEPROTO=134\n\nEPROTONOSUPPORT=10043\n\nEPROTOTYPE=10041\n\nERANGE=34\n\nEREMOTE=10071\n\nEROFS=30\n\nESHUTDOWN=10058\n\nESOCKTNOSUPPORT=10044\n\nESPIPE=29\n\nESRCH=3\n\nESTALE=10070\n\nETIME=137\n\nETIMEDOUT=10060\n\nETOOMANYREFS=10059\n\nETXTBSY=139\n\nEUSERS=10068\n\nEWOULDBLOCK=10035\n\nEXDEV=18\n\nWSABASEERR=10000\n\nWSAEACCES=10013\n\nWSAEADDRINUSE=10048\n\nWSAEADDRNOTAVAIL=10049\n\nWSAEAFNOSUPPORT=10047\n\nWSAEALREADY=10037\n\nWSAEBADF=10009\n\nWSAECONNABORTED=10053\n\nWSAECONNREFUSED=10061\n\nWSAECONNRESET=10054\n\nWSAEDESTADDRREQ=10039\n\nWSAEDISCON=10101\n\nWSAEDQUOT=10069\n\nWSAEFAULT=10014\n\nWSAEHOSTDOWN=10064\n\nWSAEHOSTUNREACH=10065\n\nWSAEINPROGRESS=10036\n\nWSAEINTR=10004\n\nWSAEINVAL=10022\n\nWSAEISCONN=10056\n\nWSAELOOP=10062\n\nWSAEMFILE=10024\n\nWSAEMSGSIZE=10040\n\nWSAENAMETOOLONG=10063\n\nWSAENETDOWN=10050\n\nWSAENETRESET=10052\n\nWSAENETUNREACH=10051\n\nWSAENOBUFS=10055\n\nWSAENOPROTOOPT=10042\n\nWSAENOTCONN=10057\n\nWSAENOTEMPTY=10066\n\nWSAENOTSOCK=10038\n\nWSAEOPNOTSUPP=10045\n\nWSAEPFNOSUPPORT=10046\n\nWSAEPROCLIM=10067\n\nWSAEPROTONOSUPPORT=10043\n\nWSAEPROTOTYPE=10041\n\nWSAEREMOTE=10071\n\nWSAESHUTDOWN=10058\n\nWSAESOCKTNOSUPPORT=10044\n\nWSAESTALE=10070\n\nWSAETIMEDOUT=10060\n\nWSAETOOMANYREFS=10059\n\nWSAEUSERS=10068\n\nWSAEWOULDBLOCK=10035\n\nWSANOTINITIALISED=10093\n\nWSASYSNOTREADY=10091\n\nWSAVERNOTSUPPORTED=10092\n\nerrorcode={v:k for(k,v)in globals().items()if k ==k.upper()}\n", []], "external_import": [".py", "import os\nimport sys\nfrom browser import doc\nimport urllib.request\n\n\n\n\n\nclass ModuleFinder:\n def __init__(self,path_entry):\n print(\"external_import here..\")\n \n self._module=None\n if path_entry.startswith('http://'):\n self.path_entry=path_entry\n else:\n raise ImportError()\n \n def __str__(self):\n return '<%s for \"%s\">'%(self.__class__.__name__,self.path_entry)\n \n def find_module(self,fullname,path=None):\n path=path or self.path_entry\n \n for _ext in['js','pyj','py']:\n _fp,_url,_headers=urllib.request.urlopen(path+'/'+'%s.%s'%(fullname,_ext))\n self._module=_fp.read()\n _fp.close()\n if self._module is not None:\n print(\"module found at %s:%s\"%(path,fullname))\n return ModuleLoader(path,fullname,self._module)\n \n print('module %s not found'%fullname)\n raise ImportError()\n return None\n \nclass ModuleLoader:\n ''\n \n def __init__(self,filepath,name,module_source):\n self._filepath=filepath\n self._name=name\n self._module_source=module_source\n \n def get_source(self):\n return self._module_source\n \n def is_package(self):\n return '.'in self._name\n \n def load_module(self):\n if self._name in sys.modules:\n \n mod=sys.modules[self._name]\n return mod\n \n _src=self.get_source()\n if self._filepath.endswith('.js'):\n mod=JSObject(import_js_module(_src,self._filepath,self._name))\n elif self._filepath.endswith('.py'):\n mod=JSObject(import_py_module(_src,self._filepath,self._name))\n elif self._filepath.endswith('.pyj'):\n mod=JSObject(import_pyj_module(_src,self._filepath,self._name))\n else:\n raise ImportError('Invalid Module: %s'%self._filepath)\n \n \n mod.__file__=self._filepath\n mod.__name__=self._name\n mod.__path__=os.path.abspath(self._filepath)\n mod.__loader__=self\n mod.__package__='.'.join(self._name.split('.')[:-1])\n \n if self.is_package():\n print('adding path for package')\n \n \n mod.__path__=[self._filepath]\n else:\n print('imported as regular module')\n \n print('creating a new module object for \"%s\"'%self._name)\n sys.modules.setdefault(self._name,mod)\n JSObject(__BRYTHON__.imported)[self._name]=mod\n \n return mod\n", ["browser", "os", "sys", "urllib.request"]], "faulthandler": [".py", "''\n\n\n_EXCEPTION_ACCESS_VIOLATION=-1073741819\n\n_EXCEPTION_INT_DIVIDE_BY_ZERO=-1073741676\n\n_EXCEPTION_NONCONTINUABLE=1\n\n_EXCEPTION_NONCONTINUABLE_EXCEPTION=-1073741787\n\n_EXCEPTION_STACK_OVERFLOW=-1073741571\n\nclass __loader__(object):\n ''\n\n\n\n\n \n \n \n __delattr__=\"\"\n \n __dict__=\"{'__module__': '_frozen_importlib', '__doc__': 'Meta path import for built-in modules.\\n\\n All methods are either class or static methods to avoid the need to\\n instantiate the class.\\n\\n ', 'module_repr': , 'find_spec': , 'find_module': , 'create_module': , 'exec_module': , 'get_code': , 'get_source': , 'is_package': , 'load_module': , '__dict__': , '__weakref__': }\"\n \n __dir__=\"\"\n \n __eq__=\"\"\n \n __format__=\"\"\n \n __ge__=\"\"\n \n __getattribute__=\"\"\n \n __gt__=\"\"\n \n __hash__=\"\"\n \n __init__=\"\"\n \n def __init_subclass__(*args,**kw):\n ''\n\n\n \n pass\n \n __le__=\"\"\n \n __lt__=\"\"\n \n __module__=\"\"\"_frozen_importlib\"\"\"\n \n __ne__=\"\"\n \n def __new__(*args,**kw):\n ''\n pass\n \n __reduce__=\"\"\n \n __reduce_ex__=\"\"\n \n __repr__=\"\"\n \n __setattr__=\"\"\n \n __sizeof__=\"\"\n \n __str__=\"\"\n \n def __subclasshook__(*args,**kw):\n ''\n\n\n\n\n \n pass\n \n __weakref__=\"\"\n \n create_module=\">\"\n \n exec_module=\">\"\n \n find_module=\">\"\n \n find_spec=\">\"\n \n get_code=\">\"\n \n get_source=\">\"\n \n is_package=\">\"\n \n load_module=\">\"\n \n def module_repr(*args,**kw):\n ''\n\n\n \n pass\n__spec__=\"ModuleSpec(name='faulthandler', loader=, origin='built-in')\"\n\ndef _fatal_error(*args,**kw):\n ''\n pass\n \ndef _fatal_error_c_thread(*args,**kw):\n ''\n pass\n \ndef _raise_exception(*args,**kw):\n ''\n pass\n \ndef _read_null(*args,**kw):\n ''\n pass\n \ndef _sigabrt(*args,**kw):\n ''\n pass\n \ndef _sigfpe(*args,**kw):\n ''\n pass\n \ndef _sigsegv(*args,**kw):\n ''\n pass\n \ndef cancel_dump_traceback_later(*args,**kw):\n ''\n pass\n \ndef disable(*args,**kw):\n ''\n pass\n \ndef dump_traceback(*args,**kw):\n ''\n pass\n \ndef dump_traceback_later(*args,**kw):\n ''\n \n pass\n \ndef enable(*args,**kw):\n ''\n pass\n \ndef is_enabled(*args,**kw):\n ''\n pass\n", []], "fnmatch": [".py", "''\n\n\n\n\n\n\n\n\n\n\nimport os\nimport posixpath\nimport re\nimport functools\n\n__all__=[\"filter\",\"fnmatch\",\"fnmatchcase\",\"translate\"]\n\ndef fnmatch(name,pat):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n name=os.path.normcase(name)\n pat=os.path.normcase(pat)\n return fnmatchcase(name,pat)\n \n@functools.lru_cache(maxsize=32768,typed=True)\ndef _compile_pattern(pat):\n if isinstance(pat,bytes):\n pat_str=str(pat,'ISO-8859-1')\n res_str=translate(pat_str)\n res=bytes(res_str,'ISO-8859-1')\n else:\n res=translate(pat)\n return re.compile(res).match\n \ndef filter(names,pat):\n ''\n result=[]\n pat=os.path.normcase(pat)\n match=_compile_pattern(pat)\n if os.path is posixpath:\n \n for name in names:\n if match(name):\n result.append(name)\n else:\n for name in names:\n if match(os.path.normcase(name)):\n result.append(name)\n return result\n \ndef fnmatchcase(name,pat):\n ''\n\n\n\n \n match=_compile_pattern(pat)\n return match(name)is not None\n \n \ndef translate(pat):\n ''\n\n\n \n \n STAR=object()\n parts=_translate(pat,STAR,'.')\n return _join_translated_parts(parts,STAR)\n \n \ndef _translate(pat,STAR,QUESTION_MARK):\n res=[]\n add=res.append\n i,n=0,len(pat)\n while i =n:\n add('\\\\[')\n else:\n stuff=pat[i:j]\n if '-'not in stuff:\n stuff=stuff.replace('\\\\',r'\\\\')\n else:\n chunks=[]\n k=i+2 if pat[i]=='!'else i+1\n while True:\n k=pat.find('-',k,j)\n if k <0:\n break\n chunks.append(pat[i:k])\n i=k+1\n k=k+3\n chunk=pat[i:j]\n if chunk:\n chunks.append(chunk)\n else:\n chunks[-1]+='-'\n \n for k in range(len(chunks)-1,0,-1):\n if chunks[k -1][-1]>chunks[k][0]:\n chunks[k -1]=chunks[k -1][:-1]+chunks[k][1:]\n del chunks[k]\n \n \n stuff='-'.join(s.replace('\\\\',r'\\\\').replace('-',r'\\-')\n for s in chunks)\n \n stuff=re.sub(r'([&~|])',r'\\\\\\1',stuff)\n i=j+1\n if not stuff:\n \n add('(?!)')\n elif stuff =='!':\n \n add('.')\n else:\n if stuff[0]=='!':\n stuff='^'+stuff[1:]\n elif stuff[0]in('^','['):\n stuff='\\\\'+stuff\n add(f'[{stuff}]')\n else:\n add(re.escape(c))\n assert i ==n\n return res\n \n \ndef _join_translated_parts(inp,STAR):\n\n res=[]\n add=res.append\n i,n=0,len(inp)\n \n while i .*?{fixed})\")\n assert i ==n\n res=\"\".join(res)\n return fr'(?s:{res})\\Z'\n", ["functools", "os", "posixpath", "re"]], "formatter": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport warnings\nwarnings.warn('the formatter module is deprecated',DeprecationWarning,\nstacklevel=2)\n\n\nAS_IS=None\n\n\nclass NullFormatter:\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,writer=None):\n if writer is None:\n writer=NullWriter()\n self.writer=writer\n def end_paragraph(self,blankline):pass\n def add_line_break(self):pass\n def add_hor_rule(self,*args,**kw):pass\n def add_label_data(self,format,counter,blankline=None):pass\n def add_flowing_data(self,data):pass\n def add_literal_data(self,data):pass\n def flush_softspace(self):pass\n def push_alignment(self,align):pass\n def pop_alignment(self):pass\n def push_font(self,x):pass\n def pop_font(self):pass\n def push_margin(self,margin):pass\n def pop_margin(self):pass\n def set_spacing(self,spacing):pass\n def push_style(self,*styles):pass\n def pop_style(self,n=1):pass\n def assert_line_data(self,flag=1):pass\n \n \nclass AbstractFormatter:\n ''\n\n\n\n\n\n \n \n \n \n \n \n \n def __init__(self,writer):\n self.writer=writer\n self.align=None\n self.align_stack=[]\n self.font_stack=[]\n self.margin_stack=[]\n self.spacing=None\n self.style_stack=[]\n self.nospace=1\n self.softspace=0\n self.para_end=1\n self.parskip=0\n self.hard_break=1\n self.have_label=0\n \n def end_paragraph(self,blankline):\n if not self.hard_break:\n self.writer.send_line_break()\n self.have_label=0\n if self.parskip 0:\n label=label+self.format_letter(c,counter)\n elif c in 'iI':\n if counter >0:\n label=label+self.format_roman(c,counter)\n else:\n label=label+c\n return label\n \n def format_letter(self,case,counter):\n label=''\n while counter >0:\n counter,x=divmod(counter -1,26)\n \n \n \n s=chr(ord(case)+x)\n label=s+label\n return label\n \n def format_roman(self,case,counter):\n ones=['i','x','c','m']\n fives=['v','l','d']\n label,index='',0\n \n while counter >0:\n counter,x=divmod(counter,10)\n if x ==9:\n label=ones[index]+ones[index+1]+label\n elif x ==4:\n label=ones[index]+fives[index]+label\n else:\n if x >=5:\n s=fives[index]\n x=x -5\n else:\n s=''\n s=s+ones[index]*x\n label=s+label\n index=index+1\n if case =='I':\n return label.upper()\n return label\n \n def add_flowing_data(self,data):\n if not data:return\n prespace=data[:1].isspace()\n postspace=data[-1:].isspace()\n data=\" \".join(data.split())\n if self.nospace and not data:\n return\n elif prespace or self.softspace:\n if not data:\n if not self.nospace:\n self.softspace=1\n self.parskip=0\n return\n if not self.nospace:\n data=' '+data\n self.hard_break=self.nospace=self.para_end=\\\n self.parskip=self.have_label=0\n self.softspace=postspace\n self.writer.send_flowing_data(data)\n \n def add_literal_data(self,data):\n if not data:return\n if self.softspace:\n self.writer.send_flowing_data(\" \")\n self.hard_break=data[-1:]=='\\n'\n self.nospace=self.para_end=self.softspace=\\\n self.parskip=self.have_label=0\n self.writer.send_literal_data(data)\n \n def flush_softspace(self):\n if self.softspace:\n self.hard_break=self.para_end=self.parskip=\\\n self.have_label=self.softspace=0\n self.nospace=1\n self.writer.send_flowing_data(' ')\n \n def push_alignment(self,align):\n if align and align !=self.align:\n self.writer.new_alignment(align)\n self.align=align\n self.align_stack.append(align)\n else:\n self.align_stack.append(self.align)\n \n def pop_alignment(self):\n if self.align_stack:\n del self.align_stack[-1]\n if self.align_stack:\n self.align=align=self.align_stack[-1]\n self.writer.new_alignment(align)\n else:\n self.align=None\n self.writer.new_alignment(None)\n \n def push_font(self,font):\n size,i,b,tt=font\n if self.softspace:\n self.hard_break=self.para_end=self.softspace=0\n self.nospace=1\n self.writer.send_flowing_data(' ')\n if self.font_stack:\n csize,ci,cb,ctt=self.font_stack[-1]\n if size is AS_IS:size=csize\n if i is AS_IS:i=ci\n if b is AS_IS:b=cb\n if tt is AS_IS:tt=ctt\n font=(size,i,b,tt)\n self.font_stack.append(font)\n self.writer.new_font(font)\n \n def pop_font(self):\n if self.font_stack:\n del self.font_stack[-1]\n if self.font_stack:\n font=self.font_stack[-1]\n else:\n font=None\n self.writer.new_font(font)\n \n def push_margin(self,margin):\n self.margin_stack.append(margin)\n fstack=[m for m in self.margin_stack if m]\n if not margin and fstack:\n margin=fstack[-1]\n self.writer.new_margin(margin,len(fstack))\n \n def pop_margin(self):\n if self.margin_stack:\n del self.margin_stack[-1]\n fstack=[m for m in self.margin_stack if m]\n if fstack:\n margin=fstack[-1]\n else:\n margin=None\n self.writer.new_margin(margin,len(fstack))\n \n def set_spacing(self,spacing):\n self.spacing=spacing\n self.writer.new_spacing(spacing)\n \n def push_style(self,*styles):\n if self.softspace:\n self.hard_break=self.para_end=self.softspace=0\n self.nospace=1\n self.writer.send_flowing_data(' ')\n for style in styles:\n self.style_stack.append(style)\n self.writer.new_styles(tuple(self.style_stack))\n \n def pop_style(self,n=1):\n del self.style_stack[-n:]\n self.writer.new_styles(tuple(self.style_stack))\n \n def assert_line_data(self,flag=1):\n self.nospace=self.hard_break=not flag\n self.para_end=self.parskip=self.have_label=0\n \n \nclass NullWriter:\n ''\n\n\n\n\n\n \n def __init__(self):pass\n def flush(self):pass\n def new_alignment(self,align):pass\n def new_font(self,font):pass\n def new_margin(self,margin,level):pass\n def new_spacing(self,spacing):pass\n def new_styles(self,styles):pass\n def send_paragraph(self,blankline):pass\n def send_line_break(self):pass\n def send_hor_rule(self,*args,**kw):pass\n def send_label_data(self,data):pass\n def send_flowing_data(self,data):pass\n def send_literal_data(self,data):pass\n \n \nclass AbstractWriter(NullWriter):\n ''\n\n\n\n\n \n \n def new_alignment(self,align):\n print(\"new_alignment(%r)\"%(align,))\n \n def new_font(self,font):\n print(\"new_font(%r)\"%(font,))\n \n def new_margin(self,margin,level):\n print(\"new_margin(%r, %d)\"%(margin,level))\n \n def new_spacing(self,spacing):\n print(\"new_spacing(%r)\"%(spacing,))\n \n def new_styles(self,styles):\n print(\"new_styles(%r)\"%(styles,))\n \n def send_paragraph(self,blankline):\n print(\"send_paragraph(%r)\"%(blankline,))\n \n def send_line_break(self):\n print(\"send_line_break()\")\n \n def send_hor_rule(self,*args,**kw):\n print(\"send_hor_rule()\")\n \n def send_label_data(self,data):\n print(\"send_label_data(%r)\"%(data,))\n \n def send_flowing_data(self,data):\n print(\"send_flowing_data(%r)\"%(data,))\n \n def send_literal_data(self,data):\n print(\"send_literal_data(%r)\"%(data,))\n \n \nclass DumbWriter(NullWriter):\n ''\n\n\n\n\n\n \n \n def __init__(self,file=None,maxcol=72):\n self.file=file or sys.stdout\n self.maxcol=maxcol\n NullWriter.__init__(self)\n self.reset()\n \n def reset(self):\n self.col=0\n self.atbreak=0\n \n def send_paragraph(self,blankline):\n self.file.write('\\n'*blankline)\n self.col=0\n self.atbreak=0\n \n def send_line_break(self):\n self.file.write('\\n')\n self.col=0\n self.atbreak=0\n \n def send_hor_rule(self,*args,**kw):\n self.file.write('\\n')\n self.file.write('-'*self.maxcol)\n self.file.write('\\n')\n self.col=0\n self.atbreak=0\n \n def send_literal_data(self,data):\n self.file.write(data)\n i=data.rfind('\\n')\n if i >=0:\n self.col=0\n data=data[i+1:]\n data=data.expandtabs()\n self.col=self.col+len(data)\n self.atbreak=0\n \n def send_flowing_data(self,data):\n if not data:return\n atbreak=self.atbreak or data[0].isspace()\n col=self.col\n maxcol=self.maxcol\n write=self.file.write\n for word in data.split():\n if atbreak:\n if col+len(word)>=maxcol:\n write('\\n')\n col=0\n else:\n write(' ')\n col=col+1\n write(word)\n col=col+len(word)\n atbreak=1\n self.col=col\n self.atbreak=data[-1].isspace()\n \n \ndef test(file=None):\n w=DumbWriter()\n f=AbstractFormatter(w)\n if file is not None:\n fp=open(file)\n elif sys.argv[1:]:\n fp=open(sys.argv[1])\n else:\n fp=sys.stdin\n try:\n for line in fp:\n if line =='\\n':\n f.end_paragraph(1)\n else:\n f.add_flowing_data(line)\n finally:\n if fp is not sys.stdin:\n fp.close()\n f.end_paragraph(0)\n \n \nif __name__ =='__main__':\n test()\n", ["sys", "warnings"]], "fractions": [".py", "\n\n\n\"\"\"Fraction, infinite-precision, rational numbers.\"\"\"\n\nfrom decimal import Decimal\nimport functools\nimport math\nimport numbers\nimport operator\nimport re\nimport sys\n\n__all__=['Fraction']\n\n\n\n\n_PyHASH_MODULUS=sys.hash_info.modulus\n\n\n_PyHASH_INF=sys.hash_info.inf\n\n@functools.lru_cache(maxsize=1 <<14)\ndef _hash_algorithm(numerator,denominator):\n\n\n\n\n\n\n try:\n dinv=pow(denominator,-1,_PyHASH_MODULUS)\n except ValueError:\n \n hash_=_PyHASH_INF\n else:\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n hash_=hash(hash(abs(numerator))*dinv)\n result=hash_ if numerator >=0 else -hash_\n return -2 if result ==-1 else result\n \n_RATIONAL_FORMAT=re.compile(r\"\"\"\n \\A\\s* # optional whitespace at the start,\n (?P[-+]?) # an optional sign, then\n (?=\\d|\\.\\d) # lookahead for digit or .digit\n (?P\\d*|\\d+(_\\d+)*) # numerator (possibly empty)\n (?: # followed by\n (?:\\s*/\\s*(?P\\d+(_\\d+)*))? # an optional denominator\n | # or\n (?:\\.(?P\\d*|\\d+(_\\d+)*))? # an optional fractional part\n (?:E(?P[-+]?\\d+(_\\d+)*))? # and optional exponent\n )\n \\s*\\Z # and optional whitespace to finish\n\"\"\",re.VERBOSE |re.IGNORECASE)\n\n\n\n\ndef _round_to_exponent(n,d,exponent,no_neg_zero=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if exponent >=0:\n d *=10 **exponent\n else:\n n *=10 **-exponent\n \n \n \n q,r=divmod(n+(d >>1),d)\n if r ==0 and d&1 ==0:\n q &=-2\n \n sign=q <0 if no_neg_zero else n <0\n return sign,abs(q)\n \n \ndef _round_to_figures(n,d,figures):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if n ==0:\n return False,0,1 -figures\n \n \n \n str_n,str_d=str(abs(n)),str(d)\n m=len(str_n)-len(str_d)+(str_d <=str_n)\n \n \n \n exponent=m -figures\n sign,significand=_round_to_exponent(n,d,exponent)\n \n \n \n if len(str(significand))==figures+1:\n significand //=10\n exponent +=1\n \n return sign,significand,exponent\n \n \n \n_GENERAL_FORMAT_SPECIFICATION_MATCHER=re.compile(r\"\"\"\n (?:\n (?P.)?\n (?P[<>=^])\n )?\n (?P[-+ ]?)\n # Alt flag forces a slash and denominator in the output, even for\n # integer-valued Fraction objects.\n (?P\\#)?\n # We don't implement the zeropad flag since there's no single obvious way\n # to interpret it.\n (?P0|[1-9][0-9]*)?\n (?P[,_])?\n\"\"\",re.DOTALL |re.VERBOSE).fullmatch\n\n\n\n\n_FLOAT_FORMAT_SPECIFICATION_MATCHER=re.compile(r\"\"\"\n (?:\n (?P.)?\n (?P[<>=^])\n )?\n (?P[-+ ]?)\n (?Pz)?\n (?P\\#)?\n # A '0' that's *not* followed by another digit is parsed as a minimum width\n # rather than a zeropad flag.\n (?P0(?=[0-9]))?\n (?P0|[1-9][0-9]*)?\n (?P[,_])?\n (?:\\.(?P0|[1-9][0-9]*))?\n (?P[eEfFgG%])\n\"\"\",re.DOTALL |re.VERBOSE).fullmatch\n\n\nclass Fraction(numbers.Rational):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('_numerator','_denominator')\n \n \n def __new__(cls,numerator=0,denominator=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self=super(Fraction,cls).__new__(cls)\n \n if denominator is None:\n if type(numerator)is int:\n self._numerator=numerator\n self._denominator=1\n return self\n \n elif isinstance(numerator,numbers.Rational):\n self._numerator=numerator.numerator\n self._denominator=numerator.denominator\n return self\n \n elif isinstance(numerator,(float,Decimal)):\n \n self._numerator,self._denominator=numerator.as_integer_ratio()\n return self\n \n elif isinstance(numerator,str):\n \n m=_RATIONAL_FORMAT.match(numerator)\n if m is None:\n raise ValueError('Invalid literal for Fraction: %r'%\n numerator)\n numerator=int(m.group('num')or '0')\n denom=m.group('denom')\n if denom:\n denominator=int(denom)\n else:\n denominator=1\n decimal=m.group('decimal')\n if decimal:\n decimal=decimal.replace('_','')\n scale=10 **len(decimal)\n numerator=numerator *scale+int(decimal)\n denominator *=scale\n exp=m.group('exp')\n if exp:\n exp=int(exp)\n if exp >=0:\n numerator *=10 **exp\n else:\n denominator *=10 **-exp\n if m.group('sign')=='-':\n numerator=-numerator\n \n else:\n raise TypeError(\"argument should be a string \"\n \"or a Rational instance\")\n \n elif type(numerator)is int is type(denominator):\n pass\n \n elif(isinstance(numerator,numbers.Rational)and\n isinstance(denominator,numbers.Rational)):\n numerator,denominator=(\n numerator.numerator *denominator.denominator,\n denominator.numerator *numerator.denominator\n )\n else:\n raise TypeError(\"both arguments should be \"\n \"Rational instances\")\n \n if denominator ==0:\n raise ZeroDivisionError('Fraction(%s, 0)'%numerator)\n g=math.gcd(numerator,denominator)\n if denominator <0:\n g=-g\n numerator //=g\n denominator //=g\n self._numerator=numerator\n self._denominator=denominator\n return self\n \n @classmethod\n def from_float(cls,f):\n ''\n\n\n\n \n if isinstance(f,numbers.Integral):\n return cls(f)\n elif not isinstance(f,float):\n raise TypeError(\"%s.from_float() only takes floats, not %r (%s)\"%\n (cls.__name__,f,type(f).__name__))\n return cls._from_coprime_ints(*f.as_integer_ratio())\n \n @classmethod\n def from_decimal(cls,dec):\n ''\n from decimal import Decimal\n if isinstance(dec,numbers.Integral):\n dec=Decimal(int(dec))\n elif not isinstance(dec,Decimal):\n raise TypeError(\n \"%s.from_decimal() only takes Decimals, not %r (%s)\"%\n (cls.__name__,dec,type(dec).__name__))\n return cls._from_coprime_ints(*dec.as_integer_ratio())\n \n @classmethod\n def _from_coprime_ints(cls,numerator,denominator,/):\n ''\n\n\n\n \n obj=super(Fraction,cls).__new__(cls)\n obj._numerator=numerator\n obj._denominator=denominator\n return obj\n \n def is_integer(self):\n ''\n return self._denominator ==1\n \n def as_integer_ratio(self):\n ''\n\n\n \n return(self._numerator,self._denominator)\n \n def limit_denominator(self,max_denominator=1000000):\n ''\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if max_denominator <1:\n raise ValueError(\"max_denominator should be at least 1\")\n if self._denominator <=max_denominator:\n return Fraction(self)\n \n p0,q0,p1,q1=0,1,1,0\n n,d=self._numerator,self._denominator\n while True:\n a=n //d\n q2=q0+a *q1\n if q2 >max_denominator:\n break\n p0,q0,p1,q1=p1,q1,p0+a *p1,q2\n n,d=d,n -a *d\n k=(max_denominator -q0)//q1\n \n \n \n \n \n if 2 *d *(q0+k *q1)<=self._denominator:\n return Fraction._from_coprime_ints(p1,q1)\n else:\n return Fraction._from_coprime_ints(p0+k *p1,q0+k *q1)\n \n @property\n def numerator(a):\n return a._numerator\n \n @property\n def denominator(a):\n return a._denominator\n \n def __repr__(self):\n ''\n return '%s(%s, %s)'%(self.__class__.__name__,\n self._numerator,self._denominator)\n \n def __str__(self):\n ''\n if self._denominator ==1:\n return str(self._numerator)\n else:\n return '%s/%s'%(self._numerator,self._denominator)\n \n def _format_general(self,match):\n ''\n\n\n\n \n \n fill=match[\"fill\"]or \" \"\n align=match[\"align\"]or \">\"\n pos_sign=\"\"if match[\"sign\"]==\"-\"else match[\"sign\"]\n alternate_form=bool(match[\"alt\"])\n minimumwidth=int(match[\"minimumwidth\"]or \"0\")\n thousands_sep=match[\"thousands_sep\"]or ''\n \n \n n,d=self._numerator,self._denominator\n if d >1 or alternate_form:\n body=f\"{abs(n):{thousands_sep}}/{d:{thousands_sep}}\"\n else:\n body=f\"{abs(n):{thousands_sep}}\"\n sign='-'if n <0 else pos_sign\n \n \n padding=fill *(minimumwidth -len(sign)-len(body))\n if align ==\">\":\n return padding+sign+body\n elif align ==\"<\":\n return sign+body+padding\n elif align ==\"^\":\n half=len(padding)//2\n return padding[:half]+sign+body+padding[half:]\n else:\n return sign+padding+body\n \n def _format_float_style(self,match):\n ''\n fill=match[\"fill\"]or \" \"\n align=match[\"align\"]or \">\"\n pos_sign=\"\"if match[\"sign\"]==\"-\"else match[\"sign\"]\n no_neg_zero=bool(match[\"no_neg_zero\"])\n alternate_form=bool(match[\"alt\"])\n zeropad=bool(match[\"zeropad\"])\n minimumwidth=int(match[\"minimumwidth\"]or \"0\")\n thousands_sep=match[\"thousands_sep\"]\n precision=int(match[\"precision\"]or \"6\")\n presentation_type=match[\"presentation_type\"]\n trim_zeros=presentation_type in \"gG\"and not alternate_form\n trim_point=not alternate_form\n exponent_indicator=\"E\"if presentation_type in \"EFG\"else \"e\"\n \n \n \n \n \n if presentation_type in \"fF%\":\n exponent=-precision\n if presentation_type ==\"%\":\n exponent -=2\n negative,significand=_round_to_exponent(\n self._numerator,self._denominator,exponent,no_neg_zero)\n scientific=False\n point_pos=precision\n else:\n figures=(\n max(precision,1)\n if presentation_type in \"gG\"\n else precision+1\n )\n negative,significand,exponent=_round_to_figures(\n self._numerator,self._denominator,figures)\n scientific=(\n presentation_type in \"eE\"\n or exponent >0\n or exponent+figures <=-4\n )\n point_pos=figures -1 if scientific else -exponent\n \n \n if presentation_type ==\"%\":\n suffix=\"%\"\n elif scientific:\n suffix=f\"{exponent_indicator}{exponent+point_pos:+03d}\"\n else:\n suffix=\"\"\n \n \n \n digits=f\"{significand:0{point_pos+1}d}\"\n \n \n \n \n sign=\"-\"if negative else pos_sign\n leading=digits[:len(digits)-point_pos]\n frac_part=digits[len(digits)-point_pos:]\n if trim_zeros:\n frac_part=frac_part.rstrip(\"0\")\n separator=\"\"if trim_point and not frac_part else \".\"\n trailing=separator+frac_part+suffix\n \n \n if zeropad:\n min_leading=minimumwidth -len(sign)-len(trailing)\n \n \n leading=leading.zfill(\n 3 *min_leading //4+1 if thousands_sep else min_leading\n )\n \n \n if thousands_sep:\n first_pos=1+(len(leading)-1)%3\n leading=leading[:first_pos]+\"\".join(\n thousands_sep+leading[pos:pos+3]\n for pos in range(first_pos,len(leading),3)\n )\n \n \n \n body=leading+trailing\n padding=fill *(minimumwidth -len(sign)-len(body))\n if align ==\">\":\n return padding+sign+body\n elif align ==\"<\":\n return sign+body+padding\n elif align ==\"^\":\n half=len(padding)//2\n return padding[:half]+sign+body+padding[half:]\n else:\n return sign+padding+body\n \n def __format__(self,format_spec,/):\n ''\n \n if match :=_GENERAL_FORMAT_SPECIFICATION_MATCHER(format_spec):\n return self._format_general(match)\n \n if match :=_FLOAT_FORMAT_SPECIFICATION_MATCHER(format_spec):\n \n \n if match[\"align\"]is None or match[\"zeropad\"]is None:\n return self._format_float_style(match)\n \n raise ValueError(\n f\"Invalid format specifier {format_spec !r} \"\n f\"for object of type {type(self).__name__ !r}\"\n )\n \n def _operator_fallbacks(monomorphic_operator,fallback_operator,\n handle_complex=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def forward(a,b):\n if isinstance(b,Fraction):\n return monomorphic_operator(a,b)\n elif isinstance(b,int):\n return monomorphic_operator(a,Fraction(b))\n elif isinstance(b,float):\n return fallback_operator(float(a),b)\n elif handle_complex and isinstance(b,complex):\n return fallback_operator(complex(a),b)\n else:\n return NotImplemented\n forward.__name__='__'+fallback_operator.__name__+'__'\n forward.__doc__=monomorphic_operator.__doc__\n \n def reverse(b,a):\n if isinstance(a,numbers.Rational):\n \n return monomorphic_operator(Fraction(a),b)\n elif isinstance(a,numbers.Real):\n return fallback_operator(float(a),float(b))\n elif handle_complex and isinstance(a,numbers.Complex):\n return fallback_operator(complex(a),complex(b))\n else:\n return NotImplemented\n reverse.__name__='__r'+fallback_operator.__name__+'__'\n reverse.__doc__=monomorphic_operator.__doc__\n \n return forward,reverse\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def _add(a,b):\n ''\n na,da=a._numerator,a._denominator\n nb,db=b._numerator,b._denominator\n g=math.gcd(da,db)\n if g ==1:\n return Fraction._from_coprime_ints(na *db+da *nb,da *db)\n s=da //g\n t=na *(db //g)+nb *s\n g2=math.gcd(t,g)\n if g2 ==1:\n return Fraction._from_coprime_ints(t,s *db)\n return Fraction._from_coprime_ints(t //g2,s *(db //g2))\n \n __add__,__radd__=_operator_fallbacks(_add,operator.add)\n \n def _sub(a,b):\n ''\n na,da=a._numerator,a._denominator\n nb,db=b._numerator,b._denominator\n g=math.gcd(da,db)\n if g ==1:\n return Fraction._from_coprime_ints(na *db -da *nb,da *db)\n s=da //g\n t=na *(db //g)-nb *s\n g2=math.gcd(t,g)\n if g2 ==1:\n return Fraction._from_coprime_ints(t,s *db)\n return Fraction._from_coprime_ints(t //g2,s *(db //g2))\n \n __sub__,__rsub__=_operator_fallbacks(_sub,operator.sub)\n \n def _mul(a,b):\n ''\n na,da=a._numerator,a._denominator\n nb,db=b._numerator,b._denominator\n g1=math.gcd(na,db)\n if g1 >1:\n na //=g1\n db //=g1\n g2=math.gcd(nb,da)\n if g2 >1:\n nb //=g2\n da //=g2\n return Fraction._from_coprime_ints(na *nb,db *da)\n \n __mul__,__rmul__=_operator_fallbacks(_mul,operator.mul)\n \n def _div(a,b):\n ''\n \n nb,db=b._numerator,b._denominator\n if nb ==0:\n raise ZeroDivisionError('Fraction(%s, 0)'%db)\n na,da=a._numerator,a._denominator\n g1=math.gcd(na,nb)\n if g1 >1:\n na //=g1\n nb //=g1\n g2=math.gcd(db,da)\n if g2 >1:\n da //=g2\n db //=g2\n n,d=na *db,nb *da\n if d <0:\n n,d=-n,-d\n return Fraction._from_coprime_ints(n,d)\n \n __truediv__,__rtruediv__=_operator_fallbacks(_div,operator.truediv)\n \n def _floordiv(a,b):\n ''\n return(a.numerator *b.denominator)//(a.denominator *b.numerator)\n \n __floordiv__,__rfloordiv__=_operator_fallbacks(_floordiv,operator.floordiv,False)\n \n def _divmod(a,b):\n ''\n da,db=a.denominator,b.denominator\n div,n_mod=divmod(a.numerator *db,da *b.numerator)\n return div,Fraction(n_mod,da *db)\n \n __divmod__,__rdivmod__=_operator_fallbacks(_divmod,divmod,False)\n \n def _mod(a,b):\n ''\n da,db=a.denominator,b.denominator\n return Fraction((a.numerator *db)%(b.numerator *da),da *db)\n \n __mod__,__rmod__=_operator_fallbacks(_mod,operator.mod,False)\n \n def __pow__(a,b):\n ''\n\n\n\n\n\n \n if isinstance(b,numbers.Rational):\n if b.denominator ==1:\n power=b.numerator\n if power >=0:\n return Fraction._from_coprime_ints(a._numerator **power,\n a._denominator **power)\n elif a._numerator >0:\n return Fraction._from_coprime_ints(a._denominator **-power,\n a._numerator **-power)\n elif a._numerator ==0:\n raise ZeroDivisionError('Fraction(%s, 0)'%\n a._denominator **-power)\n else:\n return Fraction._from_coprime_ints((-a._denominator)**-power,\n (-a._numerator)**-power)\n else:\n \n \n return float(a)**float(b)\n elif isinstance(b,(float,complex)):\n return float(a)**b\n else:\n return NotImplemented\n \n def __rpow__(b,a):\n ''\n if b._denominator ==1 and b._numerator >=0:\n \n return a **b._numerator\n \n if isinstance(a,numbers.Rational):\n return Fraction(a.numerator,a.denominator)**b\n \n if b._denominator ==1:\n return a **b._numerator\n \n return a **float(b)\n \n def __pos__(a):\n ''\n return Fraction._from_coprime_ints(a._numerator,a._denominator)\n \n def __neg__(a):\n ''\n return Fraction._from_coprime_ints(-a._numerator,a._denominator)\n \n def __abs__(a):\n ''\n return Fraction._from_coprime_ints(abs(a._numerator),a._denominator)\n \n def __int__(a,_index=operator.index):\n ''\n if a._numerator <0:\n return _index(-(-a._numerator //a._denominator))\n else:\n return _index(a._numerator //a._denominator)\n \n def __trunc__(a):\n ''\n if a._numerator <0:\n return -(-a._numerator //a._denominator)\n else:\n return a._numerator //a._denominator\n \n def __floor__(a):\n ''\n return a._numerator //a._denominator\n \n def __ceil__(a):\n ''\n \n return -(-a._numerator //a._denominator)\n \n def __round__(self,ndigits=None):\n ''\n\n\n \n if ndigits is None:\n d=self._denominator\n floor,remainder=divmod(self._numerator,d)\n if remainder *2 d:\n return floor+1\n \n elif floor %2 ==0:\n return floor\n else:\n return floor+1\n shift=10 **abs(ndigits)\n \n \n \n if ndigits >0:\n return Fraction(round(self *shift),shift)\n else:\n return Fraction(round(self /shift)*shift)\n \n def __hash__(self):\n ''\n return _hash_algorithm(self._numerator,self._denominator)\n \n def __eq__(a,b):\n ''\n if type(b)is int:\n return a._numerator ==b and a._denominator ==1\n if isinstance(b,numbers.Rational):\n return(a._numerator ==b.numerator and\n a._denominator ==b.denominator)\n if isinstance(b,numbers.Complex)and b.imag ==0:\n b=b.real\n if isinstance(b,float):\n if math.isnan(b)or math.isinf(b):\n \n \n return 0.0 ==b\n else:\n return a ==a.from_float(b)\n else:\n \n \n return NotImplemented\n \n def _richcmp(self,other,op):\n ''\n\n\n\n\n\n\n\n \n \n if isinstance(other,numbers.Rational):\n return op(self._numerator *other.denominator,\n self._denominator *other.numerator)\n if isinstance(other,float):\n if math.isnan(other)or math.isinf(other):\n return op(0.0,other)\n else:\n return op(self,self.from_float(other))\n else:\n return NotImplemented\n \n def __lt__(a,b):\n ''\n return a._richcmp(b,operator.lt)\n \n def __gt__(a,b):\n ''\n return a._richcmp(b,operator.gt)\n \n def __le__(a,b):\n ''\n return a._richcmp(b,operator.le)\n \n def __ge__(a,b):\n ''\n return a._richcmp(b,operator.ge)\n \n def __bool__(a):\n ''\n \n \n return bool(a._numerator)\n \n \n \n def __reduce__(self):\n return(self.__class__,(self._numerator,self._denominator))\n \n def __copy__(self):\n if type(self)==Fraction:\n return self\n return self.__class__(self._numerator,self._denominator)\n \n def __deepcopy__(self,memo):\n if type(self)==Fraction:\n return self\n return self.__class__(self._numerator,self._denominator)\n", ["decimal", "functools", "math", "numbers", "operator", "re", "sys"]], "functools": [".py", "''\n\n\n\n\n\n\n\n\n\n\n__all__=['update_wrapper','wraps','WRAPPER_ASSIGNMENTS','WRAPPER_UPDATES',\n'total_ordering','cache','cmp_to_key','lru_cache','reduce',\n'partial','partialmethod','singledispatch','singledispatchmethod',\n'cached_property']\n\nfrom abc import get_cache_token\nfrom collections import namedtuple\n\nfrom reprlib import recursive_repr\nfrom _thread import RLock\n\n\nGenericAlias=type(list[int])\n\n\n\n\n\n\n\n\nWRAPPER_ASSIGNMENTS=('__module__','__name__','__qualname__','__doc__',\n'__annotations__','__type_params__')\nWRAPPER_UPDATES=('__dict__',)\ndef update_wrapper(wrapper,\nwrapped,\nassigned=WRAPPER_ASSIGNMENTS,\nupdated=WRAPPER_UPDATES):\n ''\n\n\n\n\n\n\n\n\n\n \n for attr in assigned:\n try:\n value=getattr(wrapped,attr)\n except AttributeError:\n pass\n else:\n setattr(wrapper,attr,value)\n for attr in updated:\n getattr(wrapper,attr).update(getattr(wrapped,attr,{}))\n \n \n wrapper.__wrapped__=wrapped\n \n return wrapper\n \ndef wraps(wrapped,\nassigned=WRAPPER_ASSIGNMENTS,\nupdated=WRAPPER_UPDATES):\n ''\n\n\n\n\n\n\n \n return partial(update_wrapper,wrapped=wrapped,\n assigned=assigned,updated=updated)\n \n \n \n \n \n \n \n \n \n \n \ndef _gt_from_lt(self,other):\n ''\n op_result=type(self).__lt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result and self !=other\n \ndef _le_from_lt(self,other):\n ''\n op_result=type(self).__lt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return op_result or self ==other\n \ndef _ge_from_lt(self,other):\n ''\n op_result=type(self).__lt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _ge_from_le(self,other):\n ''\n op_result=type(self).__le__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result or self ==other\n \ndef _lt_from_le(self,other):\n ''\n op_result=type(self).__le__(self,other)\n if op_result is NotImplemented:\n return op_result\n return op_result and self !=other\n \ndef _gt_from_le(self,other):\n ''\n op_result=type(self).__le__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _lt_from_gt(self,other):\n ''\n op_result=type(self).__gt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result and self !=other\n \ndef _ge_from_gt(self,other):\n ''\n op_result=type(self).__gt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return op_result or self ==other\n \ndef _le_from_gt(self,other):\n ''\n op_result=type(self).__gt__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _le_from_ge(self,other):\n ''\n op_result=type(self).__ge__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result or self ==other\n \ndef _gt_from_ge(self,other):\n ''\n op_result=type(self).__ge__(self,other)\n if op_result is NotImplemented:\n return op_result\n return op_result and self !=other\n \ndef _lt_from_ge(self,other):\n ''\n op_result=type(self).__ge__(self,other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \n_convert={\n'__lt__':[('__gt__',_gt_from_lt),\n('__le__',_le_from_lt),\n('__ge__',_ge_from_lt)],\n'__le__':[('__ge__',_ge_from_le),\n('__lt__',_lt_from_le),\n('__gt__',_gt_from_le)],\n'__gt__':[('__lt__',_lt_from_gt),\n('__ge__',_ge_from_gt),\n('__le__',_le_from_gt)],\n'__ge__':[('__le__',_le_from_ge),\n('__gt__',_gt_from_ge),\n('__lt__',_lt_from_ge)]\n}\n\ndef total_ordering(cls):\n ''\n \n roots={op for op in _convert if getattr(cls,op,None)is not getattr(object,op,None)}\n if not roots:\n raise ValueError('must define at least one ordering operation: < > <= >=')\n root=max(roots)\n for opname,opfunc in _convert[root]:\n if opname not in roots:\n opfunc.__name__=opname\n setattr(cls,opname,opfunc)\n return cls\n \n \n \n \n \n \ndef cmp_to_key(mycmp):\n ''\n class K(object):\n __slots__=['obj']\n def __init__(self,obj):\n self.obj=obj\n def __lt__(self,other):\n return mycmp(self.obj,other.obj)<0\n def __gt__(self,other):\n return mycmp(self.obj,other.obj)>0\n def __eq__(self,other):\n return mycmp(self.obj,other.obj)==0\n def __le__(self,other):\n return mycmp(self.obj,other.obj)<=0\n def __ge__(self,other):\n return mycmp(self.obj,other.obj)>=0\n __hash__=None\n return K\n \ntry:\n from _functools import cmp_to_key\nexcept ImportError:\n pass\n \n \n \n \n \n \n_initial_missing=object()\n\ndef reduce(function,sequence,initial=_initial_missing):\n ''\n\n\n\n\n\n\n\n\n \n \n it=iter(sequence)\n \n if initial is _initial_missing:\n try:\n value=next(it)\n except StopIteration:\n raise TypeError(\n \"reduce() of empty iterable with no initial value\")from None\n else:\n value=initial\n \n for element in it:\n value=function(value,element)\n \n return value\n \ntry:\n from _functools import reduce\nexcept ImportError:\n pass\n \n \n \n \n \n \n \nclass partial:\n ''\n\n \n \n __slots__=\"func\",\"args\",\"keywords\",\"__dict__\",\"__weakref__\"\n \n def __new__(cls,func,/,*args,**keywords):\n if not callable(func):\n raise TypeError(\"the first argument must be callable\")\n \n if isinstance(func,partial):\n args=func.args+args\n keywords={**func.keywords,**keywords}\n func=func.func\n \n self=super(partial,cls).__new__(cls)\n \n self.func=func\n self.args=args\n self.keywords=keywords\n return self\n \n def __call__(self,/,*args,**keywords):\n keywords={**self.keywords,**keywords}\n return self.func(*self.args,*args,**keywords)\n \n @recursive_repr()\n def __repr__(self):\n cls=type(self)\n qualname=cls.__qualname__\n module=cls.__module__\n args=[repr(self.func)]\n args.extend(repr(x)for x in self.args)\n args.extend(f\"{k}={v !r}\"for(k,v)in self.keywords.items())\n return f\"{module}.{qualname}({', '.join(args)})\"\n \n def __get__(self,obj,objtype=None):\n if obj is None:\n return self\n import warnings\n warnings.warn('functools.partial will be a method descriptor in '\n 'future Python versions; wrap it in staticmethod() '\n 'if you want to preserve the old behavior',\n FutureWarning,2)\n return self\n \n def __reduce__(self):\n return type(self),(self.func,),(self.func,self.args,\n self.keywords or None,self.__dict__ or None)\n \n def __setstate__(self,state):\n if not isinstance(state,tuple):\n raise TypeError(\"argument to __setstate__ must be a tuple\")\n if len(state)!=4:\n raise TypeError(f\"expected 4 items in state, got {len(state)}\")\n func,args,kwds,namespace=state\n if(not callable(func)or not isinstance(args,tuple)or\n (kwds is not None and not isinstance(kwds,dict))or\n (namespace is not None and not isinstance(namespace,dict))):\n raise TypeError(\"invalid partial state\")\n \n args=tuple(args)\n if kwds is None:\n kwds={}\n elif type(kwds)is not dict:\n kwds=dict(kwds)\n if namespace is None:\n namespace={}\n \n self.__dict__=namespace\n self.func=func\n self.args=args\n self.keywords=kwds\n \ntry:\n from _functools import partial\nexcept ImportError:\n pass\n \n \nclass partialmethod(object):\n ''\n\n\n\n\n \n \n def __init__(self,func,/,*args,**keywords):\n if not callable(func)and not hasattr(func,\"__get__\"):\n raise TypeError(\"{!r} is not callable or a descriptor\"\n .format(func))\n \n \n \n if isinstance(func,partialmethod):\n \n \n \n self.func=func.func\n self.args=func.args+args\n self.keywords={**func.keywords,**keywords}\n else:\n self.func=func\n self.args=args\n self.keywords=keywords\n \n def __repr__(self):\n cls=type(self)\n module=cls.__module__\n qualname=cls.__qualname__\n args=[repr(self.func)]\n args.extend(map(repr,self.args))\n args.extend(f\"{k}={v !r}\"for k,v in self.keywords.items())\n return f\"{module}.{qualname}({', '.join(args)})\"\n \n def _make_unbound_method(self):\n def _method(cls_or_self,/,*args,**keywords):\n keywords={**self.keywords,**keywords}\n return self.func(cls_or_self,*self.args,*args,**keywords)\n _method.__isabstractmethod__=self.__isabstractmethod__\n _method.__partialmethod__=self\n return _method\n \n def __get__(self,obj,cls=None):\n get=getattr(self.func,\"__get__\",None)\n result=None\n if get is not None and not isinstance(self.func,partial):\n new_func=get(obj,cls)\n if new_func is not self.func:\n \n \n result=partial(new_func,*self.args,**self.keywords)\n try:\n result.__self__=new_func.__self__\n except AttributeError:\n pass\n if result is None:\n \n \n result=self._make_unbound_method().__get__(obj,cls)\n return result\n \n @property\n def __isabstractmethod__(self):\n return getattr(self.func,\"__isabstractmethod__\",False)\n \n __class_getitem__=classmethod(GenericAlias)\n \n \n \n \ndef _unwrap_partial(func):\n while isinstance(func,partial):\n func=func.func\n return func\n \ndef _unwrap_partialmethod(func):\n prev=None\n while func is not prev:\n prev=func\n while isinstance(getattr(func,\"__partialmethod__\",None),partialmethod):\n func=func.__partialmethod__\n while isinstance(func,partialmethod):\n func=getattr(func,'func')\n func=_unwrap_partial(func)\n return func\n \n \n \n \n \n_CacheInfo=namedtuple(\"CacheInfo\",[\"hits\",\"misses\",\"maxsize\",\"currsize\"])\n\nclass _HashedSeq(list):\n ''\n\n\n\n \n \n __slots__='hashvalue'\n \n def __init__(self,tup,hash=hash):\n self[:]=tup\n self.hashvalue=hash(tup)\n \n def __hash__(self):\n return self.hashvalue\n \ndef _make_key(args,kwds,typed,\nkwd_mark=(object(),),\nfasttypes={int,str},\ntuple=tuple,type=type,len=len):\n ''\n\n\n\n\n\n\n\n\n \n \n \n \n \n key=args\n if kwds:\n key +=kwd_mark\n for item in kwds.items():\n key +=item\n if typed:\n key +=tuple(type(v)for v in args)\n if kwds:\n key +=tuple(type(v)for v in kwds.values())\n elif len(key)==1 and type(key[0])in fasttypes:\n return key[0]\n return _HashedSeq(key)\n \ndef lru_cache(maxsize=128,typed=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n if isinstance(maxsize,int):\n \n if maxsize <0:\n maxsize=0\n elif callable(maxsize)and isinstance(typed,bool):\n \n user_function,maxsize=maxsize,128\n wrapper=_lru_cache_wrapper(user_function,maxsize,typed,_CacheInfo)\n wrapper.cache_parameters=lambda:{'maxsize':maxsize,'typed':typed}\n return update_wrapper(wrapper,user_function)\n elif maxsize is not None:\n raise TypeError(\n 'Expected first argument to be an integer, a callable, or None')\n \n def decorating_function(user_function):\n wrapper=_lru_cache_wrapper(user_function,maxsize,typed,_CacheInfo)\n wrapper.cache_parameters=lambda:{'maxsize':maxsize,'typed':typed}\n return update_wrapper(wrapper,user_function)\n \n return decorating_function\n \ndef _lru_cache_wrapper(user_function,maxsize,typed,_CacheInfo):\n\n sentinel=object()\n make_key=_make_key\n PREV,NEXT,KEY,RESULT=0,1,2,3\n \n cache={}\n hits=misses=0\n full=False\n cache_get=cache.get\n cache_len=cache.__len__\n lock=RLock()\n root=[]\n root[:]=[root,root,None,None]\n \n if maxsize ==0:\n \n def wrapper(*args,**kwds):\n \n nonlocal misses\n misses +=1\n result=user_function(*args,**kwds)\n return result\n \n elif maxsize is None:\n \n def wrapper(*args,**kwds):\n \n nonlocal hits,misses\n key=make_key(args,kwds,typed)\n result=cache_get(key,sentinel)\n if result is not sentinel:\n hits +=1\n return result\n misses +=1\n result=user_function(*args,**kwds)\n cache[key]=result\n return result\n \n else:\n \n def wrapper(*args,**kwds):\n \n nonlocal root,hits,misses,full\n key=make_key(args,kwds,typed)\n with lock:\n link=cache_get(key)\n if link is not None:\n \n link_prev,link_next,_key,result=link\n link_prev[NEXT]=link_next\n link_next[PREV]=link_prev\n last=root[PREV]\n last[NEXT]=root[PREV]=link\n link[PREV]=last\n link[NEXT]=root\n hits +=1\n return result\n misses +=1\n result=user_function(*args,**kwds)\n with lock:\n if key in cache:\n \n \n \n \n pass\n elif full:\n \n oldroot=root\n oldroot[KEY]=key\n oldroot[RESULT]=result\n \n \n \n \n \n \n root=oldroot[NEXT]\n oldkey=root[KEY]\n oldresult=root[RESULT]\n root[KEY]=root[RESULT]=None\n \n del cache[oldkey]\n \n \n \n cache[key]=oldroot\n else:\n \n last=root[PREV]\n link=[last,root,key,result]\n last[NEXT]=root[PREV]=cache[key]=link\n \n \n full=(cache_len()>=maxsize)\n return result\n \n def cache_info():\n ''\n with lock:\n return _CacheInfo(hits,misses,maxsize,cache_len())\n \n def cache_clear():\n ''\n nonlocal hits,misses,full\n with lock:\n cache.clear()\n root[:]=[root,root,None,None]\n hits=misses=0\n full=False\n \n wrapper.cache_info=cache_info\n wrapper.cache_clear=cache_clear\n return wrapper\n \ntry:\n from _functools import _lru_cache_wrapper\nexcept ImportError:\n pass\n \n \n \n \n \n \ndef cache(user_function,/):\n ''\n return lru_cache(maxsize=None)(user_function)\n \n \n \n \n \n \ndef _c3_merge(sequences):\n ''\n\n\n\n \n result=[]\n while True:\n sequences=[s for s in sequences if s]\n if not sequences:\n return result\n for s1 in sequences:\n candidate=s1[0]\n for s2 in sequences:\n if candidate in s2[1:]:\n candidate=None\n break\n else:\n break\n if candidate is None:\n raise RuntimeError(\"Inconsistent hierarchy\")\n result.append(candidate)\n \n for seq in sequences:\n if seq[0]==candidate:\n del seq[0]\n \ndef _c3_mro(cls,abcs=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n for i,base in enumerate(reversed(cls.__bases__)):\n if hasattr(base,'__abstractmethods__'):\n boundary=len(cls.__bases__)-i\n break\n else:\n boundary=0\n abcs=list(abcs)if abcs else[]\n explicit_bases=list(cls.__bases__[:boundary])\n abstract_bases=[]\n other_bases=list(cls.__bases__[boundary:])\n for base in abcs:\n if issubclass(cls,base)and not any(\n issubclass(b,base)for b in cls.__bases__\n ):\n \n \n abstract_bases.append(base)\n for base in abstract_bases:\n abcs.remove(base)\n explicit_c3_mros=[_c3_mro(base,abcs=abcs)for base in explicit_bases]\n abstract_c3_mros=[_c3_mro(base,abcs=abcs)for base in abstract_bases]\n other_c3_mros=[_c3_mro(base,abcs=abcs)for base in other_bases]\n return _c3_merge(\n [[cls]]+\n explicit_c3_mros+abstract_c3_mros+other_c3_mros+\n [explicit_bases]+[abstract_bases]+[other_bases]\n )\n \ndef _compose_mro(cls,types):\n ''\n\n\n\n\n \n bases=set(cls.__mro__)\n \n def is_related(typ):\n return(typ not in bases and hasattr(typ,'__mro__')\n and not isinstance(typ,GenericAlias)\n and issubclass(cls,typ))\n types=[n for n in types if is_related(n)]\n \n \n def is_strict_base(typ):\n for other in types:\n if typ !=other and typ in other.__mro__:\n return True\n return False\n types=[n for n in types if not is_strict_base(n)]\n \n \n type_set=set(types)\n mro=[]\n for typ in types:\n found=[]\n for sub in typ.__subclasses__():\n if sub not in bases and issubclass(cls,sub):\n found.append([s for s in sub.__mro__ if s in type_set])\n if not found:\n mro.append(typ)\n continue\n \n found.sort(key=len,reverse=True)\n for sub in found:\n for subcls in sub:\n if subcls not in mro:\n mro.append(subcls)\n return _c3_mro(cls,abcs=mro)\n \ndef _find_impl(cls,registry):\n ''\n\n\n\n\n\n\n\n \n mro=_compose_mro(cls,registry.keys())\n match=None\n for t in mro:\n if match is not None:\n \n \n if(t in registry and t not in cls.__mro__\n and match not in cls.__mro__\n and not issubclass(match,t)):\n raise RuntimeError(\"Ambiguous dispatch: {} or {}\".format(\n match,t))\n break\n if t in registry:\n match=t\n return registry.get(match)\n \ndef singledispatch(func):\n ''\n\n\n\n\n\n\n \n \n \n \n import types,weakref\n \n registry={}\n dispatch_cache=weakref.WeakKeyDictionary()\n cache_token=None\n \n def dispatch(cls):\n ''\n\n\n\n\n \n nonlocal cache_token\n if cache_token is not None:\n current_token=get_cache_token()\n if cache_token !=current_token:\n dispatch_cache.clear()\n cache_token=current_token\n try:\n impl=dispatch_cache[cls]\n except KeyError:\n try:\n impl=registry[cls]\n except KeyError:\n impl=_find_impl(cls,registry)\n dispatch_cache[cls]=impl\n return impl\n \n def _is_union_type(cls):\n from typing import get_origin,Union\n return get_origin(cls)in{Union,types.UnionType}\n \n def _is_valid_dispatch_type(cls):\n if isinstance(cls,type):\n return True\n from typing import get_args\n return(_is_union_type(cls)and\n all(isinstance(arg,type)for arg in get_args(cls)))\n \n def register(cls,func=None):\n ''\n\n\n\n \n nonlocal cache_token\n if _is_valid_dispatch_type(cls):\n if func is None:\n return lambda f:register(cls,f)\n else:\n if func is not None:\n raise TypeError(\n f\"Invalid first argument to `register()`. \"\n f\"{cls !r} is not a class or union type.\"\n )\n ann=getattr(cls,'__annotations__',{})\n if not ann:\n raise TypeError(\n f\"Invalid first argument to `register()`: {cls !r}. \"\n f\"Use either `@register(some_class)` or plain `@register` \"\n f\"on an annotated function.\"\n )\n func=cls\n \n \n from typing import get_type_hints\n argname,cls=next(iter(get_type_hints(func).items()))\n if not _is_valid_dispatch_type(cls):\n if _is_union_type(cls):\n raise TypeError(\n f\"Invalid annotation for {argname !r}. \"\n f\"{cls !r} not all arguments are classes.\"\n )\n else:\n raise TypeError(\n f\"Invalid annotation for {argname !r}. \"\n f\"{cls !r} is not a class.\"\n )\n \n if _is_union_type(cls):\n from typing import get_args\n \n for arg in get_args(cls):\n registry[arg]=func\n else:\n registry[cls]=func\n if cache_token is None and hasattr(cls,'__abstractmethods__'):\n cache_token=get_cache_token()\n dispatch_cache.clear()\n return func\n \n def wrapper(*args,**kw):\n if not args:\n raise TypeError(f'{funcname} requires at least '\n '1 positional argument')\n return dispatch(args[0].__class__)(*args,**kw)\n \n funcname=getattr(func,'__name__','singledispatch function')\n registry[object]=func\n wrapper.register=register\n wrapper.dispatch=dispatch\n wrapper.registry=types.MappingProxyType(registry)\n wrapper._clear_cache=dispatch_cache.clear\n update_wrapper(wrapper,func)\n return wrapper\n \n \n \nclass singledispatchmethod:\n ''\n\n\n\n \n \n def __init__(self,func):\n if not callable(func)and not hasattr(func,\"__get__\"):\n raise TypeError(f\"{func !r} is not callable or a descriptor\")\n \n self.dispatcher=singledispatch(func)\n self.func=func\n \n import weakref\n self._method_cache=weakref.WeakKeyDictionary()\n \n def register(self,cls,method=None):\n ''\n\n\n \n return self.dispatcher.register(cls,func=method)\n \n def __get__(self,obj,cls=None):\n if self._method_cache is not None:\n try:\n _method=self._method_cache[obj]\n except TypeError:\n self._method_cache=None\n except KeyError:\n pass\n else:\n return _method\n \n dispatch=self.dispatcher.dispatch\n funcname=getattr(self.func,'__name__','singledispatchmethod method')\n def _method(*args,**kwargs):\n if not args:\n raise TypeError(f'{funcname} requires at least '\n '1 positional argument')\n return dispatch(args[0].__class__).__get__(obj,cls)(*args,**kwargs)\n \n _method.__isabstractmethod__=self.__isabstractmethod__\n _method.register=self.register\n update_wrapper(_method,self.func)\n \n if self._method_cache is not None:\n self._method_cache[obj]=_method\n \n return _method\n \n @property\n def __isabstractmethod__(self):\n return getattr(self.func,'__isabstractmethod__',False)\n \n \n \n \n \n \n_NOT_FOUND=object()\n\nclass cached_property:\n def __init__(self,func):\n self.func=func\n self.attrname=None\n self.__doc__=func.__doc__\n self.__module__=func.__module__\n \n def __set_name__(self,owner,name):\n if self.attrname is None:\n self.attrname=name\n elif name !=self.attrname:\n raise TypeError(\n \"Cannot assign the same cached_property to two different names \"\n f\"({self.attrname !r} and {name !r}).\"\n )\n \n def __get__(self,instance,owner=None):\n if instance is None:\n return self\n if self.attrname is None:\n raise TypeError(\n \"Cannot use cached_property instance without calling __set_name__ on it.\")\n try:\n cache=instance.__dict__\n except AttributeError:\n msg=(\n f\"No '__dict__' attribute on {type(instance).__name__ !r} \"\n f\"instance to cache {self.attrname !r} property.\"\n )\n raise TypeError(msg)from None\n val=cache.get(self.attrname,_NOT_FOUND)\n if val is _NOT_FOUND:\n val=self.func(instance)\n try:\n cache[self.attrname]=val\n except TypeError:\n msg=(\n f\"The '__dict__' attribute on {type(instance).__name__ !r} instance \"\n f\"does not support item assignment for caching {self.attrname !r} property.\"\n )\n raise TypeError(msg)from None\n return val\n \n __class_getitem__=classmethod(GenericAlias)\n", ["_functools", "_thread", "abc", "collections", "reprlib", "types", "typing", "warnings", "weakref"]], "gc": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nDEBUG_COLLECTABLE=2\n\nDEBUG_LEAK=38\n\nDEBUG_SAVEALL=32\n\nDEBUG_STATS=1\n\nDEBUG_UNCOLLECTABLE=4\n\nclass __loader__:\n pass\n \ncallbacks=[]\n\ndef collect(*args,**kw):\n ''\n\n\n\n\n\n \n pass\n \ndef disable(*args,**kw):\n ''\n\n \n pass\n \ndef enable(*args,**kw):\n ''\n\n \n pass\n \ngarbage=[]\n\ndef get_count(*args,**kw):\n ''\n\n \n pass\n \ndef get_debug(*args,**kw):\n ''\n\n \n pass\n \ndef get_objects(*args,**kw):\n ''\n\n\n \n pass\n \ndef get_referents(*args,**kw):\n ''\n pass\n \ndef get_referrers(*args,**kw):\n ''\n pass\n \ndef get_threshold(*args,**kw):\n ''\n\n \n pass\n \ndef is_tracked(*args,**kw):\n ''\n\n\n \n pass\n \ndef isenabled(*args,**kw):\n ''\n\n \n pass\n \ndef set_debug(*args,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n \n pass\n \ndef set_threshold(*args,**kw):\n ''\n\n\n \n pass\n", []], "genericpath": [".py", "''\n\n\n\n\nimport os\nimport stat\n\n__all__=['commonprefix','exists','getatime','getctime','getmtime',\n'getsize','isdevdrive','isdir','isfile','isjunction','islink',\n'lexists','samefile','sameopenfile','samestat']\n\n\n\n\ndef exists(path):\n ''\n try:\n os.stat(path)\n except(OSError,ValueError):\n return False\n return True\n \n \n \ndef lexists(path):\n ''\n try:\n os.lstat(path)\n except(OSError,ValueError):\n return False\n return True\n \n \n \ndef isfile(path):\n ''\n try:\n st=os.stat(path)\n except(OSError,ValueError):\n return False\n return stat.S_ISREG(st.st_mode)\n \n \n \n \n \ndef isdir(s):\n ''\n try:\n st=os.stat(s)\n except(OSError,ValueError):\n return False\n return stat.S_ISDIR(st.st_mode)\n \n \n \n \n \ndef islink(path):\n ''\n try:\n st=os.lstat(path)\n except(OSError,ValueError,AttributeError):\n return False\n return stat.S_ISLNK(st.st_mode)\n \n \n \ndef isjunction(path):\n ''\n \n os.fspath(path)\n return False\n \n \ndef isdevdrive(path):\n ''\n \n os.fspath(path)\n return False\n \n \ndef getsize(filename):\n ''\n return os.stat(filename).st_size\n \n \ndef getmtime(filename):\n ''\n return os.stat(filename).st_mtime\n \n \ndef getatime(filename):\n ''\n return os.stat(filename).st_atime\n \n \ndef getctime(filename):\n ''\n return os.stat(filename).st_ctime\n \n \n \ndef commonprefix(m):\n ''\n if not m:return ''\n \n \n \n \n if not isinstance(m[0],(list,tuple)):\n m=tuple(map(os.fspath,m))\n s1=min(m)\n s2=max(m)\n for i,c in enumerate(s1):\n if c !=s2[i]:\n return s1[:i]\n return s1\n \n \n \ndef samestat(s1,s2):\n ''\n return(s1.st_ino ==s2.st_ino and\n s1.st_dev ==s2.st_dev)\n \n \n \ndef samefile(f1,f2):\n ''\n\n\n\n \n s1=os.stat(f1)\n s2=os.stat(f2)\n return samestat(s1,s2)\n \n \n \n \ndef sameopenfile(fp1,fp2):\n ''\n s1=os.fstat(fp1)\n s2=os.fstat(fp2)\n return samestat(s1,s2)\n \n \n \n \n \n \n \n \n \ndef _splitext(p,sep,altsep,extsep):\n ''\n\n\n \n \n \n sepIndex=p.rfind(sep)\n if altsep:\n altsepIndex=p.rfind(altsep)\n sepIndex=max(sepIndex,altsepIndex)\n \n dotIndex=p.rfind(extsep)\n if dotIndex >sepIndex:\n \n filenameIndex=sepIndex+1\n while filenameIndex [ \\t]+) | # spaces and horizontal tabs\n (?P[0-9]+\\b) | # decimal integer\n (?Pn\\b) | # only n is allowed\n (?P[()]) |\n (?P[-*/%+?:]|[>,\n # <=, >=, ==, !=, &&, ||,\n # ? :\n # unary and bitwise ops\n # not allowed\n (?P\\w+|.) # invalid token\n \"\"\",re.VERBOSE |re.DOTALL)\n\n\ndef _tokenize(plural):\n for mo in re.finditer(_token_pattern,plural):\n kind=mo.lastgroup\n if kind =='WHITESPACES':\n continue\n value=mo.group(kind)\n if kind =='INVALID':\n raise ValueError('invalid token in plural form: %s'%value)\n yield value\n yield ''\n \n \ndef _error(value):\n if value:\n return ValueError('unexpected token in plural form: %s'%value)\n else:\n return ValueError('unexpected end of plural form')\n \n \n_binary_ops=(\n('||',),\n('&&',),\n('==','!='),\n('<','>','<=','>='),\n('+','-'),\n('*','/','%'),\n)\n_binary_ops={op:i for i,ops in enumerate(_binary_ops,1)for op in ops}\n_c2py_ops={'||':'or','&&':'and','/':'//'}\n\n\ndef _parse(tokens,priority=-1):\n result=''\n nexttok=next(tokens)\n while nexttok =='!':\n result +='not '\n nexttok=next(tokens)\n \n if nexttok =='(':\n sub,nexttok=_parse(tokens)\n result='%s(%s)'%(result,sub)\n if nexttok !=')':\n raise ValueError('unbalanced parenthesis in plural form')\n elif nexttok =='n':\n result='%s%s'%(result,nexttok)\n else:\n try:\n value=int(nexttok,10)\n except ValueError:\n raise _error(nexttok)from None\n result='%s%d'%(result,value)\n nexttok=next(tokens)\n \n j=100\n while nexttok in _binary_ops:\n i=_binary_ops[nexttok]\n if i 1000:\n raise ValueError('plural form expression is too long')\n try:\n result,nexttok=_parse(_tokenize(plural))\n if nexttok:\n raise _error(nexttok)\n \n depth=0\n for c in result:\n if c =='(':\n depth +=1\n if depth >20:\n \n \n raise ValueError('plural form expression is too complex')\n elif c ==')':\n depth -=1\n \n ns={'_as_int':_as_int,'__name__':__name__}\n exec('''if True:\n def func(n):\n if not isinstance(n, int):\n n = _as_int(n)\n return int(%s)\n '''%result,ns)\n return ns['func']\n except RecursionError:\n \n raise ValueError('plural form expression is too complex')\n \n \ndef _expand_lang(loc):\n import locale\n loc=locale.normalize(loc)\n COMPONENT_CODESET=1 <<0\n COMPONENT_TERRITORY=1 <<1\n COMPONENT_MODIFIER=1 <<2\n \n mask=0\n pos=loc.find('@')\n if pos >=0:\n modifier=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_MODIFIER\n else:\n modifier=''\n pos=loc.find('.')\n if pos >=0:\n codeset=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_CODESET\n else:\n codeset=''\n pos=loc.find('_')\n if pos >=0:\n territory=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_TERRITORY\n else:\n territory=''\n language=loc\n ret=[]\n for i in range(mask+1):\n if not(i&~mask):\n val=language\n if i&COMPONENT_TERRITORY:val +=territory\n if i&COMPONENT_CODESET:val +=codeset\n if i&COMPONENT_MODIFIER:val +=modifier\n ret.append(val)\n ret.reverse()\n return ret\n \n \nclass NullTranslations:\n def __init__(self,fp=None):\n self._info={}\n self._charset=None\n self._fallback=None\n if fp is not None:\n self._parse(fp)\n \n def _parse(self,fp):\n pass\n \n def add_fallback(self,fallback):\n if self._fallback:\n self._fallback.add_fallback(fallback)\n else:\n self._fallback=fallback\n \n def gettext(self,message):\n if self._fallback:\n return self._fallback.gettext(message)\n return message\n \n def ngettext(self,msgid1,msgid2,n):\n if self._fallback:\n return self._fallback.ngettext(msgid1,msgid2,n)\n n=_as_int2(n)\n if n ==1:\n return msgid1\n else:\n return msgid2\n \n def pgettext(self,context,message):\n if self._fallback:\n return self._fallback.pgettext(context,message)\n return message\n \n def npgettext(self,context,msgid1,msgid2,n):\n if self._fallback:\n return self._fallback.npgettext(context,msgid1,msgid2,n)\n n=_as_int2(n)\n if n ==1:\n return msgid1\n else:\n return msgid2\n \n def info(self):\n return self._info\n \n def charset(self):\n return self._charset\n \n def install(self,names=None):\n import builtins\n builtins.__dict__['_']=self.gettext\n if names is not None:\n allowed={'gettext','ngettext','npgettext','pgettext'}\n for name in allowed&set(names):\n builtins.__dict__[name]=getattr(self,name)\n \n \nclass GNUTranslations(NullTranslations):\n\n LE_MAGIC=0x950412de\n BE_MAGIC=0xde120495\n \n \n \n CONTEXT=\"%s\\x04%s\"\n \n \n VERSIONS=(0,1)\n \n def _get_versions(self,version):\n ''\n return(version >>16,version&0xffff)\n \n def _parse(self,fp):\n ''\n \n \n from struct import unpack\n filename=getattr(fp,'name','')\n \n \n self._catalog=catalog={}\n self.plural=lambda n:int(n !=1)\n buf=fp.read()\n buflen=len(buf)\n \n magic=unpack('4I',buf[4:20])\n ii='>II'\n else:\n raise OSError(0,'Bad magic number',filename)\n \n major_version,minor_version=self._get_versions(version)\n \n if major_version not in self.VERSIONS:\n raise OSError(0,'Bad version number '+str(major_version),filename)\n \n \n \n for i in range(0,msgcount):\n mlen,moff=unpack(ii,buf[masteridx:masteridx+8])\n mend=moff+mlen\n tlen,toff=unpack(ii,buf[transidx:transidx+8])\n tend=toff+tlen\n if mend 1 else escaped_seps\n not_sep=f'[^{escaped_seps}]'\n if include_hidden:\n one_last_segment=f'{not_sep}+'\n one_segment=f'{one_last_segment}{any_sep}'\n any_segments=f'(?:.+{any_sep})?'\n any_last_segments='.*'\n else:\n one_last_segment=f'[^{escaped_seps}.]{not_sep}*'\n one_segment=f'{one_last_segment}{any_sep}'\n any_segments=f'(?:{one_segment})*'\n any_last_segments=f'{any_segments}(?:{one_last_segment})?'\n \n results=[]\n parts=re.split(any_sep,pat)\n last_part_idx=len(parts)-1\n for idx,part in enumerate(parts):\n if part =='*':\n results.append(one_segment if idx '\n \n def _init_write(self,filename):\n self.name=filename\n self.crc=zlib.crc32(b\"\")\n self.size=0\n self.writebuf=[]\n self.bufsize=0\n self.offset=0\n \n def _write_gzip_header(self,compresslevel):\n self.fileobj.write(b'\\037\\213')\n self.fileobj.write(b'\\010')\n try:\n \n \n fname=os.path.basename(self.name)\n if not isinstance(fname,bytes):\n fname=fname.encode('latin-1')\n if fname.endswith(b'.gz'):\n fname=fname[:-3]\n except UnicodeEncodeError:\n fname=b''\n flags=0\n if fname:\n flags=FNAME\n self.fileobj.write(chr(flags).encode('latin-1'))\n mtime=self._write_mtime\n if mtime is None:\n mtime=time.time()\n write32u(self.fileobj,int(mtime))\n if compresslevel ==_COMPRESS_LEVEL_BEST:\n xfl=b'\\002'\n elif compresslevel ==_COMPRESS_LEVEL_FAST:\n xfl=b'\\004'\n else:\n xfl=b'\\000'\n self.fileobj.write(xfl)\n self.fileobj.write(b'\\377')\n if fname:\n self.fileobj.write(fname+b'\\000')\n \n def write(self,data):\n self._check_not_closed()\n if self.mode !=WRITE:\n import errno\n raise OSError(errno.EBADF,\"write() on read-only GzipFile object\")\n \n if self.fileobj is None:\n raise ValueError(\"write() on closed GzipFile object\")\n \n if isinstance(data,(bytes,bytearray)):\n length=len(data)\n else:\n \n data=memoryview(data)\n length=data.nbytes\n \n if length >0:\n self.fileobj.write(self.compress.compress(data))\n self.size +=length\n self.crc=zlib.crc32(data,self.crc)\n self.offset +=length\n \n return length\n \n def read(self,size=-1):\n self._check_not_closed()\n if self.mode !=READ:\n import errno\n raise OSError(errno.EBADF,\"read() on write-only GzipFile object\")\n return self._buffer.read(size)\n \n def read1(self,size=-1):\n ''\n\n \n self._check_not_closed()\n if self.mode !=READ:\n import errno\n raise OSError(errno.EBADF,\"read1() on write-only GzipFile object\")\n \n if size <0:\n size=io.DEFAULT_BUFFER_SIZE\n return self._buffer.read1(size)\n \n def peek(self,n):\n self._check_not_closed()\n if self.mode !=READ:\n import errno\n raise OSError(errno.EBADF,\"peek() on write-only GzipFile object\")\n return self._buffer.peek(n)\n \n @property\n def closed(self):\n return self.fileobj is None\n \n def close(self):\n fileobj=self.fileobj\n if fileobj is None:\n return\n self.fileobj=None\n try:\n if self.mode ==WRITE:\n fileobj.write(self.compress.flush())\n write32u(fileobj,self.crc)\n \n write32u(fileobj,self.size&0xffffffff)\n elif self.mode ==READ:\n self._buffer.close()\n finally:\n myfileobj=self.myfileobj\n if myfileobj:\n self.myfileobj=None\n myfileobj.close()\n \n def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):\n self._check_not_closed()\n if self.mode ==WRITE:\n \n self.fileobj.write(self.compress.flush(zlib_mode))\n self.fileobj.flush()\n \n def fileno(self):\n ''\n\n\n\n \n return self.fileobj.fileno()\n \n def rewind(self):\n ''\n \n if self.mode !=READ:\n raise OSError(\"Can't rewind in write mode\")\n self._buffer.seek(0)\n \n def readable(self):\n return self.mode ==READ\n \n def writable(self):\n return self.mode ==WRITE\n \n def seekable(self):\n return True\n \n def seek(self,offset,whence=io.SEEK_SET):\n if self.mode ==WRITE:\n if whence !=io.SEEK_SET:\n if whence ==io.SEEK_CUR:\n offset=self.offset+offset\n else:\n raise ValueError('Seek from end not supported')\n if offset startpos:\n parentpos=(pos -1)>>1\n parent=heap[parentpos]\n if newitem startpos:\n parentpos=(pos -1)>>1\n parent=heap[parentpos]\n if parent 1:\n try:\n while True:\n value,order,next=s=h[0]\n yield value\n s[0]=next()\n _heapreplace(h,s)\n except StopIteration:\n _heappop(h)\n if h:\n \n value,order,next=h[0]\n yield value\n yield from next.__self__\n return\n \n for order,it in enumerate(map(iter,iterables)):\n try:\n next=it.__next__\n value=next()\n h_append([key(value),order *direction,value,next])\n except StopIteration:\n pass\n _heapify(h)\n while len(h)>1:\n try:\n while True:\n key_value,order,value,next=s=h[0]\n yield value\n value=next()\n s[0]=key(value)\n s[2]=value\n _heapreplace(h,s)\n except StopIteration:\n _heappop(h)\n if h:\n key_value,order,value,next=h[0]\n yield value\n yield from next.__self__\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef nsmallest(n,iterable,key=None):\n ''\n\n\n \n \n \n if n ==1:\n it=iter(iterable)\n sentinel=object()\n result=min(it,default=sentinel,key=key)\n return[]if result is sentinel else[result]\n \n \n try:\n size=len(iterable)\n except(TypeError,AttributeError):\n pass\n else:\n if n >=size:\n return sorted(iterable,key=key)[:n]\n \n \n if key is None:\n it=iter(iterable)\n \n \n result=[(elem,i)for i,elem in zip(range(n),it)]\n if not result:\n return result\n _heapify_max(result)\n top=result[0][0]\n order=n\n _heapreplace=_heapreplace_max\n for elem in it:\n if elem =size:\n return sorted(iterable,key=key,reverse=True)[:n]\n \n \n if key is None:\n it=iter(iterable)\n result=[(elem,i)for i,elem in zip(range(0,-n,-1),it)]\n if not result:\n return result\n heapify(result)\n top=result[0][0]\n order=-n\n _heapreplace=heapreplace\n for elem in it:\n if top blocksize:\n key=digest_cons(key).digest()\n \n \n \n self.block_size=blocksize\n \n key=key.ljust(blocksize,b'\\0')\n self._outer.update(key.translate(trans_5C))\n self._inner.update(key.translate(trans_36))\n if msg is not None:\n self.update(msg)\n \n @property\n def name(self):\n if self._hmac:\n return self._hmac.name\n else:\n return f\"hmac-{self._inner.name}\"\n \n def update(self,msg):\n ''\n inst=self._hmac or self._inner\n inst.update(msg)\n \n def copy(self):\n ''\n\n\n \n \n other=self.__class__.__new__(self.__class__)\n other.digest_size=self.digest_size\n if self._hmac:\n other._hmac=self._hmac.copy()\n other._inner=other._outer=None\n else:\n other._hmac=None\n other._inner=self._inner.copy()\n other._outer=self._outer.copy()\n return other\n \n def _current(self):\n ''\n\n\n \n if self._hmac:\n return self._hmac\n else:\n h=self._outer.copy()\n h.update(self._inner.digest())\n return h\n \n def digest(self):\n ''\n\n\n\n\n \n h=self._current()\n return h.digest()\n \n def hexdigest(self):\n ''\n \n h=self._current()\n return h.hexdigest()\n \ndef new(key,msg=None,digestmod=''):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return HMAC(key,msg,digestmod)\n \n \ndef digest(key,msg,digest):\n ''\n\n\n\n\n\n\n \n if _hashopenssl is not None and isinstance(digest,(str,_functype)):\n try:\n return _hashopenssl.hmac_digest(key,msg,digest)\n except _hashopenssl.UnsupportedDigestmodError:\n pass\n \n if callable(digest):\n digest_cons=digest\n elif isinstance(digest,str):\n digest_cons=lambda d=b'':_hashlib.new(digest,d)\n else:\n digest_cons=lambda d=b'':digest.new(d)\n \n inner=digest_cons()\n outer=digest_cons()\n blocksize=getattr(inner,'block_size',64)\n if len(key)>blocksize:\n key=digest_cons(key).digest()\n key=key+b'\\x00'*(blocksize -len(key))\n inner.update(key.translate(trans_36))\n outer.update(key.translate(trans_5C))\n inner.update(msg)\n outer.update(inner.digest())\n return outer.digest()\n", ["_hashlib", "_operator", "hashlib", "warnings"]], "imp": [".py", "''\n\n\n\n\n\n\n\nfrom _imp import(lock_held,acquire_lock,release_lock,\nget_frozen_object,is_frozen_package,\ninit_frozen,is_builtin,is_frozen,\n_fix_co_filename,_frozen_module_names)\ntry:\n from _imp import create_dynamic\nexcept ImportError:\n\n create_dynamic=None\n \nfrom importlib._bootstrap import _ERR_MSG,_exec,_load,_builtin_from_name\nfrom importlib._bootstrap_external import SourcelessFileLoader\n\nfrom importlib import machinery\nfrom importlib import util\nimport importlib\nimport os\nimport sys\nimport tokenize\nimport types\nimport warnings\n\nwarnings.warn(\"the imp module is deprecated in favour of importlib and slated \"\n\"for removal in Python 3.12; \"\n\"see the module's documentation for alternative uses\",\nDeprecationWarning,stacklevel=2)\n\n\nSEARCH_ERROR=0\nPY_SOURCE=1\nPY_COMPILED=2\nC_EXTENSION=3\nPY_RESOURCE=4\nPKG_DIRECTORY=5\nC_BUILTIN=6\nPY_FROZEN=7\nPY_CODERESOURCE=8\nIMP_HOOK=9\n\n\ndef new_module(name):\n ''\n\n\n\n\n\n \n return types.ModuleType(name)\n \n \ndef get_magic():\n ''\n\n\n \n return util.MAGIC_NUMBER\n \n \ndef get_tag():\n ''\n return sys.implementation.cache_tag\n \n \ndef cache_from_source(path,debug_override=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n return util.cache_from_source(path,debug_override)\n \n \ndef source_from_cache(path):\n ''\n\n\n\n\n\n\n\n\n \n return util.source_from_cache(path)\n \n \ndef get_suffixes():\n ''\n extensions=[(s,'rb',C_EXTENSION)for s in machinery.EXTENSION_SUFFIXES]\n source=[(s,'r',PY_SOURCE)for s in machinery.SOURCE_SUFFIXES]\n bytecode=[(s,'rb',PY_COMPILED)for s in machinery.BYTECODE_SUFFIXES]\n \n return extensions+source+bytecode\n \n \nclass NullImporter:\n\n ''\n\n\n\n \n \n def __init__(self,path):\n if path =='':\n raise ImportError('empty pathname',path='')\n elif os.path.isdir(path):\n raise ImportError('existing directory',path=path)\n \n def find_module(self,fullname):\n ''\n return None\n \n \nclass _HackedGetData:\n\n ''\n \n \n def __init__(self,fullname,path,file=None):\n super().__init__(fullname,path)\n self.file=file\n \n def get_data(self,path):\n ''\n if self.file and path ==self.path:\n \n \n if not self.file.closed:\n file=self.file\n if 'b'not in file.mode:\n file.close()\n if self.file.closed:\n self.file=file=open(self.path,'rb')\n \n with file:\n return file.read()\n else:\n return super().get_data(path)\n \n \nclass _LoadSourceCompatibility(_HackedGetData,machinery.SourceFileLoader):\n\n ''\n \n \ndef load_source(name,pathname,file=None):\n loader=_LoadSourceCompatibility(name,pathname,file)\n spec=util.spec_from_file_location(name,pathname,loader=loader)\n if name in sys.modules:\n module=_exec(spec,sys.modules[name])\n else:\n module=_load(spec)\n \n \n module.__loader__=machinery.SourceFileLoader(name,pathname)\n module.__spec__.loader=module.__loader__\n return module\n \n \nclass _LoadCompiledCompatibility(_HackedGetData,SourcelessFileLoader):\n\n ''\n \n \ndef load_compiled(name,pathname,file=None):\n ''\n loader=_LoadCompiledCompatibility(name,pathname,file)\n spec=util.spec_from_file_location(name,pathname,loader=loader)\n if name in sys.modules:\n module=_exec(spec,sys.modules[name])\n else:\n module=_load(spec)\n \n \n module.__loader__=SourcelessFileLoader(name,pathname)\n module.__spec__.loader=module.__loader__\n return module\n \n \ndef load_package(name,path):\n ''\n if os.path.isdir(path):\n extensions=(machinery.SOURCE_SUFFIXES[:]+\n machinery.BYTECODE_SUFFIXES[:])\n for extension in extensions:\n init_path=os.path.join(path,'__init__'+extension)\n if os.path.exists(init_path):\n path=init_path\n break\n else:\n raise ValueError('{!r} is not a package'.format(path))\n spec=util.spec_from_file_location(name,path,\n submodule_search_locations=[])\n if name in sys.modules:\n return _exec(spec,sys.modules[name])\n else:\n return _load(spec)\n \n \ndef load_module(name,file,filename,details):\n ''\n\n\n\n\n\n \n suffix,mode,type_=details\n if mode and(not mode.startswith('r')or '+'in mode):\n raise ValueError('invalid file open mode {!r}'.format(mode))\n elif file is None and type_ in{PY_SOURCE,PY_COMPILED}:\n msg='file object required for import (type code {})'.format(type_)\n raise ValueError(msg)\n elif type_ ==PY_SOURCE:\n return load_source(name,filename,file)\n elif type_ ==PY_COMPILED:\n return load_compiled(name,filename,file)\n elif type_ ==C_EXTENSION and load_dynamic is not None:\n if file is None:\n with open(filename,'rb')as opened_file:\n return load_dynamic(name,filename,opened_file)\n else:\n return load_dynamic(name,filename,file)\n elif type_ ==PKG_DIRECTORY:\n return load_package(name,filename)\n elif type_ ==C_BUILTIN:\n return init_builtin(name)\n elif type_ ==PY_FROZEN:\n return init_frozen(name)\n else:\n msg=\"Don't know how to import {} (type code {})\".format(name,type_)\n raise ImportError(msg,name=name)\n \n \ndef find_module(name,path=None):\n ''\n\n\n\n\n\n\n\n\n \n if not isinstance(name,str):\n raise TypeError(\"'name' must be a str, not {}\".format(type(name)))\n elif not isinstance(path,(type(None),list)):\n \n raise RuntimeError(\"'path' must be None or a list, \"\n \"not {}\".format(type(path)))\n \n if path is None:\n if is_builtin(name):\n return None,None,('','',C_BUILTIN)\n elif is_frozen(name):\n return None,None,('','',PY_FROZEN)\n else:\n path=sys.path\n \n for entry in path:\n package_directory=os.path.join(entry,name)\n for suffix in['.py',machinery.BYTECODE_SUFFIXES[0]]:\n package_file_name='__init__'+suffix\n file_path=os.path.join(package_directory,package_file_name)\n if os.path.isfile(file_path):\n return None,package_directory,('','',PKG_DIRECTORY)\n for suffix,mode,type_ in get_suffixes():\n file_name=name+suffix\n file_path=os.path.join(entry,file_name)\n if os.path.isfile(file_path):\n break\n else:\n continue\n break\n else:\n raise ImportError(_ERR_MSG.format(name),name=name)\n \n encoding=None\n if 'b'not in mode:\n with open(file_path,'rb')as file:\n encoding=tokenize.detect_encoding(file.readline)[0]\n file=open(file_path,mode,encoding=encoding)\n return file,file_path,(suffix,mode,type_)\n \n \ndef reload(module):\n ''\n\n\n\n\n\n \n return importlib.reload(module)\n \n \ndef init_builtin(name):\n ''\n\n\n\n \n try:\n return _builtin_from_name(name)\n except ImportError:\n return None\n \n \nif create_dynamic:\n def load_dynamic(name,path,file=None):\n ''\n\n\n \n import importlib.machinery\n loader=importlib.machinery.ExtensionFileLoader(name,path)\n \n \n \n spec=importlib.machinery.ModuleSpec(\n name=name,loader=loader,origin=path)\n return _load(spec)\n \nelse:\n load_dynamic=None\n", ["_imp", "importlib", "importlib._bootstrap", "importlib._bootstrap_external", "importlib.machinery", "importlib.util", "os", "sys", "tokenize", "types", "warnings"]], "inspect": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__=('Ka-Ping Yee ',\n'Yury Selivanov ')\n\n__all__=[\n\"AGEN_CLOSED\",\n\"AGEN_CREATED\",\n\"AGEN_RUNNING\",\n\"AGEN_SUSPENDED\",\n\"ArgInfo\",\n\"Arguments\",\n\"Attribute\",\n\"BlockFinder\",\n\"BoundArguments\",\n\"BufferFlags\",\n\"CORO_CLOSED\",\n\"CORO_CREATED\",\n\"CORO_RUNNING\",\n\"CORO_SUSPENDED\",\n\"CO_ASYNC_GENERATOR\",\n\"CO_COROUTINE\",\n\"CO_GENERATOR\",\n\"CO_ITERABLE_COROUTINE\",\n\"CO_NESTED\",\n\"CO_NEWLOCALS\",\n\"CO_NOFREE\",\n\"CO_OPTIMIZED\",\n\"CO_VARARGS\",\n\"CO_VARKEYWORDS\",\n\"ClassFoundException\",\n\"ClosureVars\",\n\"EndOfBlock\",\n\"FrameInfo\",\n\"FullArgSpec\",\n\"GEN_CLOSED\",\n\"GEN_CREATED\",\n\"GEN_RUNNING\",\n\"GEN_SUSPENDED\",\n\"Parameter\",\n\"Signature\",\n\"TPFLAGS_IS_ABSTRACT\",\n\"Traceback\",\n\"classify_class_attrs\",\n\"cleandoc\",\n\"currentframe\",\n\"findsource\",\n\"formatannotation\",\n\"formatannotationrelativeto\",\n\"formatargvalues\",\n\"get_annotations\",\n\"getabsfile\",\n\"getargs\",\n\"getargvalues\",\n\"getasyncgenlocals\",\n\"getasyncgenstate\",\n\"getattr_static\",\n\"getblock\",\n\"getcallargs\",\n\"getclasstree\",\n\"getclosurevars\",\n\"getcomments\",\n\"getcoroutinelocals\",\n\"getcoroutinestate\",\n\"getdoc\",\n\"getfile\",\n\"getframeinfo\",\n\"getfullargspec\",\n\"getgeneratorlocals\",\n\"getgeneratorstate\",\n\"getinnerframes\",\n\"getlineno\",\n\"getmembers\",\n\"getmembers_static\",\n\"getmodule\",\n\"getmodulename\",\n\"getmro\",\n\"getouterframes\",\n\"getsource\",\n\"getsourcefile\",\n\"getsourcelines\",\n\"indentsize\",\n\"isabstract\",\n\"isasyncgen\",\n\"isasyncgenfunction\",\n\"isawaitable\",\n\"isbuiltin\",\n\"isclass\",\n\"iscode\",\n\"iscoroutine\",\n\"iscoroutinefunction\",\n\"isdatadescriptor\",\n\"isframe\",\n\"isfunction\",\n\"isgenerator\",\n\"isgeneratorfunction\",\n\"isgetsetdescriptor\",\n\"ismemberdescriptor\",\n\"ismethod\",\n\"ismethoddescriptor\",\n\"ismethodwrapper\",\n\"ismodule\",\n\"isroutine\",\n\"istraceback\",\n\"markcoroutinefunction\",\n\"signature\",\n\"stack\",\n\"trace\",\n\"unwrap\",\n\"walktree\",\n]\n\n\nimport abc\nimport ast\nimport dis\nimport collections.abc\nimport enum\nimport importlib.machinery\nimport itertools\nimport linecache\nimport os\nimport re\nimport sys\nimport tokenize\nimport token\nimport types\nimport functools\nimport builtins\nfrom keyword import iskeyword\nfrom operator import attrgetter\nfrom collections import namedtuple,OrderedDict\nfrom weakref import ref as make_weakref\n\n\n\nmod_dict=globals()\nfor k,v in dis.COMPILER_FLAG_NAMES.items():\n mod_dict[\"CO_\"+v]=k\ndel k,v,mod_dict\n\n\nTPFLAGS_IS_ABSTRACT=1 <<20\n\n\ndef get_annotations(obj,*,globals=None,locals=None,eval_str=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(obj,type):\n \n obj_dict=getattr(obj,'__dict__',None)\n if obj_dict and hasattr(obj_dict,'get'):\n ann=obj_dict.get('__annotations__',None)\n if isinstance(ann,types.GetSetDescriptorType):\n ann=None\n else:\n ann=None\n \n obj_globals=None\n module_name=getattr(obj,'__module__',None)\n if module_name:\n module=sys.modules.get(module_name,None)\n if module:\n obj_globals=getattr(module,'__dict__',None)\n obj_locals=dict(vars(obj))\n unwrap=obj\n elif isinstance(obj,types.ModuleType):\n \n ann=getattr(obj,'__annotations__',None)\n obj_globals=getattr(obj,'__dict__')\n obj_locals=None\n unwrap=None\n elif callable(obj):\n \n \n \n ann=getattr(obj,'__annotations__',None)\n obj_globals=getattr(obj,'__globals__',None)\n obj_locals=None\n unwrap=obj\n else:\n raise TypeError(f\"{obj !r} is not a module, class, or callable.\")\n \n if ann is None:\n return{}\n \n if not isinstance(ann,dict):\n raise ValueError(f\"{obj !r}.__annotations__ is neither a dict nor None\")\n \n if not ann:\n return{}\n \n if not eval_str:\n return dict(ann)\n \n if unwrap is not None:\n while True:\n if hasattr(unwrap,'__wrapped__'):\n unwrap=unwrap.__wrapped__\n continue\n if isinstance(unwrap,functools.partial):\n unwrap=unwrap.func\n continue\n break\n if hasattr(unwrap,\"__globals__\"):\n obj_globals=unwrap.__globals__\n \n if globals is None:\n globals=obj_globals\n if locals is None:\n locals=obj_locals or{}\n \n \n \n \n if type_params :=getattr(obj,\"__type_params__\",()):\n locals={param.__name__:param for param in type_params}|locals\n \n return_value={key:\n value if not isinstance(value,str)else eval(value,globals,locals)\n for key,value in ann.items()}\n return return_value\n \n \n \ndef ismodule(object):\n ''\n return isinstance(object,types.ModuleType)\n \ndef isclass(object):\n ''\n return isinstance(object,type)\n \ndef ismethod(object):\n ''\n return isinstance(object,types.MethodType)\n \ndef ismethoddescriptor(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isclass(object)or ismethod(object)or isfunction(object):\n \n return False\n tp=type(object)\n return(hasattr(tp,\"__get__\")\n and not hasattr(tp,\"__set__\")\n and not hasattr(tp,\"__delete__\"))\n \ndef isdatadescriptor(object):\n ''\n\n\n\n\n\n \n if isclass(object)or ismethod(object)or isfunction(object):\n \n return False\n tp=type(object)\n return hasattr(tp,\"__set__\")or hasattr(tp,\"__delete__\")\n \nif hasattr(types,'MemberDescriptorType'):\n\n def ismemberdescriptor(object):\n ''\n\n\n \n return isinstance(object,types.MemberDescriptorType)\nelse:\n\n def ismemberdescriptor(object):\n ''\n\n\n \n return False\n \nif hasattr(types,'GetSetDescriptorType'):\n\n def isgetsetdescriptor(object):\n ''\n\n\n \n return isinstance(object,types.GetSetDescriptorType)\nelse:\n\n def isgetsetdescriptor(object):\n ''\n\n\n \n return False\n \ndef isfunction(object):\n ''\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.FunctionType)\n \ndef _has_code_flag(f,flag):\n ''\n\n\n \n f=functools._unwrap_partialmethod(f)\n while ismethod(f):\n f=f.__func__\n f=functools._unwrap_partial(f)\n if not(isfunction(f)or _signature_is_functionlike(f)):\n return False\n return bool(f.__code__.co_flags&flag)\n \ndef isgeneratorfunction(obj):\n ''\n\n\n \n return _has_code_flag(obj,CO_GENERATOR)\n \n \n_is_coroutine_mark=object()\n\ndef _has_coroutine_mark(f):\n while ismethod(f):\n f=f.__func__\n f=functools._unwrap_partial(f)\n return getattr(f,\"_is_coroutine_marker\",None)is _is_coroutine_mark\n \ndef markcoroutinefunction(func):\n ''\n\n \n if hasattr(func,'__func__'):\n func=func.__func__\n func._is_coroutine_marker=_is_coroutine_mark\n return func\n \ndef iscoroutinefunction(obj):\n ''\n\n\n\n \n return _has_code_flag(obj,CO_COROUTINE)or _has_coroutine_mark(obj)\n \ndef isasyncgenfunction(obj):\n ''\n\n\n\n \n return _has_code_flag(obj,CO_ASYNC_GENERATOR)\n \ndef isasyncgen(object):\n ''\n return isinstance(object,types.AsyncGeneratorType)\n \ndef isgenerator(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.GeneratorType)\n \ndef iscoroutine(object):\n ''\n return isinstance(object,types.CoroutineType)\n \ndef isawaitable(object):\n ''\n return(isinstance(object,types.CoroutineType)or\n isinstance(object,types.GeneratorType)and\n bool(object.gi_code.co_flags&CO_ITERABLE_COROUTINE)or\n isinstance(object,collections.abc.Awaitable))\n \ndef istraceback(object):\n ''\n\n\n\n\n\n \n return isinstance(object,types.TracebackType)\n \ndef isframe(object):\n ''\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.FrameType)\n \ndef iscode(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.CodeType)\n \ndef isbuiltin(object):\n ''\n\n\n\n\n \n return isinstance(object,types.BuiltinFunctionType)\n \ndef ismethodwrapper(object):\n ''\n return isinstance(object,types.MethodWrapperType)\n \ndef isroutine(object):\n ''\n return(isbuiltin(object)\n or isfunction(object)\n or ismethod(object)\n or ismethoddescriptor(object)\n or ismethodwrapper(object))\n \ndef isabstract(object):\n ''\n if not isinstance(object,type):\n return False\n if object.__flags__&TPFLAGS_IS_ABSTRACT:\n return True\n if not issubclass(type(object),abc.ABCMeta):\n return False\n if hasattr(object,'__abstractmethods__'):\n \n \n return False\n \n \n for name,value in object.__dict__.items():\n if getattr(value,\"__isabstractmethod__\",False):\n return True\n for base in object.__bases__:\n for name in getattr(base,\"__abstractmethods__\",()):\n value=getattr(object,name,None)\n if getattr(value,\"__isabstractmethod__\",False):\n return True\n return False\n \ndef _getmembers(object,predicate,getter):\n results=[]\n processed=set()\n names=dir(object)\n if isclass(object):\n mro=getmro(object)\n \n \n \n try:\n for base in object.__bases__:\n for k,v in base.__dict__.items():\n if isinstance(v,types.DynamicClassAttribute):\n names.append(k)\n except AttributeError:\n pass\n else:\n mro=()\n for key in names:\n \n \n \n try:\n value=getter(object,key)\n \n if key in processed:\n raise AttributeError\n except AttributeError:\n for base in mro:\n if key in base.__dict__:\n value=base.__dict__[key]\n break\n else:\n \n \n continue\n if not predicate or predicate(value):\n results.append((key,value))\n processed.add(key)\n results.sort(key=lambda pair:pair[0])\n return results\n \ndef getmembers(object,predicate=None):\n ''\n \n return _getmembers(object,predicate,getattr)\n \ndef getmembers_static(object,predicate=None):\n ''\n\n\n\n\n\n\n\n\n\n \n return _getmembers(object,predicate,getattr_static)\n \nAttribute=namedtuple('Attribute','name kind defining_class object')\n\ndef classify_class_attrs(cls):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n mro=getmro(cls)\n metamro=getmro(type(cls))\n metamro=tuple(cls for cls in metamro if cls not in(type,object))\n class_bases=(cls,)+mro\n all_bases=class_bases+metamro\n names=dir(cls)\n \n \n \n for base in mro:\n for k,v in base.__dict__.items():\n if isinstance(v,types.DynamicClassAttribute)and v.fget is not None:\n names.append(k)\n result=[]\n processed=set()\n \n for name in names:\n \n \n \n \n \n \n \n \n \n homecls=None\n get_obj=None\n dict_obj=None\n if name not in processed:\n try:\n if name =='__dict__':\n raise Exception(\"__dict__ is special, don't want the proxy\")\n get_obj=getattr(cls,name)\n except Exception:\n pass\n else:\n homecls=getattr(get_obj,\"__objclass__\",homecls)\n if homecls not in class_bases:\n \n \n homecls=None\n last_cls=None\n \n for srch_cls in class_bases:\n srch_obj=getattr(srch_cls,name,None)\n if srch_obj is get_obj:\n last_cls=srch_cls\n \n for srch_cls in metamro:\n try:\n srch_obj=srch_cls.__getattr__(cls,name)\n except AttributeError:\n continue\n if srch_obj is get_obj:\n last_cls=srch_cls\n if last_cls is not None:\n homecls=last_cls\n for base in all_bases:\n if name in base.__dict__:\n dict_obj=base.__dict__[name]\n if homecls not in metamro:\n homecls=base\n break\n if homecls is None:\n \n \n continue\n obj=get_obj if get_obj is not None else dict_obj\n \n if isinstance(dict_obj,(staticmethod,types.BuiltinMethodType)):\n kind=\"static method\"\n obj=dict_obj\n elif isinstance(dict_obj,(classmethod,types.ClassMethodDescriptorType)):\n kind=\"class method\"\n obj=dict_obj\n elif isinstance(dict_obj,property):\n kind=\"property\"\n obj=dict_obj\n elif isroutine(obj):\n kind=\"method\"\n else:\n kind=\"data\"\n result.append(Attribute(name,kind,homecls,obj))\n processed.add(name)\n return result\n \n \n \ndef getmro(cls):\n ''\n return cls.__mro__\n \n \n \ndef unwrap(func,*,stop=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n f=func\n \n \n memo={id(f):f}\n recursion_limit=sys.getrecursionlimit()\n while not isinstance(func,type)and hasattr(func,'__wrapped__'):\n if stop is not None and stop(func):\n break\n func=func.__wrapped__\n id_func=id(func)\n if(id_func in memo)or(len(memo)>=recursion_limit):\n raise ValueError('wrapper loop when unwrapping {!r}'.format(f))\n memo[id_func]=func\n return func\n \n \ndef indentsize(line):\n ''\n expline=line.expandtabs()\n return len(expline)-len(expline.lstrip())\n \ndef _findclass(func):\n cls=sys.modules.get(func.__module__)\n if cls is None:\n return None\n for name in func.__qualname__.split('.')[:-1]:\n cls=getattr(cls,name)\n if not isclass(cls):\n return None\n return cls\n \ndef _finddoc(obj):\n if isclass(obj):\n for base in obj.__mro__:\n if base is not object:\n try:\n doc=base.__doc__\n except AttributeError:\n continue\n if doc is not None:\n return doc\n return None\n \n if ismethod(obj):\n name=obj.__func__.__name__\n self=obj.__self__\n if(isclass(self)and\n getattr(getattr(self,name,None),'__func__')is obj.__func__):\n \n cls=self\n else:\n cls=self.__class__\n elif isfunction(obj):\n name=obj.__name__\n cls=_findclass(obj)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif isbuiltin(obj):\n name=obj.__name__\n self=obj.__self__\n if(isclass(self)and\n self.__qualname__+'.'+name ==obj.__qualname__):\n \n cls=self\n else:\n cls=self.__class__\n \n elif isinstance(obj,property):\n name=obj.__name__\n cls=_findclass(obj.fget)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif ismethoddescriptor(obj)or isdatadescriptor(obj):\n name=obj.__name__\n cls=obj.__objclass__\n if getattr(cls,name)is not obj:\n return None\n if ismemberdescriptor(obj):\n slots=getattr(cls,'__slots__',None)\n if isinstance(slots,dict)and name in slots:\n return slots[name]\n else:\n return None\n for base in cls.__mro__:\n try:\n doc=getattr(base,name).__doc__\n except AttributeError:\n continue\n if doc is not None:\n return doc\n return None\n \ndef getdoc(object):\n ''\n\n\n\n \n try:\n doc=object.__doc__\n except AttributeError:\n return None\n if doc is None:\n try:\n doc=_finddoc(object)\n except(AttributeError,TypeError):\n return None\n if not isinstance(doc,str):\n return None\n return cleandoc(doc)\n \ndef cleandoc(doc):\n ''\n\n\n \n lines=doc.expandtabs().split('\\n')\n \n \n margin=sys.maxsize\n for line in lines[1:]:\n content=len(line.lstrip(' '))\n if content:\n indent=len(line)-content\n margin=min(margin,indent)\n \n if lines:\n lines[0]=lines[0].lstrip(' ')\n if margin ')))or file.endswith('.fwork'):\n raise OSError('source code not available')\n \n module=getmodule(object,file)\n if module:\n lines=linecache.getlines(file,module.__dict__)\n else:\n lines=linecache.getlines(file)\n if not lines:\n raise OSError('could not get source code')\n \n if ismodule(object):\n return lines,0\n \n if isclass(object):\n try:\n firstlineno=object.__firstlineno__\n except AttributeError:\n raise OSError('source code not available')\n return lines,object.__firstlineno__ -1\n \n if ismethod(object):\n object=object.__func__\n if isfunction(object):\n object=object.__code__\n if istraceback(object):\n object=object.tb_frame\n if isframe(object):\n object=object.f_code\n if iscode(object):\n if not hasattr(object,'co_firstlineno'):\n raise OSError('could not find function definition')\n lnum=object.co_firstlineno -1\n if lnum >=len(lines):\n raise OSError('lineno is out of bounds')\n return lines,lnum\n raise OSError('could not find code object')\n \ndef getcomments(object):\n ''\n\n\n \n try:\n lines,lnum=findsource(object)\n except(OSError,TypeError):\n return None\n \n if ismodule(object):\n \n start=0\n if lines and lines[0][:2]=='#!':start=1\n while start 0:\n indent=indentsize(lines[lnum])\n end=lnum -1\n if end >=0 and lines[end].lstrip()[:1]=='#'and\\\n indentsize(lines[end])==indent:\n comments=[lines[end].expandtabs().lstrip()]\n if end >0:\n end=end -1\n comment=lines[end].expandtabs().lstrip()\n while comment[:1]=='#'and indentsize(lines[end])==indent:\n comments[:0]=[comment]\n end=end -1\n if end <0:break\n comment=lines[end].expandtabs().lstrip()\n while comments and comments[0].strip()=='#':\n comments[:1]=[]\n while comments and comments[-1].strip()=='#':\n comments[-1:]=[]\n return ''.join(comments)\n \nclass EndOfBlock(Exception):pass\n\nclass BlockFinder:\n ''\n def __init__(self):\n self.indent=0\n self.islambda=False\n self.started=False\n self.passline=False\n self.indecorator=False\n self.last=1\n self.body_col0=None\n \n def tokeneater(self,type,token,srowcol,erowcol,line):\n if not self.started and not self.indecorator:\n \n if token ==\"@\":\n self.indecorator=True\n \n elif token in(\"def\",\"class\",\"lambda\"):\n if token ==\"lambda\":\n self.islambda=True\n self.started=True\n self.passline=True\n elif type ==tokenize.NEWLINE:\n self.passline=False\n self.last=srowcol[0]\n if self.islambda:\n raise EndOfBlock\n \n \n if self.indecorator:\n self.indecorator=False\n elif self.passline:\n pass\n elif type ==tokenize.INDENT:\n if self.body_col0 is None and self.started:\n self.body_col0=erowcol[1]\n self.indent=self.indent+1\n self.passline=True\n elif type ==tokenize.DEDENT:\n self.indent=self.indent -1\n \n \n \n if self.indent <=0:\n raise EndOfBlock\n elif type ==tokenize.COMMENT:\n if self.body_col0 is not None and srowcol[1]>=self.body_col0:\n \n self.last=srowcol[0]\n elif self.indent ==0 and type not in(tokenize.COMMENT,tokenize.NL):\n \n \n raise EndOfBlock\n \ndef getblock(lines):\n ''\n blockfinder=BlockFinder()\n try:\n tokens=tokenize.generate_tokens(iter(lines).__next__)\n for _token in tokens:\n blockfinder.tokeneater(*_token)\n except(EndOfBlock,IndentationError):\n pass\n except SyntaxError as e:\n if \"unmatched\"not in e.msg:\n raise e from None\n _,*_token_info=_token\n try:\n blockfinder.tokeneater(tokenize.NEWLINE,*_token_info)\n except(EndOfBlock,IndentationError):\n pass\n return lines[:blockfinder.last]\n \ndef getsourcelines(object):\n ''\n\n\n\n\n\n \n object=unwrap(object)\n lines,lnum=findsource(object)\n \n if istraceback(object):\n object=object.tb_frame\n \n \n if(ismodule(object)or\n (isframe(object)and object.f_code.co_name ==\"\")):\n return lines,0\n else:\n return getblock(lines[lnum:]),lnum+1\n \ndef getsource(object):\n ''\n\n\n\n \n lines,lnum=getsourcelines(object)\n return ''.join(lines)\n \n \ndef walktree(classes,children,parent):\n ''\n results=[]\n classes.sort(key=attrgetter('__module__','__name__'))\n for c in classes:\n results.append((c,c.__bases__))\n if c in children:\n results.append(walktree(children[c],children,c))\n return results\n \ndef getclasstree(classes,unique=False):\n ''\n\n\n\n\n\n\n \n children={}\n roots=[]\n for c in classes:\n if c.__bases__:\n for parent in c.__bases__:\n if parent not in children:\n children[parent]=[]\n if c not in children[parent]:\n children[parent].append(c)\n if unique and parent in classes:break\n elif c not in roots:\n roots.append(c)\n for parent in children:\n if parent not in classes:\n roots.append(parent)\n return walktree(roots,children,None)\n \n \nArguments=namedtuple('Arguments','args, varargs, varkw')\n\ndef getargs(co):\n ''\n\n\n\n\n \n if not iscode(co):\n raise TypeError('{!r} is not a code object'.format(co))\n \n names=co.co_varnames\n nargs=co.co_argcount\n nkwargs=co.co_kwonlyargcount\n args=list(names[:nargs])\n kwonlyargs=list(names[nargs:nargs+nkwargs])\n \n nargs +=nkwargs\n varargs=None\n if co.co_flags&CO_VARARGS:\n varargs=co.co_varnames[nargs]\n nargs=nargs+1\n varkw=None\n if co.co_flags&CO_VARKEYWORDS:\n varkw=co.co_varnames[nargs]\n return Arguments(args+kwonlyargs,varargs,varkw)\n \n \nFullArgSpec=namedtuple('FullArgSpec',\n'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')\n\ndef getfullargspec(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n sig=_signature_from_callable(func,\n follow_wrapper_chains=False,\n skip_bound_arg=False,\n sigcls=Signature,\n eval_str=False)\n except Exception as ex:\n \n \n \n \n raise TypeError('unsupported callable')from ex\n \n args=[]\n varargs=None\n varkw=None\n posonlyargs=[]\n kwonlyargs=[]\n annotations={}\n defaults=()\n kwdefaults={}\n \n if sig.return_annotation is not sig.empty:\n annotations['return']=sig.return_annotation\n \n for param in sig.parameters.values():\n kind=param.kind\n name=param.name\n \n if kind is _POSITIONAL_ONLY:\n posonlyargs.append(name)\n if param.default is not param.empty:\n defaults +=(param.default,)\n elif kind is _POSITIONAL_OR_KEYWORD:\n args.append(name)\n if param.default is not param.empty:\n defaults +=(param.default,)\n elif kind is _VAR_POSITIONAL:\n varargs=name\n elif kind is _KEYWORD_ONLY:\n kwonlyargs.append(name)\n if param.default is not param.empty:\n kwdefaults[name]=param.default\n elif kind is _VAR_KEYWORD:\n varkw=name\n \n if param.annotation is not param.empty:\n annotations[name]=param.annotation\n \n if not kwdefaults:\n \n kwdefaults=None\n \n if not defaults:\n \n defaults=None\n \n return FullArgSpec(posonlyargs+args,varargs,varkw,defaults,\n kwonlyargs,kwdefaults,annotations)\n \n \nArgInfo=namedtuple('ArgInfo','args varargs keywords locals')\n\ndef getargvalues(frame):\n ''\n\n\n\n\n \n args,varargs,varkw=getargs(frame.f_code)\n return ArgInfo(args,varargs,varkw,frame.f_locals)\n \ndef formatannotation(annotation,base_module=None):\n if getattr(annotation,'__module__',None)=='typing':\n def repl(match):\n text=match.group()\n return text.removeprefix('typing.')\n return re.sub(r'[\\w\\.]+',repl,repr(annotation))\n if isinstance(annotation,types.GenericAlias):\n return str(annotation)\n if isinstance(annotation,type):\n if annotation.__module__ in('builtins',base_module):\n return annotation.__qualname__\n return annotation.__module__+'.'+annotation.__qualname__\n return repr(annotation)\n \ndef formatannotationrelativeto(object):\n module=getattr(object,'__module__',None)\n def _formatannotation(annotation):\n return formatannotation(annotation,module)\n return _formatannotation\n \n \ndef formatargvalues(args,varargs,varkw,locals,\nformatarg=str,\nformatvarargs=lambda name:'*'+name,\nformatvarkw=lambda name:'**'+name,\nformatvalue=lambda value:'='+repr(value)):\n ''\n\n\n\n\n \n def convert(name,locals=locals,\n formatarg=formatarg,formatvalue=formatvalue):\n return formatarg(name)+formatvalue(locals[name])\n specs=[]\n for i in range(len(args)):\n specs.append(convert(args[i]))\n if varargs:\n specs.append(formatvarargs(varargs)+formatvalue(locals[varargs]))\n if varkw:\n specs.append(formatvarkw(varkw)+formatvalue(locals[varkw]))\n return '('+', '.join(specs)+')'\n \ndef _missing_arguments(f_name,argnames,pos,values):\n names=[repr(name)for name in argnames if name not in values]\n missing=len(names)\n if missing ==1:\n s=names[0]\n elif missing ==2:\n s=\"{} and {}\".format(*names)\n else:\n tail=\", {} and {}\".format(*names[-2:])\n del names[-2:]\n s=\", \".join(names)+tail\n raise TypeError(\"%s() missing %i required %s argument%s: %s\"%\n (f_name,missing,\n \"positional\"if pos else \"keyword-only\",\n \"\"if missing ==1 else \"s\",s))\n \ndef _too_many(f_name,args,kwonly,varargs,defcount,given,values):\n atleast=len(args)-defcount\n kwonly_given=len([arg for arg in kwonly if arg in values])\n if varargs:\n plural=atleast !=1\n sig=\"at least %d\"%(atleast,)\n elif defcount:\n plural=True\n sig=\"from %d to %d\"%(atleast,len(args))\n else:\n plural=len(args)!=1\n sig=str(len(args))\n kwonly_sig=\"\"\n if kwonly_given:\n msg=\" positional argument%s (and %d keyword-only argument%s)\"\n kwonly_sig=(msg %(\"s\"if given !=1 else \"\",kwonly_given,\n \"s\"if kwonly_given !=1 else \"\"))\n raise TypeError(\"%s() takes %s positional argument%s but %d%s %s given\"%\n (f_name,sig,\"s\"if plural else \"\",given,kwonly_sig,\n \"was\"if given ==1 and not kwonly_given else \"were\"))\n \ndef getcallargs(func,/,*positional,**named):\n ''\n\n\n\n \n spec=getfullargspec(func)\n args,varargs,varkw,defaults,kwonlyargs,kwonlydefaults,ann=spec\n f_name=func.__name__\n arg2value={}\n \n \n if ismethod(func)and func.__self__ is not None:\n \n positional=(func.__self__,)+positional\n num_pos=len(positional)\n num_args=len(args)\n num_defaults=len(defaults)if defaults else 0\n \n n=min(num_pos,num_args)\n for i in range(n):\n arg2value[args[i]]=positional[i]\n if varargs:\n arg2value[varargs]=tuple(positional[n:])\n possible_kwargs=set(args+kwonlyargs)\n if varkw:\n arg2value[varkw]={}\n for kw,value in named.items():\n if kw not in possible_kwargs:\n if not varkw:\n raise TypeError(\"%s() got an unexpected keyword argument %r\"%\n (f_name,kw))\n arg2value[varkw][kw]=value\n continue\n if kw in arg2value:\n raise TypeError(\"%s() got multiple values for argument %r\"%\n (f_name,kw))\n arg2value[kw]=value\n if num_pos >num_args and not varargs:\n _too_many(f_name,args,kwonlyargs,varargs,num_defaults,\n num_pos,arg2value)\n if num_pos 0:\n start=lineno -1 -context //2\n try:\n lines,lnum=findsource(frame)\n except OSError:\n lines=index=None\n else:\n start=max(0,min(start,len(lines)-context))\n lines=lines[start:start+context]\n index=lineno -1 -start\n else:\n lines=index=None\n \n return Traceback(filename,lineno,frame.f_code.co_name,lines,\n index,positions=dis.Positions(*positions))\n \ndef getlineno(frame):\n ''\n \n return frame.f_lineno\n \n_FrameInfo=namedtuple('_FrameInfo',('frame',)+Traceback._fields)\nclass FrameInfo(_FrameInfo):\n def __new__(cls,frame,filename,lineno,function,code_context,index,*,positions=None):\n instance=super().__new__(cls,frame,filename,lineno,function,code_context,index)\n instance.positions=positions\n return instance\n \n def __repr__(self):\n return('FrameInfo(frame={!r}, filename={!r}, lineno={!r}, function={!r}, '\n 'code_context={!r}, index={!r}, positions={!r})'.format(\n self.frame,self.filename,self.lineno,self.function,\n self.code_context,self.index,self.positions))\n \ndef getouterframes(frame,context=1):\n ''\n\n\n \n framelist=[]\n while frame:\n traceback_info=getframeinfo(frame,context)\n frameinfo=(frame,)+traceback_info\n framelist.append(FrameInfo(*frameinfo,positions=traceback_info.positions))\n frame=frame.f_back\n return framelist\n \ndef getinnerframes(tb,context=1):\n ''\n\n\n \n framelist=[]\n while tb:\n traceback_info=getframeinfo(tb,context)\n frameinfo=(tb.tb_frame,)+traceback_info\n framelist.append(FrameInfo(*frameinfo,positions=traceback_info.positions))\n tb=tb.tb_next\n return framelist\n \ndef currentframe():\n ''\n return sys._getframe(1)if hasattr(sys,\"_getframe\")else None\n \ndef stack(context=1):\n ''\n return getouterframes(sys._getframe(1),context)\n \ndef trace(context=1):\n ''\n exc=sys.exception()\n tb=None if exc is None else exc.__traceback__\n return getinnerframes(tb,context)\n \n \n \n \n_sentinel=object()\n_static_getmro=type.__dict__['__mro__'].__get__\n_get_dunder_dict_of_class=type.__dict__[\"__dict__\"].__get__\n\n\ndef _check_instance(obj,attr):\n instance_dict={}\n try:\n instance_dict=object.__getattribute__(obj,\"__dict__\")\n except AttributeError:\n pass\n return dict.get(instance_dict,attr,_sentinel)\n \n \ndef _check_class(klass,attr):\n for entry in _static_getmro(klass):\n if _shadowed_dict(type(entry))is _sentinel and attr in entry.__dict__:\n return entry.__dict__[attr]\n return _sentinel\n \n \n@functools.lru_cache()\ndef _shadowed_dict_from_weakref_mro_tuple(*weakref_mro):\n for weakref_entry in weakref_mro:\n \n \n \n \n \n entry=weakref_entry()\n dunder_dict=_get_dunder_dict_of_class(entry)\n if '__dict__'in dunder_dict:\n class_dict=dunder_dict['__dict__']\n if not(type(class_dict)is types.GetSetDescriptorType and\n class_dict.__name__ ==\"__dict__\"and\n class_dict.__objclass__ is entry):\n return class_dict\n return _sentinel\n \n \ndef _shadowed_dict(klass):\n\n\n\n\n\n\n\n return _shadowed_dict_from_weakref_mro_tuple(\n *[make_weakref(entry)for entry in _static_getmro(klass)]\n )\n \n \ndef getattr_static(obj,attr,default=_sentinel):\n ''\n\n\n\n\n\n\n\n\n \n instance_result=_sentinel\n \n objtype=type(obj)\n if type not in _static_getmro(objtype):\n klass=objtype\n dict_attr=_shadowed_dict(klass)\n if(dict_attr is _sentinel or\n type(dict_attr)is types.MemberDescriptorType):\n instance_result=_check_instance(obj,attr)\n else:\n klass=obj\n \n klass_result=_check_class(klass,attr)\n \n if instance_result is not _sentinel and klass_result is not _sentinel:\n if _check_class(type(klass_result),\"__get__\")is not _sentinel and(\n _check_class(type(klass_result),\"__set__\")is not _sentinel\n or _check_class(type(klass_result),\"__delete__\")is not _sentinel\n ):\n return klass_result\n \n if instance_result is not _sentinel:\n return instance_result\n if klass_result is not _sentinel:\n return klass_result\n \n if obj is klass:\n \n for entry in _static_getmro(type(klass)):\n if(\n _shadowed_dict(type(entry))is _sentinel\n and attr in entry.__dict__\n ):\n return entry.__dict__[attr]\n if default is not _sentinel:\n return default\n raise AttributeError(attr)\n \n \n \n \nGEN_CREATED='GEN_CREATED'\nGEN_RUNNING='GEN_RUNNING'\nGEN_SUSPENDED='GEN_SUSPENDED'\nGEN_CLOSED='GEN_CLOSED'\n\ndef getgeneratorstate(generator):\n ''\n\n\n\n\n\n\n \n if generator.gi_running:\n return GEN_RUNNING\n if generator.gi_suspended:\n return GEN_SUSPENDED\n if generator.gi_frame is None:\n return GEN_CLOSED\n return GEN_CREATED\n \n \ndef getgeneratorlocals(generator):\n ''\n\n\n\n \n \n if not isgenerator(generator):\n raise TypeError(\"{!r} is not a Python generator\".format(generator))\n \n frame=getattr(generator,\"gi_frame\",None)\n if frame is not None:\n return generator.gi_frame.f_locals\n else:\n return{}\n \n \n \n \nCORO_CREATED='CORO_CREATED'\nCORO_RUNNING='CORO_RUNNING'\nCORO_SUSPENDED='CORO_SUSPENDED'\nCORO_CLOSED='CORO_CLOSED'\n\ndef getcoroutinestate(coroutine):\n ''\n\n\n\n\n\n\n \n if coroutine.cr_running:\n return CORO_RUNNING\n if coroutine.cr_suspended:\n return CORO_SUSPENDED\n if coroutine.cr_frame is None:\n return CORO_CLOSED\n return CORO_CREATED\n \n \ndef getcoroutinelocals(coroutine):\n ''\n\n\n\n \n frame=getattr(coroutine,\"cr_frame\",None)\n if frame is not None:\n return frame.f_locals\n else:\n return{}\n \n \n \n \nAGEN_CREATED='AGEN_CREATED'\nAGEN_RUNNING='AGEN_RUNNING'\nAGEN_SUSPENDED='AGEN_SUSPENDED'\nAGEN_CLOSED='AGEN_CLOSED'\n\n\ndef getasyncgenstate(agen):\n ''\n\n\n\n\n\n\n \n if agen.ag_running:\n return AGEN_RUNNING\n if agen.ag_suspended:\n return AGEN_SUSPENDED\n if agen.ag_frame is None:\n return AGEN_CLOSED\n return AGEN_CREATED\n \n \ndef getasyncgenlocals(agen):\n ''\n\n\n\n\n \n \n if not isasyncgen(agen):\n raise TypeError(f\"{agen !r} is not a Python async generator\")\n \n frame=getattr(agen,\"ag_frame\",None)\n if frame is not None:\n return agen.ag_frame.f_locals\n else:\n return{}\n \n \n \n \n \n \n \n_NonUserDefinedCallables=(types.WrapperDescriptorType,\ntypes.MethodWrapperType,\ntypes.ClassMethodDescriptorType,\ntypes.BuiltinFunctionType)\n\n\ndef _signature_get_user_defined_method(cls,method_name):\n ''\n\n\n \n if method_name =='__new__':\n meth=getattr(cls,method_name,None)\n else:\n meth=getattr_static(cls,method_name,None)\n if meth is None or isinstance(meth,_NonUserDefinedCallables):\n \n \n return None\n if method_name !='__new__':\n meth=_descriptor_get(meth,cls)\n return meth\n \n \ndef _signature_get_partial(wrapped_sig,partial,extra_args=()):\n ''\n\n\n \n \n old_params=wrapped_sig.parameters\n new_params=OrderedDict(old_params.items())\n \n partial_args=partial.args or()\n partial_keywords=partial.keywords or{}\n \n if extra_args:\n partial_args=extra_args+partial_args\n \n try:\n ba=wrapped_sig.bind_partial(*partial_args,**partial_keywords)\n except TypeError as ex:\n msg='partial object {!r} has incorrect arguments'.format(partial)\n raise ValueError(msg)from ex\n \n \n transform_to_kwonly=False\n for param_name,param in old_params.items():\n try:\n arg_value=ba.arguments[param_name]\n except KeyError:\n pass\n else:\n if param.kind is _POSITIONAL_ONLY:\n \n \n new_params.pop(param_name)\n continue\n \n if param.kind is _POSITIONAL_OR_KEYWORD:\n if param_name in partial_keywords:\n \n \n \n \n \n \n \n \n \n \n \n \n transform_to_kwonly=True\n \n new_params[param_name]=param.replace(default=arg_value)\n else:\n \n new_params.pop(param.name)\n continue\n \n if param.kind is _KEYWORD_ONLY:\n \n new_params[param_name]=param.replace(default=arg_value)\n \n if transform_to_kwonly:\n assert param.kind is not _POSITIONAL_ONLY\n \n if param.kind is _POSITIONAL_OR_KEYWORD:\n new_param=new_params[param_name].replace(kind=_KEYWORD_ONLY)\n new_params[param_name]=new_param\n new_params.move_to_end(param_name)\n elif param.kind in(_KEYWORD_ONLY,_VAR_KEYWORD):\n new_params.move_to_end(param_name)\n elif param.kind is _VAR_POSITIONAL:\n new_params.pop(param.name)\n \n return wrapped_sig.replace(parameters=new_params.values())\n \n \ndef _signature_bound_method(sig):\n ''\n\n \n \n params=tuple(sig.parameters.values())\n \n if not params or params[0].kind in(_VAR_KEYWORD,_KEYWORD_ONLY):\n raise ValueError('invalid method signature')\n \n kind=params[0].kind\n if kind in(_POSITIONAL_OR_KEYWORD,_POSITIONAL_ONLY):\n \n \n params=params[1:]\n else:\n if kind is not _VAR_POSITIONAL:\n \n \n raise ValueError('invalid argument type')\n \n \n \n return sig.replace(parameters=params)\n \n \ndef _signature_is_builtin(obj):\n ''\n\n \n return(isbuiltin(obj)or\n ismethoddescriptor(obj)or\n isinstance(obj,_NonUserDefinedCallables)or\n \n \n \n \n obj is type or obj is object)\n \n \ndef _signature_is_functionlike(obj):\n ''\n\n\n\n \n \n if not callable(obj)or isclass(obj):\n \n \n return False\n \n name=getattr(obj,'__name__',None)\n code=getattr(obj,'__code__',None)\n defaults=getattr(obj,'__defaults__',_void)\n kwdefaults=getattr(obj,'__kwdefaults__',_void)\n annotations=getattr(obj,'__annotations__',None)\n \n return(isinstance(code,types.CodeType)and\n isinstance(name,str)and\n (defaults is None or isinstance(defaults,tuple))and\n (kwdefaults is None or isinstance(kwdefaults,dict))and\n (isinstance(annotations,(dict))or annotations is None))\n \n \ndef _signature_strip_non_python_syntax(signature):\n ''\n\n\n\n\n\n\n\n \n \n if not signature:\n return signature,None\n \n self_parameter=None\n \n lines=[l.encode('ascii')for l in signature.split('\\n')if l]\n generator=iter(lines).__next__\n token_stream=tokenize.tokenize(generator)\n \n text=[]\n add=text.append\n \n current_parameter=0\n OP=token.OP\n ERRORTOKEN=token.ERRORTOKEN\n \n \n t=next(token_stream)\n assert t.type ==tokenize.ENCODING\n \n for t in token_stream:\n type,string=t.type,t.string\n \n if type ==OP:\n if string ==',':\n current_parameter +=1\n \n if(type ==OP)and(string =='$'):\n assert self_parameter is None\n self_parameter=current_parameter\n continue\n \n add(string)\n if(string ==','):\n add(' ')\n clean_signature=''.join(text).strip().replace(\"\\n\",\"\")\n return clean_signature,self_parameter\n \n \ndef _signature_fromstr(cls,obj,s,skip_bound_arg=True):\n ''\n\n \n Parameter=cls._parameter_cls\n \n clean_signature,self_parameter=_signature_strip_non_python_syntax(s)\n \n program=\"def foo\"+clean_signature+\": pass\"\n \n try:\n module=ast.parse(program)\n except SyntaxError:\n module=None\n \n if not isinstance(module,ast.Module):\n raise ValueError(\"{!r} builtin has invalid signature\".format(obj))\n \n f=module.body[0]\n \n parameters=[]\n empty=Parameter.empty\n \n module=None\n module_dict={}\n \n module_name=getattr(obj,'__module__',None)\n if not module_name:\n objclass=getattr(obj,'__objclass__',None)\n module_name=getattr(objclass,'__module__',None)\n \n if module_name:\n module=sys.modules.get(module_name,None)\n if module:\n module_dict=module.__dict__\n sys_module_dict=sys.modules.copy()\n \n def parse_name(node):\n assert isinstance(node,ast.arg)\n if node.annotation is not None:\n raise ValueError(\"Annotations are not currently supported\")\n return node.arg\n \n def wrap_value(s):\n try:\n value=eval(s,module_dict)\n except NameError:\n try:\n value=eval(s,sys_module_dict)\n except NameError:\n raise ValueError\n \n if isinstance(value,(str,int,float,bytes,bool,type(None))):\n return ast.Constant(value)\n raise ValueError\n \n class RewriteSymbolics(ast.NodeTransformer):\n def visit_Attribute(self,node):\n a=[]\n n=node\n while isinstance(n,ast.Attribute):\n a.append(n.attr)\n n=n.value\n if not isinstance(n,ast.Name):\n raise ValueError\n a.append(n.id)\n value=\".\".join(reversed(a))\n return wrap_value(value)\n \n def visit_Name(self,node):\n if not isinstance(node.ctx,ast.Load):\n raise ValueError()\n return wrap_value(node.id)\n \n def visit_BinOp(self,node):\n \n \n left=self.visit(node.left)\n right=self.visit(node.right)\n if not isinstance(left,ast.Constant)or not isinstance(right,ast.Constant):\n raise ValueError\n if isinstance(node.op,ast.Add):\n return ast.Constant(left.value+right.value)\n elif isinstance(node.op,ast.Sub):\n return ast.Constant(left.value -right.value)\n elif isinstance(node.op,ast.BitOr):\n return ast.Constant(left.value |right.value)\n raise ValueError\n \n def p(name_node,default_node,default=empty):\n name=parse_name(name_node)\n if default_node and default_node is not _empty:\n try:\n default_node=RewriteSymbolics().visit(default_node)\n default=ast.literal_eval(default_node)\n except ValueError:\n raise ValueError(\"{!r} builtin has invalid signature\".format(obj))from None\n parameters.append(Parameter(name,kind,default=default,annotation=empty))\n \n \n total_non_kw_args=len(f.args.posonlyargs)+len(f.args.args)\n required_non_kw_args=total_non_kw_args -len(f.args.defaults)\n defaults=itertools.chain(itertools.repeat(None,required_non_kw_args),f.args.defaults)\n \n kind=Parameter.POSITIONAL_ONLY\n for(name,default)in zip(f.args.posonlyargs,defaults):\n p(name,default)\n \n kind=Parameter.POSITIONAL_OR_KEYWORD\n for(name,default)in zip(f.args.args,defaults):\n p(name,default)\n \n \n if f.args.vararg:\n kind=Parameter.VAR_POSITIONAL\n p(f.args.vararg,empty)\n \n \n kind=Parameter.KEYWORD_ONLY\n for name,default in zip(f.args.kwonlyargs,f.args.kw_defaults):\n p(name,default)\n \n \n if f.args.kwarg:\n kind=Parameter.VAR_KEYWORD\n p(f.args.kwarg,empty)\n \n if self_parameter is not None:\n \n \n \n \n \n assert parameters\n _self=getattr(obj,'__self__',None)\n self_isbound=_self is not None\n self_ismodule=ismodule(_self)\n if self_isbound and(self_ismodule or skip_bound_arg):\n parameters.pop(0)\n else:\n \n p=parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)\n parameters[0]=p\n \n return cls(parameters,return_annotation=cls.empty)\n \n \ndef _signature_from_builtin(cls,func,skip_bound_arg=True):\n ''\n\n \n \n if not _signature_is_builtin(func):\n raise TypeError(\"{!r} is not a Python builtin \"\n \"function\".format(func))\n \n s=getattr(func,\"__text_signature__\",None)\n if not s:\n raise ValueError(\"no signature found for builtin {!r}\".format(func))\n \n return _signature_fromstr(cls,func,s,skip_bound_arg)\n \n \ndef _signature_from_function(cls,func,skip_bound_arg=True,\nglobals=None,locals=None,eval_str=False):\n ''\n \n is_duck_function=False\n if not isfunction(func):\n if _signature_is_functionlike(func):\n is_duck_function=True\n else:\n \n \n raise TypeError('{!r} is not a Python function'.format(func))\n \n s=getattr(func,\"__text_signature__\",None)\n if s:\n return _signature_fromstr(cls,func,s,skip_bound_arg)\n \n Parameter=cls._parameter_cls\n \n \n func_code=func.__code__\n pos_count=func_code.co_argcount\n arg_names=func_code.co_varnames\n posonly_count=func_code.co_posonlyargcount\n positional=arg_names[:pos_count]\n keyword_only_count=func_code.co_kwonlyargcount\n keyword_only=arg_names[pos_count:pos_count+keyword_only_count]\n annotations=get_annotations(func,globals=globals,locals=locals,eval_str=eval_str)\n defaults=func.__defaults__\n kwdefaults=func.__kwdefaults__\n \n if defaults:\n pos_default_count=len(defaults)\n else:\n pos_default_count=0\n \n parameters=[]\n \n non_default_count=pos_count -pos_default_count\n posonly_left=posonly_count\n \n \n for name in positional[:non_default_count]:\n kind=_POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=kind))\n if posonly_left:\n posonly_left -=1\n \n \n for offset,name in enumerate(positional[non_default_count:]):\n kind=_POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=kind,\n default=defaults[offset]))\n if posonly_left:\n posonly_left -=1\n \n \n if func_code.co_flags&CO_VARARGS:\n name=arg_names[pos_count+keyword_only_count]\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_VAR_POSITIONAL))\n \n \n for name in keyword_only:\n default=_empty\n if kwdefaults is not None:\n default=kwdefaults.get(name,_empty)\n \n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_KEYWORD_ONLY,\n default=default))\n \n if func_code.co_flags&CO_VARKEYWORDS:\n index=pos_count+keyword_only_count\n if func_code.co_flags&CO_VARARGS:\n index +=1\n \n name=arg_names[index]\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_VAR_KEYWORD))\n \n \n \n return cls(parameters,\n return_annotation=annotations.get('return',_empty),\n __validate_parameters__=is_duck_function)\n \n \ndef _descriptor_get(descriptor,obj):\n if isclass(descriptor):\n return descriptor\n get=getattr(type(descriptor),'__get__',_sentinel)\n if get is _sentinel:\n return descriptor\n return get(descriptor,obj,type(obj))\n \n \ndef _signature_from_callable(obj,*,\nfollow_wrapper_chains=True,\nskip_bound_arg=True,\nglobals=None,\nlocals=None,\neval_str=False,\nsigcls):\n\n ''\n\n \n \n _get_signature_of=functools.partial(_signature_from_callable,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n globals=globals,\n locals=locals,\n sigcls=sigcls,\n eval_str=eval_str)\n \n if not callable(obj):\n raise TypeError('{!r} is not a callable object'.format(obj))\n \n if isinstance(obj,types.MethodType):\n \n \n sig=_get_signature_of(obj.__func__)\n \n if skip_bound_arg:\n return _signature_bound_method(sig)\n else:\n return sig\n \n \n if follow_wrapper_chains:\n \n \n obj=unwrap(obj,stop=(lambda f:hasattr(f,\"__signature__\")\n or isinstance(f,types.MethodType)))\n if isinstance(obj,types.MethodType):\n \n \n \n return _get_signature_of(obj)\n \n try:\n sig=obj.__signature__\n except AttributeError:\n pass\n else:\n if sig is not None:\n \n \n \n o_sig=sig\n if not isinstance(sig,(Signature,str))and callable(sig):\n sig=sig()\n if isinstance(sig,str):\n sig=_signature_fromstr(sigcls,obj,sig)\n if not isinstance(sig,Signature):\n raise TypeError(\n 'unexpected object {!r} in __signature__ '\n 'attribute'.format(o_sig))\n return sig\n \n try:\n partialmethod=obj.__partialmethod__\n except AttributeError:\n pass\n else:\n if isinstance(partialmethod,functools.partialmethod):\n \n \n \n \n \n \n \n wrapped_sig=_get_signature_of(partialmethod.func)\n \n sig=_signature_get_partial(wrapped_sig,partialmethod,(None,))\n first_wrapped_param=tuple(wrapped_sig.parameters.values())[0]\n if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:\n \n \n return sig\n else:\n sig_params=tuple(sig.parameters.values())\n assert(not sig_params or\n first_wrapped_param is not sig_params[0])\n new_params=(first_wrapped_param,)+sig_params\n return sig.replace(parameters=new_params)\n \n if isinstance(obj,functools.partial):\n wrapped_sig=_get_signature_of(obj.func)\n return _signature_get_partial(wrapped_sig,obj)\n \n if isfunction(obj)or _signature_is_functionlike(obj):\n \n \n return _signature_from_function(sigcls,obj,\n skip_bound_arg=skip_bound_arg,\n globals=globals,locals=locals,eval_str=eval_str)\n \n if _signature_is_builtin(obj):\n return _signature_from_builtin(sigcls,obj,\n skip_bound_arg=skip_bound_arg)\n \n if isinstance(obj,type):\n \n \n \n \n call=_signature_get_user_defined_method(type(obj),'__call__')\n if call is not None:\n return _get_signature_of(call)\n \n new=_signature_get_user_defined_method(obj,'__new__')\n init=_signature_get_user_defined_method(obj,'__init__')\n \n \n \n for base in obj.__mro__:\n \n if new is not None and '__new__'in base.__dict__:\n sig=_get_signature_of(new)\n if skip_bound_arg:\n sig=_signature_bound_method(sig)\n return sig\n \n elif init is not None and '__init__'in base.__dict__:\n return _get_signature_of(init)\n \n \n \n \n for base in obj.__mro__[:-1]:\n \n \n \n \n \n \n \n try:\n text_sig=base.__text_signature__\n except AttributeError:\n pass\n else:\n if text_sig:\n \n \n return _signature_fromstr(sigcls,base,text_sig)\n \n \n \n \n if type not in obj.__mro__:\n \n \n if(obj.__init__ is object.__init__ and\n obj.__new__ is object.__new__):\n \n return sigcls.from_callable(object)\n else:\n raise ValueError(\n 'no signature found for builtin type {!r}'.format(obj))\n \n else:\n \n call=getattr_static(type(obj),'__call__',None)\n if call is not None:\n try:\n text_sig=obj.__text_signature__\n except AttributeError:\n pass\n else:\n if text_sig:\n return _signature_fromstr(sigcls,obj,text_sig)\n call=_descriptor_get(call,obj)\n return _get_signature_of(call)\n \n raise ValueError('callable {!r} is not supported by signature'.format(obj))\n \n \nclass _void:\n ''\n \n \nclass _empty:\n ''\n \n \nclass _ParameterKind(enum.IntEnum):\n POSITIONAL_ONLY='positional-only'\n POSITIONAL_OR_KEYWORD='positional or keyword'\n VAR_POSITIONAL='variadic positional'\n KEYWORD_ONLY='keyword-only'\n VAR_KEYWORD='variadic keyword'\n \n def __new__(cls,description):\n value=len(cls.__members__)\n member=int.__new__(cls,value)\n member._value_=value\n member.description=description\n return member\n \n def __str__(self):\n return self.name\n \n_POSITIONAL_ONLY=_ParameterKind.POSITIONAL_ONLY\n_POSITIONAL_OR_KEYWORD=_ParameterKind.POSITIONAL_OR_KEYWORD\n_VAR_POSITIONAL=_ParameterKind.VAR_POSITIONAL\n_KEYWORD_ONLY=_ParameterKind.KEYWORD_ONLY\n_VAR_KEYWORD=_ParameterKind.VAR_KEYWORD\n\n\nclass Parameter:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('_name','_kind','_default','_annotation')\n \n POSITIONAL_ONLY=_POSITIONAL_ONLY\n POSITIONAL_OR_KEYWORD=_POSITIONAL_OR_KEYWORD\n VAR_POSITIONAL=_VAR_POSITIONAL\n KEYWORD_ONLY=_KEYWORD_ONLY\n VAR_KEYWORD=_VAR_KEYWORD\n \n empty=_empty\n \n def __init__(self,name,kind,*,default=_empty,annotation=_empty):\n try:\n self._kind=_ParameterKind(kind)\n except ValueError:\n raise ValueError(f'value {kind !r} is not a valid Parameter.kind')\n if default is not _empty:\n if self._kind in(_VAR_POSITIONAL,_VAR_KEYWORD):\n msg='{} parameters cannot have default values'\n msg=msg.format(self._kind.description)\n raise ValueError(msg)\n self._default=default\n self._annotation=annotation\n \n if name is _empty:\n raise ValueError('name is a required attribute for Parameter')\n \n if not isinstance(name,str):\n msg='name must be a str, not a {}'.format(type(name).__name__)\n raise TypeError(msg)\n \n if name[0]=='.'and name[1:].isdigit():\n \n \n \n \n if self._kind !=_POSITIONAL_OR_KEYWORD:\n msg=(\n 'implicit arguments must be passed as '\n 'positional or keyword arguments, not {}'\n )\n msg=msg.format(self._kind.description)\n raise ValueError(msg)\n self._kind=_POSITIONAL_ONLY\n name='implicit{}'.format(name[1:])\n \n \n \n is_keyword=iskeyword(name)and self._kind is not _POSITIONAL_ONLY\n if is_keyword or not name.isidentifier():\n raise ValueError('{!r} is not a valid parameter name'.format(name))\n \n self._name=name\n \n def __reduce__(self):\n return(type(self),\n (self._name,self._kind),\n {'_default':self._default,\n '_annotation':self._annotation})\n \n def __setstate__(self,state):\n self._default=state['_default']\n self._annotation=state['_annotation']\n \n @property\n def name(self):\n return self._name\n \n @property\n def default(self):\n return self._default\n \n @property\n def annotation(self):\n return self._annotation\n \n @property\n def kind(self):\n return self._kind\n \n def replace(self,*,name=_void,kind=_void,\n annotation=_void,default=_void):\n ''\n \n if name is _void:\n name=self._name\n \n if kind is _void:\n kind=self._kind\n \n if annotation is _void:\n annotation=self._annotation\n \n if default is _void:\n default=self._default\n \n return type(self)(name,kind,default=default,annotation=annotation)\n \n def __str__(self):\n kind=self.kind\n formatted=self._name\n \n \n if self._annotation is not _empty:\n formatted='{}: {}'.format(formatted,\n formatannotation(self._annotation))\n \n if self._default is not _empty:\n if self._annotation is not _empty:\n formatted='{} = {}'.format(formatted,repr(self._default))\n else:\n formatted='{}={}'.format(formatted,repr(self._default))\n \n if kind ==_VAR_POSITIONAL:\n formatted='*'+formatted\n elif kind ==_VAR_KEYWORD:\n formatted='**'+formatted\n \n return formatted\n \n __replace__=replace\n \n def __repr__(self):\n return '<{} \"{}\">'.format(self.__class__.__name__,self)\n \n def __hash__(self):\n return hash((self._name,self._kind,self._annotation,self._default))\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,Parameter):\n return NotImplemented\n return(self._name ==other._name and\n self._kind ==other._kind and\n self._default ==other._default and\n self._annotation ==other._annotation)\n \n \nclass BoundArguments:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('arguments','_signature','__weakref__')\n \n def __init__(self,signature,arguments):\n self.arguments=arguments\n self._signature=signature\n \n @property\n def signature(self):\n return self._signature\n \n @property\n def args(self):\n args=[]\n for param_name,param in self._signature.parameters.items():\n if param.kind in(_VAR_KEYWORD,_KEYWORD_ONLY):\n break\n \n try:\n arg=self.arguments[param_name]\n except KeyError:\n \n \n break\n else:\n if param.kind ==_VAR_POSITIONAL:\n \n args.extend(arg)\n else:\n \n args.append(arg)\n \n return tuple(args)\n \n @property\n def kwargs(self):\n kwargs={}\n kwargs_started=False\n for param_name,param in self._signature.parameters.items():\n if not kwargs_started:\n if param.kind in(_VAR_KEYWORD,_KEYWORD_ONLY):\n kwargs_started=True\n else:\n if param_name not in self.arguments:\n kwargs_started=True\n continue\n \n if not kwargs_started:\n continue\n \n try:\n arg=self.arguments[param_name]\n except KeyError:\n pass\n else:\n if param.kind ==_VAR_KEYWORD:\n \n kwargs.update(arg)\n else:\n \n kwargs[param_name]=arg\n \n return kwargs\n \n def apply_defaults(self):\n ''\n\n\n\n\n\n\n \n arguments=self.arguments\n new_arguments=[]\n for name,param in self._signature.parameters.items():\n try:\n new_arguments.append((name,arguments[name]))\n except KeyError:\n if param.default is not _empty:\n val=param.default\n elif param.kind is _VAR_POSITIONAL:\n val=()\n elif param.kind is _VAR_KEYWORD:\n val={}\n else:\n \n \n continue\n new_arguments.append((name,val))\n self.arguments=dict(new_arguments)\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,BoundArguments):\n return NotImplemented\n return(self.signature ==other.signature and\n self.arguments ==other.arguments)\n \n def __setstate__(self,state):\n self._signature=state['_signature']\n self.arguments=state['arguments']\n \n def __getstate__(self):\n return{'_signature':self._signature,'arguments':self.arguments}\n \n def __repr__(self):\n args=[]\n for arg,value in self.arguments.items():\n args.append('{}={!r}'.format(arg,value))\n return '<{} ({})>'.format(self.__class__.__name__,', '.join(args))\n \n \nclass Signature:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('_return_annotation','_parameters')\n \n _parameter_cls=Parameter\n _bound_arguments_cls=BoundArguments\n \n empty=_empty\n \n def __init__(self,parameters=None,*,return_annotation=_empty,\n __validate_parameters__=True):\n ''\n\n \n \n if parameters is None:\n params=OrderedDict()\n else:\n if __validate_parameters__:\n params=OrderedDict()\n top_kind=_POSITIONAL_ONLY\n seen_default=False\n \n for param in parameters:\n kind=param.kind\n name=param.name\n \n if kind top_kind:\n top_kind=kind\n \n if kind in(_POSITIONAL_ONLY,_POSITIONAL_OR_KEYWORD):\n if param.default is _empty:\n if seen_default:\n \n \n msg='non-default argument follows default '\\\n 'argument'\n raise ValueError(msg)\n else:\n \n seen_default=True\n \n if name in params:\n msg='duplicate parameter name: {!r}'.format(name)\n raise ValueError(msg)\n \n params[name]=param\n else:\n params=OrderedDict((param.name,param)for param in parameters)\n \n self._parameters=types.MappingProxyType(params)\n self._return_annotation=return_annotation\n \n @classmethod\n def from_callable(cls,obj,*,\n follow_wrapped=True,globals=None,locals=None,eval_str=False):\n ''\n return _signature_from_callable(obj,sigcls=cls,\n follow_wrapper_chains=follow_wrapped,\n globals=globals,locals=locals,eval_str=eval_str)\n \n @property\n def parameters(self):\n return self._parameters\n \n @property\n def return_annotation(self):\n return self._return_annotation\n \n def replace(self,*,parameters=_void,return_annotation=_void):\n ''\n\n\n \n \n if parameters is _void:\n parameters=self.parameters.values()\n \n if return_annotation is _void:\n return_annotation=self._return_annotation\n \n return type(self)(parameters,\n return_annotation=return_annotation)\n \n __replace__=replace\n \n def _hash_basis(self):\n params=tuple(param for param in self.parameters.values()\n if param.kind !=_KEYWORD_ONLY)\n \n kwo_params={param.name:param for param in self.parameters.values()\n if param.kind ==_KEYWORD_ONLY}\n \n return params,kwo_params,self.return_annotation\n \n def __hash__(self):\n params,kwo_params,return_annotation=self._hash_basis()\n kwo_params=frozenset(kwo_params.values())\n return hash((params,kwo_params,return_annotation))\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,Signature):\n return NotImplemented\n return self._hash_basis()==other._hash_basis()\n \n def _bind(self,args,kwargs,*,partial=False):\n ''\n \n arguments={}\n \n parameters=iter(self.parameters.values())\n parameters_ex=()\n arg_vals=iter(args)\n \n pos_only_param_in_kwargs=[]\n \n while True:\n \n \n try:\n arg_val=next(arg_vals)\n except StopIteration:\n \n try:\n param=next(parameters)\n except StopIteration:\n \n \n break\n else:\n if param.kind ==_VAR_POSITIONAL:\n \n \n break\n elif param.name in kwargs:\n if param.kind ==_POSITIONAL_ONLY:\n \n \n pos_only_param_in_kwargs.append(param)\n continue\n parameters_ex=(param,)\n break\n elif(param.kind ==_VAR_KEYWORD or\n param.default is not _empty):\n \n \n \n parameters_ex=(param,)\n break\n else:\n \n \n if partial:\n parameters_ex=(param,)\n break\n else:\n if param.kind ==_KEYWORD_ONLY:\n argtype=' keyword-only'\n else:\n argtype=''\n msg='missing a required{argtype} argument: {arg!r}'\n msg=msg.format(arg=param.name,argtype=argtype)\n raise TypeError(msg)from None\n else:\n \n try:\n param=next(parameters)\n except StopIteration:\n raise TypeError('too many positional arguments')from None\n else:\n if param.kind in(_VAR_KEYWORD,_KEYWORD_ONLY):\n \n \n raise TypeError(\n 'too many positional arguments')from None\n \n if param.kind ==_VAR_POSITIONAL:\n \n \n \n values=[arg_val]\n values.extend(arg_vals)\n arguments[param.name]=tuple(values)\n break\n \n if param.name in kwargs and param.kind !=_POSITIONAL_ONLY:\n raise TypeError(\n 'multiple values for argument {arg!r}'.format(\n arg=param.name))from None\n \n arguments[param.name]=arg_val\n \n \n \n kwargs_param=None\n for param in itertools.chain(parameters_ex,parameters):\n if param.kind ==_VAR_KEYWORD:\n \n kwargs_param=param\n continue\n \n if param.kind ==_VAR_POSITIONAL:\n \n \n \n continue\n \n param_name=param.name\n try:\n arg_val=kwargs.pop(param_name)\n except KeyError:\n \n \n \n \n if(not partial and param.kind !=_VAR_POSITIONAL and\n param.default is _empty):\n raise TypeError('missing a required argument: {arg!r}'.\\\n format(arg=param_name))from None\n \n else:\n arguments[param_name]=arg_val\n \n if kwargs:\n if kwargs_param is not None:\n \n arguments[kwargs_param.name]=kwargs\n elif pos_only_param_in_kwargs:\n raise TypeError(\n 'got some positional-only arguments passed as '\n 'keyword arguments: {arg!r}'.format(\n arg=', '.join(\n param.name\n for param in pos_only_param_in_kwargs\n ),\n ),\n )\n else:\n raise TypeError(\n 'got an unexpected keyword argument {arg!r}'.format(\n arg=next(iter(kwargs))))\n \n return self._bound_arguments_cls(self,arguments)\n \n def bind(self,/,*args,**kwargs):\n ''\n\n\n \n return self._bind(args,kwargs)\n \n def bind_partial(self,/,*args,**kwargs):\n ''\n\n\n \n return self._bind(args,kwargs,partial=True)\n \n def __reduce__(self):\n return(type(self),\n (tuple(self._parameters.values()),),\n {'_return_annotation':self._return_annotation})\n \n def __setstate__(self,state):\n self._return_annotation=state['_return_annotation']\n \n def __repr__(self):\n return '<{} {}>'.format(self.__class__.__name__,self)\n \n def __str__(self):\n return self.format()\n \n def format(self,*,max_width=None):\n ''\n\n\n\n\n\n \n result=[]\n render_pos_only_separator=False\n render_kw_only_separator=True\n for param in self.parameters.values():\n formatted=str(param)\n \n kind=param.kind\n \n if kind ==_POSITIONAL_ONLY:\n render_pos_only_separator=True\n elif render_pos_only_separator:\n \n \n result.append('/')\n render_pos_only_separator=False\n \n if kind ==_VAR_POSITIONAL:\n \n \n render_kw_only_separator=False\n elif kind ==_KEYWORD_ONLY and render_kw_only_separator:\n \n \n \n result.append('*')\n \n \n render_kw_only_separator=False\n \n result.append(formatted)\n \n if render_pos_only_separator:\n \n \n result.append('/')\n \n rendered='({})'.format(', '.join(result))\n if max_width is not None and len(rendered)>max_width:\n rendered='(\\n {}\\n)'.format(',\\n '.join(result))\n \n if self.return_annotation is not _empty:\n anno=formatannotation(self.return_annotation)\n rendered +=' -> {}'.format(anno)\n \n return rendered\n \n \ndef signature(obj,*,follow_wrapped=True,globals=None,locals=None,eval_str=False):\n ''\n return Signature.from_callable(obj,follow_wrapped=follow_wrapped,\n globals=globals,locals=locals,eval_str=eval_str)\n \n \nclass BufferFlags(enum.IntFlag):\n SIMPLE=0x0\n WRITABLE=0x1\n FORMAT=0x4\n ND=0x8\n STRIDES=0x10 |ND\n C_CONTIGUOUS=0x20 |STRIDES\n F_CONTIGUOUS=0x40 |STRIDES\n ANY_CONTIGUOUS=0x80 |STRIDES\n INDIRECT=0x100 |STRIDES\n CONTIG=ND |WRITABLE\n CONTIG_RO=ND\n STRIDED=STRIDES |WRITABLE\n STRIDED_RO=STRIDES\n RECORDS=STRIDES |WRITABLE |FORMAT\n RECORDS_RO=STRIDES |FORMAT\n FULL=INDIRECT |WRITABLE |FORMAT\n FULL_RO=INDIRECT |FORMAT\n READ=0x100\n WRITE=0x200\n \n \ndef _main():\n ''\n import argparse\n import importlib\n \n parser=argparse.ArgumentParser()\n parser.add_argument(\n 'object',\n help=\"The object to be analysed. \"\n \"It supports the 'module:qualname' syntax\")\n parser.add_argument(\n '-d','--details',action='store_true',\n help='Display info about the module rather than its source code')\n \n args=parser.parse_args()\n \n target=args.object\n mod_name,has_attrs,attrs=target.partition(\":\")\n try:\n obj=module=importlib.import_module(mod_name)\n except Exception as exc:\n msg=\"Failed to import {} ({}: {})\".format(mod_name,\n type(exc).__name__,\n exc)\n print(msg,file=sys.stderr)\n sys.exit(2)\n \n if has_attrs:\n parts=attrs.split(\".\")\n obj=module\n for part in parts:\n obj=getattr(obj,part)\n \n if module.__name__ in sys.builtin_module_names:\n print(\"Can't get info for builtin modules.\",file=sys.stderr)\n sys.exit(1)\n \n if args.details:\n print('Target: {}'.format(target))\n print('Origin: {}'.format(getsourcefile(module)))\n print('Cached: {}'.format(module.__cached__))\n if obj is module:\n print('Loader: {}'.format(repr(module.__loader__)))\n if hasattr(module,'__path__'):\n print('Submodule search path: {}'.format(module.__path__))\n else:\n try:\n __,lineno=findsource(obj)\n except Exception:\n pass\n else:\n print('Line: {}'.format(lineno))\n \n print('\\n')\n else:\n print(getsource(obj))\n \n \nif __name__ ==\"__main__\":\n _main()\n", ["abc", "argparse", "ast", "builtins", "collections", "collections.abc", "dis", "enum", "functools", "importlib", "importlib.machinery", "itertools", "keyword", "linecache", "operator", "os", "re", "sys", "token", "tokenize", "types", "weakref"]], "interpreter": [".py", "import sys\nimport builtins\nimport re\n\nimport tb as traceback\n\nfrom browser import console,document,window,html,DOMNode\nfrom browser.widgets.dialog import Dialog\n\n_credits=\"\"\" Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\n for supporting Python development. See www.python.org for more information.\"\"\"\n\n_copyright=\"\"\"Copyright (c) 2012, Pierre Quentel pierre.quentel@gmail.com\nAll Rights Reserved.\n\nCopyright (c) 2001-2022 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.\"\"\"\n\n_help=\"Type help() for interactive help, or help(object) for help about object.\"\n\n_license=\"\"\"Copyright (c) 2012, Pierre Quentel pierre.quentel@gmail.com\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer. Redistributions in binary\nform must reproduce the above copyright notice, this list of conditions and\nthe following disclaimer in the documentation and/or other materials provided\nwith the distribution.\nNeither the name of the nor the names of its contributors may\nbe used to endorse or promote products derived from this software without\nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nclass Info:\n\n def __init__(self,msg):\n self.msg=msg\n \n def __repr__(self):\n return self.msg\n \n \n \neditor_ns={\n'credits':Info(_credits),\n'copyright':Info(_copyright),\n'license':Info(_license),\n'__annotations__':{},\n'__builtins__':builtins,\n'__doc__':None,\n'__file__':'',\n'__name__':'__main__'\n}\n\n\nstyle_sheet=\"\"\"\n.brython-interpreter {\n background-color: #000;\n color: #fff;\n font-family: consolas, courier;\n caret-color: #fff;\n overflow-y: auto;\n overflow-x: hidden;\n}\n\n@keyframes blinker {\n 50% {\n opacity: 0;\n }\n}\n\npre{\n display:inline;\n}\n\"\"\"\n\nactive=[]\n\nclass Output:\n\n def __init__(self,interpreter):\n self.interpreter=interpreter\n \n def write(self,*args,**kw):\n self.interpreter.write(*args,**kw)\n \n def __len__(self):\n return len(self.interpreter.buffer)\n \n \n \n \ncolor_character_pattern=re.compile(r'^\\033\\[([0-9;]*)m')\n\ndef swap_color_bgcolor(element):\n ''\n element.style.color,element.style.backgroundColor=\\\n element.style.backgroundColor,element.style.color\n \ncc_styles={\n0:[\"fontStyle\",\"normal\"],\n1:[\"fontWeight\",\"bold\"],\n2:[\"fontWeight\",\"lighter\"],\n3:[\"fontStyle\",\"italic\"],\n4:[\"textDecoration\",\"underline\"],\n5:[\"animation\",\"blinker 1s step-start infinite\"],\n6:[\"animation\",\"blinker 0.5s step-start infinite\"],\n7:swap_color_bgcolor\n}\n\ncc_colors={\n30:\"Black\",\n31:\"Red\",\n32:\"Green\",\n33:\"Yellow\",\n34:\"Blue\",\n35:\"Magenta\",\n36:\"Cyan\",\n37:\"White\"\n}\n\ncc_bgcolors={k+10:v for(k,v)in cc_colors.items()}\n\n\nclass Trace:\n\n def __init__(self,exc):\n self.buf=\"\"\n self.is_syntax_error=exc.__name__ in['SyntaxError',\n 'IndentationError']\n \n def write(self,data):\n self.buf +=str(data)\n \n def format(self):\n ''\n lines=self.buf.strip().split(\"\\n\")\n stripped=[lines[0]]if not self.is_syntax_error else['']\n for i in range(1,len(lines),2):\n if __file__ in lines[i]:\n continue\n stripped +=lines[i:i+2]\n return \"\\n\".join(stripped)\n \n \nclass Interpreter:\n ''\n \n def __init__(self,elt_id=None,title=\"Interactive Interpreter\",\n globals=None,locals=None,history=None,\n rows=30,cols=120,default_css=True,\n clear_zone=True,banner=True):\n ''\n\n\n\n\n\n \n if default_css:\n \n for stylesheet in document.styleSheets:\n if stylesheet.ownerNode.id ==\"brython-interpreter\":\n break\n else:\n document <=html.STYLE(style_sheet,id=\"brython-interpreter\")\n \n self.cc_style=None\n self.cc_color=None\n self.cc_bgcolor=None\n self.default_cc_color='#fff'\n self.default_cc_bgcolor='#000'\n \n if elt_id is None:\n self.dialog=Dialog(title=title,top=10,left=10,\n default_css=default_css)\n self.dialog.bind('blur',self.blur)\n self.dialog.bind('click',self.focus)\n self.dialog.close_button.bind('click',self.close)\n self.zone=html.DIV(Class=\"brython-interpreter\",\n contenteditable=True)\n self.zone.style.width=f'{cols}ch'\n self.zone.style.height=f'{rows}ch'\n self.dialog.panel <=self.zone\n else:\n if isinstance(elt_id,str):\n try:\n elt=document[elt_id]\n if elt.tagName !=\"DIV\":\n raise ValueError(\n f\"element {elt_id} is a {elt.tagName}, \"+\n \"not a DIV\")\n self.zone=elt\n except KeyError:\n raise KeyError(f\"no element with id '{elt_id}'\")\n elif isinstance(elt_id,DOMNode):\n if elt_id.tagName ==\"DIV\":\n self.zone=elt_id\n else:\n raise ValueError(\"element is not a DIV\")\n else:\n raise ValueError(\"element should be a string or \"+\n f\"a DIV, got '{elt_id.__class__.__name__}'\")\n if self.zone.contentEditable !='true':\n raise ValueError(\"DIV element must be contenteditable\")\n v=sys.implementation.version\n if clear_zone:\n self.clear()\n if banner:\n self.insert(\n f\"Brython {v[0]}.{v[1]}.{v[2]} on \"\n f\"{window.navigator.appName} {window.navigator.appVersion}\"\n \"\\n\"\n )\n self.insert('Type \"help\", \"copyright\", \"credits\" '\n 'or \"license\" for more information.'+'\\n')\n self.insert_prompt()\n \n self._status=\"main\"\n self.history=history or[]\n self.current=len(self.history)\n \n self.globals={}if globals is None else globals\n self.globals.update(editor_ns)\n self.locals=self.globals if locals is None else locals\n \n self.zone.bind('keypress',self.keypress)\n self.zone.bind('keydown',self.keydown)\n self.zone.bind('mouseup',self.mouseup)\n \n self.zone.bind('focus',self.focus)\n self.zone.bind('blur',self.blur)\n self.focus()\n \n self.cursor_to_end()\n \n active.append(self)\n \n def clear(self):\n self.zone.text=''\n \n def insert(self,text):\n \n pre=html.PRE(style=\"display:inline;white-space:pre-wrap;\")\n pre.text=text\n if self.cc_color is not None:\n pre.style.color=self.cc_color\n if self.cc_bgcolor is not None:\n pre.style.backgroundColor=self.cc_bgcolor\n if self.cc_style is not None:\n style=cc_styles[self.cc_style]\n if isinstance(style,list):\n attr,value=style\n setattr(pre.style,attr,value)\n else:\n style(pre)\n self.zone <=pre\n \n def insert_prompt(self):\n self.insert('>>> ')\n \n def insert_continuation(self):\n self.insert('\\n... ')\n \n def insert_cr(self):\n self.insert('\\n')\n \n def get_content(self):\n return self.zone.text\n \n def blur(self,ev):\n if hasattr(self,'dialog'):\n self.dialog.style.zIndex=0\n \n def close(self,ev):\n active.remove(self)\n \n def cursor_to_end(self,*args):\n \n sel=window.getSelection()\n \n last_child=self.zone.lastChild.firstChild\n if last_child is None:\n last_child=self.zone.lastChild\n pos=len(last_child.text)\n \n sel.setBaseAndExtent(last_child,pos,last_child,pos)\n \n self.zone.lastChild.scrollIntoView({\"block\":\"end\",\"behaviour\":\"smooth\"})\n \n def focus(self,*args):\n ''\n if hasattr(self,'dialog'):\n \n for w in active:\n if w is not self:\n w.dialog.style.zIndex=0\n self.dialog.style.zIndex=1\n sys.stdout=sys.stderr=Output(self)\n self.zone.focus()\n \n def keypress(self,event):\n if event.key ==\"Tab\":\n event.preventDefault()\n self.insert(\" \")\n elif event.key ==\"Enter\":\n event.preventDefault()\n selection=window.getSelection().toString()\n if selection:\n \n self.cursor_to_end()\n return\n self.handle_line(event)\n \n def feed(self,src):\n ''\n\n\n \n current_indent=0\n lines=src.strip().split('\\n')\n for line in lines:\n self.insert(line)\n self.handle_line()\n \n def add_to_history(self,line):\n self.history.append(line)\n \n def handle_line(self,event=None):\n src=self.get_content().strip()\n if self._status ==\"main\":\n currentLine=src[src.rfind('\\n>>>')+5:]\n elif self._status in[\"3string\",\"parenth_expr\"]:\n currentLine=src[src.rfind('\\n>>>')+5:]\n currentLine=currentLine.replace('\\n... ','\\n')\n else:\n currentLine=src[src.rfind('\\n...')+5:]\n if self._status =='main'and not currentLine.strip():\n self.insert_cr()\n self.insert_prompt()\n self.cursor_to_end()\n if event is not None:\n event.preventDefault()\n return\n self.add_to_history(currentLine)\n self.current=len(self.history)\n if self._status in[\"main\",\"3string\",\"parenth_expr\"]:\n \n if currentLine ==\"help\":\n self.insert_cr()\n self.write(_help)\n self.insert_cr()\n self.insert_prompt()\n self.cursor_to_end()\n if event is not None:\n event.preventDefault()\n return\n try:\n code=compile(currentLine,'','eval')\n except IndentationError:\n self.insert_continuation()\n self._status=\"block\"\n except SyntaxError as msg:\n if str(msg).startswith('unterminated triple-quoted string literal'):\n self.insert_continuation()\n self._status=\"3string\"\n elif str(msg)=='decorator expects function':\n self.insert_continuation()\n self._status=\"block\"\n elif str(msg).endswith('was never closed'):\n self.insert_continuation()\n self._status=\"parenth_expr\"\n else:\n try:\n code=compile(currentLine,'','exec')\n exec(code,self.globals,self.locals)\n except SyntaxError as exc:\n if exc.args[0].startswith('expected an indented block'):\n self.insert_continuation()\n self._status=\"block\"\n else:\n self.insert_cr()\n self.print_tb(exc)\n self.insert_prompt()\n except Exception as exc:\n self.insert_cr()\n self.print_tb(msg)\n self.insert_prompt()\n self._status=\"main\"\n else:\n self.insert_cr()\n self.insert_prompt()\n self._status=\"main\"\n except Exception as exc:\n \n \n \n self.print_tb(exc)\n self.insert_prompt()\n self._status=\"main\"\n else:\n self.insert_cr()\n try:\n self.globals['_']=eval(code,\n self.globals,\n self.locals)\n if self.globals['_']is not None:\n self.write(repr(self.globals['_'])+'\\n')\n self.insert_prompt()\n self._status=\"main\"\n except Exception as exc:\n self.print_tb(exc)\n self.insert_prompt()\n self._status=\"main\"\n \n elif currentLine ==\"\":\n block=src[src.rfind('\\n>>>')+5:].splitlines()\n block=[block[0]]+[b[4:]for b in block[1:]]\n block_src='\\n'.join(block)\n self.insert_cr()\n mode=eval if self._status ==\"parenth_expr\"else exec\n \n self._status=\"main\"\n if mode is eval:\n try:\n self.globals['_']=eval(block_src,\n self.globals,\n self.locals)\n if self.globals['_']is not None:\n self.write(repr(self.globals['_'])+'\\n')\n self._status=\"main\"\n except Exception as exc:\n self.print_tb(exc)\n self._status=\"main\"\n else:\n try:\n mode(block_src,self.globals,self.locals)\n except Exception as exc:\n self.print_tb(exc)\n self.insert_prompt()\n \n else:\n self.insert_continuation()\n \n self.cursor_to_end()\n if event is not None:\n event.preventDefault()\n \n def keydown(self,event):\n sel=window.getSelection()\n if event.key in(\"ArrowLeft\",\"Backspace\"):\n \n if sel.anchorNode is not self.zone:\n caret_column=sel.anchorOffset\n if caret_column >=5:\n return\n event.preventDefault()\n event.stopPropagation()\n elif event.key ==\"Home\":\n anchor=sel.anchorNode\n sel.setBaseAndExtent(anchor,4,anchor,4)\n event.preventDefault()\n event.stopPropagation()\n elif event.key ==\"ArrowUp\":\n line=sel.anchorNode.data\n if not line.startswith('\\n...'):\n if self.current >0:\n last_child=self.zone.lastChild\n last_child.text=last_child.text[:4]+self.history[self.current -1]\n self.current -=1\n self.cursor_to_end()\n event.preventDefault()\n elif event.key ==\"ArrowDown\":\n node=sel.anchorNode.parentNode\n if not node.nextSibling:\n if self.current \",\">\")\n frames_sel <=html.OPTION(name)\n frame=frame.f_back\n frames_sel.bind(\"change\",self.change_frame)\n frame_div=html.DIV(\"Frame \"+frames_sel)\n panel_style=window.getComputedStyle(self.dialog.panel)\n frame_div.style.paddingLeft=panel_style.paddingLeft\n frame_div.style.paddingTop=panel_style.paddingTop\n self.dialog.insertBefore(frame_div,self.dialog.panel)\n \n def change_frame(self,ev):\n self.globals,self.locals=self.frames[ev.target.selectedIndex]\n \n", ["browser", "browser.widgets.dialog", "builtins", "re", "sys", "tb"]], "io": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__=(\"Guido van Rossum , \"\n\"Mike Verdone , \"\n\"Mark Russell , \"\n\"Antoine Pitrou , \"\n\"Amaury Forgeot d'Arc , \"\n\"Benjamin Peterson \")\n\n__all__=[\"BlockingIOError\",\"open\",\"open_code\",\"IOBase\",\"RawIOBase\",\n\"FileIO\",\"BytesIO\",\"StringIO\",\"BufferedIOBase\",\n\"BufferedReader\",\"BufferedWriter\",\"BufferedRWPair\",\n\"BufferedRandom\",\"TextIOBase\",\"TextIOWrapper\",\n\"UnsupportedOperation\",\"SEEK_SET\",\"SEEK_CUR\",\"SEEK_END\",\n\"DEFAULT_BUFFER_SIZE\",\"text_encoding\",\"IncrementalNewlineDecoder\"]\n\n\nimport _io\nimport abc\n\nfrom _io import(DEFAULT_BUFFER_SIZE,BlockingIOError,UnsupportedOperation,\nopen,open_code,FileIO,BytesIO,StringIO,BufferedReader,\nBufferedWriter,BufferedRWPair,BufferedRandom,\nIncrementalNewlineDecoder,text_encoding,TextIOWrapper)\n\n\n\nUnsupportedOperation.__module__=\"io\"\n\n\nSEEK_SET=0\nSEEK_CUR=1\nSEEK_END=2\n\n\n\n\nclass IOBase(_io._IOBase,metaclass=abc.ABCMeta):\n __doc__=_io._IOBase.__doc__\n \nclass RawIOBase(_io._RawIOBase,IOBase):\n __doc__=_io._RawIOBase.__doc__\n \nclass BufferedIOBase(_io._BufferedIOBase,IOBase):\n __doc__=_io._BufferedIOBase.__doc__\n \nclass TextIOBase(_io._TextIOBase,IOBase):\n __doc__=_io._TextIOBase.__doc__\n \nRawIOBase.register(FileIO)\n\nfor klass in(BytesIO,BufferedReader,BufferedWriter,BufferedRandom,\nBufferedRWPair):\n BufferedIOBase.register(klass)\n \nfor klass in(StringIO,TextIOWrapper):\n TextIOBase.register(klass)\ndel klass\n\ntry:\n from _io import _WindowsConsoleIO\nexcept ImportError:\n pass\nelse:\n RawIOBase.register(_WindowsConsoleIO)\n", ["_io", "abc"]], "ipaddress": [".py", "\n\n\n\"\"\"A fast, lightweight IPv4/IPv6 manipulation library in Python.\n\nThis library is used to create/poke/manipulate IPv4 and IPv6 addresses\nand networks.\n\n\"\"\"\n\n__version__='1.0'\n\n\nimport functools\n\nIPV4LENGTH=32\nIPV6LENGTH=128\n\n\nclass AddressValueError(ValueError):\n ''\n \n \nclass NetmaskValueError(ValueError):\n ''\n \n \ndef ip_address(address):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return IPv4Address(address)\n except(AddressValueError,NetmaskValueError):\n pass\n \n try:\n return IPv6Address(address)\n except(AddressValueError,NetmaskValueError):\n pass\n \n raise ValueError(f'{address !r} does not appear to be an IPv4 or IPv6 address')\n \n \ndef ip_network(address,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return IPv4Network(address,strict)\n except(AddressValueError,NetmaskValueError):\n pass\n \n try:\n return IPv6Network(address,strict)\n except(AddressValueError,NetmaskValueError):\n pass\n \n raise ValueError(f'{address !r} does not appear to be an IPv4 or IPv6 network')\n \n \ndef ip_interface(address):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return IPv4Interface(address)\n except(AddressValueError,NetmaskValueError):\n pass\n \n try:\n return IPv6Interface(address)\n except(AddressValueError,NetmaskValueError):\n pass\n \n raise ValueError(f'{address !r} does not appear to be an IPv4 or IPv6 interface')\n \n \ndef v4_int_to_packed(address):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return address.to_bytes(4)\n except OverflowError:\n raise ValueError(\"Address negative or too large for IPv4\")\n \n \ndef v6_int_to_packed(address):\n ''\n\n\n\n\n\n\n\n \n try:\n return address.to_bytes(16)\n except OverflowError:\n raise ValueError(\"Address negative or too large for IPv6\")\n \n \ndef _split_optional_netmask(address):\n ''\n addr=str(address).split('/')\n if len(addr)>2:\n raise AddressValueError(f\"Only one '/' permitted in {address !r}\")\n return addr\n \n \ndef _find_address_range(addresses):\n ''\n\n\n\n\n\n\n\n \n it=iter(addresses)\n first=last=next(it)\n for ip in it:\n if ip._ip !=last._ip+1:\n yield first,last\n first=ip\n last=ip\n yield first,last\n \n \ndef _count_righthand_zero_bits(number,bits):\n ''\n\n\n\n\n\n\n\n\n \n if number ==0:\n return bits\n return min(bits,(~number&(number -1)).bit_length())\n \n \ndef summarize_address_range(first,last):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if(not(isinstance(first,_BaseAddress)and\n isinstance(last,_BaseAddress))):\n raise TypeError('first and last must be IP addresses, not networks')\n if first.version !=last.version:\n raise TypeError(\"%s and %s are not of the same version\"%(\n first,last))\n if first >last:\n raise ValueError('last IP address must be greater than first')\n \n if first.version ==4:\n ip=IPv4Network\n elif first.version ==6:\n ip=IPv6Network\n else:\n raise ValueError('unknown IP version')\n \n ip_bits=first._max_prefixlen\n first_int=first._ip\n last_int=last._ip\n while first_int <=last_int:\n nbits=min(_count_righthand_zero_bits(first_int,ip_bits),\n (last_int -first_int+1).bit_length()-1)\n net=ip((first_int,ip_bits -nbits))\n yield net\n first_int +=1 <=net.broadcast_address:\n continue\n yield net\n last=net\n \n \ndef collapse_addresses(addresses):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n addrs=[]\n ips=[]\n nets=[]\n \n \n for ip in addresses:\n if isinstance(ip,_BaseAddress):\n if ips and ips[-1]._version !=ip._version:\n raise TypeError(\"%s and %s are not of the same version\"%(\n ip,ips[-1]))\n ips.append(ip)\n elif ip._prefixlen ==ip._max_prefixlen:\n if ips and ips[-1]._version !=ip._version:\n raise TypeError(\"%s and %s are not of the same version\"%(\n ip,ips[-1]))\n try:\n ips.append(ip.ip)\n except AttributeError:\n ips.append(ip.network_address)\n else:\n if nets and nets[-1]._version !=ip._version:\n raise TypeError(\"%s and %s are not of the same version\"%(\n ip,nets[-1]))\n nets.append(ip)\n \n \n ips=sorted(set(ips))\n \n \n if ips:\n for first,last in _find_address_range(ips):\n addrs.extend(summarize_address_range(first,last))\n \n return _collapse_addresses_internal(addrs+nets)\n \n \ndef get_mixed_type_key(obj):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(obj,_BaseNetwork):\n return obj._get_networks_key()\n elif isinstance(obj,_BaseAddress):\n return obj._get_address_key()\n return NotImplemented\n \n \nclass _IPAddressBase:\n\n ''\n \n __slots__=()\n \n @property\n def exploded(self):\n ''\n return self._explode_shorthand_ip_string()\n \n @property\n def compressed(self):\n ''\n return str(self)\n \n @property\n def reverse_pointer(self):\n ''\n\n\n\n\n\n \n return self._reverse_pointer()\n \n @property\n def version(self):\n msg='%200s has no version specified'%(type(self),)\n raise NotImplementedError(msg)\n \n def _check_int_address(self,address):\n if address <0:\n msg=\"%d (< 0) is not permitted as an IPv%d address\"\n raise AddressValueError(msg %(address,self._version))\n if address >self._ALL_ONES:\n msg=\"%d (>= 2**%d) is not permitted as an IPv%d address\"\n raise AddressValueError(msg %(address,self._max_prefixlen,\n self._version))\n \n def _check_packed_address(self,address,expected_len):\n address_len=len(address)\n if address_len !=expected_len:\n msg=\"%r (len %d != %d) is not permitted as an IPv%d address\"\n raise AddressValueError(msg %(address,address_len,\n expected_len,self._version))\n \n @classmethod\n def _ip_int_from_prefix(cls,prefixlen):\n ''\n\n\n\n\n\n\n\n \n return cls._ALL_ONES ^(cls._ALL_ONES >>prefixlen)\n \n @classmethod\n def _prefix_from_ip_int(cls,ip_int):\n ''\n\n\n\n\n\n\n\n\n\n \n trailing_zeroes=_count_righthand_zero_bits(ip_int,\n cls._max_prefixlen)\n prefixlen=cls._max_prefixlen -trailing_zeroes\n leading_ones=ip_int >>trailing_zeroes\n all_ones=(1 <1:\n return address\n return address[0],cls._max_prefixlen\n \n def __reduce__(self):\n return self.__class__,(str(self),)\n \n \n_address_fmt_re=None\n\n@functools.total_ordering\nclass _BaseAddress(_IPAddressBase):\n\n ''\n\n\n\n \n \n __slots__=()\n \n def __int__(self):\n return self._ip\n \n def __eq__(self,other):\n try:\n return(self._ip ==other._ip\n and self._version ==other._version)\n except AttributeError:\n return NotImplemented\n \n def __lt__(self,other):\n if not isinstance(other,_BaseAddress):\n return NotImplemented\n if self._version !=other._version:\n raise TypeError('%s and %s are not of the same version'%(\n self,other))\n if self._ip !=other._ip:\n return self._ip =0:\n if network+n >broadcast:\n raise IndexError('address out of range')\n return self._address_class(network+n)\n else:\n n +=1\n if broadcast+n other.network_address:\n return 1\n \n if self.netmask other.netmask:\n return 1\n return 0\n \n def _get_networks_key(self):\n ''\n\n\n\n\n\n \n return(self._version,self.network_address,self.netmask)\n \n def subnets(self,prefixlen_diff=1,new_prefix=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self._prefixlen ==self._max_prefixlen:\n yield self\n return\n \n if new_prefix is not None:\n if new_prefix 0')\n new_prefixlen=self._prefixlen+prefixlen_diff\n \n if new_prefixlen >self._max_prefixlen:\n raise ValueError(\n 'prefix length diff %d is invalid for netblock %s'%(\n new_prefixlen,self))\n \n start=int(self.network_address)\n end=int(self.broadcast_address)+1\n step=(int(self.hostmask)+1)>>prefixlen_diff\n for new_addr in range(start,end,step):\n current=self.__class__((new_addr,new_prefixlen))\n yield current\n \n def supernet(self,prefixlen_diff=1,new_prefix=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self._prefixlen ==0:\n return self\n \n if new_prefix is not None:\n if new_prefix >self._prefixlen:\n raise ValueError('new prefix must be shorter')\n if prefixlen_diff !=1:\n raise ValueError('cannot set prefixlen_diff and new_prefix')\n prefixlen_diff=self._prefixlen -new_prefix\n \n new_prefixlen=self.prefixlen -prefixlen_diff\n if new_prefixlen <0:\n raise ValueError(\n 'current prefixlen is %d, cannot have a prefixlen_diff of %d'%\n (self.prefixlen,prefixlen_diff))\n return self.__class__((\n int(self.network_address)&(int(self.netmask)<=a.broadcast_address)\n except AttributeError:\n raise TypeError(f\"Unable to test subnet containment \"\n f\"between {a} and {b}\")\n \n def subnet_of(self,other):\n ''\n return self._is_subnet_of(self,other)\n \n def supernet_of(self,other):\n ''\n return self._is_subnet_of(other,self)\n \n @property\n def is_reserved(self):\n ''\n\n\n\n\n\n \n return(self.network_address.is_reserved and\n self.broadcast_address.is_reserved)\n \n @property\n def is_link_local(self):\n ''\n\n\n\n\n \n return(self.network_address.is_link_local and\n self.broadcast_address.is_link_local)\n \n @property\n def is_private(self):\n ''\n\n\n\n\n\n \n return(self.network_address.is_private and\n self.broadcast_address.is_private)\n \n @property\n def is_global(self):\n ''\n\n\n\n\n\n \n return not self.is_private\n \n @property\n def is_unspecified(self):\n ''\n\n\n\n\n\n \n return(self.network_address.is_unspecified and\n self.broadcast_address.is_unspecified)\n \n @property\n def is_loopback(self):\n ''\n\n\n\n\n\n \n return(self.network_address.is_loopback and\n self.broadcast_address.is_loopback)\n \nclass _BaseV4:\n\n ''\n\n\n\n\n \n \n __slots__=()\n _version=4\n \n _ALL_ONES=(2 **IPV4LENGTH)-1\n \n _max_prefixlen=IPV4LENGTH\n \n \n _netmask_cache={}\n \n def _explode_shorthand_ip_string(self):\n return str(self)\n \n @classmethod\n def _make_netmask(cls,arg):\n ''\n\n\n\n\n\n \n if arg not in cls._netmask_cache:\n if isinstance(arg,int):\n prefixlen=arg\n if not(0 <=prefixlen <=cls._max_prefixlen):\n cls._report_invalid_netmask(prefixlen)\n else:\n try:\n \n prefixlen=cls._prefix_from_prefix_string(arg)\n except NetmaskValueError:\n \n \n prefixlen=cls._prefix_from_ip_string(arg)\n netmask=IPv4Address(cls._ip_int_from_prefix(prefixlen))\n cls._netmask_cache[arg]=netmask,prefixlen\n return cls._netmask_cache[arg]\n \n @classmethod\n def _ip_int_from_string(cls,ip_str):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not ip_str:\n raise AddressValueError('Address cannot be empty')\n \n octets=ip_str.split('.')\n if len(octets)!=4:\n raise AddressValueError(\"Expected 4 octets in %r\"%ip_str)\n \n try:\n return int.from_bytes(map(cls._parse_octet,octets),'big')\n except ValueError as exc:\n raise AddressValueError(\"%s in %r\"%(exc,ip_str))from None\n \n @classmethod\n def _parse_octet(cls,octet_str):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not octet_str:\n raise ValueError(\"Empty octet not permitted\")\n \n if not(octet_str.isascii()and octet_str.isdigit()):\n msg=\"Only decimal digits permitted in %r\"\n raise ValueError(msg %octet_str)\n \n \n if len(octet_str)>3:\n msg=\"At most 3 characters permitted in %r\"\n raise ValueError(msg %octet_str)\n \n \n if octet_str !='0'and octet_str[0]=='0':\n msg=\"Leading zeros are not permitted in %r\"\n raise ValueError(msg %octet_str)\n \n octet_int=int(octet_str,10)\n if octet_int >255:\n raise ValueError(\"Octet %d (> 255) not permitted\"%octet_int)\n return octet_int\n \n @classmethod\n def _string_from_ip_int(cls,ip_int):\n ''\n\n\n\n\n\n\n\n \n return '.'.join(map(str,ip_int.to_bytes(4,'big')))\n \n def _reverse_pointer(self):\n ''\n\n\n\n \n reverse_octets=str(self).split('.')[::-1]\n return '.'.join(reverse_octets)+'.in-addr.arpa'\n \n @property\n def max_prefixlen(self):\n return self._max_prefixlen\n \n @property\n def version(self):\n return self._version\n \n \nclass IPv4Address(_BaseV4,_BaseAddress):\n\n ''\n \n __slots__=('_ip','__weakref__')\n \n def __init__(self,address):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if isinstance(address,int):\n self._check_int_address(address)\n self._ip=address\n return\n \n \n if isinstance(address,bytes):\n self._check_packed_address(address,4)\n self._ip=int.from_bytes(address)\n return\n \n \n \n addr_str=str(address)\n if '/'in addr_str:\n raise AddressValueError(f\"Unexpected '/' in {address !r}\")\n self._ip=self._ip_int_from_string(addr_str)\n \n @property\n def packed(self):\n ''\n return v4_int_to_packed(self._ip)\n \n @property\n def is_reserved(self):\n ''\n\n\n\n\n\n \n return self in self._constants._reserved_network\n \n @property\n @functools.lru_cache()\n def is_private(self):\n ''\n\n\n\n\n\n \n return any(self in net for net in self._constants._private_networks)\n \n @property\n @functools.lru_cache()\n def is_global(self):\n return self not in self._constants._public_network and not self.is_private\n \n @property\n def is_multicast(self):\n ''\n\n\n\n\n\n \n return self in self._constants._multicast_network\n \n @property\n def is_unspecified(self):\n ''\n\n\n\n\n\n \n return self ==self._constants._unspecified_address\n \n @property\n def is_loopback(self):\n ''\n\n\n\n\n \n return self in self._constants._loopback_network\n \n @property\n def is_link_local(self):\n ''\n\n\n\n\n \n return self in self._constants._linklocal_network\n \n \nclass IPv4Interface(IPv4Address):\n\n def __init__(self,address):\n addr,mask=self._split_addr_prefix(address)\n \n IPv4Address.__init__(self,addr)\n self.network=IPv4Network((addr,mask),strict=False)\n self.netmask=self.network.netmask\n self._prefixlen=self.network._prefixlen\n \n @functools.cached_property\n def hostmask(self):\n return self.network.hostmask\n \n def __str__(self):\n return '%s/%d'%(self._string_from_ip_int(self._ip),\n self._prefixlen)\n \n def __eq__(self,other):\n address_equal=IPv4Address.__eq__(self,other)\n if address_equal is NotImplemented or not address_equal:\n return address_equal\n try:\n return self.network ==other.network\n except AttributeError:\n \n \n \n return False\n \n def __lt__(self,other):\n address_less=IPv4Address.__lt__(self,other)\n if address_less is NotImplemented:\n return NotImplemented\n try:\n return(self.network >16)&0xFFFF))\n parts.append('%x'%(ipv4_int&0xFFFF))\n \n \n \n \n _max_parts=cls._HEXTET_COUNT+1\n if len(parts)>_max_parts:\n msg=\"At most %d colons permitted in %r\"%(_max_parts -1,ip_str)\n raise AddressValueError(msg)\n \n \n \n skip_index=None\n for i in range(1,len(parts)-1):\n if not parts[i]:\n if skip_index is not None:\n \n msg=\"At most one '::' permitted in %r\"%ip_str\n raise AddressValueError(msg)\n skip_index=i\n \n \n \n if skip_index is not None:\n \n parts_hi=skip_index\n parts_lo=len(parts)-skip_index -1\n if not parts[0]:\n parts_hi -=1\n if parts_hi:\n msg=\"Leading ':' only permitted as part of '::' in %r\"\n raise AddressValueError(msg %ip_str)\n if not parts[-1]:\n parts_lo -=1\n if parts_lo:\n msg=\"Trailing ':' only permitted as part of '::' in %r\"\n raise AddressValueError(msg %ip_str)\n parts_skipped=cls._HEXTET_COUNT -(parts_hi+parts_lo)\n if parts_skipped <1:\n msg=\"Expected at most %d other parts with '::' in %r\"\n raise AddressValueError(msg %(cls._HEXTET_COUNT -1,ip_str))\n else:\n \n \n \n if len(parts)!=cls._HEXTET_COUNT:\n msg=\"Exactly %d parts expected without '::' in %r\"\n raise AddressValueError(msg %(cls._HEXTET_COUNT,ip_str))\n if not parts[0]:\n msg=\"Leading ':' only permitted as part of '::' in %r\"\n raise AddressValueError(msg %ip_str)\n if not parts[-1]:\n msg=\"Trailing ':' only permitted as part of '::' in %r\"\n raise AddressValueError(msg %ip_str)\n parts_hi=len(parts)\n parts_lo=0\n parts_skipped=0\n \n try:\n \n ip_int=0\n for i in range(parts_hi):\n ip_int <<=16\n ip_int |=cls._parse_hextet(parts[i])\n ip_int <<=16 *parts_skipped\n for i in range(-parts_lo,0):\n ip_int <<=16\n ip_int |=cls._parse_hextet(parts[i])\n return ip_int\n except ValueError as exc:\n raise AddressValueError(\"%s in %r\"%(exc,ip_str))from None\n \n @classmethod\n def _parse_hextet(cls,hextet_str):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not cls._HEX_DIGITS.issuperset(hextet_str):\n raise ValueError(\"Only hex digits permitted in %r\"%hextet_str)\n \n \n if len(hextet_str)>4:\n msg=\"At most 4 characters permitted in %r\"\n raise ValueError(msg %hextet_str)\n \n return int(hextet_str,16)\n \n @classmethod\n def _compress_hextets(cls,hextets):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n best_doublecolon_start=-1\n best_doublecolon_len=0\n doublecolon_start=-1\n doublecolon_len=0\n for index,hextet in enumerate(hextets):\n if hextet =='0':\n doublecolon_len +=1\n if doublecolon_start ==-1:\n \n doublecolon_start=index\n if doublecolon_len >best_doublecolon_len:\n \n best_doublecolon_len=doublecolon_len\n best_doublecolon_start=doublecolon_start\n else:\n doublecolon_len=0\n doublecolon_start=-1\n \n if best_doublecolon_len >1:\n best_doublecolon_end=(best_doublecolon_start+\n best_doublecolon_len)\n \n if best_doublecolon_end ==len(hextets):\n hextets +=['']\n hextets[best_doublecolon_start:best_doublecolon_end]=['']\n \n if best_doublecolon_start ==0:\n hextets=['']+hextets\n \n return hextets\n \n @classmethod\n def _string_from_ip_int(cls,ip_int=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if ip_int is None:\n ip_int=int(cls._ip)\n \n if ip_int >cls._ALL_ONES:\n raise ValueError('IPv6 address is too large')\n \n hex_str='%032x'%ip_int\n hextets=['%x'%int(hex_str[x:x+4],16)for x in range(0,32,4)]\n \n hextets=cls._compress_hextets(hextets)\n return ':'.join(hextets)\n \n def _explode_shorthand_ip_string(self):\n ''\n\n\n\n\n\n\n\n \n if isinstance(self,IPv6Network):\n ip_str=str(self.network_address)\n elif isinstance(self,IPv6Interface):\n ip_str=str(self.ip)\n else:\n ip_str=str(self)\n \n ip_int=self._ip_int_from_string(ip_str)\n hex_str='%032x'%ip_int\n parts=[hex_str[x:x+4]for x in range(0,32,4)]\n if isinstance(self,(_BaseNetwork,IPv6Interface)):\n return '%s/%d'%(':'.join(parts),self._prefixlen)\n return ':'.join(parts)\n \n def _reverse_pointer(self):\n ''\n\n\n\n \n reverse_chars=self.exploded[::-1].replace(':','')\n return '.'.join(reverse_chars)+'.ip6.arpa'\n \n @staticmethod\n def _split_scope_id(ip_str):\n ''\n\n\n\n\n\n\n\n\n\n \n addr,sep,scope_id=ip_str.partition('%')\n if not sep:\n scope_id=None\n elif not scope_id or '%'in scope_id:\n raise AddressValueError('Invalid IPv6 address: \"%r\"'%ip_str)\n return addr,scope_id\n \n @property\n def max_prefixlen(self):\n return self._max_prefixlen\n \n @property\n def version(self):\n return self._version\n \n \nclass IPv6Address(_BaseV6,_BaseAddress):\n\n ''\n \n __slots__=('_ip','_scope_id','__weakref__')\n \n def __init__(self,address):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if isinstance(address,int):\n self._check_int_address(address)\n self._ip=address\n self._scope_id=None\n return\n \n \n if isinstance(address,bytes):\n self._check_packed_address(address,16)\n self._ip=int.from_bytes(address,'big')\n self._scope_id=None\n return\n \n \n \n addr_str=str(address)\n if '/'in addr_str:\n raise AddressValueError(f\"Unexpected '/' in {address !r}\")\n addr_str,self._scope_id=self._split_scope_id(addr_str)\n \n self._ip=self._ip_int_from_string(addr_str)\n \n def __str__(self):\n ip_str=super().__str__()\n return ip_str+'%'+self._scope_id if self._scope_id else ip_str\n \n def __hash__(self):\n return hash((self._ip,self._scope_id))\n \n def __eq__(self,other):\n address_equal=super().__eq__(other)\n if address_equal is NotImplemented:\n return NotImplemented\n if not address_equal:\n return False\n return self._scope_id ==getattr(other,'_scope_id',None)\n \n @property\n def scope_id(self):\n ''\n\n\n\n\n\n\n \n return self._scope_id\n \n @property\n def packed(self):\n ''\n return v6_int_to_packed(self._ip)\n \n @property\n def is_multicast(self):\n ''\n\n\n\n\n\n \n return self in self._constants._multicast_network\n \n @property\n def is_reserved(self):\n ''\n\n\n\n\n\n \n return any(self in x for x in self._constants._reserved_networks)\n \n @property\n def is_link_local(self):\n ''\n\n\n\n\n \n return self in self._constants._linklocal_network\n \n @property\n def is_site_local(self):\n ''\n\n\n\n\n\n\n\n\n \n return self in self._constants._sitelocal_network\n \n @property\n @functools.lru_cache()\n def is_private(self):\n ''\n\n\n\n\n\n\n \n ipv4_mapped=self.ipv4_mapped\n if ipv4_mapped is not None:\n return ipv4_mapped.is_private\n return any(self in net for net in self._constants._private_networks)\n \n @property\n def is_global(self):\n ''\n\n\n\n\n\n \n return not self.is_private\n \n @property\n def is_unspecified(self):\n ''\n\n\n\n\n\n \n return self._ip ==0\n \n @property\n def is_loopback(self):\n ''\n\n\n\n\n\n \n return self._ip ==1\n \n @property\n def ipv4_mapped(self):\n ''\n\n\n\n\n\n \n if(self._ip >>32)!=0xFFFF:\n return None\n return IPv4Address(self._ip&0xFFFFFFFF)\n \n @property\n def teredo(self):\n ''\n\n\n\n\n\n\n \n if(self._ip >>96)!=0x20010000:\n return None\n return(IPv4Address((self._ip >>64)&0xFFFFFFFF),\n IPv4Address(~self._ip&0xFFFFFFFF))\n \n @property\n def sixtofour(self):\n ''\n\n\n\n\n\n \n if(self._ip >>112)!=0x2002:\n return None\n return IPv4Address((self._ip >>80)&0xFFFFFFFF)\n \n \nclass IPv6Interface(IPv6Address):\n\n def __init__(self,address):\n addr,mask=self._split_addr_prefix(address)\n \n IPv6Address.__init__(self,addr)\n self.network=IPv6Network((addr,mask),strict=False)\n self.netmask=self.network.netmask\n self._prefixlen=self.network._prefixlen\n \n @functools.cached_property\n def hostmask(self):\n return self.network.hostmask\n \n def __str__(self):\n return '%s/%d'%(super().__str__(),\n self._prefixlen)\n \n def __eq__(self,other):\n address_equal=IPv6Address.__eq__(self,other)\n if address_equal is NotImplemented or not address_equal:\n return address_equal\n try:\n return self.network ==other.network\n except AttributeError:\n \n \n \n return False\n \n def __lt__(self,other):\n address_less=IPv6Address.__lt__(self,other)\n if address_less is NotImplemented:\n return address_less\n try:\n return(self.network self.n:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in self.indices)\n else:\n try:\n for i in reversed(range(self.r)):\n if self.indices[i]!=i+self.n -self.r:\n break\n self.indices[i]+=1\n for j in range(i+1,self.r):\n self.indices[j]=self.indices[j -1]+1\n return tuple(self.pool[i]for i in self.indices)\n except:\n raise StopIteration\n \nclass combinations_with_replacement:\n def __init__(self,iterable,r):\n self.pool=tuple(iterable)\n self.n=len(self.pool)\n self.r=r\n self.indices=[0]*self.r\n self.zero=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if not self.n and self.r:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in self.indices)\n else:\n try:\n for i in reversed(range(self.r)):\n if self.indices[i]!=self.n -1:\n break\n self.indices[i:]=[self.indices[i]+1]*(self.r -i)\n return tuple(self.pool[i]for i in self.indices)\n except:\n raise StopIteration\n \n \n \nclass compress:\n def __init__(self,data,selectors):\n self.data=iter(data)\n self.selectors=iter(selectors)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n while True:\n next_item=next(self.data)\n next_selector=next(self.selectors)\n if bool(next_selector):\n return next_item\n \n \n \n \nclass count:\n ''\n\n\n\n \n def __init__(self,start=0,step=1):\n if not isinstance(start,(int,float)):\n raise TypeError('a number is required')\n self.times=start -step\n self.step=step\n \n def __iter__(self):\n return self\n \n def __next__(self):\n self.times +=self.step\n return self.times\n \n def __repr__(self):\n return 'count(%d)'%(self.times+self.step)\n \n \n \nclass cycle:\n def __init__(self,iterable):\n self._cur_iter=iter(iterable)\n self._saved=[]\n self._must_save=True\n \n def __iter__(self):\n return self\n \n def __next__(self):\n try:\n next_elt=next(self._cur_iter)\n if self._must_save:\n self._saved.append(next_elt)\n except StopIteration:\n self._cur_iter=iter(self._saved)\n next_elt=next(self._cur_iter)\n self._must_save=False\n return next_elt\n \n \n \nclass dropwhile:\n def __init__(self,predicate,iterable):\n self._predicate=predicate\n self._iter=iter(iterable)\n self._dropped=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n value=next(self._iter)\n if self._dropped:\n return value\n while self._predicate(value):\n value=next(self._iter)\n self._dropped=True\n return value\n \n \n \nclass filterfalse:\n def __init__(self,predicate,iterable):\n \n self._iter=iter(iterable)\n if predicate is None:\n self._predicate=bool\n else:\n self._predicate=predicate\n \n def __iter__(self):\n return self\n def __next__(self):\n next_elt=next(self._iter)\n while True:\n if not self._predicate(next_elt):\n return next_elt\n next_elt=next(self._iter)\n \nclass groupby:\n\n\n def __init__(self,iterable,key=None):\n if key is None:\n key=lambda x:x\n self.keyfunc=key\n self.it=iter(iterable)\n self.tgtkey=self.currkey=self.currvalue=object()\n def __iter__(self):\n return self\n def __next__(self):\n while self.currkey ==self.tgtkey:\n self.currvalue=next(self.it)\n self.currkey=self.keyfunc(self.currvalue)\n self.tgtkey=self.currkey\n return(self.currkey,self._grouper(self.tgtkey))\n def _grouper(self,tgtkey):\n while self.currkey ==tgtkey:\n yield self.currvalue\n self.currvalue=next(self.it)\n self.currkey=self.keyfunc(self.currvalue)\n \n \n \nclass islice:\n def __init__(self,iterable,*args):\n s=slice(*args)\n self.start,self.stop,self.step=s.start or 0,s.stop,s.step\n if not isinstance(self.start,int):\n raise ValueError(\"Start argument must be an integer\")\n if self.stop !=None and not isinstance(self.stop,int):\n raise ValueError(\"Stop argument must be an integer or None\")\n if self.step is None:\n self.step=1\n if self.start <0 or(self.stop !=None and self.stop <0\n )or self.step <=0:\n raise ValueError(\"indices for islice() must be positive\")\n self.it=iter(iterable)\n self.donext=None\n self.cnt=0\n \n def __iter__(self):\n return self\n \n def __next__(self):\n nextindex=self.start\n if self.stop !=None and nextindex >=self.stop:\n raise StopIteration\n while self.cnt <=nextindex:\n nextitem=next(self.it)\n self.cnt +=1\n self.start +=self.step\n return nextitem\n \nclass permutations:\n def __init__(self,iterable,r=None):\n self.pool=tuple(iterable)\n self.n=len(self.pool)\n self.r=self.n if r is None else r\n self.indices=list(range(self.n))\n self.cycles=list(range(self.n,self.n -self.r,-1))\n self.zero=False\n self.stop=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n indices=self.indices\n if self.r >self.n:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in indices[:self.r])\n \n i=self.r -1\n while i >=0:\n j=self.cycles[i]-1\n if j >0:\n self.cycles[i]=j\n indices[i],indices[-j]=indices[-j],indices[i]\n return tuple(self.pool[i]for i in indices[:self.r])\n self.cycles[i]=len(indices)-i\n n1=len(indices)-1\n assert n1 >=0\n num=indices[i]\n for k in range(i,n1):\n indices[k]=indices[k+1]\n indices[n1]=num\n i -=1\n raise StopIteration\n \n \ndef product(*args,repeat=1):\n\n\n pools=[tuple(pool)for pool in args]*repeat\n result=[[]]\n for pool in pools:\n result=[x+[y]for x in result for y in pool]\n for prod in result:\n yield tuple(prod)\n \n \n \n \n \n \n \n \nclass _product:\n def __init__(self,*args,**kw):\n if len(kw)>1:\n raise TypeError(\"product() takes at most 1 argument (%d given)\"%\n len(kw))\n self.repeat=kw.get('repeat',1)\n if not isinstance(self.repeat,int):\n raise TypeError(\"integer argument expected, got %s\"%\n type(self.repeat))\n self.gears=[x for x in args]*self.repeat\n self.num_gears=len(self.gears)\n \n self.indicies=[(0,len(self.gears[x]))\n for x in range(0,self.num_gears)]\n self.cont=True\n self.zero=False\n \n def roll_gears(self):\n \n \n \n should_carry=True\n for n in range(0,self.num_gears):\n nth_gear=self.num_gears -n -1\n if should_carry:\n count,lim=self.indicies[nth_gear]\n count +=1\n if count ==lim and nth_gear ==0:\n self.cont=False\n if count ==lim:\n should_carry=True\n count=0\n else:\n should_carry=False\n self.indicies[nth_gear]=(count,lim)\n else:\n break\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if self.zero:\n raise StopIteration\n if self.repeat >0:\n if not self.cont:\n raise StopIteration\n l=[]\n for x in range(0,self.num_gears):\n index,limit=self.indicies[x]\n print('itertools 353',self.gears,x,index)\n l.append(self.gears[x][index])\n self.roll_gears()\n return tuple(l)\n elif self.repeat ==0:\n self.zero=True\n return()\n else:\n raise ValueError(\"repeat argument cannot be negative\")\n \n \n \nclass repeat:\n def __init__(self,obj,times=None):\n self._obj=obj\n if times is not None:\n range(times)\n if times <0:\n times=0\n self._times=times\n \n def __iter__(self):\n return self\n \n def __next__(self):\n \n if self._times is not None:\n if self._times <=0:\n raise StopIteration()\n self._times -=1\n return self._obj\n \n def __repr__(self):\n if self._times is not None:\n return 'repeat(%r, %r)'%(self._obj,self._times)\n else:\n return 'repeat(%r)'%(self._obj,)\n \n def __len__(self):\n if self._times ==-1 or self._times is None:\n raise TypeError(\"len() of uniszed object\")\n return self._times\n \n \n \nclass starmap(object):\n def __init__(self,function,iterable):\n self._func=function\n self._iter=iter(iterable)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n t=next(self._iter)\n return self._func(*t)\n \n \n \nclass takewhile(object):\n def __init__(self,predicate,iterable):\n self._predicate=predicate\n self._iter=iter(iterable)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n value=next(self._iter)\n if not self._predicate(value):\n raise StopIteration()\n return value\n \n \n \nclass TeeData(object):\n def __init__(self,iterator):\n self.data=[]\n self._iter=iterator\n \n def __getitem__(self,i):\n \n while i >=len(self.data):\n self.data.append(next(self._iter))\n return self.data[i]\n \n \nclass TeeObject(object):\n def __init__(self,iterable=None,tee_data=None):\n if tee_data:\n self.tee_data=tee_data\n self.pos=0\n \n elif isinstance(iterable,TeeObject):\n self.tee_data=iterable.tee_data\n self.pos=iterable.pos\n else:\n self.tee_data=TeeData(iter(iterable))\n self.pos=0\n \n def __next__(self):\n data=self.tee_data[self.pos]\n self.pos +=1\n return data\n \n def __iter__(self):\n return self\n \n \ndef tee(iterable,n=2):\n if isinstance(iterable,TeeObject):\n return tuple([iterable]+\n [TeeObject(tee_data=iterable.tee_data)for i in range(n -1)])\n tee_data=TeeData(iter(iterable))\n return tuple([TeeObject(tee_data=tee_data)for i in range(n)])\n \nclass zip_longest:\n def __init__(self,*args,fillvalue=None):\n self.args=[iter(arg)for arg in args]\n self.fillvalue=fillvalue\n self.units=len(args)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n temp=[]\n nb=0\n for i in range(self.units):\n try:\n temp.append(next(self.args[i]))\n nb +=1\n except StopIteration:\n temp.append(self.fillvalue)\n if nb ==0:\n raise StopIteration\n return tuple(temp)\n", ["operator"]], "keyword": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\"iskeyword\",\"issoftkeyword\",\"kwlist\",\"softkwlist\"]\n\nkwlist=[\n'False',\n'None',\n'True',\n'and',\n'as',\n'assert',\n'async',\n'await',\n'break',\n'class',\n'continue',\n'def',\n'del',\n'elif',\n'else',\n'except',\n'finally',\n'for',\n'from',\n'global',\n'if',\n'import',\n'in',\n'is',\n'lambda',\n'nonlocal',\n'not',\n'or',\n'pass',\n'raise',\n'return',\n'try',\n'while',\n'with',\n'yield'\n]\n\nsoftkwlist=[\n'_',\n'case',\n'match',\n'type'\n]\n\niskeyword=frozenset(kwlist).__contains__\nissoftkeyword=frozenset(softkwlist).__contains__\n", []], "linecache": [".py", "''\n\n\n\n\n\n\n__all__=[\"getline\",\"clearcache\",\"checkcache\",\"lazycache\"]\n\n\n\n\ncache={}\n\n\ndef clearcache():\n ''\n cache.clear()\n \n \ndef getline(filename,lineno,module_globals=None):\n ''\n \n \n lines=getlines(filename,module_globals)\n if 1 <=lineno <=len(lines):\n return lines[lineno -1]\n return ''\n \n \ndef getlines(filename,module_globals=None):\n ''\n \n \n if filename in cache:\n entry=cache[filename]\n if len(entry)!=1:\n return cache[filename][2]\n \n try:\n return updatecache(filename,module_globals)\n except MemoryError:\n clearcache()\n return[]\n \n \ndef checkcache(filename=None):\n ''\n \n \n if filename is None:\n filenames=list(cache.keys())\n elif filename in cache:\n filenames=[filename]\n else:\n return\n \n for filename in filenames:\n entry=cache[filename]\n if len(entry)==1:\n \n continue\n size,mtime,lines,fullname=entry\n if mtime is None:\n continue\n try:\n \n import os\n except ImportError:\n return\n try:\n stat=os.stat(fullname)\n except OSError:\n cache.pop(filename,None)\n continue\n if size !=stat.st_size or mtime !=stat.st_mtime:\n cache.pop(filename,None)\n \n \ndef updatecache(filename,module_globals=None):\n ''\n\n \n \n \n \n \n import os\n import sys\n import tokenize\n \n if filename in cache:\n if len(cache[filename])!=1:\n cache.pop(filename,None)\n if not filename or(filename.startswith('<')and filename.endswith('>')):\n return[]\n \n fullname=filename\n try:\n stat=os.stat(fullname)\n except OSError:\n basename=filename\n \n \n \n if lazycache(filename,module_globals):\n try:\n data=cache[filename][0]()\n except(ImportError,OSError):\n pass\n else:\n if data is None:\n \n \n return[]\n cache[filename]=(\n len(data),\n None,\n [line+'\\n'for line in data.splitlines()],\n fullname\n )\n return cache[filename][2]\n \n \n \n if os.path.isabs(filename):\n return[]\n \n for dirname in sys.path:\n try:\n fullname=os.path.join(dirname,basename)\n except(TypeError,AttributeError):\n \n continue\n try:\n stat=os.stat(fullname)\n break\n except OSError:\n pass\n else:\n return[]\n try:\n with tokenize.open(fullname)as fp:\n lines=fp.readlines()\n except(OSError,UnicodeDecodeError,SyntaxError):\n return[]\n if not lines:\n lines=['\\n']\n elif not lines[-1].endswith('\\n'):\n lines[-1]+='\\n'\n size,mtime=stat.st_size,stat.st_mtime\n cache[filename]=size,mtime,lines,fullname\n return lines\n \n \ndef lazycache(filename,module_globals):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if filename in cache:\n if len(cache[filename])==1:\n return True\n else:\n return False\n if not filename or(filename.startswith('<')and filename.endswith('>')):\n return False\n \n if module_globals and '__name__'in module_globals:\n spec=module_globals.get('__spec__')\n name=getattr(spec,'name',None)or module_globals['__name__']\n loader=getattr(spec,'loader',None)\n if loader is None:\n loader=module_globals.get('__loader__')\n get_source=getattr(loader,'get_source',None)\n \n if name and get_source:\n def get_lines(name=name,*args,**kwargs):\n return get_source(name,*args,**kwargs)\n cache[filename]=(get_lines,)\n return True\n return False\n \n \ndef _register_code(code,string,name):\n cache[code]=(\n len(string),\n None,\n [line+'\\n'for line in string.splitlines()],\n name)\n", ["os", "sys", "tokenize"]], "locale": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport encodings\nimport encodings.aliases\nimport re\nimport _collections_abc\nfrom builtins import str as _builtin_str\nimport functools\n\n\n\n\n\n\n\n__all__=[\"getlocale\",\"getdefaultlocale\",\"getpreferredencoding\",\"Error\",\n\"setlocale\",\"localeconv\",\"strcoll\",\"strxfrm\",\n\"str\",\"atof\",\"atoi\",\"format_string\",\"currency\",\n\"normalize\",\"LC_CTYPE\",\"LC_COLLATE\",\"LC_TIME\",\"LC_MONETARY\",\n\"LC_NUMERIC\",\"LC_ALL\",\"CHAR_MAX\",\"getencoding\"]\n\ndef _strcoll(a,b):\n ''\n\n \n return(a >b)-(a .*?)\\))?'\nr'(?P[-#0-9 +*.hlL]*?)[eEfFgGdiouxXcrs%]')\n\ndef _format(percent,value,grouping=False,monetary=False,*additional):\n if additional:\n formatted=percent %((value,)+additional)\n else:\n formatted=percent %value\n if percent[-1]in 'eEfFgGdiu':\n formatted=_localize(formatted,grouping,monetary)\n return formatted\n \n \ndef _localize(formatted,grouping=False,monetary=False):\n\n if '.'in formatted:\n seps=0\n parts=formatted.split('.')\n if grouping:\n parts[0],seps=_group(parts[0],monetary=monetary)\n decimal_point=localeconv()[monetary and 'mon_decimal_point'\n or 'decimal_point']\n formatted=decimal_point.join(parts)\n if seps:\n formatted=_strip_padding(formatted,seps)\n else:\n seps=0\n if grouping:\n formatted,seps=_group(formatted,monetary=monetary)\n if seps:\n formatted=_strip_padding(formatted,seps)\n return formatted\n \ndef format_string(f,val,grouping=False,monetary=False):\n ''\n\n\n\n\n \n percents=list(_percent_re.finditer(f))\n new_f=_percent_re.sub('%s',f)\n \n if isinstance(val,_collections_abc.Mapping):\n new_val=[]\n for perc in percents:\n if perc.group()[-1]=='%':\n new_val.append('%')\n else:\n new_val.append(_format(perc.group(),val,grouping,monetary))\n else:\n if not isinstance(val,tuple):\n val=(val,)\n new_val=[]\n i=0\n for perc in percents:\n if perc.group()[-1]=='%':\n new_val.append('%')\n else:\n starcount=perc.group('modifiers').count('*')\n new_val.append(_format(perc.group(),\n val[i],\n grouping,\n monetary,\n *val[i+1:i+1+starcount]))\n i +=(1+starcount)\n val=tuple(new_val)\n \n return new_f %val\n \ndef currency(val,symbol=True,grouping=False,international=False):\n ''\n \n conv=localeconv()\n \n \n digits=conv[international and 'int_frac_digits'or 'frac_digits']\n if digits ==127:\n raise ValueError(\"Currency formatting is not possible using \"\n \"the 'C' locale.\")\n \n s=_localize(f'{abs(val):.{digits}f}',grouping,monetary=True)\n \n s='<'+s+'>'\n \n if symbol:\n smb=conv[international and 'int_curr_symbol'or 'currency_symbol']\n precedes=conv[val <0 and 'n_cs_precedes'or 'p_cs_precedes']\n separated=conv[val <0 and 'n_sep_by_space'or 'p_sep_by_space']\n \n if precedes:\n s=smb+(separated and ' 'or '')+s\n else:\n if international and smb[-1]==' ':\n smb=smb[:-1]\n s=s+(separated and ' 'or '')+smb\n \n sign_pos=conv[val <0 and 'n_sign_posn'or 'p_sign_posn']\n sign=conv[val <0 and 'negative_sign'or 'positive_sign']\n \n if sign_pos ==0:\n s='('+s+')'\n elif sign_pos ==1:\n s=sign+s\n elif sign_pos ==2:\n s=s+sign\n elif sign_pos ==3:\n s=s.replace('<',sign)\n elif sign_pos ==4:\n s=s.replace('>',sign)\n else:\n \n \n s=sign+s\n \n return s.replace('<','').replace('>','')\n \ndef str(val):\n ''\n return _format(\"%.12g\",val)\n \ndef delocalize(string):\n ''\n \n conv=localeconv()\n \n \n ts=conv['thousands_sep']\n if ts:\n string=string.replace(ts,'')\n \n \n dd=conv['decimal_point']\n if dd:\n string=string.replace(dd,'.')\n return string\n \ndef localize(string,grouping=False,monetary=False):\n ''\n return _localize(string,grouping,monetary)\n \ndef atof(string,func=float):\n ''\n return func(delocalize(string))\n \ndef atoi(string):\n ''\n return int(delocalize(string))\n \ndef _test():\n setlocale(LC_ALL,\"\")\n \n s1=format_string(\"%d\",123456789,1)\n print(s1,\"is\",atoi(s1))\n \n s1=str(3.14)\n print(s1,\"is\",atof(s1))\n \n \n \n \n \n \n \n \n_setlocale=setlocale\n\ndef _replace_encoding(code,encoding):\n if '.'in code:\n langname=code[:code.index('.')]\n else:\n langname=code\n \n norm_encoding=encodings.normalize_encoding(encoding)\n \n norm_encoding=encodings.aliases.aliases.get(norm_encoding.lower(),\n norm_encoding)\n \n encoding=norm_encoding\n norm_encoding=norm_encoding.lower()\n if norm_encoding in locale_encoding_alias:\n encoding=locale_encoding_alias[norm_encoding]\n else:\n norm_encoding=norm_encoding.replace('_','')\n norm_encoding=norm_encoding.replace('-','')\n if norm_encoding in locale_encoding_alias:\n encoding=locale_encoding_alias[norm_encoding]\n \n return langname+'.'+encoding\n \ndef _append_modifier(code,modifier):\n if modifier =='euro':\n if '.'not in code:\n return code+'.ISO8859-15'\n _,_,encoding=code.partition('.')\n if encoding in('ISO8859-15','UTF-8'):\n return code\n if encoding =='ISO8859-1':\n return _replace_encoding(code,'ISO8859-15')\n return code+'@'+modifier\n \ndef normalize(localename):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n code=localename.lower()\n if ':'in code:\n \n code=code.replace(':','.')\n if '@'in code:\n code,modifier=code.split('@',1)\n else:\n modifier=''\n if '.'in code:\n langname,encoding=code.split('.')[:2]\n else:\n langname=code\n encoding=''\n \n \n lang_enc=langname\n if encoding:\n norm_encoding=encoding.replace('-','')\n norm_encoding=norm_encoding.replace('_','')\n lang_enc +='.'+norm_encoding\n lookup_name=lang_enc\n if modifier:\n lookup_name +='@'+modifier\n code=locale_alias.get(lookup_name,None)\n if code is not None:\n return code\n \n \n if modifier:\n \n code=locale_alias.get(lang_enc,None)\n if code is not None:\n \n if '@'not in code:\n return _append_modifier(code,modifier)\n if code.split('@',1)[1].lower()==modifier:\n return code\n \n \n if encoding:\n \n lookup_name=langname\n if modifier:\n lookup_name +='@'+modifier\n code=locale_alias.get(lookup_name,None)\n if code is not None:\n \n if '@'not in code:\n return _replace_encoding(code,encoding)\n code,modifier=code.split('@',1)\n return _replace_encoding(code,encoding)+'@'+modifier\n \n if modifier:\n \n code=locale_alias.get(langname,None)\n if code is not None:\n \n if '@'not in code:\n code=_replace_encoding(code,encoding)\n return _append_modifier(code,modifier)\n code,defmod=code.split('@',1)\n if defmod.lower()==modifier:\n return _replace_encoding(code,encoding)+'@'+defmod\n \n return localename\n \ndef _parse_localename(localename):\n\n ''\n\n\n\n\n\n\n\n\n\n\n \n code=normalize(localename)\n if '@'in code:\n \n code,modifier=code.split('@',1)\n if modifier =='euro'and '.'not in code:\n \n \n \n return code,'iso-8859-15'\n \n if '.'in code:\n return tuple(code.split('.')[:2])\n elif code =='C':\n return None,None\n elif code =='UTF-8':\n \n \n return None,'UTF-8'\n raise ValueError('unknown locale: %s'%localename)\n \ndef _build_localename(localetuple):\n\n ''\n\n\n\n\n \n try:\n language,encoding=localetuple\n \n if language is None:\n language='C'\n if encoding is None:\n return language\n else:\n return language+'.'+encoding\n except(TypeError,ValueError):\n raise TypeError('Locale must be None, a string, or an iterable of '\n 'two strings -- language code, encoding.')from None\n \ndef getdefaultlocale(envvars=('LC_ALL','LC_CTYPE','LANG','LANGUAGE')):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n import warnings\n warnings._deprecated(\n \"locale.getdefaultlocale\",\n \"{name!r} is deprecated and slated for removal in Python {remove}. \"\n \"Use setlocale(), getencoding() and getlocale() instead.\",\n remove=(3,15))\n return _getdefaultlocale(envvars)\n \n \ndef _getdefaultlocale(envvars=('LC_ALL','LC_CTYPE','LANG','LANGUAGE')):\n try:\n \n import _locale\n code,encoding=_locale._getdefaultlocale()\n except(ImportError,AttributeError):\n pass\n else:\n \n if sys.platform ==\"win32\"and code and code[:2]==\"0x\":\n \n code=windows_locale.get(int(code,0))\n \n \n return code,encoding\n \n \n import os\n lookup=os.environ.get\n for variable in envvars:\n localename=lookup(variable,None)\n if localename:\n if variable =='LANGUAGE':\n localename=localename.split(':')[0]\n break\n else:\n localename='C'\n return _parse_localename(localename)\n \n \ndef getlocale(category=LC_CTYPE):\n\n ''\n\n\n\n\n\n\n\n\n\n \n localename=_setlocale(category)\n if category ==LC_ALL and ';'in localename:\n raise TypeError('category LC_ALL is not supported')\n return _parse_localename(localename)\n \ndef setlocale(category,locale=None):\n\n ''\n\n\n\n\n\n\n\n\n \n if locale and not isinstance(locale,_builtin_str):\n \n locale=normalize(_build_localename(locale))\n return _setlocale(category,locale)\n \n \ntry:\n from _locale import getencoding\nexcept ImportError:\n\n\n def getencoding():\n return sys.getfilesystemencoding()\n \n \ntry:\n CODESET\nexcept NameError:\n def getpreferredencoding(do_setlocale=True):\n ''\n if sys.flags.warn_default_encoding:\n import warnings\n warnings.warn(\n \"UTF-8 Mode affects locale.getpreferredencoding(). Consider locale.getencoding() instead.\",\n EncodingWarning,2)\n if sys.flags.utf8_mode:\n return 'utf-8'\n return getencoding()\nelse:\n\n def getpreferredencoding(do_setlocale=True):\n ''\n \n \n if sys.flags.warn_default_encoding:\n import warnings\n warnings.warn(\n \"UTF-8 Mode affects locale.getpreferredencoding(). Consider locale.getencoding() instead.\",\n EncodingWarning,2)\n if sys.flags.utf8_mode:\n return 'utf-8'\n \n if not do_setlocale:\n return getencoding()\n \n old_loc=setlocale(LC_CTYPE)\n try:\n try:\n setlocale(LC_CTYPE,\"\")\n except Error:\n pass\n return getencoding()\n finally:\n setlocale(LC_CTYPE,old_loc)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nlocale_encoding_alias={\n\n\n'437':'C',\n'c':'C',\n'en':'ISO8859-1',\n'jis':'JIS7',\n'jis7':'JIS7',\n'ajec':'eucJP',\n'koi8c':'KOI8-C',\n'microsoftcp1251':'CP1251',\n'microsoftcp1255':'CP1255',\n'microsoftcp1256':'CP1256',\n'88591':'ISO8859-1',\n'88592':'ISO8859-2',\n'88595':'ISO8859-5',\n'885915':'ISO8859-15',\n\n\n'ascii':'ISO8859-1',\n'latin_1':'ISO8859-1',\n'iso8859_1':'ISO8859-1',\n'iso8859_10':'ISO8859-10',\n'iso8859_11':'ISO8859-11',\n'iso8859_13':'ISO8859-13',\n'iso8859_14':'ISO8859-14',\n'iso8859_15':'ISO8859-15',\n'iso8859_16':'ISO8859-16',\n'iso8859_2':'ISO8859-2',\n'iso8859_3':'ISO8859-3',\n'iso8859_4':'ISO8859-4',\n'iso8859_5':'ISO8859-5',\n'iso8859_6':'ISO8859-6',\n'iso8859_7':'ISO8859-7',\n'iso8859_8':'ISO8859-8',\n'iso8859_9':'ISO8859-9',\n'iso2022_jp':'JIS7',\n'shift_jis':'SJIS',\n'tactis':'TACTIS',\n'euc_jp':'eucJP',\n'euc_kr':'eucKR',\n'utf_8':'UTF-8',\n'koi8_r':'KOI8-R',\n'koi8_t':'KOI8-T',\n'koi8_u':'KOI8-U',\n'kz1048':'RK1048',\n'cp1251':'CP1251',\n'cp1255':'CP1255',\n'cp1256':'CP1256',\n\n\n\n}\n\nfor k,v in sorted(locale_encoding_alias.items()):\n k=k.replace('_','')\n locale_encoding_alias.setdefault(k,v)\ndel k,v\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nlocale_alias={\n'a3':'az_AZ.KOI8-C',\n'a3_az':'az_AZ.KOI8-C',\n'a3_az.koic':'az_AZ.KOI8-C',\n'aa_dj':'aa_DJ.ISO8859-1',\n'aa_er':'aa_ER.UTF-8',\n'aa_et':'aa_ET.UTF-8',\n'af':'af_ZA.ISO8859-1',\n'af_za':'af_ZA.ISO8859-1',\n'agr_pe':'agr_PE.UTF-8',\n'ak_gh':'ak_GH.UTF-8',\n'am':'am_ET.UTF-8',\n'am_et':'am_ET.UTF-8',\n'american':'en_US.ISO8859-1',\n'an_es':'an_ES.ISO8859-15',\n'anp_in':'anp_IN.UTF-8',\n'ar':'ar_AA.ISO8859-6',\n'ar_aa':'ar_AA.ISO8859-6',\n'ar_ae':'ar_AE.ISO8859-6',\n'ar_bh':'ar_BH.ISO8859-6',\n'ar_dz':'ar_DZ.ISO8859-6',\n'ar_eg':'ar_EG.ISO8859-6',\n'ar_in':'ar_IN.UTF-8',\n'ar_iq':'ar_IQ.ISO8859-6',\n'ar_jo':'ar_JO.ISO8859-6',\n'ar_kw':'ar_KW.ISO8859-6',\n'ar_lb':'ar_LB.ISO8859-6',\n'ar_ly':'ar_LY.ISO8859-6',\n'ar_ma':'ar_MA.ISO8859-6',\n'ar_om':'ar_OM.ISO8859-6',\n'ar_qa':'ar_QA.ISO8859-6',\n'ar_sa':'ar_SA.ISO8859-6',\n'ar_sd':'ar_SD.ISO8859-6',\n'ar_ss':'ar_SS.UTF-8',\n'ar_sy':'ar_SY.ISO8859-6',\n'ar_tn':'ar_TN.ISO8859-6',\n'ar_ye':'ar_YE.ISO8859-6',\n'arabic':'ar_AA.ISO8859-6',\n'as':'as_IN.UTF-8',\n'as_in':'as_IN.UTF-8',\n'ast_es':'ast_ES.ISO8859-15',\n'ayc_pe':'ayc_PE.UTF-8',\n'az':'az_AZ.ISO8859-9E',\n'az_az':'az_AZ.ISO8859-9E',\n'az_az.iso88599e':'az_AZ.ISO8859-9E',\n'az_ir':'az_IR.UTF-8',\n'be':'be_BY.CP1251',\n'be@latin':'be_BY.UTF-8@latin',\n'be_bg.utf8':'bg_BG.UTF-8',\n'be_by':'be_BY.CP1251',\n'be_by@latin':'be_BY.UTF-8@latin',\n'bem_zm':'bem_ZM.UTF-8',\n'ber_dz':'ber_DZ.UTF-8',\n'ber_ma':'ber_MA.UTF-8',\n'bg':'bg_BG.CP1251',\n'bg_bg':'bg_BG.CP1251',\n'bhb_in.utf8':'bhb_IN.UTF-8',\n'bho_in':'bho_IN.UTF-8',\n'bho_np':'bho_NP.UTF-8',\n'bi_vu':'bi_VU.UTF-8',\n'bn_bd':'bn_BD.UTF-8',\n'bn_in':'bn_IN.UTF-8',\n'bo_cn':'bo_CN.UTF-8',\n'bo_in':'bo_IN.UTF-8',\n'bokmal':'nb_NO.ISO8859-1',\n'bokm\\xe5l':'nb_NO.ISO8859-1',\n'br':'br_FR.ISO8859-1',\n'br_fr':'br_FR.ISO8859-1',\n'brx_in':'brx_IN.UTF-8',\n'bs':'bs_BA.ISO8859-2',\n'bs_ba':'bs_BA.ISO8859-2',\n'bulgarian':'bg_BG.CP1251',\n'byn_er':'byn_ER.UTF-8',\n'c':'C',\n'c-french':'fr_CA.ISO8859-1',\n'c.ascii':'C',\n'c.en':'C',\n'c.iso88591':'en_US.ISO8859-1',\n'c.utf8':'C.UTF-8',\n'c_c':'C',\n'c_c.c':'C',\n'ca':'ca_ES.ISO8859-1',\n'ca_ad':'ca_AD.ISO8859-1',\n'ca_es':'ca_ES.ISO8859-1',\n'ca_es@valencia':'ca_ES.UTF-8@valencia',\n'ca_fr':'ca_FR.ISO8859-1',\n'ca_it':'ca_IT.ISO8859-1',\n'catalan':'ca_ES.ISO8859-1',\n'ce_ru':'ce_RU.UTF-8',\n'cextend':'en_US.ISO8859-1',\n'chinese-s':'zh_CN.eucCN',\n'chinese-t':'zh_TW.eucTW',\n'chr_us':'chr_US.UTF-8',\n'ckb_iq':'ckb_IQ.UTF-8',\n'cmn_tw':'cmn_TW.UTF-8',\n'crh_ua':'crh_UA.UTF-8',\n'croatian':'hr_HR.ISO8859-2',\n'cs':'cs_CZ.ISO8859-2',\n'cs_cs':'cs_CZ.ISO8859-2',\n'cs_cz':'cs_CZ.ISO8859-2',\n'csb_pl':'csb_PL.UTF-8',\n'cv_ru':'cv_RU.UTF-8',\n'cy':'cy_GB.ISO8859-1',\n'cy_gb':'cy_GB.ISO8859-1',\n'cz':'cs_CZ.ISO8859-2',\n'cz_cz':'cs_CZ.ISO8859-2',\n'czech':'cs_CZ.ISO8859-2',\n'da':'da_DK.ISO8859-1',\n'da_dk':'da_DK.ISO8859-1',\n'danish':'da_DK.ISO8859-1',\n'dansk':'da_DK.ISO8859-1',\n'de':'de_DE.ISO8859-1',\n'de_at':'de_AT.ISO8859-1',\n'de_be':'de_BE.ISO8859-1',\n'de_ch':'de_CH.ISO8859-1',\n'de_de':'de_DE.ISO8859-1',\n'de_it':'de_IT.ISO8859-1',\n'de_li.utf8':'de_LI.UTF-8',\n'de_lu':'de_LU.ISO8859-1',\n'deutsch':'de_DE.ISO8859-1',\n'doi_in':'doi_IN.UTF-8',\n'dutch':'nl_NL.ISO8859-1',\n'dutch.iso88591':'nl_BE.ISO8859-1',\n'dv_mv':'dv_MV.UTF-8',\n'dz_bt':'dz_BT.UTF-8',\n'ee':'ee_EE.ISO8859-4',\n'ee_ee':'ee_EE.ISO8859-4',\n'eesti':'et_EE.ISO8859-1',\n'el':'el_GR.ISO8859-7',\n'el_cy':'el_CY.ISO8859-7',\n'el_gr':'el_GR.ISO8859-7',\n'el_gr@euro':'el_GR.ISO8859-15',\n'en':'en_US.ISO8859-1',\n'en_ag':'en_AG.UTF-8',\n'en_au':'en_AU.ISO8859-1',\n'en_be':'en_BE.ISO8859-1',\n'en_bw':'en_BW.ISO8859-1',\n'en_ca':'en_CA.ISO8859-1',\n'en_dk':'en_DK.ISO8859-1',\n'en_dl.utf8':'en_DL.UTF-8',\n'en_gb':'en_GB.ISO8859-1',\n'en_hk':'en_HK.ISO8859-1',\n'en_ie':'en_IE.ISO8859-1',\n'en_il':'en_IL.UTF-8',\n'en_in':'en_IN.ISO8859-1',\n'en_ng':'en_NG.UTF-8',\n'en_nz':'en_NZ.ISO8859-1',\n'en_ph':'en_PH.ISO8859-1',\n'en_sc.utf8':'en_SC.UTF-8',\n'en_sg':'en_SG.ISO8859-1',\n'en_uk':'en_GB.ISO8859-1',\n'en_us':'en_US.ISO8859-1',\n'en_us@euro@euro':'en_US.ISO8859-15',\n'en_za':'en_ZA.ISO8859-1',\n'en_zm':'en_ZM.UTF-8',\n'en_zw':'en_ZW.ISO8859-1',\n'en_zw.utf8':'en_ZS.UTF-8',\n'eng_gb':'en_GB.ISO8859-1',\n'english':'en_EN.ISO8859-1',\n'english.iso88591':'en_US.ISO8859-1',\n'english_uk':'en_GB.ISO8859-1',\n'english_united-states':'en_US.ISO8859-1',\n'english_united-states.437':'C',\n'english_us':'en_US.ISO8859-1',\n'eo':'eo_XX.ISO8859-3',\n'eo.utf8':'eo.UTF-8',\n'eo_eo':'eo_EO.ISO8859-3',\n'eo_us.utf8':'eo_US.UTF-8',\n'eo_xx':'eo_XX.ISO8859-3',\n'es':'es_ES.ISO8859-1',\n'es_ar':'es_AR.ISO8859-1',\n'es_bo':'es_BO.ISO8859-1',\n'es_cl':'es_CL.ISO8859-1',\n'es_co':'es_CO.ISO8859-1',\n'es_cr':'es_CR.ISO8859-1',\n'es_cu':'es_CU.UTF-8',\n'es_do':'es_DO.ISO8859-1',\n'es_ec':'es_EC.ISO8859-1',\n'es_es':'es_ES.ISO8859-1',\n'es_gt':'es_GT.ISO8859-1',\n'es_hn':'es_HN.ISO8859-1',\n'es_mx':'es_MX.ISO8859-1',\n'es_ni':'es_NI.ISO8859-1',\n'es_pa':'es_PA.ISO8859-1',\n'es_pe':'es_PE.ISO8859-1',\n'es_pr':'es_PR.ISO8859-1',\n'es_py':'es_PY.ISO8859-1',\n'es_sv':'es_SV.ISO8859-1',\n'es_us':'es_US.ISO8859-1',\n'es_uy':'es_UY.ISO8859-1',\n'es_ve':'es_VE.ISO8859-1',\n'estonian':'et_EE.ISO8859-1',\n'et':'et_EE.ISO8859-15',\n'et_ee':'et_EE.ISO8859-15',\n'eu':'eu_ES.ISO8859-1',\n'eu_es':'eu_ES.ISO8859-1',\n'eu_fr':'eu_FR.ISO8859-1',\n'fa':'fa_IR.UTF-8',\n'fa_ir':'fa_IR.UTF-8',\n'fa_ir.isiri3342':'fa_IR.ISIRI-3342',\n'ff_sn':'ff_SN.UTF-8',\n'fi':'fi_FI.ISO8859-15',\n'fi_fi':'fi_FI.ISO8859-15',\n'fil_ph':'fil_PH.UTF-8',\n'finnish':'fi_FI.ISO8859-1',\n'fo':'fo_FO.ISO8859-1',\n'fo_fo':'fo_FO.ISO8859-1',\n'fr':'fr_FR.ISO8859-1',\n'fr_be':'fr_BE.ISO8859-1',\n'fr_ca':'fr_CA.ISO8859-1',\n'fr_ch':'fr_CH.ISO8859-1',\n'fr_fr':'fr_FR.ISO8859-1',\n'fr_lu':'fr_LU.ISO8859-1',\n'fran\\xe7ais':'fr_FR.ISO8859-1',\n'fre_fr':'fr_FR.ISO8859-1',\n'french':'fr_FR.ISO8859-1',\n'french.iso88591':'fr_CH.ISO8859-1',\n'french_france':'fr_FR.ISO8859-1',\n'fur_it':'fur_IT.UTF-8',\n'fy_de':'fy_DE.UTF-8',\n'fy_nl':'fy_NL.UTF-8',\n'ga':'ga_IE.ISO8859-1',\n'ga_ie':'ga_IE.ISO8859-1',\n'galego':'gl_ES.ISO8859-1',\n'galician':'gl_ES.ISO8859-1',\n'gd':'gd_GB.ISO8859-1',\n'gd_gb':'gd_GB.ISO8859-1',\n'ger_de':'de_DE.ISO8859-1',\n'german':'de_DE.ISO8859-1',\n'german.iso88591':'de_CH.ISO8859-1',\n'german_germany':'de_DE.ISO8859-1',\n'gez_er':'gez_ER.UTF-8',\n'gez_et':'gez_ET.UTF-8',\n'gl':'gl_ES.ISO8859-1',\n'gl_es':'gl_ES.ISO8859-1',\n'greek':'el_GR.ISO8859-7',\n'gu_in':'gu_IN.UTF-8',\n'gv':'gv_GB.ISO8859-1',\n'gv_gb':'gv_GB.ISO8859-1',\n'ha_ng':'ha_NG.UTF-8',\n'hak_tw':'hak_TW.UTF-8',\n'he':'he_IL.ISO8859-8',\n'he_il':'he_IL.ISO8859-8',\n'hebrew':'he_IL.ISO8859-8',\n'hi':'hi_IN.ISCII-DEV',\n'hi_in':'hi_IN.ISCII-DEV',\n'hi_in.isciidev':'hi_IN.ISCII-DEV',\n'hif_fj':'hif_FJ.UTF-8',\n'hne':'hne_IN.UTF-8',\n'hne_in':'hne_IN.UTF-8',\n'hr':'hr_HR.ISO8859-2',\n'hr_hr':'hr_HR.ISO8859-2',\n'hrvatski':'hr_HR.ISO8859-2',\n'hsb_de':'hsb_DE.ISO8859-2',\n'ht_ht':'ht_HT.UTF-8',\n'hu':'hu_HU.ISO8859-2',\n'hu_hu':'hu_HU.ISO8859-2',\n'hungarian':'hu_HU.ISO8859-2',\n'hy_am':'hy_AM.UTF-8',\n'hy_am.armscii8':'hy_AM.ARMSCII_8',\n'ia':'ia.UTF-8',\n'ia_fr':'ia_FR.UTF-8',\n'icelandic':'is_IS.ISO8859-1',\n'id':'id_ID.ISO8859-1',\n'id_id':'id_ID.ISO8859-1',\n'ig_ng':'ig_NG.UTF-8',\n'ik_ca':'ik_CA.UTF-8',\n'in':'id_ID.ISO8859-1',\n'in_id':'id_ID.ISO8859-1',\n'is':'is_IS.ISO8859-1',\n'is_is':'is_IS.ISO8859-1',\n'iso-8859-1':'en_US.ISO8859-1',\n'iso-8859-15':'en_US.ISO8859-15',\n'iso8859-1':'en_US.ISO8859-1',\n'iso8859-15':'en_US.ISO8859-15',\n'iso_8859_1':'en_US.ISO8859-1',\n'iso_8859_15':'en_US.ISO8859-15',\n'it':'it_IT.ISO8859-1',\n'it_ch':'it_CH.ISO8859-1',\n'it_it':'it_IT.ISO8859-1',\n'italian':'it_IT.ISO8859-1',\n'iu':'iu_CA.NUNACOM-8',\n'iu_ca':'iu_CA.NUNACOM-8',\n'iu_ca.nunacom8':'iu_CA.NUNACOM-8',\n'iw':'he_IL.ISO8859-8',\n'iw_il':'he_IL.ISO8859-8',\n'iw_il.utf8':'iw_IL.UTF-8',\n'ja':'ja_JP.eucJP',\n'ja_jp':'ja_JP.eucJP',\n'ja_jp.euc':'ja_JP.eucJP',\n'ja_jp.mscode':'ja_JP.SJIS',\n'ja_jp.pck':'ja_JP.SJIS',\n'japan':'ja_JP.eucJP',\n'japanese':'ja_JP.eucJP',\n'japanese-euc':'ja_JP.eucJP',\n'japanese.euc':'ja_JP.eucJP',\n'jp_jp':'ja_JP.eucJP',\n'ka':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge.georgianacademy':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge.georgianps':'ka_GE.GEORGIAN-PS',\n'ka_ge.georgianrs':'ka_GE.GEORGIAN-ACADEMY',\n'kab_dz':'kab_DZ.UTF-8',\n'kk_kz':'kk_KZ.ptcp154',\n'kl':'kl_GL.ISO8859-1',\n'kl_gl':'kl_GL.ISO8859-1',\n'km_kh':'km_KH.UTF-8',\n'kn':'kn_IN.UTF-8',\n'kn_in':'kn_IN.UTF-8',\n'ko':'ko_KR.eucKR',\n'ko_kr':'ko_KR.eucKR',\n'ko_kr.euc':'ko_KR.eucKR',\n'kok_in':'kok_IN.UTF-8',\n'korean':'ko_KR.eucKR',\n'korean.euc':'ko_KR.eucKR',\n'ks':'ks_IN.UTF-8',\n'ks_in':'ks_IN.UTF-8',\n'ks_in@devanagari.utf8':'ks_IN.UTF-8@devanagari',\n'ku_tr':'ku_TR.ISO8859-9',\n'kw':'kw_GB.ISO8859-1',\n'kw_gb':'kw_GB.ISO8859-1',\n'ky':'ky_KG.UTF-8',\n'ky_kg':'ky_KG.UTF-8',\n'lb_lu':'lb_LU.UTF-8',\n'lg_ug':'lg_UG.ISO8859-10',\n'li_be':'li_BE.UTF-8',\n'li_nl':'li_NL.UTF-8',\n'lij_it':'lij_IT.UTF-8',\n'lithuanian':'lt_LT.ISO8859-13',\n'ln_cd':'ln_CD.UTF-8',\n'lo':'lo_LA.MULELAO-1',\n'lo_la':'lo_LA.MULELAO-1',\n'lo_la.cp1133':'lo_LA.IBM-CP1133',\n'lo_la.ibmcp1133':'lo_LA.IBM-CP1133',\n'lo_la.mulelao1':'lo_LA.MULELAO-1',\n'lt':'lt_LT.ISO8859-13',\n'lt_lt':'lt_LT.ISO8859-13',\n'lv':'lv_LV.ISO8859-13',\n'lv_lv':'lv_LV.ISO8859-13',\n'lzh_tw':'lzh_TW.UTF-8',\n'mag_in':'mag_IN.UTF-8',\n'mai':'mai_IN.UTF-8',\n'mai_in':'mai_IN.UTF-8',\n'mai_np':'mai_NP.UTF-8',\n'mfe_mu':'mfe_MU.UTF-8',\n'mg_mg':'mg_MG.ISO8859-15',\n'mhr_ru':'mhr_RU.UTF-8',\n'mi':'mi_NZ.ISO8859-1',\n'mi_nz':'mi_NZ.ISO8859-1',\n'miq_ni':'miq_NI.UTF-8',\n'mjw_in':'mjw_IN.UTF-8',\n'mk':'mk_MK.ISO8859-5',\n'mk_mk':'mk_MK.ISO8859-5',\n'ml':'ml_IN.UTF-8',\n'ml_in':'ml_IN.UTF-8',\n'mn_mn':'mn_MN.UTF-8',\n'mni_in':'mni_IN.UTF-8',\n'mr':'mr_IN.UTF-8',\n'mr_in':'mr_IN.UTF-8',\n'ms':'ms_MY.ISO8859-1',\n'ms_my':'ms_MY.ISO8859-1',\n'mt':'mt_MT.ISO8859-3',\n'mt_mt':'mt_MT.ISO8859-3',\n'my_mm':'my_MM.UTF-8',\n'nan_tw':'nan_TW.UTF-8',\n'nb':'nb_NO.ISO8859-1',\n'nb_no':'nb_NO.ISO8859-1',\n'nds_de':'nds_DE.UTF-8',\n'nds_nl':'nds_NL.UTF-8',\n'ne_np':'ne_NP.UTF-8',\n'nhn_mx':'nhn_MX.UTF-8',\n'niu_nu':'niu_NU.UTF-8',\n'niu_nz':'niu_NZ.UTF-8',\n'nl':'nl_NL.ISO8859-1',\n'nl_aw':'nl_AW.UTF-8',\n'nl_be':'nl_BE.ISO8859-1',\n'nl_nl':'nl_NL.ISO8859-1',\n'nn':'nn_NO.ISO8859-1',\n'nn_no':'nn_NO.ISO8859-1',\n'no':'no_NO.ISO8859-1',\n'no@nynorsk':'ny_NO.ISO8859-1',\n'no_no':'no_NO.ISO8859-1',\n'no_no.iso88591@bokmal':'no_NO.ISO8859-1',\n'no_no.iso88591@nynorsk':'no_NO.ISO8859-1',\n'norwegian':'no_NO.ISO8859-1',\n'nr':'nr_ZA.ISO8859-1',\n'nr_za':'nr_ZA.ISO8859-1',\n'nso':'nso_ZA.ISO8859-15',\n'nso_za':'nso_ZA.ISO8859-15',\n'ny':'ny_NO.ISO8859-1',\n'ny_no':'ny_NO.ISO8859-1',\n'nynorsk':'nn_NO.ISO8859-1',\n'oc':'oc_FR.ISO8859-1',\n'oc_fr':'oc_FR.ISO8859-1',\n'om_et':'om_ET.UTF-8',\n'om_ke':'om_KE.ISO8859-1',\n'or':'or_IN.UTF-8',\n'or_in':'or_IN.UTF-8',\n'os_ru':'os_RU.UTF-8',\n'pa':'pa_IN.UTF-8',\n'pa_in':'pa_IN.UTF-8',\n'pa_pk':'pa_PK.UTF-8',\n'pap_an':'pap_AN.UTF-8',\n'pap_aw':'pap_AW.UTF-8',\n'pap_cw':'pap_CW.UTF-8',\n'pd':'pd_US.ISO8859-1',\n'pd_de':'pd_DE.ISO8859-1',\n'pd_us':'pd_US.ISO8859-1',\n'ph':'ph_PH.ISO8859-1',\n'ph_ph':'ph_PH.ISO8859-1',\n'pl':'pl_PL.ISO8859-2',\n'pl_pl':'pl_PL.ISO8859-2',\n'polish':'pl_PL.ISO8859-2',\n'portuguese':'pt_PT.ISO8859-1',\n'portuguese_brazil':'pt_BR.ISO8859-1',\n'posix':'C',\n'posix-utf2':'C',\n'pp':'pp_AN.ISO8859-1',\n'pp_an':'pp_AN.ISO8859-1',\n'ps_af':'ps_AF.UTF-8',\n'pt':'pt_PT.ISO8859-1',\n'pt_br':'pt_BR.ISO8859-1',\n'pt_pt':'pt_PT.ISO8859-1',\n'quz_pe':'quz_PE.UTF-8',\n'raj_in':'raj_IN.UTF-8',\n'ro':'ro_RO.ISO8859-2',\n'ro_ro':'ro_RO.ISO8859-2',\n'romanian':'ro_RO.ISO8859-2',\n'ru':'ru_RU.UTF-8',\n'ru_ru':'ru_RU.UTF-8',\n'ru_ua':'ru_UA.KOI8-U',\n'rumanian':'ro_RO.ISO8859-2',\n'russian':'ru_RU.KOI8-R',\n'rw':'rw_RW.ISO8859-1',\n'rw_rw':'rw_RW.ISO8859-1',\n'sa_in':'sa_IN.UTF-8',\n'sat_in':'sat_IN.UTF-8',\n'sc_it':'sc_IT.UTF-8',\n'sd':'sd_IN.UTF-8',\n'sd_in':'sd_IN.UTF-8',\n'sd_in@devanagari.utf8':'sd_IN.UTF-8@devanagari',\n'sd_pk':'sd_PK.UTF-8',\n'se_no':'se_NO.UTF-8',\n'serbocroatian':'sr_RS.UTF-8@latin',\n'sgs_lt':'sgs_LT.UTF-8',\n'sh':'sr_RS.UTF-8@latin',\n'sh_ba.iso88592@bosnia':'sr_CS.ISO8859-2',\n'sh_hr':'sh_HR.ISO8859-2',\n'sh_hr.iso88592':'hr_HR.ISO8859-2',\n'sh_sp':'sr_CS.ISO8859-2',\n'sh_yu':'sr_RS.UTF-8@latin',\n'shn_mm':'shn_MM.UTF-8',\n'shs_ca':'shs_CA.UTF-8',\n'si':'si_LK.UTF-8',\n'si_lk':'si_LK.UTF-8',\n'sid_et':'sid_ET.UTF-8',\n'sinhala':'si_LK.UTF-8',\n'sk':'sk_SK.ISO8859-2',\n'sk_sk':'sk_SK.ISO8859-2',\n'sl':'sl_SI.ISO8859-2',\n'sl_cs':'sl_CS.ISO8859-2',\n'sl_si':'sl_SI.ISO8859-2',\n'slovak':'sk_SK.ISO8859-2',\n'slovene':'sl_SI.ISO8859-2',\n'slovenian':'sl_SI.ISO8859-2',\n'sm_ws':'sm_WS.UTF-8',\n'so_dj':'so_DJ.ISO8859-1',\n'so_et':'so_ET.UTF-8',\n'so_ke':'so_KE.ISO8859-1',\n'so_so':'so_SO.ISO8859-1',\n'sp':'sr_CS.ISO8859-5',\n'sp_yu':'sr_CS.ISO8859-5',\n'spanish':'es_ES.ISO8859-1',\n'spanish_spain':'es_ES.ISO8859-1',\n'sq':'sq_AL.ISO8859-2',\n'sq_al':'sq_AL.ISO8859-2',\n'sq_mk':'sq_MK.UTF-8',\n'sr':'sr_RS.UTF-8',\n'sr@cyrillic':'sr_RS.UTF-8',\n'sr@latn':'sr_CS.UTF-8@latin',\n'sr_cs':'sr_CS.UTF-8',\n'sr_cs.iso88592@latn':'sr_CS.ISO8859-2',\n'sr_cs@latn':'sr_CS.UTF-8@latin',\n'sr_me':'sr_ME.UTF-8',\n'sr_rs':'sr_RS.UTF-8',\n'sr_rs@latn':'sr_RS.UTF-8@latin',\n'sr_sp':'sr_CS.ISO8859-2',\n'sr_yu':'sr_RS.UTF-8@latin',\n'sr_yu.cp1251@cyrillic':'sr_CS.CP1251',\n'sr_yu.iso88592':'sr_CS.ISO8859-2',\n'sr_yu.iso88595':'sr_CS.ISO8859-5',\n'sr_yu.iso88595@cyrillic':'sr_CS.ISO8859-5',\n'sr_yu.microsoftcp1251@cyrillic':'sr_CS.CP1251',\n'sr_yu.utf8':'sr_RS.UTF-8',\n'sr_yu.utf8@cyrillic':'sr_RS.UTF-8',\n'sr_yu@cyrillic':'sr_RS.UTF-8',\n'ss':'ss_ZA.ISO8859-1',\n'ss_za':'ss_ZA.ISO8859-1',\n'st':'st_ZA.ISO8859-1',\n'st_za':'st_ZA.ISO8859-1',\n'sv':'sv_SE.ISO8859-1',\n'sv_fi':'sv_FI.ISO8859-1',\n'sv_se':'sv_SE.ISO8859-1',\n'sw_ke':'sw_KE.UTF-8',\n'sw_tz':'sw_TZ.UTF-8',\n'swedish':'sv_SE.ISO8859-1',\n'szl_pl':'szl_PL.UTF-8',\n'ta':'ta_IN.TSCII-0',\n'ta_in':'ta_IN.TSCII-0',\n'ta_in.tscii':'ta_IN.TSCII-0',\n'ta_in.tscii0':'ta_IN.TSCII-0',\n'ta_lk':'ta_LK.UTF-8',\n'tcy_in.utf8':'tcy_IN.UTF-8',\n'te':'te_IN.UTF-8',\n'te_in':'te_IN.UTF-8',\n'tg':'tg_TJ.KOI8-C',\n'tg_tj':'tg_TJ.KOI8-C',\n'th':'th_TH.ISO8859-11',\n'th_th':'th_TH.ISO8859-11',\n'th_th.tactis':'th_TH.TIS620',\n'th_th.tis620':'th_TH.TIS620',\n'thai':'th_TH.ISO8859-11',\n'the_np':'the_NP.UTF-8',\n'ti_er':'ti_ER.UTF-8',\n'ti_et':'ti_ET.UTF-8',\n'tig_er':'tig_ER.UTF-8',\n'tk_tm':'tk_TM.UTF-8',\n'tl':'tl_PH.ISO8859-1',\n'tl_ph':'tl_PH.ISO8859-1',\n'tn':'tn_ZA.ISO8859-15',\n'tn_za':'tn_ZA.ISO8859-15',\n'to_to':'to_TO.UTF-8',\n'tpi_pg':'tpi_PG.UTF-8',\n'tr':'tr_TR.ISO8859-9',\n'tr_cy':'tr_CY.ISO8859-9',\n'tr_tr':'tr_TR.ISO8859-9',\n'ts':'ts_ZA.ISO8859-1',\n'ts_za':'ts_ZA.ISO8859-1',\n'tt':'tt_RU.TATAR-CYR',\n'tt_ru':'tt_RU.TATAR-CYR',\n'tt_ru.tatarcyr':'tt_RU.TATAR-CYR',\n'tt_ru@iqtelif':'tt_RU.UTF-8@iqtelif',\n'turkish':'tr_TR.ISO8859-9',\n'ug_cn':'ug_CN.UTF-8',\n'uk':'uk_UA.KOI8-U',\n'uk_ua':'uk_UA.KOI8-U',\n'univ':'en_US.utf',\n'universal':'en_US.utf',\n'universal.utf8@ucs4':'en_US.UTF-8',\n'unm_us':'unm_US.UTF-8',\n'ur':'ur_PK.CP1256',\n'ur_in':'ur_IN.UTF-8',\n'ur_pk':'ur_PK.CP1256',\n'uz':'uz_UZ.UTF-8',\n'uz_uz':'uz_UZ.UTF-8',\n'uz_uz@cyrillic':'uz_UZ.UTF-8',\n've':'ve_ZA.UTF-8',\n've_za':'ve_ZA.UTF-8',\n'vi':'vi_VN.TCVN',\n'vi_vn':'vi_VN.TCVN',\n'vi_vn.tcvn':'vi_VN.TCVN',\n'vi_vn.tcvn5712':'vi_VN.TCVN',\n'vi_vn.viscii':'vi_VN.VISCII',\n'vi_vn.viscii111':'vi_VN.VISCII',\n'wa':'wa_BE.ISO8859-1',\n'wa_be':'wa_BE.ISO8859-1',\n'wae_ch':'wae_CH.UTF-8',\n'wal_et':'wal_ET.UTF-8',\n'wo_sn':'wo_SN.UTF-8',\n'xh':'xh_ZA.ISO8859-1',\n'xh_za':'xh_ZA.ISO8859-1',\n'yi':'yi_US.CP1255',\n'yi_us':'yi_US.CP1255',\n'yo_ng':'yo_NG.UTF-8',\n'yue_hk':'yue_HK.UTF-8',\n'yuw_pg':'yuw_PG.UTF-8',\n'zh':'zh_CN.eucCN',\n'zh_cn':'zh_CN.gb2312',\n'zh_cn.big5':'zh_TW.big5',\n'zh_cn.euc':'zh_CN.eucCN',\n'zh_hk':'zh_HK.big5hkscs',\n'zh_hk.big5hk':'zh_HK.big5hkscs',\n'zh_sg':'zh_SG.GB2312',\n'zh_sg.gbk':'zh_SG.GBK',\n'zh_tw':'zh_TW.big5',\n'zh_tw.euc':'zh_TW.eucTW',\n'zh_tw.euctw':'zh_TW.eucTW',\n'zu':'zu_ZA.ISO8859-1',\n'zu_za':'zu_ZA.ISO8859-1',\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nwindows_locale={\n0x0436:\"af_ZA\",\n0x041c:\"sq_AL\",\n0x0484:\"gsw_FR\",\n0x045e:\"am_ET\",\n0x0401:\"ar_SA\",\n0x0801:\"ar_IQ\",\n0x0c01:\"ar_EG\",\n0x1001:\"ar_LY\",\n0x1401:\"ar_DZ\",\n0x1801:\"ar_MA\",\n0x1c01:\"ar_TN\",\n0x2001:\"ar_OM\",\n0x2401:\"ar_YE\",\n0x2801:\"ar_SY\",\n0x2c01:\"ar_JO\",\n0x3001:\"ar_LB\",\n0x3401:\"ar_KW\",\n0x3801:\"ar_AE\",\n0x3c01:\"ar_BH\",\n0x4001:\"ar_QA\",\n0x042b:\"hy_AM\",\n0x044d:\"as_IN\",\n0x042c:\"az_AZ\",\n0x082c:\"az_AZ\",\n0x046d:\"ba_RU\",\n0x042d:\"eu_ES\",\n0x0423:\"be_BY\",\n0x0445:\"bn_IN\",\n0x201a:\"bs_BA\",\n0x141a:\"bs_BA\",\n0x047e:\"br_FR\",\n0x0402:\"bg_BG\",\n\n0x0403:\"ca_ES\",\n0x0004:\"zh_CHS\",\n0x0404:\"zh_TW\",\n0x0804:\"zh_CN\",\n0x0c04:\"zh_HK\",\n0x1004:\"zh_SG\",\n0x1404:\"zh_MO\",\n0x7c04:\"zh_CHT\",\n0x0483:\"co_FR\",\n0x041a:\"hr_HR\",\n0x101a:\"hr_BA\",\n0x0405:\"cs_CZ\",\n0x0406:\"da_DK\",\n0x048c:\"gbz_AF\",\n0x0465:\"div_MV\",\n0x0413:\"nl_NL\",\n0x0813:\"nl_BE\",\n0x0409:\"en_US\",\n0x0809:\"en_GB\",\n0x0c09:\"en_AU\",\n0x1009:\"en_CA\",\n0x1409:\"en_NZ\",\n0x1809:\"en_IE\",\n0x1c09:\"en_ZA\",\n0x2009:\"en_JA\",\n0x2409:\"en_CB\",\n0x2809:\"en_BZ\",\n0x2c09:\"en_TT\",\n0x3009:\"en_ZW\",\n0x3409:\"en_PH\",\n0x4009:\"en_IN\",\n0x4409:\"en_MY\",\n0x4809:\"en_IN\",\n0x0425:\"et_EE\",\n0x0438:\"fo_FO\",\n0x0464:\"fil_PH\",\n0x040b:\"fi_FI\",\n0x040c:\"fr_FR\",\n0x080c:\"fr_BE\",\n0x0c0c:\"fr_CA\",\n0x100c:\"fr_CH\",\n0x140c:\"fr_LU\",\n0x180c:\"fr_MC\",\n0x0462:\"fy_NL\",\n0x0456:\"gl_ES\",\n0x0437:\"ka_GE\",\n0x0407:\"de_DE\",\n0x0807:\"de_CH\",\n0x0c07:\"de_AT\",\n0x1007:\"de_LU\",\n0x1407:\"de_LI\",\n0x0408:\"el_GR\",\n0x046f:\"kl_GL\",\n0x0447:\"gu_IN\",\n0x0468:\"ha_NG\",\n0x040d:\"he_IL\",\n0x0439:\"hi_IN\",\n0x040e:\"hu_HU\",\n0x040f:\"is_IS\",\n0x0421:\"id_ID\",\n0x045d:\"iu_CA\",\n0x085d:\"iu_CA\",\n0x083c:\"ga_IE\",\n0x0410:\"it_IT\",\n0x0810:\"it_CH\",\n0x0411:\"ja_JP\",\n0x044b:\"kn_IN\",\n0x043f:\"kk_KZ\",\n0x0453:\"kh_KH\",\n0x0486:\"qut_GT\",\n0x0487:\"rw_RW\",\n0x0457:\"kok_IN\",\n0x0412:\"ko_KR\",\n0x0440:\"ky_KG\",\n0x0454:\"lo_LA\",\n0x0426:\"lv_LV\",\n0x0427:\"lt_LT\",\n0x082e:\"dsb_DE\",\n0x046e:\"lb_LU\",\n0x042f:\"mk_MK\",\n0x043e:\"ms_MY\",\n0x083e:\"ms_BN\",\n0x044c:\"ml_IN\",\n0x043a:\"mt_MT\",\n0x0481:\"mi_NZ\",\n0x047a:\"arn_CL\",\n0x044e:\"mr_IN\",\n0x047c:\"moh_CA\",\n0x0450:\"mn_MN\",\n0x0850:\"mn_CN\",\n0x0461:\"ne_NP\",\n0x0414:\"nb_NO\",\n0x0814:\"nn_NO\",\n0x0482:\"oc_FR\",\n0x0448:\"or_IN\",\n0x0463:\"ps_AF\",\n0x0429:\"fa_IR\",\n0x0415:\"pl_PL\",\n0x0416:\"pt_BR\",\n0x0816:\"pt_PT\",\n0x0446:\"pa_IN\",\n0x046b:\"quz_BO\",\n0x086b:\"quz_EC\",\n0x0c6b:\"quz_PE\",\n0x0418:\"ro_RO\",\n0x0417:\"rm_CH\",\n0x0419:\"ru_RU\",\n0x243b:\"smn_FI\",\n0x103b:\"smj_NO\",\n0x143b:\"smj_SE\",\n0x043b:\"se_NO\",\n0x083b:\"se_SE\",\n0x0c3b:\"se_FI\",\n0x203b:\"sms_FI\",\n0x183b:\"sma_NO\",\n0x1c3b:\"sma_SE\",\n0x044f:\"sa_IN\",\n0x0c1a:\"sr_SP\",\n0x1c1a:\"sr_BA\",\n0x081a:\"sr_SP\",\n0x181a:\"sr_BA\",\n0x045b:\"si_LK\",\n0x046c:\"ns_ZA\",\n0x0432:\"tn_ZA\",\n0x041b:\"sk_SK\",\n0x0424:\"sl_SI\",\n0x040a:\"es_ES\",\n0x080a:\"es_MX\",\n0x0c0a:\"es_ES\",\n0x100a:\"es_GT\",\n0x140a:\"es_CR\",\n0x180a:\"es_PA\",\n0x1c0a:\"es_DO\",\n0x200a:\"es_VE\",\n0x240a:\"es_CO\",\n0x280a:\"es_PE\",\n0x2c0a:\"es_AR\",\n0x300a:\"es_EC\",\n0x340a:\"es_CL\",\n0x380a:\"es_UR\",\n0x3c0a:\"es_PY\",\n0x400a:\"es_BO\",\n0x440a:\"es_SV\",\n0x480a:\"es_HN\",\n0x4c0a:\"es_NI\",\n0x500a:\"es_PR\",\n0x540a:\"es_US\",\n\n0x0441:\"sw_KE\",\n0x041d:\"sv_SE\",\n0x081d:\"sv_FI\",\n0x045a:\"syr_SY\",\n0x0428:\"tg_TJ\",\n0x085f:\"tmz_DZ\",\n0x0449:\"ta_IN\",\n0x0444:\"tt_RU\",\n0x044a:\"te_IN\",\n0x041e:\"th_TH\",\n0x0851:\"bo_BT\",\n0x0451:\"bo_CN\",\n0x041f:\"tr_TR\",\n0x0442:\"tk_TM\",\n0x0480:\"ug_CN\",\n0x0422:\"uk_UA\",\n0x042e:\"wen_DE\",\n0x0420:\"ur_PK\",\n0x0820:\"ur_IN\",\n0x0443:\"uz_UZ\",\n0x0843:\"uz_UZ\",\n0x042a:\"vi_VN\",\n0x0452:\"cy_GB\",\n0x0488:\"wo_SN\",\n0x0434:\"xh_ZA\",\n0x0485:\"sah_RU\",\n0x0478:\"ii_CN\",\n0x046a:\"yo_NG\",\n0x0435:\"zu_ZA\",\n}\n\ndef _print_locale():\n\n ''\n \n categories={}\n def _init_categories(categories=categories):\n for k,v in globals().items():\n if k[:3]=='LC_':\n categories[k]=v\n _init_categories()\n del categories['LC_ALL']\n \n print('Locale defaults as determined by getdefaultlocale():')\n print('-'*72)\n lang,enc=getdefaultlocale()\n print('Language: ',lang or '(undefined)')\n print('Encoding: ',enc or '(undefined)')\n print()\n \n print('Locale settings on startup:')\n print('-'*72)\n for name,category in categories.items():\n print(name,'...')\n lang,enc=getlocale(category)\n print(' Language: ',lang or '(undefined)')\n print(' Encoding: ',enc or '(undefined)')\n print()\n \n try:\n setlocale(LC_ALL,\"\")\n except:\n print('NOTE:')\n print('setlocale(LC_ALL, \"\") does not support the default locale')\n print('given in the OS environment variables.')\n else:\n print()\n print('Locale settings after calling setlocale(LC_ALL, \"\"):')\n print('-'*72)\n for name,category in categories.items():\n print(name,'...')\n lang,enc=getlocale(category)\n print(' Language: ',lang or '(undefined)')\n print(' Encoding: ',enc or '(undefined)')\n print()\n \n \n \ntry:\n LC_MESSAGES\nexcept NameError:\n pass\nelse:\n __all__.append(\"LC_MESSAGES\")\n \nif __name__ =='__main__':\n print('Locale aliasing:')\n print()\n _print_locale()\n print()\n print('Number formatting:')\n print()\n _test()\n", ["_collections_abc", "_locale", "builtins", "encodings", "encodings.aliases", "functools", "os", "re", "sys", "warnings"]], "mimetypes": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport os\nimport sys\nimport posixpath\nimport urllib.parse\n\ntry:\n from _winapi import _mimetypes_read_windows_registry\nexcept ImportError:\n _mimetypes_read_windows_registry=None\n \ntry:\n import winreg as _winreg\nexcept ImportError:\n _winreg=None\n \n__all__=[\n\"knownfiles\",\"inited\",\"MimeTypes\",\n\"guess_type\",\"guess_file_type\",\"guess_all_extensions\",\"guess_extension\",\n\"add_type\",\"init\",\"read_mime_types\",\n\"suffix_map\",\"encodings_map\",\"types_map\",\"common_types\"\n]\n\nknownfiles=[\n\"/etc/mime.types\",\n\"/etc/httpd/mime.types\",\n\"/etc/httpd/conf/mime.types\",\n\"/etc/apache/mime.types\",\n\"/etc/apache2/mime.types\",\n\"/usr/local/etc/httpd/conf/mime.types\",\n\"/usr/local/lib/netscape/mime.types\",\n\"/usr/local/etc/httpd/conf/mime.types\",\n\"/usr/local/etc/mime.types\",\n]\n\ninited=False\n_db=None\n\n\nclass MimeTypes:\n ''\n\n\n\n\n \n \n def __init__(self,filenames=(),strict=True):\n if not inited:\n init()\n self.encodings_map=_encodings_map_default.copy()\n self.suffix_map=_suffix_map_default.copy()\n self.types_map=({},{})\n self.types_map_inv=({},{})\n for(ext,type)in _types_map_default.items():\n self.add_type(type,ext,True)\n for(ext,type)in _common_types_default.items():\n self.add_type(type,ext,False)\n for name in filenames:\n self.read(name,strict)\n \n def add_type(self,type,ext,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n \n self.types_map[strict][ext]=type\n exts=self.types_map_inv[strict].setdefault(type,[])\n if ext not in exts:\n exts.append(ext)\n \n def guess_type(self,url,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n url=os.fspath(url)\n p=urllib.parse.urlparse(url)\n if p.scheme and len(p.scheme)>1:\n scheme=p.scheme\n url=p.path\n else:\n return self.guess_file_type(url,strict=strict)\n if scheme =='data':\n \n \n \n \n \n \n comma=url.find(',')\n if comma <0:\n \n return None,None\n semi=url.find(';',0,comma)\n if semi >=0:\n type=url[:semi]\n else:\n type=url[:comma]\n if '='in type or '/'not in type:\n type='text/plain'\n return type,None\n return self._guess_file_type(url,strict,posixpath.splitext)\n \n def guess_file_type(self,path,*,strict=True):\n ''\n\n\n \n path=os.fsdecode(path)\n path=os.path.splitdrive(path)[1]\n return self._guess_file_type(path,strict,os.path.splitext)\n \n def _guess_file_type(self,path,strict,splitext):\n base,ext=splitext(path)\n while(ext_lower :=ext.lower())in self.suffix_map:\n base,ext=splitext(base+self.suffix_map[ext_lower])\n \n if ext in self.encodings_map:\n encoding=self.encodings_map[ext]\n base,ext=splitext(base)\n else:\n encoding=None\n ext=ext.lower()\n types_map=self.types_map[True]\n if ext in types_map:\n return types_map[ext],encoding\n elif strict:\n return None,encoding\n types_map=self.types_map[False]\n if ext in types_map:\n return types_map[ext],encoding\n else:\n return None,encoding\n \n def guess_all_extensions(self,type,strict=True):\n ''\n\n\n\n\n\n\n\n\n \n type=type.lower()\n extensions=list(self.types_map_inv[True].get(type,[]))\n if not strict:\n for ext in self.types_map_inv[False].get(type,[]):\n if ext not in extensions:\n extensions.append(ext)\n return extensions\n \n def guess_extension(self,type,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n \n extensions=self.guess_all_extensions(type,strict)\n if not extensions:\n return None\n return extensions[0]\n \n def read(self,filename,strict=True):\n ''\n\n\n\n\n\n \n with open(filename,encoding='utf-8')as fp:\n self.readfp(fp,strict)\n \n def readfp(self,fp,strict=True):\n ''\n\n\n\n\n\n \n while line :=fp.readline():\n words=line.split()\n for i in range(len(words)):\n if words[i][0]=='#':\n del words[i:]\n break\n if not words:\n continue\n type,suffixes=words[0],words[1:]\n for suff in suffixes:\n self.add_type(type,'.'+suff,strict)\n \n def read_windows_registry(self,strict=True):\n ''\n\n\n\n\n\n \n \n if not _mimetypes_read_windows_registry and not _winreg:\n return\n \n add_type=self.add_type\n if strict:\n add_type=lambda type,ext:self.add_type(type,ext,True)\n \n \n if _mimetypes_read_windows_registry:\n _mimetypes_read_windows_registry(add_type)\n elif _winreg:\n self._read_windows_registry(add_type)\n \n @classmethod\n def _read_windows_registry(cls,add_type):\n def enum_types(mimedb):\n i=0\n while True:\n try:\n ctype=_winreg.EnumKey(mimedb,i)\n except OSError:\n break\n else:\n if '\\0'not in ctype:\n yield ctype\n i +=1\n \n with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,'')as hkcr:\n for subkeyname in enum_types(hkcr):\n try:\n with _winreg.OpenKey(hkcr,subkeyname)as subkey:\n \n if not subkeyname.startswith(\".\"):\n continue\n \n mimetype,datatype=_winreg.QueryValueEx(\n subkey,'Content Type')\n if datatype !=_winreg.REG_SZ:\n continue\n add_type(mimetype,subkeyname)\n except OSError:\n continue\n \ndef guess_type(url,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if _db is None:\n init()\n return _db.guess_type(url,strict)\n \n \ndef guess_file_type(path,*,strict=True):\n ''\n\n\n \n if _db is None:\n init()\n return _db.guess_file_type(path,strict=strict)\n \n \ndef guess_all_extensions(type,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if _db is None:\n init()\n return _db.guess_all_extensions(type,strict)\n \ndef guess_extension(type,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n \n if _db is None:\n init()\n return _db.guess_extension(type,strict)\n \ndef add_type(type,ext,strict=True):\n ''\n\n\n\n\n\n\n\n\n\n \n if _db is None:\n init()\n return _db.add_type(type,ext,strict)\n \n \ndef init(files=None):\n global suffix_map,types_map,encodings_map,common_types\n global inited,_db\n inited=True\n \n if files is None or _db is None:\n db=MimeTypes()\n \n db.read_windows_registry()\n \n if files is None:\n files=knownfiles\n else:\n files=knownfiles+list(files)\n else:\n db=_db\n \n for file in files:\n if os.path.isfile(file):\n db.read(file)\n encodings_map=db.encodings_map\n suffix_map=db.suffix_map\n types_map=db.types_map[True]\n common_types=db.types_map[False]\n \n _db=db\n \n \ndef read_mime_types(file):\n try:\n f=open(file,encoding='utf-8')\n except OSError:\n return None\n with f:\n db=MimeTypes()\n db.readfp(f,True)\n return db.types_map[True]\n \n \ndef _default_mime_types():\n global suffix_map,_suffix_map_default\n global encodings_map,_encodings_map_default\n global types_map,_types_map_default\n global common_types,_common_types_default\n \n suffix_map=_suffix_map_default={\n '.svgz':'.svg.gz',\n '.tgz':'.tar.gz',\n '.taz':'.tar.gz',\n '.tz':'.tar.gz',\n '.tbz2':'.tar.bz2',\n '.txz':'.tar.xz',\n }\n \n encodings_map=_encodings_map_default={\n '.gz':'gzip',\n '.Z':'compress',\n '.bz2':'bzip2',\n '.xz':'xz',\n '.br':'br',\n }\n \n \n \n \n \n \n \n \n types_map=_types_map_default={\n '.js':'text/javascript',\n '.mjs':'text/javascript',\n '.json':'application/json',\n '.webmanifest':'application/manifest+json',\n '.doc':'application/msword',\n '.dot':'application/msword',\n '.wiz':'application/msword',\n '.nq':'application/n-quads',\n '.nt':'application/n-triples',\n '.bin':'application/octet-stream',\n '.a':'application/octet-stream',\n '.dll':'application/octet-stream',\n '.exe':'application/octet-stream',\n '.o':'application/octet-stream',\n '.obj':'application/octet-stream',\n '.so':'application/octet-stream',\n '.oda':'application/oda',\n '.pdf':'application/pdf',\n '.p7c':'application/pkcs7-mime',\n '.ps':'application/postscript',\n '.ai':'application/postscript',\n '.eps':'application/postscript',\n '.trig':'application/trig',\n '.m3u':'application/vnd.apple.mpegurl',\n '.m3u8':'application/vnd.apple.mpegurl',\n '.xls':'application/vnd.ms-excel',\n '.xlb':'application/vnd.ms-excel',\n '.ppt':'application/vnd.ms-powerpoint',\n '.pot':'application/vnd.ms-powerpoint',\n '.ppa':'application/vnd.ms-powerpoint',\n '.pps':'application/vnd.ms-powerpoint',\n '.pwz':'application/vnd.ms-powerpoint',\n '.wasm':'application/wasm',\n '.bcpio':'application/x-bcpio',\n '.cpio':'application/x-cpio',\n '.csh':'application/x-csh',\n '.dvi':'application/x-dvi',\n '.gtar':'application/x-gtar',\n '.hdf':'application/x-hdf',\n '.h5':'application/x-hdf5',\n '.latex':'application/x-latex',\n '.mif':'application/x-mif',\n '.cdf':'application/x-netcdf',\n '.nc':'application/x-netcdf',\n '.p12':'application/x-pkcs12',\n '.pfx':'application/x-pkcs12',\n '.ram':'application/x-pn-realaudio',\n '.pyc':'application/x-python-code',\n '.pyo':'application/x-python-code',\n '.sh':'application/x-sh',\n '.shar':'application/x-shar',\n '.swf':'application/x-shockwave-flash',\n '.sv4cpio':'application/x-sv4cpio',\n '.sv4crc':'application/x-sv4crc',\n '.tar':'application/x-tar',\n '.tcl':'application/x-tcl',\n '.tex':'application/x-tex',\n '.texi':'application/x-texinfo',\n '.texinfo':'application/x-texinfo',\n '.roff':'application/x-troff',\n '.t':'application/x-troff',\n '.tr':'application/x-troff',\n '.man':'application/x-troff-man',\n '.me':'application/x-troff-me',\n '.ms':'application/x-troff-ms',\n '.ustar':'application/x-ustar',\n '.src':'application/x-wais-source',\n '.xsl':'application/xml',\n '.rdf':'application/xml',\n '.wsdl':'application/xml',\n '.xpdl':'application/xml',\n '.zip':'application/zip',\n '.3gp':'audio/3gpp',\n '.3gpp':'audio/3gpp',\n '.3g2':'audio/3gpp2',\n '.3gpp2':'audio/3gpp2',\n '.aac':'audio/aac',\n '.adts':'audio/aac',\n '.loas':'audio/aac',\n '.ass':'audio/aac',\n '.au':'audio/basic',\n '.snd':'audio/basic',\n '.mp3':'audio/mpeg',\n '.mp2':'audio/mpeg',\n '.opus':'audio/opus',\n '.aif':'audio/x-aiff',\n '.aifc':'audio/x-aiff',\n '.aiff':'audio/x-aiff',\n '.ra':'audio/x-pn-realaudio',\n '.wav':'audio/x-wav',\n '.avif':'image/avif',\n '.bmp':'image/bmp',\n '.gif':'image/gif',\n '.ief':'image/ief',\n '.jpg':'image/jpeg',\n '.jpe':'image/jpeg',\n '.jpeg':'image/jpeg',\n '.heic':'image/heic',\n '.heif':'image/heif',\n '.png':'image/png',\n '.svg':'image/svg+xml',\n '.tiff':'image/tiff',\n '.tif':'image/tiff',\n '.ico':'image/vnd.microsoft.icon',\n '.webp':'image/webp',\n '.ras':'image/x-cmu-raster',\n '.pnm':'image/x-portable-anymap',\n '.pbm':'image/x-portable-bitmap',\n '.pgm':'image/x-portable-graymap',\n '.ppm':'image/x-portable-pixmap',\n '.rgb':'image/x-rgb',\n '.xbm':'image/x-xbitmap',\n '.xpm':'image/x-xpixmap',\n '.xwd':'image/x-xwindowdump',\n '.eml':'message/rfc822',\n '.mht':'message/rfc822',\n '.mhtml':'message/rfc822',\n '.nws':'message/rfc822',\n '.css':'text/css',\n '.csv':'text/csv',\n '.html':'text/html',\n '.htm':'text/html',\n '.md':'text/markdown',\n '.markdown':'text/markdown',\n '.n3':'text/n3',\n '.txt':'text/plain',\n '.bat':'text/plain',\n '.c':'text/plain',\n '.h':'text/plain',\n '.ksh':'text/plain',\n '.pl':'text/plain',\n '.srt':'text/plain',\n '.rtx':'text/richtext',\n '.rtf':'text/rtf',\n '.tsv':'text/tab-separated-values',\n '.vtt':'text/vtt',\n '.py':'text/x-python',\n '.rst':'text/x-rst',\n '.etx':'text/x-setext',\n '.sgm':'text/x-sgml',\n '.sgml':'text/x-sgml',\n '.vcf':'text/x-vcard',\n '.xml':'text/xml',\n '.mp4':'video/mp4',\n '.mpeg':'video/mpeg',\n '.m1v':'video/mpeg',\n '.mpa':'video/mpeg',\n '.mpe':'video/mpeg',\n '.mpg':'video/mpeg',\n '.mov':'video/quicktime',\n '.qt':'video/quicktime',\n '.webm':'video/webm',\n '.avi':'video/x-msvideo',\n '.movie':'video/x-sgi-movie',\n }\n \n \n \n \n \n common_types=_common_types_default={\n '.rtf':'application/rtf',\n '.midi':'audio/midi',\n '.mid':'audio/midi',\n '.jpg':'image/jpg',\n '.pict':'image/pict',\n '.pct':'image/pict',\n '.pic':'image/pict',\n '.xul':'text/xul',\n }\n \n \n_default_mime_types()\n\n\ndef _main():\n import getopt\n \n USAGE=\"\"\"\\\nUsage: mimetypes.py [options] type\n\nOptions:\n --help / -h -- print this message and exit\n --lenient / -l -- additionally search of some common, but non-standard\n types.\n --extension / -e -- guess extension instead of type\n\nMore than one type argument may be given.\n\"\"\"\n \n def usage(code,msg=''):\n print(USAGE)\n if msg:print(msg)\n sys.exit(code)\n \n try:\n opts,args=getopt.getopt(sys.argv[1:],'hle',\n ['help','lenient','extension'])\n except getopt.error as msg:\n usage(1,msg)\n \n strict=1\n extension=0\n for opt,arg in opts:\n if opt in('-h','--help'):\n usage(0)\n elif opt in('-l','--lenient'):\n strict=0\n elif opt in('-e','--extension'):\n extension=1\n for gtype in args:\n if extension:\n guess=guess_extension(gtype,strict)\n if not guess:print(\"I don't know anything about type\",gtype)\n else:print(guess)\n else:\n guess,encoding=guess_type(gtype,strict)\n if not guess:print(\"I don't know anything about type\",gtype)\n else:print('type:',guess,'encoding:',encoding)\n \n \nif __name__ =='__main__':\n _main()\n", ["_winapi", "getopt", "os", "posixpath", "sys", "urllib.parse", "winreg"]], "ntpath": [".py", "\n''\n\n\n\n\n\n\n\n\ncurdir='.'\npardir='..'\nextsep='.'\nsep='\\\\'\npathsep=';'\naltsep='/'\ndefpath='.;C:\\\\bin'\ndevnull='nul'\n\nimport os\nimport sys\nimport stat\nimport genericpath\nfrom genericpath import *\n\n\n__all__=[\"normcase\",\"isabs\",\"join\",\"splitdrive\",\"splitroot\",\"split\",\"splitext\",\n\"basename\",\"dirname\",\"commonprefix\",\"getsize\",\"getmtime\",\n\"getatime\",\"getctime\",\"islink\",\"exists\",\"lexists\",\"isdir\",\"isfile\",\n\"ismount\",\"expanduser\",\"expandvars\",\"normpath\",\"abspath\",\n\"curdir\",\"pardir\",\"sep\",\"pathsep\",\"defpath\",\"altsep\",\n\"extsep\",\"devnull\",\"realpath\",\"supports_unicode_filenames\",\"relpath\",\n\"samefile\",\"sameopenfile\",\"samestat\",\"commonpath\",\"isjunction\"]\n\ndef _get_bothseps(path):\n if isinstance(path,bytes):\n return b'\\\\/'\n else:\n return '\\\\/'\n \n \n \n \n \ntry:\n from _winapi import(\n LCMapStringEx as _LCMapStringEx,\n LOCALE_NAME_INVARIANT as _LOCALE_NAME_INVARIANT,\n LCMAP_LOWERCASE as _LCMAP_LOWERCASE)\n \n def normcase(s):\n ''\n\n\n \n s=os.fspath(s)\n if not s:\n return s\n if isinstance(s,bytes):\n encoding=sys.getfilesystemencoding()\n s=s.decode(encoding,'surrogateescape').replace('/','\\\\')\n s=_LCMapStringEx(_LOCALE_NAME_INVARIANT,\n _LCMAP_LOWERCASE,s)\n return s.encode(encoding,'surrogateescape')\n else:\n return _LCMapStringEx(_LOCALE_NAME_INVARIANT,\n _LCMAP_LOWERCASE,\n s.replace('/','\\\\'))\nexcept ImportError:\n def normcase(s):\n ''\n\n\n \n s=os.fspath(s)\n if isinstance(s,bytes):\n return os.fsencode(os.fsdecode(s).replace('/','\\\\').lower())\n return s.replace('/','\\\\').lower()\n \n \n \n \n \n \n \n \ndef isabs(s):\n ''\n s=os.fspath(s)\n if isinstance(s,bytes):\n sep=b'\\\\'\n altsep=b'/'\n colon_sep=b':\\\\'\n else:\n sep='\\\\'\n altsep='/'\n colon_sep=':\\\\'\n s=s[:3].replace(altsep,sep)\n \n \n if s.startswith(sep)or s.startswith(colon_sep,1):\n return True\n return False\n \n \n \ndef join(path,*paths):\n path=os.fspath(path)\n if isinstance(path,bytes):\n sep=b'\\\\'\n seps=b'\\\\/'\n colon=b':'\n else:\n sep='\\\\'\n seps='\\\\/'\n colon=':'\n try:\n if not paths:\n path[:0]+sep\n result_drive,result_root,result_path=splitroot(path)\n for p in map(os.fspath,paths):\n p_drive,p_root,p_path=splitroot(p)\n if p_root:\n \n if p_drive or not result_drive:\n result_drive=p_drive\n result_root=p_root\n result_path=p_path\n continue\n elif p_drive and p_drive !=result_drive:\n if p_drive.lower()!=result_drive.lower():\n \n result_drive=p_drive\n result_root=p_root\n result_path=p_path\n continue\n \n result_drive=p_drive\n \n if result_path and result_path[-1]not in seps:\n result_path=result_path+sep\n result_path=result_path+p_path\n \n if(result_path and not result_root and\n result_drive and result_drive[-1:]not in colon+seps):\n return result_drive+sep+result_path\n return result_drive+result_root+result_path\n except(TypeError,AttributeError,BytesWarning):\n genericpath._check_arg_types('join',path,*paths)\n raise\n \n \n \n \n \ndef splitdrive(p):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n drive,root,tail=splitroot(p)\n return drive,root+tail\n \n \ndef splitroot(p):\n ''\n\n\n\n\n\n\n\n\n \n p=os.fspath(p)\n if isinstance(p,bytes):\n sep=b'\\\\'\n altsep=b'/'\n colon=b':'\n unc_prefix=b'\\\\\\\\?\\\\UNC\\\\'\n empty=b''\n else:\n sep='\\\\'\n altsep='/'\n colon=':'\n unc_prefix='\\\\\\\\?\\\\UNC\\\\'\n empty=''\n normp=p.replace(altsep,sep)\n if normp[:1]==sep:\n if normp[1:2]==sep:\n \n \n start=8 if normp[:8].upper()==unc_prefix else 2\n index=normp.find(sep,start)\n if index ==-1:\n return p,empty,empty\n index2=normp.find(sep,index+1)\n if index2 ==-1:\n return p,empty,empty\n return p[:index2],p[index2:index2+1],p[index2+1:]\n else:\n \n return empty,p[:1],p[1:]\n elif normp[1:2]==colon:\n if normp[2:3]==sep:\n \n return p[:2],p[2:3],p[3:]\n else:\n \n return p[:2],empty,p[2:]\n else:\n \n return empty,empty,p\n \n \n \n \n \n \n \ndef split(p):\n ''\n\n\n \n p=os.fspath(p)\n seps=_get_bothseps(p)\n d,r,p=splitroot(p)\n \n i=len(p)\n while i and p[i -1]not in seps:\n i -=1\n head,tail=p[:i],p[i:]\n return d+r+head.rstrip(seps),tail\n \n \n \n \n \n \n \ndef splitext(p):\n p=os.fspath(p)\n if isinstance(p,bytes):\n return genericpath._splitext(p,b'\\\\',b'/',b'.')\n else:\n return genericpath._splitext(p,'\\\\','/','.')\nsplitext.__doc__=genericpath._splitext.__doc__\n\n\n\n\ndef basename(p):\n ''\n return split(p)[1]\n \n \n \n \ndef dirname(p):\n ''\n return split(p)[0]\n \n \n \n \nif hasattr(os.stat_result,'st_reparse_tag'):\n def isjunction(path):\n ''\n try:\n st=os.lstat(path)\n except(OSError,ValueError,AttributeError):\n return False\n return bool(st.st_reparse_tag ==stat.IO_REPARSE_TAG_MOUNT_POINT)\nelse:\n def isjunction(path):\n ''\n os.fspath(path)\n return False\n \n \n \n \ndef lexists(path):\n ''\n try:\n st=os.lstat(path)\n except(OSError,ValueError):\n return False\n return True\n \n \n \n \n \n \n \n \n \n \n \ntry:\n from nt import _getvolumepathname\nexcept ImportError:\n _getvolumepathname=None\ndef ismount(path):\n ''\n \n path=os.fspath(path)\n seps=_get_bothseps(path)\n path=abspath(path)\n drive,root,rest=splitroot(path)\n if drive and drive[0]in seps:\n return not rest\n if root and not rest:\n return True\n \n if _getvolumepathname:\n x=path.rstrip(seps)\n y=_getvolumepathname(path).rstrip(seps)\n return x.casefold()==y.casefold()\n else:\n return False\n \n \n \n \n \n \n \n \n \n \n \ndef expanduser(path):\n ''\n\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n tilde=b'~'\n else:\n tilde='~'\n if not path.startswith(tilde):\n return path\n i,n=1,len(path)\n while i 0 and comps[i -1]!=pardir:\n del comps[i -1:i+1]\n i -=1\n elif i ==0 and root:\n del comps[i]\n else:\n i +=1\n else:\n i +=1\n \n if not prefix and not comps:\n comps.append(curdir)\n return prefix+sep.join(comps)\n \nelse:\n def normpath(path):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n return os.fsencode(_path_normpath(os.fsdecode(path)))or b\".\"\n return _path_normpath(path)or \".\"\n \n \ndef _abspath_fallback(path):\n ''\n\n\n\n \n \n path=os.fspath(path)\n if not isabs(path):\n if isinstance(path,bytes):\n cwd=os.getcwdb()\n else:\n cwd=os.getcwd()\n path=join(cwd,path)\n return normpath(path)\n \n \ntry:\n from nt import _getfullpathname\n \nexcept ImportError:\n abspath=_abspath_fallback\n \nelse:\n def abspath(path):\n ''\n try:\n return _getfullpathname(normpath(path))\n except(OSError,ValueError):\n return _abspath_fallback(path)\n \ntry:\n from nt import _getfinalpathname,readlink as _nt_readlink\nexcept ImportError:\n\n realpath=abspath\nelse:\n def _readlink_deep(path):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n allowed_winerror=1,2,3,5,21,32,50,67,87,4390,4392,4393\n \n seen=set()\n while normcase(path)not in seen:\n seen.add(normcase(path))\n try:\n old_path=path\n path=_nt_readlink(path)\n \n \n if not isabs(path):\n \n \n \n if not islink(old_path):\n path=old_path\n break\n path=normpath(join(dirname(old_path),path))\n except OSError as ex:\n if ex.winerror in allowed_winerror:\n break\n raise\n except ValueError:\n \n break\n return path\n \n def _getfinalpathname_nonstrict(path):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n allowed_winerror=1,2,3,5,21,32,50,53,65,67,87,123,161,1920,1921\n \n \n \n tail=path[:0]\n while path:\n try:\n path=_getfinalpathname(path)\n return join(path,tail)if tail else path\n except OSError as ex:\n if ex.winerror not in allowed_winerror:\n raise\n try:\n \n \n \n new_path=_readlink_deep(path)\n if new_path !=path:\n return join(new_path,tail)if tail else new_path\n except OSError:\n \n pass\n path,name=split(path)\n \n \n \n if path and not name:\n return path+tail\n tail=join(name,tail)if tail else name\n return tail\n \n def realpath(path,*,strict=False):\n path=normpath(path)\n if isinstance(path,bytes):\n prefix=b'\\\\\\\\?\\\\'\n unc_prefix=b'\\\\\\\\?\\\\UNC\\\\'\n new_unc_prefix=b'\\\\\\\\'\n cwd=os.getcwdb()\n \n if normcase(path)==normcase(os.fsencode(devnull)):\n return b'\\\\\\\\.\\\\NUL'\n else:\n prefix='\\\\\\\\?\\\\'\n unc_prefix='\\\\\\\\?\\\\UNC\\\\'\n new_unc_prefix='\\\\\\\\'\n cwd=os.getcwd()\n \n if normcase(path)==normcase(devnull):\n return '\\\\\\\\.\\\\NUL'\n had_prefix=path.startswith(prefix)\n if not had_prefix and not isabs(path):\n path=join(cwd,path)\n try:\n path=_getfinalpathname(path)\n initial_winerror=0\n except OSError as ex:\n if strict:\n raise\n initial_winerror=ex.winerror\n path=_getfinalpathname_nonstrict(path)\n \n \n \n if not had_prefix and path.startswith(prefix):\n \n \n if path.startswith(unc_prefix):\n spath=new_unc_prefix+path[len(unc_prefix):]\n else:\n spath=path[len(prefix):]\n \n try:\n if _getfinalpathname(spath)==path:\n path=spath\n except OSError as ex:\n \n \n if ex.winerror ==initial_winerror:\n path=spath\n return path\n \n \n \nsupports_unicode_filenames=True\n\ndef relpath(path,start=None):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n sep=b'\\\\'\n curdir=b'.'\n pardir=b'..'\n else:\n sep='\\\\'\n curdir='.'\n pardir='..'\n \n if start is None:\n start=curdir\n \n if not path:\n raise ValueError(\"no path specified\")\n \n start=os.fspath(start)\n try:\n start_abs=abspath(normpath(start))\n path_abs=abspath(normpath(path))\n start_drive,_,start_rest=splitroot(start_abs)\n path_drive,_,path_rest=splitroot(path_abs)\n if normcase(start_drive)!=normcase(path_drive):\n raise ValueError(\"path is on mount %r, start on mount %r\"%(\n path_drive,start_drive))\n \n start_list=[x for x in start_rest.split(sep)if x]\n path_list=[x for x in path_rest.split(sep)if x]\n \n i=0\n for e1,e2 in zip(start_list,path_list):\n if normcase(e1)!=normcase(e2):\n break\n i +=1\n \n rel_list=[pardir]*(len(start_list)-i)+path_list[i:]\n if not rel_list:\n return curdir\n return join(*rel_list)\n except(TypeError,ValueError,AttributeError,BytesWarning,DeprecationWarning):\n genericpath._check_arg_types('relpath',path,start)\n raise\n \n \n \n \n \n \n \n \n \n \n \n \ndef commonpath(paths):\n ''\n \n if not paths:\n raise ValueError('commonpath() arg is an empty sequence')\n \n paths=tuple(map(os.fspath,paths))\n if isinstance(paths[0],bytes):\n sep=b'\\\\'\n altsep=b'/'\n curdir=b'.'\n else:\n sep='\\\\'\n altsep='/'\n curdir='.'\n \n try:\n drivesplits=[splitroot(p.replace(altsep,sep).lower())for p in paths]\n split_paths=[p.split(sep)for d,r,p in drivesplits]\n \n if len({r for d,r,p in drivesplits})!=1:\n raise ValueError(\"Can't mix absolute and relative paths\")\n \n \n \n \n if len({d for d,r,p in drivesplits})!=1:\n raise ValueError(\"Paths don't have the same drive\")\n \n drive,root,path=splitroot(paths[0].replace(altsep,sep))\n common=path.split(sep)\n common=[c for c in common if c and c !=curdir]\n \n split_paths=[[c for c in s if c and c !=curdir]for s in split_paths]\n s1=min(split_paths)\n s2=max(split_paths)\n for i,c in enumerate(s1):\n if c !=s2[i]:\n common=common[:i]\n break\n else:\n common=common[:len(s1)]\n \n return drive+root+sep.join(common)\n except(TypeError,AttributeError):\n genericpath._check_arg_types('commonpath',*paths)\n raise\n \n \ntry:\n\n\n\n from nt import _path_isdir as isdir\n from nt import _path_isfile as isfile\n from nt import _path_islink as islink\n from nt import _path_exists as exists\nexcept ImportError:\n\n pass\n \n \ntry:\n from nt import _path_isdevdrive\nexcept ImportError:\n def isdevdrive(path):\n ''\n \n return False\nelse:\n def isdevdrive(path):\n ''\n try:\n return _path_isdevdrive(abspath(path))\n except OSError:\n return False\n", ["_winapi", "genericpath", "nt", "os", "stat", "string", "sys"]], "numbers": [".py", "\n\n\n\"\"\"Abstract Base Classes (ABCs) for numbers, according to PEP 3141.\n\nTODO: Fill out more detailed documentation on the operators.\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom abc import ABCMeta,abstractmethod\n\n__all__=[\"Number\",\"Complex\",\"Real\",\"Rational\",\"Integral\"]\n\nclass Number(metaclass=ABCMeta):\n ''\n\n\n\n \n __slots__=()\n \n \n __hash__=None\n \n \n \n \n \n \n \n \n \n \nclass Complex(Number):\n ''\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __complex__(self):\n ''\n \n def __bool__(self):\n ''\n return self !=0\n \n @property\n @abstractmethod\n def real(self):\n ''\n\n\n \n raise NotImplementedError\n \n @property\n @abstractmethod\n def imag(self):\n ''\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __add__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __radd__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __neg__(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __pos__(self):\n ''\n raise NotImplementedError\n \n def __sub__(self,other):\n ''\n return self+-other\n \n def __rsub__(self,other):\n ''\n return -self+other\n \n @abstractmethod\n def __mul__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rmul__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __truediv__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rtruediv__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __pow__(self,exponent):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rpow__(self,base):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __abs__(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def conjugate(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __eq__(self,other):\n ''\n raise NotImplementedError\n \nComplex.register(complex)\n\n\nclass Real(Complex):\n ''\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __float__(self):\n ''\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __trunc__(self):\n ''\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __floor__(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __ceil__(self):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __round__(self,ndigits=None):\n ''\n\n\n\n \n raise NotImplementedError\n \n def __divmod__(self,other):\n ''\n\n\n\n \n return(self //other,self %other)\n \n def __rdivmod__(self,other):\n ''\n\n\n\n \n return(other //self,other %self)\n \n @abstractmethod\n def __floordiv__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rfloordiv__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __mod__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rmod__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __lt__(self,other):\n ''\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __le__(self,other):\n ''\n raise NotImplementedError\n \n \n def __complex__(self):\n ''\n return complex(float(self))\n \n @property\n def real(self):\n ''\n return+self\n \n @property\n def imag(self):\n ''\n return 0\n \n def conjugate(self):\n ''\n return+self\n \nReal.register(float)\n\n\nclass Rational(Real):\n ''\n \n __slots__=()\n \n @property\n @abstractmethod\n def numerator(self):\n raise NotImplementedError\n \n @property\n @abstractmethod\n def denominator(self):\n raise NotImplementedError\n \n \n def __float__(self):\n ''\n\n\n\n\n\n \n return int(self.numerator)/int(self.denominator)\n \n \nclass Integral(Rational):\n ''\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __int__(self):\n ''\n raise NotImplementedError\n \n def __index__(self):\n ''\n return int(self)\n \n @abstractmethod\n def __pow__(self,exponent,modulus=None):\n ''\n\n\n\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def __lshift__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rlshift__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rshift__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rrshift__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __and__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rand__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __xor__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __rxor__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __or__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __ror__(self,other):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def __invert__(self):\n ''\n raise NotImplementedError\n \n \n def __float__(self):\n ''\n return float(int(self))\n \n @property\n def numerator(self):\n ''\n return+self\n \n @property\n def denominator(self):\n ''\n return 1\n \nIntegral.register(int)\n", ["abc"]], "opcode": [".py", "\n\"\"\"\nopcode module - potentially shared between dis and other modules which\noperate on bytecodes (e.g. peephole optimizers).\n\"\"\"\n\n\n__all__=[\"cmp_op\",\"stack_effect\",\"hascompare\",\"opname\",\"opmap\",\n\"HAVE_ARGUMENT\",\"EXTENDED_ARG\",\"hasarg\",\"hasconst\",\"hasname\",\n\"hasjump\",\"hasjrel\",\"hasjabs\",\"hasfree\",\"haslocal\",\"hasexc\"]\n\nimport _opcode\nfrom _opcode import stack_effect\n\nfrom _opcode_metadata import(_specializations,_specialized_opmap,opmap,\nHAVE_ARGUMENT,MIN_INSTRUMENTED_OPCODE)\nEXTENDED_ARG=opmap['EXTENDED_ARG']\n\nopname=['<%r>'%(op,)for op in range(max(opmap.values())+1)]\nfor op,i in opmap.items():\n opname[i]=op\n \ncmp_op=('<','<=','==','!=','>','>=')\n\n\nhasarg=[op for op in opmap.values()if _opcode.has_arg(op)]\nhasconst=[op for op in opmap.values()if _opcode.has_const(op)]\nhasname=[op for op in opmap.values()if _opcode.has_name(op)]\nhasjump=[op for op in opmap.values()if _opcode.has_jump(op)]\nhasjrel=hasjump\nhasjabs=[]\nhasfree=[op for op in opmap.values()if _opcode.has_free(op)]\nhaslocal=[op for op in opmap.values()if _opcode.has_local(op)]\nhasexc=[op for op in opmap.values()if _opcode.has_exc(op)]\n\n\n_intrinsic_1_descs=_opcode.get_intrinsic1_descs()\n_intrinsic_2_descs=_opcode.get_intrinsic2_descs()\n_nb_ops=_opcode.get_nb_ops()\n\nhascompare=[opmap[\"COMPARE_OP\"]]\n\n_cache_format={\n\"LOAD_GLOBAL\":{\n\"counter\":1,\n\"index\":1,\n\"module_keys_version\":1,\n\"builtin_keys_version\":1,\n},\n\"BINARY_OP\":{\n\"counter\":1,\n},\n\"UNPACK_SEQUENCE\":{\n\"counter\":1,\n},\n\"COMPARE_OP\":{\n\"counter\":1,\n},\n\"CONTAINS_OP\":{\n\"counter\":1,\n},\n\"BINARY_SUBSCR\":{\n\"counter\":1,\n},\n\"FOR_ITER\":{\n\"counter\":1,\n},\n\"LOAD_SUPER_ATTR\":{\n\"counter\":1,\n},\n\"LOAD_ATTR\":{\n\"counter\":1,\n\"version\":2,\n\"keys_version\":2,\n\"descr\":4,\n},\n\"STORE_ATTR\":{\n\"counter\":1,\n\"version\":2,\n\"index\":1,\n},\n\"CALL\":{\n\"counter\":1,\n\"func_version\":2,\n},\n\"STORE_SUBSCR\":{\n\"counter\":1,\n},\n\"SEND\":{\n\"counter\":1,\n},\n\"JUMP_BACKWARD\":{\n\"counter\":1,\n},\n\"TO_BOOL\":{\n\"counter\":1,\n\"version\":2,\n},\n\"POP_JUMP_IF_TRUE\":{\n\"counter\":1,\n},\n\"POP_JUMP_IF_FALSE\":{\n\"counter\":1,\n},\n\"POP_JUMP_IF_NONE\":{\n\"counter\":1,\n},\n\"POP_JUMP_IF_NOT_NONE\":{\n\"counter\":1,\n},\n}\n\n_inline_cache_entries={\nname:sum(value.values())for(name,value)in _cache_format.items()\n}\n", ["_opcode", "_opcode_metadata"]], "operator": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n__all__=['abs','add','and_','attrgetter','call','concat','contains','countOf',\n'delitem','eq','floordiv','ge','getitem','gt','iadd','iand',\n'iconcat','ifloordiv','ilshift','imatmul','imod','imul',\n'index','indexOf','inv','invert','ior','ipow','irshift',\n'is_','is_not','isub','itemgetter','itruediv','ixor','le',\n'length_hint','lshift','lt','matmul','methodcaller','mod',\n'mul','ne','neg','not_','or_','pos','pow','rshift',\n'setitem','sub','truediv','truth','xor']\n\nfrom builtins import abs as _abs\n\n\n\n\ndef lt(a,b):\n ''\n return a =b\n \ndef gt(a,b):\n ''\n return a >b\n \n \n \ndef not_(a):\n ''\n return not a\n \ndef truth(a):\n ''\n return True if a else False\n \ndef is_(a,b):\n ''\n return a is b\n \ndef is_not(a,b):\n ''\n return a is not b\n \n \n \ndef abs(a):\n ''\n return _abs(a)\n \ndef add(a,b):\n ''\n return a+b\n \ndef and_(a,b):\n ''\n return a&b\n \ndef floordiv(a,b):\n ''\n return a //b\n \ndef index(a):\n ''\n return a.__index__()\n \ndef inv(a):\n ''\n return ~a\ninvert=inv\n\ndef lshift(a,b):\n ''\n return a <>b\n \ndef sub(a,b):\n ''\n return a -b\n \ndef truediv(a,b):\n ''\n return a /b\n \ndef xor(a,b):\n ''\n return a ^b\n \n \n \ndef concat(a,b):\n ''\n if not hasattr(a,'__getitem__'):\n msg=\"'%s' object can't be concatenated\"%type(a).__name__\n raise TypeError(msg)\n return a+b\n \ndef contains(a,b):\n ''\n return b in a\n \ndef countOf(a,b):\n ''\n count=0\n for i in a:\n if i is b or i ==b:\n count +=1\n return count\n \ndef delitem(a,b):\n ''\n del a[b]\n \ndef getitem(a,b):\n ''\n return a[b]\n \ndef indexOf(a,b):\n ''\n for i,j in enumerate(a):\n if j is b or j ==b:\n return i\n else:\n raise ValueError('sequence.index(x): x not in sequence')\n \ndef setitem(a,b,c):\n ''\n a[b]=c\n \ndef length_hint(obj,default=0):\n ''\n\n\n\n\n\n\n \n if not isinstance(default,int):\n msg=(\"'%s' object cannot be interpreted as an integer\"%\n type(default).__name__)\n raise TypeError(msg)\n \n try:\n return len(obj)\n except TypeError:\n pass\n \n try:\n hint=type(obj).__length_hint__\n except AttributeError:\n return default\n \n try:\n val=hint(obj)\n except TypeError:\n return default\n if val is NotImplemented:\n return default\n if not isinstance(val,int):\n msg=('__length_hint__ must be integer, not %s'%\n type(val).__name__)\n raise TypeError(msg)\n if val <0:\n msg='__length_hint__() should return >= 0'\n raise ValueError(msg)\n return val\n \n \n \ndef call(obj,/,*args,**kwargs):\n ''\n return obj(*args,**kwargs)\n \n \n \nclass attrgetter:\n ''\n\n\n\n\n\n \n __slots__=('_attrs','_call')\n \n def __init__(self,attr,/,*attrs):\n if not attrs:\n if not isinstance(attr,str):\n raise TypeError('attribute name must be a string')\n self._attrs=(attr,)\n names=attr.split('.')\n def func(obj):\n for name in names:\n obj=getattr(obj,name)\n return obj\n self._call=func\n else:\n self._attrs=(attr,)+attrs\n getters=tuple(map(attrgetter,self._attrs))\n def func(obj):\n return tuple(getter(obj)for getter in getters)\n self._call=func\n \n def __call__(self,obj,/):\n return self._call(obj)\n \n def __repr__(self):\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__qualname__,\n ', '.join(map(repr,self._attrs)))\n \n def __reduce__(self):\n return self.__class__,self._attrs\n \nclass itemgetter:\n ''\n\n\n\n \n __slots__=('_items','_call')\n \n def __init__(self,item,/,*items):\n if not items:\n self._items=(item,)\n def func(obj):\n return obj[item]\n self._call=func\n else:\n self._items=items=(item,)+items\n def func(obj):\n return tuple(obj[i]for i in items)\n self._call=func\n \n def __call__(self,obj,/):\n return self._call(obj)\n \n def __repr__(self):\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__name__,\n ', '.join(map(repr,self._items)))\n \n def __reduce__(self):\n return self.__class__,self._items\n \nclass methodcaller:\n ''\n\n\n\n\n \n __slots__=('_name','_args','_kwargs')\n \n def __init__(self,name,/,*args,**kwargs):\n self._name=name\n if not isinstance(self._name,str):\n raise TypeError('method name must be a string')\n self._args=args\n self._kwargs=kwargs\n \n def __call__(self,obj,/):\n return getattr(obj,self._name)(*self._args,**self._kwargs)\n \n def __repr__(self):\n args=[repr(self._name)]\n args.extend(map(repr,self._args))\n args.extend('%s=%r'%(k,v)for k,v in self._kwargs.items())\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__name__,\n ', '.join(args))\n \n def __reduce__(self):\n if not self._kwargs:\n return self.__class__,(self._name,)+self._args\n else:\n from functools import partial\n return partial(self.__class__,self._name,**self._kwargs),self._args\n \n \n \n \ndef iadd(a,b):\n ''\n a +=b\n return a\n \ndef iand(a,b):\n ''\n a &=b\n return a\n \ndef iconcat(a,b):\n ''\n if not hasattr(a,'__getitem__'):\n msg=\"'%s' object can't be concatenated\"%type(a).__name__\n raise TypeError(msg)\n a +=b\n return a\n \ndef ifloordiv(a,b):\n ''\n a //=b\n return a\n \ndef ilshift(a,b):\n ''\n a <<=b\n return a\n \ndef imod(a,b):\n ''\n a %=b\n return a\n \ndef imul(a,b):\n ''\n a *=b\n return a\n \ndef imatmul(a,b):\n ''\n a @=b\n return a\n \ndef ior(a,b):\n ''\n a |=b\n return a\n \ndef ipow(a,b):\n ''\n a **=b\n return a\n \ndef irshift(a,b):\n ''\n a >>=b\n return a\n \ndef isub(a,b):\n ''\n a -=b\n return a\n \ndef itruediv(a,b):\n ''\n a /=b\n return a\n \ndef ixor(a,b):\n ''\n a ^=b\n return a\n \n \ntry:\n from _operator import *\nexcept ImportError:\n pass\nelse:\n from _operator import __doc__\n \n \n \n__lt__=lt\n__le__=le\n__eq__=eq\n__ne__=ne\n__ge__=ge\n__gt__=gt\n__not__=not_\n__abs__=abs\n__add__=add\n__and__=and_\n__call__=call\n__floordiv__=floordiv\n__index__=index\n__inv__=inv\n__invert__=invert\n__lshift__=lshift\n__mod__=mod\n__mul__=mul\n__matmul__=matmul\n__neg__=neg\n__or__=or_\n__pos__=pos\n__pow__=pow\n__rshift__=rshift\n__sub__=sub\n__truediv__=truediv\n__xor__=xor\n__concat__=concat\n__contains__=contains\n__delitem__=delitem\n__getitem__=getitem\n__setitem__=setitem\n__iadd__=iadd\n__iand__=iand\n__iconcat__=iconcat\n__ifloordiv__=ifloordiv\n__ilshift__=ilshift\n__imod__=imod\n__imul__=imul\n__imatmul__=imatmul\n__ior__=ior\n__ipow__=ipow\n__irshift__=irshift\n__isub__=isub\n__itruediv__=itruediv\n__ixor__=ixor\n", ["_operator", "builtins", "functools"]], "optparse": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__=\"1.5.3\"\n\n__all__=['Option',\n'make_option',\n'SUPPRESS_HELP',\n'SUPPRESS_USAGE',\n'Values',\n'OptionContainer',\n'OptionGroup',\n'OptionParser',\n'HelpFormatter',\n'IndentedHelpFormatter',\n'TitledHelpFormatter',\n'OptParseError',\n'OptionError',\n'OptionConflictError',\n'OptionValueError',\n'BadOptionError',\n'check_choice']\n\n__copyright__=\"\"\"\nCopyright (c) 2001-2006 Gregory P. Ward. All rights reserved.\nCopyright (c) 2002-2006 Python Software Foundation. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport sys,os\nimport textwrap\n\ndef _repr(self):\n return \"<%s at 0x%x: %s>\"%(self.__class__.__name__,id(self),self)\n \n \n \n \n \n \n \n \ntry:\n from gettext import gettext,ngettext\nexcept ImportError:\n def gettext(message):\n return message\n \n def ngettext(singular,plural,n):\n if n ==1:\n return singular\n return plural\n \n_=gettext\n\n\nclass OptParseError(Exception):\n def __init__(self,msg):\n self.msg=msg\n \n def __str__(self):\n return self.msg\n \n \nclass OptionError(OptParseError):\n ''\n\n\n \n \n def __init__(self,msg,option):\n self.msg=msg\n self.option_id=str(option)\n \n def __str__(self):\n if self.option_id:\n return \"option %s: %s\"%(self.option_id,self.msg)\n else:\n return self.msg\n \nclass OptionConflictError(OptionError):\n ''\n\n \n \nclass OptionValueError(OptParseError):\n ''\n\n\n \n \nclass BadOptionError(OptParseError):\n ''\n\n \n def __init__(self,opt_str):\n self.opt_str=opt_str\n \n def __str__(self):\n return _(\"no such option: %s\")%self.opt_str\n \nclass AmbiguousOptionError(BadOptionError):\n ''\n\n \n def __init__(self,opt_str,possibilities):\n BadOptionError.__init__(self,opt_str)\n self.possibilities=possibilities\n \n def __str__(self):\n return(_(\"ambiguous option: %s (%s?)\")\n %(self.opt_str,\", \".join(self.possibilities)))\n \n \nclass HelpFormatter:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n NO_DEFAULT_VALUE=\"none\"\n \n def __init__(self,\n indent_increment,\n max_help_position,\n width,\n short_first):\n self.parser=None\n self.indent_increment=indent_increment\n if width is None:\n try:\n width=int(os.environ['COLUMNS'])\n except(KeyError,ValueError):\n width=80\n width -=2\n self.width=width\n self.help_position=self.max_help_position=\\\n min(max_help_position,max(width -20,indent_increment *2))\n self.current_indent=0\n self.level=0\n self.help_width=None\n self.short_first=short_first\n self.default_tag=\"%default\"\n self.option_strings={}\n self._short_opt_fmt=\"%s %s\"\n self._long_opt_fmt=\"%s=%s\"\n \n def set_parser(self,parser):\n self.parser=parser\n \n def set_short_opt_delimiter(self,delim):\n if delim not in(\"\",\" \"):\n raise ValueError(\n \"invalid metavar delimiter for short options: %r\"%delim)\n self._short_opt_fmt=\"%s\"+delim+\"%s\"\n \n def set_long_opt_delimiter(self,delim):\n if delim not in(\"=\",\" \"):\n raise ValueError(\n \"invalid metavar delimiter for long options: %r\"%delim)\n self._long_opt_fmt=\"%s\"+delim+\"%s\"\n \n def indent(self):\n self.current_indent +=self.indent_increment\n self.level +=1\n \n def dedent(self):\n self.current_indent -=self.indent_increment\n assert self.current_indent >=0,\"Indent decreased below 0.\"\n self.level -=1\n \n def format_usage(self,usage):\n raise NotImplementedError(\"subclasses must implement\")\n \n def format_heading(self,heading):\n raise NotImplementedError(\"subclasses must implement\")\n \n def _format_text(self,text):\n ''\n\n\n \n text_width=max(self.width -self.current_indent,11)\n indent=\" \"*self.current_indent\n return textwrap.fill(text,\n text_width,\n initial_indent=indent,\n subsequent_indent=indent)\n \n def format_description(self,description):\n if description:\n return self._format_text(description)+\"\\n\"\n else:\n return \"\"\n \n def format_epilog(self,epilog):\n if epilog:\n return \"\\n\"+self._format_text(epilog)+\"\\n\"\n else:\n return \"\"\n \n \n def expand_default(self,option):\n if self.parser is None or not self.default_tag:\n return option.help\n \n default_value=self.parser.defaults.get(option.dest)\n if default_value is NO_DEFAULT or default_value is None:\n default_value=self.NO_DEFAULT_VALUE\n \n return option.help.replace(self.default_tag,str(default_value))\n \n def format_option(self,option):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n result=[]\n opts=self.option_strings[option]\n opt_width=self.help_position -self.current_indent -2\n if len(opts)>opt_width:\n opts=\"%*s%s\\n\"%(self.current_indent,\"\",opts)\n indent_first=self.help_position\n else:\n opts=\"%*s%-*s \"%(self.current_indent,\"\",opt_width,opts)\n indent_first=0\n result.append(opts)\n if option.help:\n help_text=self.expand_default(option)\n help_lines=textwrap.wrap(help_text,self.help_width)\n result.append(\"%*s%s\\n\"%(indent_first,\"\",help_lines[0]))\n result.extend([\"%*s%s\\n\"%(self.help_position,\"\",line)\n for line in help_lines[1:]])\n elif opts[-1]!=\"\\n\":\n result.append(\"\\n\")\n return \"\".join(result)\n \n def store_option_strings(self,parser):\n self.indent()\n max_len=0\n for opt in parser.option_list:\n strings=self.format_option_strings(opt)\n self.option_strings[opt]=strings\n max_len=max(max_len,len(strings)+self.current_indent)\n self.indent()\n for group in parser.option_groups:\n for opt in group.option_list:\n strings=self.format_option_strings(opt)\n self.option_strings[opt]=strings\n max_len=max(max_len,len(strings)+self.current_indent)\n self.dedent()\n self.dedent()\n self.help_position=min(max_len+2,self.max_help_position)\n self.help_width=max(self.width -self.help_position,11)\n \n def format_option_strings(self,option):\n ''\n if option.takes_value():\n metavar=option.metavar or option.dest.upper()\n short_opts=[self._short_opt_fmt %(sopt,metavar)\n for sopt in option._short_opts]\n long_opts=[self._long_opt_fmt %(lopt,metavar)\n for lopt in option._long_opts]\n else:\n short_opts=option._short_opts\n long_opts=option._long_opts\n \n if self.short_first:\n opts=short_opts+long_opts\n else:\n opts=long_opts+short_opts\n \n return \", \".join(opts)\n \nclass IndentedHelpFormatter(HelpFormatter):\n ''\n \n \n def __init__(self,\n indent_increment=2,\n max_help_position=24,\n width=None,\n short_first=1):\n HelpFormatter.__init__(\n self,indent_increment,max_help_position,width,short_first)\n \n def format_usage(self,usage):\n return _(\"Usage: %s\\n\")%usage\n \n def format_heading(self,heading):\n return \"%*s%s:\\n\"%(self.current_indent,\"\",heading)\n \n \nclass TitledHelpFormatter(HelpFormatter):\n ''\n \n \n def __init__(self,\n indent_increment=0,\n max_help_position=24,\n width=None,\n short_first=0):\n HelpFormatter.__init__(\n self,indent_increment,max_help_position,width,short_first)\n \n def format_usage(self,usage):\n return \"%s %s\\n\"%(self.format_heading(_(\"Usage\")),usage)\n \n def format_heading(self,heading):\n return \"%s\\n%s\\n\"%(heading,\"=-\"[self.level]*len(heading))\n \n \ndef _parse_num(val,type):\n if val[:2].lower()==\"0x\":\n radix=16\n elif val[:2].lower()==\"0b\":\n radix=2\n val=val[2:]or \"0\"\n elif val[:1]==\"0\":\n radix=8\n else:\n radix=10\n \n return type(val,radix)\n \ndef _parse_int(val):\n return _parse_num(val,int)\n \n_builtin_cvt={\"int\":(_parse_int,_(\"integer\")),\n\"long\":(_parse_int,_(\"integer\")),\n\"float\":(float,_(\"floating-point\")),\n\"complex\":(complex,_(\"complex\"))}\n\ndef check_builtin(option,opt,value):\n (cvt,what)=_builtin_cvt[option.type]\n try:\n return cvt(value)\n except ValueError:\n raise OptionValueError(\n _(\"option %s: invalid %s value: %r\")%(opt,what,value))\n \ndef check_choice(option,opt,value):\n if value in option.choices:\n return value\n else:\n choices=\", \".join(map(repr,option.choices))\n raise OptionValueError(\n _(\"option %s: invalid choice: %r (choose from %s)\")\n %(opt,value,choices))\n \n \n \nNO_DEFAULT=(\"NO\",\"DEFAULT\")\n\n\nclass Option:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n ATTRS=['action',\n 'type',\n 'dest',\n 'default',\n 'nargs',\n 'const',\n 'choices',\n 'callback',\n 'callback_args',\n 'callback_kwargs',\n 'help',\n 'metavar']\n \n \n \n ACTIONS=(\"store\",\n \"store_const\",\n \"store_true\",\n \"store_false\",\n \"append\",\n \"append_const\",\n \"count\",\n \"callback\",\n \"help\",\n \"version\")\n \n \n \n \n STORE_ACTIONS=(\"store\",\n \"store_const\",\n \"store_true\",\n \"store_false\",\n \"append\",\n \"append_const\",\n \"count\")\n \n \n \n TYPED_ACTIONS=(\"store\",\n \"append\",\n \"callback\")\n \n \n \n ALWAYS_TYPED_ACTIONS=(\"store\",\n \"append\")\n \n \n CONST_ACTIONS=(\"store_const\",\n \"append_const\")\n \n \n \n TYPES=(\"string\",\"int\",\"long\",\"float\",\"complex\",\"choice\")\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n TYPE_CHECKER={\"int\":check_builtin,\n \"long\":check_builtin,\n \"float\":check_builtin,\n \"complex\":check_builtin,\n \"choice\":check_choice,\n }\n \n \n \n \n \n \n \n \n \n \n CHECK_METHODS=None\n \n \n \n \n def __init__(self,*opts,**attrs):\n \n \n self._short_opts=[]\n self._long_opts=[]\n opts=self._check_opt_strings(opts)\n self._set_opt_strings(opts)\n \n \n self._set_attrs(attrs)\n \n \n \n \n \n \n for checker in self.CHECK_METHODS:\n checker(self)\n \n def _check_opt_strings(self,opts):\n \n \n \n opts=[opt for opt in opts if opt]\n if not opts:\n raise TypeError(\"at least one option string must be supplied\")\n return opts\n \n def _set_opt_strings(self,opts):\n for opt in opts:\n if len(opt)<2:\n raise OptionError(\n \"invalid option string %r: \"\n \"must be at least two characters long\"%opt,self)\n elif len(opt)==2:\n if not(opt[0]==\"-\"and opt[1]!=\"-\"):\n raise OptionError(\n \"invalid short option string %r: \"\n \"must be of the form -x, (x any non-dash char)\"%opt,\n self)\n self._short_opts.append(opt)\n else:\n if not(opt[0:2]==\"--\"and opt[2]!=\"-\"):\n raise OptionError(\n \"invalid long option string %r: \"\n \"must start with --, followed by non-dash\"%opt,\n self)\n self._long_opts.append(opt)\n \n def _set_attrs(self,attrs):\n for attr in self.ATTRS:\n if attr in attrs:\n setattr(self,attr,attrs[attr])\n del attrs[attr]\n else:\n if attr =='default':\n setattr(self,attr,NO_DEFAULT)\n else:\n setattr(self,attr,None)\n if attrs:\n attrs=sorted(attrs.keys())\n raise OptionError(\n \"invalid keyword arguments: %s\"%\", \".join(attrs),\n self)\n \n \n \n \n def _check_action(self):\n if self.action is None:\n self.action=\"store\"\n elif self.action not in self.ACTIONS:\n raise OptionError(\"invalid action: %r\"%self.action,self)\n \n def _check_type(self):\n if self.type is None:\n if self.action in self.ALWAYS_TYPED_ACTIONS:\n if self.choices is not None:\n \n self.type=\"choice\"\n else:\n \n self.type=\"string\"\n else:\n \n \n if isinstance(self.type,type):\n self.type=self.type.__name__\n \n if self.type ==\"str\":\n self.type=\"string\"\n \n if self.type not in self.TYPES:\n raise OptionError(\"invalid option type: %r\"%self.type,self)\n if self.action not in self.TYPED_ACTIONS:\n raise OptionError(\n \"must not supply a type for action %r\"%self.action,self)\n \n def _check_choice(self):\n if self.type ==\"choice\":\n if self.choices is None:\n raise OptionError(\n \"must supply a list of choices for type 'choice'\",self)\n elif not isinstance(self.choices,(tuple,list)):\n raise OptionError(\n \"choices must be a list of strings ('%s' supplied)\"\n %str(type(self.choices)).split(\"'\")[1],self)\n elif self.choices is not None:\n raise OptionError(\n \"must not supply choices for type %r\"%self.type,self)\n \n def _check_dest(self):\n \n \n takes_value=(self.action in self.STORE_ACTIONS or\n self.type is not None)\n if self.dest is None and takes_value:\n \n \n \n if self._long_opts:\n \n self.dest=self._long_opts[0][2:].replace('-','_')\n else:\n self.dest=self._short_opts[0][1]\n \n def _check_const(self):\n if self.action not in self.CONST_ACTIONS and self.const is not None:\n raise OptionError(\n \"'const' must not be supplied for action %r\"%self.action,\n self)\n \n def _check_nargs(self):\n if self.action in self.TYPED_ACTIONS:\n if self.nargs is None:\n self.nargs=1\n elif self.nargs is not None:\n raise OptionError(\n \"'nargs' must not be supplied for action %r\"%self.action,\n self)\n \n def _check_callback(self):\n if self.action ==\"callback\":\n if not callable(self.callback):\n raise OptionError(\n \"callback not callable: %r\"%self.callback,self)\n if(self.callback_args is not None and\n not isinstance(self.callback_args,tuple)):\n raise OptionError(\n \"callback_args, if supplied, must be a tuple: not %r\"\n %self.callback_args,self)\n if(self.callback_kwargs is not None and\n not isinstance(self.callback_kwargs,dict)):\n raise OptionError(\n \"callback_kwargs, if supplied, must be a dict: not %r\"\n %self.callback_kwargs,self)\n else:\n if self.callback is not None:\n raise OptionError(\n \"callback supplied (%r) for non-callback option\"\n %self.callback,self)\n if self.callback_args is not None:\n raise OptionError(\n \"callback_args supplied for non-callback option\",self)\n if self.callback_kwargs is not None:\n raise OptionError(\n \"callback_kwargs supplied for non-callback option\",self)\n \n \n CHECK_METHODS=[_check_action,\n _check_type,\n _check_choice,\n _check_dest,\n _check_const,\n _check_nargs,\n _check_callback]\n \n \n \n \n def __str__(self):\n return \"/\".join(self._short_opts+self._long_opts)\n \n __repr__=_repr\n \n def takes_value(self):\n return self.type is not None\n \n def get_opt_string(self):\n if self._long_opts:\n return self._long_opts[0]\n else:\n return self._short_opts[0]\n \n \n \n \n def check_value(self,opt,value):\n checker=self.TYPE_CHECKER.get(self.type)\n if checker is None:\n return value\n else:\n return checker(self,opt,value)\n \n def convert_value(self,opt,value):\n if value is not None:\n if self.nargs ==1:\n return self.check_value(opt,value)\n else:\n return tuple([self.check_value(opt,v)for v in value])\n \n def process(self,opt,value,values,parser):\n \n \n \n value=self.convert_value(opt,value)\n \n \n \n \n return self.take_action(\n self.action,self.dest,opt,value,values,parser)\n \n def take_action(self,action,dest,opt,value,values,parser):\n if action ==\"store\":\n setattr(values,dest,value)\n elif action ==\"store_const\":\n setattr(values,dest,self.const)\n elif action ==\"store_true\":\n setattr(values,dest,True)\n elif action ==\"store_false\":\n setattr(values,dest,False)\n elif action ==\"append\":\n values.ensure_value(dest,[]).append(value)\n elif action ==\"append_const\":\n values.ensure_value(dest,[]).append(self.const)\n elif action ==\"count\":\n setattr(values,dest,values.ensure_value(dest,0)+1)\n elif action ==\"callback\":\n args=self.callback_args or()\n kwargs=self.callback_kwargs or{}\n self.callback(self,opt,value,parser,*args,**kwargs)\n elif action ==\"help\":\n parser.print_help()\n parser.exit()\n elif action ==\"version\":\n parser.print_version()\n parser.exit()\n else:\n raise ValueError(\"unknown action %r\"%self.action)\n \n return 1\n \n \n \n \nSUPPRESS_HELP=\"SUPPRESS\"+\"HELP\"\nSUPPRESS_USAGE=\"SUPPRESS\"+\"USAGE\"\n\nclass Values:\n\n def __init__(self,defaults=None):\n if defaults:\n for(attr,val)in defaults.items():\n setattr(self,attr,val)\n \n def __str__(self):\n return str(self.__dict__)\n \n __repr__=_repr\n \n def __eq__(self,other):\n if isinstance(other,Values):\n return self.__dict__ ==other.__dict__\n elif isinstance(other,dict):\n return self.__dict__ ==other\n else:\n return NotImplemented\n \n def _update_careful(self,dict):\n ''\n\n\n\n\n \n for attr in dir(self):\n if attr in dict:\n dval=dict[attr]\n if dval is not None:\n setattr(self,attr,dval)\n \n def _update_loose(self,dict):\n ''\n\n\n\n \n self.__dict__.update(dict)\n \n def _update(self,dict,mode):\n if mode ==\"careful\":\n self._update_careful(dict)\n elif mode ==\"loose\":\n self._update_loose(dict)\n else:\n raise ValueError(\"invalid update mode: %r\"%mode)\n \n def read_module(self,modname,mode=\"careful\"):\n __import__(modname)\n mod=sys.modules[modname]\n self._update(vars(mod),mode)\n \n def read_file(self,filename,mode=\"careful\"):\n vars={}\n exec(open(filename).read(),vars)\n self._update(vars,mode)\n \n def ensure_value(self,attr,value):\n if not hasattr(self,attr)or getattr(self,attr)is None:\n setattr(self,attr,value)\n return getattr(self,attr)\n \n \nclass OptionContainer:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,option_class,conflict_handler,description):\n \n \n \n \n self._create_option_list()\n \n self.option_class=option_class\n self.set_conflict_handler(conflict_handler)\n self.set_description(description)\n \n def _create_option_mappings(self):\n \n \n \n self._short_opt={}\n self._long_opt={}\n self.defaults={}\n \n \n def _share_option_mappings(self,parser):\n \n \n self._short_opt=parser._short_opt\n self._long_opt=parser._long_opt\n self.defaults=parser.defaults\n \n def set_conflict_handler(self,handler):\n if handler not in(\"error\",\"resolve\"):\n raise ValueError(\"invalid conflict_resolution value %r\"%handler)\n self.conflict_handler=handler\n \n def set_description(self,description):\n self.description=description\n \n def get_description(self):\n return self.description\n \n \n def destroy(self):\n ''\n del self._short_opt\n del self._long_opt\n del self.defaults\n \n \n \n \n def _check_conflict(self,option):\n conflict_opts=[]\n for opt in option._short_opts:\n if opt in self._short_opt:\n conflict_opts.append((opt,self._short_opt[opt]))\n for opt in option._long_opts:\n if opt in self._long_opt:\n conflict_opts.append((opt,self._long_opt[opt]))\n \n if conflict_opts:\n handler=self.conflict_handler\n if handler ==\"error\":\n raise OptionConflictError(\n \"conflicting option string(s): %s\"\n %\", \".join([co[0]for co in conflict_opts]),\n option)\n elif handler ==\"resolve\":\n for(opt,c_option)in conflict_opts:\n if opt.startswith(\"--\"):\n c_option._long_opts.remove(opt)\n del self._long_opt[opt]\n else:\n c_option._short_opts.remove(opt)\n del self._short_opt[opt]\n if not(c_option._short_opts or c_option._long_opts):\n c_option.container.option_list.remove(c_option)\n \n def add_option(self,*args,**kwargs):\n ''\n\n \n if isinstance(args[0],str):\n option=self.option_class(*args,**kwargs)\n elif len(args)==1 and not kwargs:\n option=args[0]\n if not isinstance(option,Option):\n raise TypeError(\"not an Option instance: %r\"%option)\n else:\n raise TypeError(\"invalid arguments\")\n \n self._check_conflict(option)\n \n self.option_list.append(option)\n option.container=self\n for opt in option._short_opts:\n self._short_opt[opt]=option\n for opt in option._long_opts:\n self._long_opt[opt]=option\n \n if option.dest is not None:\n if option.default is not NO_DEFAULT:\n self.defaults[option.dest]=option.default\n elif option.dest not in self.defaults:\n self.defaults[option.dest]=None\n \n return option\n \n def add_options(self,option_list):\n for option in option_list:\n self.add_option(option)\n \n \n \n def get_option(self,opt_str):\n return(self._short_opt.get(opt_str)or\n self._long_opt.get(opt_str))\n \n def has_option(self,opt_str):\n return(opt_str in self._short_opt or\n opt_str in self._long_opt)\n \n def remove_option(self,opt_str):\n option=self._short_opt.get(opt_str)\n if option is None:\n option=self._long_opt.get(opt_str)\n if option is None:\n raise ValueError(\"no such option %r\"%opt_str)\n \n for opt in option._short_opts:\n del self._short_opt[opt]\n for opt in option._long_opts:\n del self._long_opt[opt]\n option.container.option_list.remove(option)\n \n \n \n \n def format_option_help(self,formatter):\n if not self.option_list:\n return \"\"\n result=[]\n for option in self.option_list:\n if not option.help is SUPPRESS_HELP:\n result.append(formatter.format_option(option))\n return \"\".join(result)\n \n def format_description(self,formatter):\n return formatter.format_description(self.get_description())\n \n def format_help(self,formatter):\n result=[]\n if self.description:\n result.append(self.format_description(formatter))\n if self.option_list:\n result.append(self.format_option_help(formatter))\n return \"\\n\".join(result)\n \n \nclass OptionGroup(OptionContainer):\n\n def __init__(self,parser,title,description=None):\n self.parser=parser\n OptionContainer.__init__(\n self,parser.option_class,parser.conflict_handler,description)\n self.title=title\n \n def _create_option_list(self):\n self.option_list=[]\n self._share_option_mappings(self.parser)\n \n def set_title(self,title):\n self.title=title\n \n def destroy(self):\n ''\n OptionContainer.destroy(self)\n del self.option_list\n \n \n \n def format_help(self,formatter):\n result=formatter.format_heading(self.title)\n formatter.indent()\n result +=OptionContainer.format_help(self,formatter)\n formatter.dedent()\n return result\n \n \nclass OptionParser(OptionContainer):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n standard_option_list=[]\n \n def __init__(self,\n usage=None,\n option_list=None,\n option_class=Option,\n version=None,\n conflict_handler=\"error\",\n description=None,\n formatter=None,\n add_help_option=True,\n prog=None,\n epilog=None):\n OptionContainer.__init__(\n self,option_class,conflict_handler,description)\n self.set_usage(usage)\n self.prog=prog\n self.version=version\n self.allow_interspersed_args=True\n self.process_default_values=True\n if formatter is None:\n formatter=IndentedHelpFormatter()\n self.formatter=formatter\n self.formatter.set_parser(self)\n self.epilog=epilog\n \n \n \n \n \n self._populate_option_list(option_list,\n add_help=add_help_option)\n \n self._init_parsing_state()\n \n \n def destroy(self):\n ''\n\n\n\n\n \n OptionContainer.destroy(self)\n for group in self.option_groups:\n group.destroy()\n del self.option_list\n del self.option_groups\n del self.formatter\n \n \n \n \n \n def _create_option_list(self):\n self.option_list=[]\n self.option_groups=[]\n self._create_option_mappings()\n \n def _add_help_option(self):\n self.add_option(\"-h\",\"--help\",\n action=\"help\",\n help=_(\"show this help message and exit\"))\n \n def _add_version_option(self):\n self.add_option(\"--version\",\n action=\"version\",\n help=_(\"show program's version number and exit\"))\n \n def _populate_option_list(self,option_list,add_help=True):\n if self.standard_option_list:\n self.add_options(self.standard_option_list)\n if option_list:\n self.add_options(option_list)\n if self.version:\n self._add_version_option()\n if add_help:\n self._add_help_option()\n \n def _init_parsing_state(self):\n \n self.rargs=None\n self.largs=None\n self.values=None\n \n \n \n \n def set_usage(self,usage):\n if usage is None:\n self.usage=_(\"%prog [options]\")\n elif usage is SUPPRESS_USAGE:\n self.usage=None\n \n elif usage.lower().startswith(\"usage: \"):\n self.usage=usage[7:]\n else:\n self.usage=usage\n \n def enable_interspersed_args(self):\n ''\n\n\n\n \n self.allow_interspersed_args=True\n \n def disable_interspersed_args(self):\n ''\n\n\n\n \n self.allow_interspersed_args=False\n \n def set_process_default_values(self,process):\n self.process_default_values=process\n \n def set_default(self,dest,value):\n self.defaults[dest]=value\n \n def set_defaults(self,**kwargs):\n self.defaults.update(kwargs)\n \n def _get_all_options(self):\n options=self.option_list[:]\n for group in self.option_groups:\n options.extend(group.option_list)\n return options\n \n def get_default_values(self):\n if not self.process_default_values:\n \n return Values(self.defaults)\n \n defaults=self.defaults.copy()\n for option in self._get_all_options():\n default=defaults.get(option.dest)\n if isinstance(default,str):\n opt_str=option.get_opt_string()\n defaults[option.dest]=option.check_value(opt_str,default)\n \n return Values(defaults)\n \n \n \n \n def add_option_group(self,*args,**kwargs):\n \n if isinstance(args[0],str):\n group=OptionGroup(self,*args,**kwargs)\n elif len(args)==1 and not kwargs:\n group=args[0]\n if not isinstance(group,OptionGroup):\n raise TypeError(\"not an OptionGroup instance: %r\"%group)\n if group.parser is not self:\n raise ValueError(\"invalid OptionGroup (wrong parser)\")\n else:\n raise TypeError(\"invalid arguments\")\n \n self.option_groups.append(group)\n return group\n \n def get_option_group(self,opt_str):\n option=(self._short_opt.get(opt_str)or\n self._long_opt.get(opt_str))\n if option and option.container is not self:\n return option.container\n return None\n \n \n \n \n def _get_args(self,args):\n if args is None:\n return sys.argv[1:]\n else:\n return args[:]\n \n def parse_args(self,args=None,values=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n rargs=self._get_args(args)\n if values is None:\n values=self.get_default_values()\n \n \n \n \n \n \n \n \n \n \n self.rargs=rargs\n self.largs=largs=[]\n self.values=values\n \n try:\n stop=self._process_args(largs,rargs,values)\n except(BadOptionError,OptionValueError)as err:\n self.error(str(err))\n \n args=largs+rargs\n return self.check_values(values,args)\n \n def check_values(self,values,args):\n ''\n\n\n\n\n\n\n\n\n \n return(values,args)\n \n def _process_args(self,largs,rargs,values):\n ''\n\n\n\n\n\n\n\n \n while rargs:\n arg=rargs[0]\n \n \n \n if arg ==\"--\":\n del rargs[0]\n return\n elif arg[0:2]==\"--\":\n \n self._process_long_opt(rargs,values)\n elif arg[:1]==\"-\"and len(arg)>1:\n \n \n self._process_short_opts(rargs,values)\n elif self.allow_interspersed_args:\n largs.append(arg)\n del rargs[0]\n else:\n return\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def _match_long_opt(self,opt):\n ''\n\n\n\n\n \n return _match_abbrev(opt,self._long_opt)\n \n def _process_long_opt(self,rargs,values):\n arg=rargs.pop(0)\n \n \n \n if \"=\"in arg:\n (opt,next_arg)=arg.split(\"=\",1)\n rargs.insert(0,next_arg)\n had_explicit_value=True\n else:\n opt=arg\n had_explicit_value=False\n \n opt=self._match_long_opt(opt)\n option=self._long_opt[opt]\n if option.takes_value():\n nargs=option.nargs\n if len(rargs)\".format(self.path)\n return \"\"\n \n def add_dll_directory(path):\n ''\n\n\n\n\n\n\n\n \n import nt\n cookie=nt._add_dll_directory(path)\n return _AddedDllDirectory(\n path,\n cookie,\n nt._remove_dll_directory\n )\n \n \ndef scandir(*args,**kw):\n raise NotImplementedError('browsers cannot read a directory content')\n \ndef waitstatus_to_exitcode(status):\n return status >>8\n \n_set=set()\n\nsupports_dir_fd=_set\n\nsupports_effective_ids=_set\n\nsupports_fd=_set\n\nsupports_follow_symlinks=_set\n\n", ["abc", "nt", "os.path", "posix", "posixpath", "sys"]], "pathlib": [".py", "''\n\n\n\n\n\n\nimport fnmatch\nimport functools\nimport io\nimport ntpath\nimport os\nimport posixpath\nimport re\nimport sys\nimport warnings\nfrom _collections_abc import Sequence\nfrom errno import ENOENT,ENOTDIR,EBADF,ELOOP\nfrom stat import S_ISDIR,S_ISLNK,S_ISREG,S_ISSOCK,S_ISBLK,S_ISCHR,S_ISFIFO\nfrom urllib.parse import quote_from_bytes as urlquote_from_bytes\n\n\n__all__=[\n\"PurePath\",\"PurePosixPath\",\"PureWindowsPath\",\n\"Path\",\"PosixPath\",\"WindowsPath\",\n]\n\n\n\n\n\n\n\n_WIN_RESERVED_NAMES=frozenset(\n{'CON','PRN','AUX','NUL','CONIN$','CONOUT$'}|\n{f'COM{c}'for c in '123456789\\xb9\\xb2\\xb3'}|\n{f'LPT{c}'for c in '123456789\\xb9\\xb2\\xb3'}\n)\n\n_WINERROR_NOT_READY=21\n_WINERROR_INVALID_NAME=123\n_WINERROR_CANT_RESOLVE_FILENAME=1921\n\n\n_IGNORED_ERRNOS=(ENOENT,ENOTDIR,EBADF,ELOOP)\n\n_IGNORED_WINERRORS=(\n_WINERROR_NOT_READY,\n_WINERROR_INVALID_NAME,\n_WINERROR_CANT_RESOLVE_FILENAME)\n\ndef _ignore_error(exception):\n return(getattr(exception,'errno',None)in _IGNORED_ERRNOS or\n getattr(exception,'winerror',None)in _IGNORED_WINERRORS)\n \n \n@functools.cache\ndef _is_case_sensitive(flavour):\n return flavour.normcase('Aa')=='Aa'\n \n \n \n \n \n \n \n \n \n \n \n \n \n_FNMATCH_PREFIX,_FNMATCH_SUFFIX=fnmatch.translate('_').split('_')\n_FNMATCH_SLICE=slice(len(_FNMATCH_PREFIX),-len(_FNMATCH_SUFFIX))\n_SWAP_SEP_AND_NEWLINE={\n'/':str.maketrans({'/':'\\n','\\n':'/'}),\n'\\\\':str.maketrans({'\\\\':'\\n','\\n':'\\\\'}),\n}\n\n\n@functools.lru_cache()\ndef _make_selector(pattern_parts,flavour,case_sensitive):\n pat=pattern_parts[0]\n if not pat:\n return _TerminatingSelector()\n if pat =='**':\n child_parts_idx=1\n while child_parts_idx =len(self)or idx <-len(self):\n raise IndexError(idx)\n if idx <0:\n idx +=len(self)\n return self._path._from_parsed_parts(self._drv,self._root,\n self._tail[:-idx -1])\n \n def __repr__(self):\n return \"<{}.parents>\".format(type(self._path).__name__)\n \n \nclass PurePath(object):\n ''\n\n\n\n\n\n\n \n \n __slots__=(\n \n \n '_raw_paths',\n \n \n \n \n \n \n \n \n '_drv','_root','_tail_cached',\n \n \n \n \n '_str',\n \n \n \n \n \n '_str_normcase_cached',\n \n \n \n \n \n '_parts_normcase_cached',\n \n \n \n '_lines_cached',\n \n \n \n '_hash',\n )\n _flavour=os.path\n \n def __new__(cls,*args,**kwargs):\n ''\n\n\n\n \n if cls is PurePath:\n cls=PureWindowsPath if os.name =='nt'else PurePosixPath\n return object.__new__(cls)\n \n def __reduce__(self):\n \n \n return(self.__class__,self.parts)\n \n def __init__(self,*args):\n paths=[]\n for arg in args:\n if isinstance(arg,PurePath):\n if arg._flavour is ntpath and self._flavour is posixpath:\n \n paths.extend(path.replace('\\\\','/')for path in arg._raw_paths)\n else:\n paths.extend(arg._raw_paths)\n else:\n try:\n path=os.fspath(arg)\n except TypeError:\n path=arg\n if not isinstance(path,str):\n raise TypeError(\n \"argument should be a str or an os.PathLike \"\n \"object where __fspath__ returns a str, \"\n f\"not {type(path).__name__ !r}\")\n paths.append(path)\n self._raw_paths=paths\n \n def with_segments(self,*pathsegments):\n ''\n\n\n \n return type(self)(*pathsegments)\n \n @classmethod\n def _parse_path(cls,path):\n if not path:\n return '','',[]\n sep=cls._flavour.sep\n altsep=cls._flavour.altsep\n if altsep:\n path=path.replace(altsep,sep)\n drv,root,rel=cls._flavour.splitroot(path)\n if not root and drv.startswith(sep)and not drv.endswith(sep):\n drv_parts=drv.split(sep)\n if len(drv_parts)==4 and drv_parts[2]not in '?.':\n \n root=sep\n elif len(drv_parts)==6:\n \n root=sep\n parsed=[sys.intern(str(x))for x in rel.split(sep)if x and x !='.']\n return drv,root,parsed\n \n def _load_parts(self):\n paths=self._raw_paths\n if len(paths)==0:\n path=''\n elif len(paths)==1:\n path=paths[0]\n else:\n path=self._flavour.join(*paths)\n drv,root,tail=self._parse_path(path)\n self._drv=drv\n self._root=root\n self._tail_cached=tail\n \n def _from_parsed_parts(self,drv,root,tail):\n path_str=self._format_parsed_parts(drv,root,tail)\n path=self.with_segments(path_str)\n path._str=path_str or '.'\n path._drv=drv\n path._root=root\n path._tail_cached=tail\n return path\n \n @classmethod\n def _format_parsed_parts(cls,drv,root,tail):\n if drv or root:\n return drv+root+cls._flavour.sep.join(tail)\n elif tail and cls._flavour.splitdrive(tail[0])[0]:\n tail=['.']+tail\n return cls._flavour.sep.join(tail)\n \n def __str__(self):\n ''\n \n try:\n return self._str\n except AttributeError:\n self._str=self._format_parsed_parts(self.drive,self.root,\n self._tail)or '.'\n return self._str\n \n def __fspath__(self):\n return str(self)\n \n def as_posix(self):\n ''\n \n f=self._flavour\n return str(self).replace(f.sep,'/')\n \n def __bytes__(self):\n ''\n \n return os.fsencode(self)\n \n def __repr__(self):\n return \"{}({!r})\".format(self.__class__.__name__,self.as_posix())\n \n def as_uri(self):\n ''\n if not self.is_absolute():\n raise ValueError(\"relative path can't be expressed as a file URI\")\n \n drive=self.drive\n if len(drive)==2 and drive[1]==':':\n \n prefix='file:///'+drive\n path=self.as_posix()[2:]\n elif drive:\n \n prefix='file:'\n path=self.as_posix()\n else:\n \n prefix='file://'\n path=str(self)\n return prefix+urlquote_from_bytes(os.fsencode(path))\n \n @property\n def _str_normcase(self):\n \n try:\n return self._str_normcase_cached\n except AttributeError:\n if _is_case_sensitive(self._flavour):\n self._str_normcase_cached=str(self)\n else:\n self._str_normcase_cached=str(self).lower()\n return self._str_normcase_cached\n \n @property\n def _parts_normcase(self):\n \n try:\n return self._parts_normcase_cached\n except AttributeError:\n self._parts_normcase_cached=self._str_normcase.split(self._flavour.sep)\n return self._parts_normcase_cached\n \n @property\n def _lines(self):\n \n try:\n return self._lines_cached\n except AttributeError:\n path_str=str(self)\n if path_str =='.':\n self._lines_cached=''\n else:\n trans=_SWAP_SEP_AND_NEWLINE[self._flavour.sep]\n self._lines_cached=path_str.translate(trans)\n return self._lines_cached\n \n def __eq__(self,other):\n if not isinstance(other,PurePath):\n return NotImplemented\n return self._str_normcase ==other._str_normcase and self._flavour is other._flavour\n \n def __hash__(self):\n try:\n return self._hash\n except AttributeError:\n self._hash=hash(self._str_normcase)\n return self._hash\n \n def __lt__(self,other):\n if not isinstance(other,PurePath)or self._flavour is not other._flavour:\n return NotImplemented\n return self._parts_normcase other._parts_normcase\n \n def __ge__(self,other):\n if not isinstance(other,PurePath)or self._flavour is not other._flavour:\n return NotImplemented\n return self._parts_normcase >=other._parts_normcase\n \n @property\n def drive(self):\n ''\n try:\n return self._drv\n except AttributeError:\n self._load_parts()\n return self._drv\n \n @property\n def root(self):\n ''\n try:\n return self._root\n except AttributeError:\n self._load_parts()\n return self._root\n \n @property\n def _tail(self):\n try:\n return self._tail_cached\n except AttributeError:\n self._load_parts()\n return self._tail_cached\n \n @property\n def anchor(self):\n ''\n anchor=self.drive+self.root\n return anchor\n \n @property\n def name(self):\n ''\n tail=self._tail\n if not tail:\n return ''\n return tail[-1]\n \n @property\n def suffix(self):\n ''\n\n\n\n \n name=self.name\n i=name.rfind('.')\n if 0 >> import pdb\n >>> pdb.run('')\n\nThe debugger's prompt is '(Pdb) '. This will stop in the first\nfunction call in .\n\nAlternatively, if a statement terminated with an unhandled exception,\nyou can use pdb's post-mortem facility to inspect the contents of the\ntraceback:\n\n >>> \n \n >>> import pdb\n >>> pdb.pm()\n\nThe commands recognized by the debugger are listed in the next\nsection. Most can be abbreviated as indicated; e.g., h(elp) means\nthat 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',\nnor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in\nsquare brackets. Alternatives in the command syntax are separated\nby a vertical bar (|).\n\nA blank line repeats the previous command literally, except for\n'list', where it lists the next 11 lines.\n\nCommands that the debugger doesn't recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged. Python statements can also be prefixed with an exclamation\npoint ('!'). This is a powerful way to inspect the program being\ndebugged; it is even possible to change variables or call functions.\nWhen an exception occurs in such a statement, the exception name is\nprinted but the debugger's state is not changed.\n\nThe debugger supports aliases, which can save typing. And aliases can\nhave parameters (see the alias help entry) which allows one a certain\nlevel of adaptability to the context under examination.\n\nMultiple commands may be entered on a single line, separated by the\npair ';;'. No intelligence is applied to separating the commands; the\ninput is split at the first ';;', even if it is in the middle of a\nquoted string.\n\nIf a file \".pdbrc\" exists in your home directory or in the current\ndirectory, it is read in and executed as if it had been typed at the\ndebugger prompt. This is particularly useful for aliases. If both\nfiles exist, the one in the home directory is read first and aliases\ndefined there can be overridden by the local file. This behavior can be\ndisabled by passing the \"readrc=False\" argument to the Pdb constructor.\n\nAside from aliases, the debugger is not directly programmable; but it\nis implemented as a class from which you can derive your own debugger\nclass, which you can make as fancy as you like.\n\n\nDebugger commands\n=================\n\n\"\"\"\n\n\n\nimport os\nimport io\nimport re\nimport sys\nimport cmd\nimport bdb\nimport dis\nimport code\nimport glob\nimport token\nimport types\nimport codeop\nimport pprint\nimport signal\nimport inspect\nimport textwrap\nimport tokenize\nimport traceback\nimport linecache\nimport _colorize\n\nfrom contextlib import contextmanager\nfrom rlcompleter import Completer\nfrom types import CodeType\n\n\nclass Restart(Exception):\n ''\n pass\n \n__all__=[\"run\",\"pm\",\"Pdb\",\"runeval\",\"runctx\",\"runcall\",\"set_trace\",\n\"post_mortem\",\"help\"]\n\n\ndef find_first_executable_line(code):\n ''\n\n\n\n\n\n \n prev=None\n for instr in dis.get_instructions(code):\n if prev is not None and prev.opname =='RESUME':\n if instr.positions.lineno is not None:\n return instr.positions.lineno\n return code.co_firstlineno\n prev=instr\n return code.co_firstlineno\n \ndef find_function(funcname,filename):\n cre=re.compile(r'def\\s+%s\\s*[(]'%re.escape(funcname))\n try:\n fp=tokenize.open(filename)\n except OSError:\n lines=linecache.getlines(filename)\n if not lines:\n return None\n fp=io.StringIO(''.join(lines))\n funcdef=\"\"\n funcstart=None\n \n with fp:\n for lineno,line in enumerate(fp,start=1):\n if cre.match(line):\n funcstart,funcdef=lineno,line\n elif funcdef:\n funcdef +=line\n \n if funcdef:\n try:\n funccode=compile(funcdef,filename,'exec').co_consts[0]\n except SyntaxError:\n continue\n lineno_offset=find_first_executable_line(funccode)\n return funcname,filename,funcstart+lineno_offset -1\n return None\n \ndef lasti2lineno(code,lasti):\n linestarts=list(dis.findlinestarts(code))\n linestarts.reverse()\n for i,lineno in linestarts:\n if lasti >=i:\n return lineno\n return 0\n \n \nclass _rstr(str):\n ''\n def __repr__(self):\n return self\n \n \nclass _ExecutableTarget:\n filename:str\n code:CodeType |str\n namespace:dict\n \n \nclass _ScriptTarget(_ExecutableTarget):\n def __init__(self,target):\n self._target=os.path.realpath(target)\n \n if not os.path.exists(self._target):\n print(f'Error: {target} does not exist')\n sys.exit(1)\n if os.path.isdir(self._target):\n print(f'Error: {target} is a directory')\n sys.exit(1)\n \n \n \n if not sys.flags.safe_path:\n sys.path[0]=os.path.dirname(self._target)\n \n def __repr__(self):\n return self._target\n \n @property\n def filename(self):\n return self._target\n \n @property\n def code(self):\n \n with io.open_code(self._target)as fp:\n return f\"exec(compile({fp.read()!r}, {self._target !r}, 'exec'))\"\n \n @property\n def namespace(self):\n return dict(\n __name__='__main__',\n __file__=self._target,\n __builtins__=__builtins__,\n __spec__=None,\n )\n \n \nclass _ModuleTarget(_ExecutableTarget):\n def __init__(self,target):\n self._target=target\n \n import runpy\n try:\n _,self._spec,self._code=runpy._get_module_details(self._target)\n except ImportError as e:\n print(f\"ImportError: {e}\")\n sys.exit(1)\n except Exception:\n traceback.print_exc()\n sys.exit(1)\n \n def __repr__(self):\n return self._target\n \n @property\n def filename(self):\n return self._code.co_filename\n \n @property\n def code(self):\n return self._code\n \n @property\n def namespace(self):\n return dict(\n __name__='__main__',\n __file__=os.path.normcase(os.path.abspath(self.filename)),\n __package__=self._spec.parent,\n __loader__=self._spec.loader,\n __spec__=self._spec,\n __builtins__=__builtins__,\n )\n \n \nclass _ZipTarget(_ExecutableTarget):\n def __init__(self,target):\n import runpy\n \n self._target=os.path.realpath(target)\n sys.path.insert(0,self._target)\n try:\n _,self._spec,self._code=runpy._get_main_module_details()\n except ImportError as e:\n print(f\"ImportError: {e}\")\n sys.exit(1)\n except Exception:\n traceback.print_exc()\n sys.exit(1)\n \n def __repr__(self):\n return self._target\n \n @property\n def filename(self):\n return self._code.co_filename\n \n @property\n def code(self):\n return self._code\n \n @property\n def namespace(self):\n return dict(\n __name__='__main__',\n __file__=os.path.normcase(os.path.abspath(self.filename)),\n __package__=self._spec.parent,\n __loader__=self._spec.loader,\n __spec__=self._spec,\n __builtins__=__builtins__,\n )\n \n \nclass _PdbInteractiveConsole(code.InteractiveConsole):\n def __init__(self,ns,message):\n self._message=message\n super().__init__(locals=ns,local_exit=True)\n \n def write(self,data):\n self._message(data,end='')\n \n \n \n \n \n \n \nline_prefix='\\n-> '\n\n\n\nclass Pdb(bdb.Bdb,cmd.Cmd):\n _previous_sigint_handler=None\n \n \n \n MAX_CHAINED_EXCEPTION_DEPTH=999\n \n _file_mtime_table={}\n \n def __init__(self,completekey='tab',stdin=None,stdout=None,skip=None,\n nosigint=False,readrc=True):\n bdb.Bdb.__init__(self,skip=skip)\n cmd.Cmd.__init__(self,completekey,stdin,stdout)\n sys.audit(\"pdb.Pdb\")\n if stdout:\n self.use_rawinput=0\n self.prompt='(Pdb) '\n self.aliases={}\n self.displaying={}\n self.mainpyfile=''\n self._wait_for_mainpyfile=False\n self.tb_lineno={}\n \n try:\n import readline\n \n readline.set_completer_delims(' \\t\\n`@#%^&*()=+[{]}\\\\|;:\\'\",<>?')\n except ImportError:\n pass\n self.allow_kbdint=False\n self.nosigint=nosigint\n \n \n self.identchars=cmd.Cmd.identchars+'=.[](),\"\\'+-*/%@&|<>~^'\n \n \n self.rcLines=[]\n if readrc:\n try:\n with open(os.path.expanduser('~/.pdbrc'),encoding='utf-8')as rcFile:\n self.rcLines.extend(rcFile)\n except OSError:\n pass\n try:\n with open(\".pdbrc\",encoding='utf-8')as rcFile:\n self.rcLines.extend(rcFile)\n except OSError:\n pass\n \n self.commands={}\n self.commands_doprompt={}\n \n self.commands_silent={}\n \n self.commands_defining=False\n \n self.commands_bnum=None\n \n \n self._chained_exceptions=tuple()\n self._chained_exception_index=0\n \n def sigint_handler(self,signum,frame):\n if self.allow_kbdint:\n raise KeyboardInterrupt\n self.message(\"\\nProgram interrupted. (Use 'cont' to resume).\")\n self.set_step()\n self.set_trace(frame)\n \n def reset(self):\n bdb.Bdb.reset(self)\n self.forget()\n \n def forget(self):\n self.lineno=None\n self.stack=[]\n self.curindex=0\n if hasattr(self,'curframe')and self.curframe:\n self.curframe.f_globals.pop('__pdb_convenience_variables',None)\n self.curframe=None\n self.tb_lineno.clear()\n \n def setup(self,f,tb):\n self.forget()\n self.stack,self.curindex=self.get_stack(f,tb)\n while tb:\n \n \n \n lineno=lasti2lineno(tb.tb_frame.f_code,tb.tb_lasti)\n self.tb_lineno[tb.tb_frame]=lineno\n tb=tb.tb_next\n self.curframe=self.stack[self.curindex][0]\n \n \n \n \n \n \n self.curframe_locals=self.curframe.f_locals\n self.set_convenience_variable(self.curframe,'_frame',self.curframe)\n \n if self._chained_exceptions:\n self.set_convenience_variable(\n self.curframe,\n '_exception',\n self._chained_exceptions[self._chained_exception_index],\n )\n \n if self.rcLines:\n self.cmdqueue=[\n line for line in self.rcLines\n if line.strip()and not line.strip().startswith(\"#\")\n ]\n self.rcLines=[]\n \n \n \n def user_call(self,frame,argument_list):\n ''\n \n if self._wait_for_mainpyfile:\n return\n if self.stop_here(frame):\n self.message('--Call--')\n self.interaction(frame,None)\n \n def user_line(self,frame):\n ''\n if self._wait_for_mainpyfile:\n if(self.mainpyfile !=self.canonic(frame.f_code.co_filename)\n or frame.f_lineno <=0):\n return\n self._wait_for_mainpyfile=False\n if self.bp_commands(frame):\n self.interaction(frame,None)\n \n user_opcode=user_line\n \n def bp_commands(self,frame):\n ''\n\n\n\n \n \n if getattr(self,\"currentbp\",False)and\\\n self.currentbp in self.commands:\n currentbp=self.currentbp\n self.currentbp=0\n lastcmd_back=self.lastcmd\n self.setup(frame,None)\n for line in self.commands[currentbp]:\n self.onecmd(line)\n self.lastcmd=lastcmd_back\n if not self.commands_silent[currentbp]:\n self.print_stack_entry(self.stack[self.curindex])\n if self.commands_doprompt[currentbp]:\n self._cmdloop()\n self.forget()\n return\n return 1\n \n def user_return(self,frame,return_value):\n ''\n if self._wait_for_mainpyfile:\n return\n frame.f_locals['__return__']=return_value\n self.set_convenience_variable(frame,'_retval',return_value)\n self.message('--Return--')\n self.interaction(frame,None)\n \n def user_exception(self,frame,exc_info):\n ''\n \n if self._wait_for_mainpyfile:\n return\n exc_type,exc_value,exc_traceback=exc_info\n frame.f_locals['__exception__']=exc_type,exc_value\n self.set_convenience_variable(frame,'_exception',exc_value)\n \n \n \n \n \n \n prefix='Internal 'if(not exc_traceback\n and exc_type is StopIteration)else ''\n self.message('%s%s'%(prefix,self._format_exc(exc_value)))\n self.interaction(frame,exc_traceback)\n \n \n def _cmdloop(self):\n while True:\n try:\n \n \n self.allow_kbdint=True\n self.cmdloop()\n self.allow_kbdint=False\n break\n except KeyboardInterrupt:\n self.message('--KeyboardInterrupt--')\n \n def _validate_file_mtime(self):\n ''\n \n try:\n filename=self.curframe.f_code.co_filename\n mtime=os.path.getmtime(filename)\n except Exception:\n return\n if(filename in self._file_mtime_table and\n mtime !=self._file_mtime_table[filename]):\n self.message(f\"*** WARNING: file '{filename}' was edited, \"\n \"running stale code until the program is rerun\")\n self._file_mtime_table[filename]=mtime\n \n \n \n def _show_display(self):\n displaying=self.displaying.get(self.curframe)\n if displaying:\n for expr,oldvalue in displaying.items():\n newvalue=self._getval_except(expr)\n \n \n \n if newvalue is not oldvalue and newvalue !=oldvalue:\n displaying[expr]=newvalue\n self.message('display %s: %s [old: %s]'%\n (expr,self._safe_repr(newvalue,expr),\n self._safe_repr(oldvalue,expr)))\n \n def _get_tb_and_exceptions(self,tb_or_exc):\n ''\n\n\n\n\n\n\n\n \n _exceptions=[]\n if isinstance(tb_or_exc,BaseException):\n traceback,current=tb_or_exc.__traceback__,tb_or_exc\n \n while current is not None:\n if current in _exceptions:\n break\n _exceptions.append(current)\n if current.__cause__ is not None:\n current=current.__cause__\n elif(\n current.__context__ is not None and not current.__suppress_context__\n ):\n current=current.__context__\n \n if len(_exceptions)>=self.MAX_CHAINED_EXCEPTION_DEPTH:\n self.message(\n f\"More than {self.MAX_CHAINED_EXCEPTION_DEPTH}\"\n \" chained exceptions found, not all exceptions\"\n \"will be browsable with `exceptions`.\"\n )\n break\n else:\n traceback=tb_or_exc\n return tuple(reversed(_exceptions)),traceback\n \n @contextmanager\n def _hold_exceptions(self,exceptions):\n ''\n\n\n\n\n\n\n\n \n try:\n self._chained_exceptions=exceptions\n self._chained_exception_index=len(exceptions)-1\n yield\n finally:\n \n \n self._chained_exceptions=tuple()\n self._chained_exception_index=0\n \n def interaction(self,frame,tb_or_exc):\n \n if Pdb._previous_sigint_handler:\n try:\n signal.signal(signal.SIGINT,Pdb._previous_sigint_handler)\n except ValueError:\n pass\n else:\n Pdb._previous_sigint_handler=None\n \n _chained_exceptions,tb=self._get_tb_and_exceptions(tb_or_exc)\n if isinstance(tb_or_exc,BaseException):\n assert tb is not None,\"main exception must have a traceback\"\n with self._hold_exceptions(_chained_exceptions):\n self.setup(frame,tb)\n \n \n \n \n \n self.cmdqueue.append('_pdbcmd_print_frame_status')\n self._cmdloop()\n \n if self.cmdqueue and self.cmdqueue[-1]=='_pdbcmd_print_frame_status':\n self.cmdqueue.pop()\n self.forget()\n \n def displayhook(self,obj):\n ''\n\n \n \n if obj is not None:\n self.message(repr(obj))\n \n @contextmanager\n def _disable_command_completion(self):\n completenames=self.completenames\n try:\n self.completenames=self.completedefault\n yield\n finally:\n self.completenames=completenames\n return\n \n def _exec_in_closure(self,source,globals,locals):\n ''\n\n\n\n \n \n \n \n \n \n code=compile(source,\"\",\"exec\")\n if not any(isinstance(const,CodeType)for const in code.co_consts):\n return False\n \n \n \n locals_copy=dict(locals)\n \n locals_copy[\"__pdb_eval__\"]={\n \"result\":None,\n \"write_back\":{}\n }\n \n \n try:\n compile(source,\"\",\"eval\")\n except SyntaxError:\n pass\n else:\n source=\"__pdb_eval__['result'] = \"+source\n \n \n source=(\"try:\\n\"+\n textwrap.indent(source,\" \")+\"\\n\"+\n \"finally:\\n\"+\n \" __pdb_eval__['write_back'] = locals()\")\n \n \n \n \n \n \n \n \n source_with_closure=(\"def __pdb_outer():\\n\"+\n \"\\n\".join(f\" {var} = None\"for var in locals_copy)+\"\\n\"+\n \" def __pdb_scope():\\n\"+\n \"\\n\".join(f\" nonlocal {var}\"for var in locals_copy)+\"\\n\"+\n textwrap.indent(source,\" \")+\"\\n\"+\n \" return __pdb_scope.__code__\"\n )\n \n \n \n \n ns={}\n try:\n exec(source_with_closure,{},ns)\n except Exception:\n return False\n code=ns[\"__pdb_outer\"]()\n \n cells=tuple(types.CellType(locals_copy.get(var))for var in code.co_freevars)\n \n try:\n exec(code,globals,locals_copy,closure=cells)\n except Exception:\n return False\n \n \n pdb_eval=locals_copy[\"__pdb_eval__\"]\n \n \n pdb_eval[\"write_back\"].pop(\"__pdb_eval__\")\n \n \n locals.update(pdb_eval[\"write_back\"])\n eval_result=pdb_eval[\"result\"]\n if eval_result is not None:\n print(repr(eval_result))\n \n return True\n \n def default(self,line):\n if line[:1]=='!':line=line[1:].strip()\n locals=self.curframe_locals\n globals=self.curframe.f_globals\n try:\n buffer=line\n if(code :=codeop.compile_command(line+'\\n','','single'))is None:\n \n with self._disable_command_completion():\n buffer=line\n continue_prompt=\"... \"\n while(code :=codeop.compile_command(buffer,'','single'))is None:\n if self.use_rawinput:\n try:\n line=input(continue_prompt)\n except(EOFError,KeyboardInterrupt):\n self.lastcmd=\"\"\n print('\\n')\n return\n else:\n self.stdout.write(continue_prompt)\n self.stdout.flush()\n line=self.stdin.readline()\n if not len(line):\n self.lastcmd=\"\"\n self.stdout.write('\\n')\n self.stdout.flush()\n return\n else:\n line=line.rstrip('\\r\\n')\n buffer +='\\n'+line\n save_stdout=sys.stdout\n save_stdin=sys.stdin\n save_displayhook=sys.displayhook\n try:\n sys.stdin=self.stdin\n sys.stdout=self.stdout\n sys.displayhook=self.displayhook\n if not self._exec_in_closure(buffer,globals,locals):\n exec(code,globals,locals)\n finally:\n sys.stdout=save_stdout\n sys.stdin=save_stdin\n sys.displayhook=save_displayhook\n except:\n self._error_exc()\n \n def _replace_convenience_variables(self,line):\n ''\n\n \n \n if \"$\"not in line:\n return line\n \n dollar_start=dollar_end=-1\n replace_variables=[]\n try:\n for t in tokenize.generate_tokens(io.StringIO(line).readline):\n token_type,token_string,start,end,_=t\n if token_type ==token.OP and token_string =='$':\n dollar_start,dollar_end=start,end\n elif start ==dollar_end and token_type ==token.NAME:\n \n replace_variables.append((dollar_start[1],end[1],token_string))\n except tokenize.TokenError:\n return line\n \n if not replace_variables:\n return line\n \n last_end=0\n line_pieces=[]\n for start,end,name in replace_variables:\n line_pieces.append(line[last_end:start]+f'__pdb_convenience_variables[\"{name}\"]')\n last_end=end\n line_pieces.append(line[last_end:])\n \n return ''.join(line_pieces)\n \n def precmd(self,line):\n ''\n if not line.strip():\n return line\n args=line.split()\n while args[0]in self.aliases:\n line=self.aliases[args[0]]\n for idx in range(1,10):\n if f'%{idx}'in line:\n if idx >=len(args):\n self.error(f\"Not enough arguments for alias '{args[0]}'\")\n \n return \"!\"\n line=line.replace(f'%{idx}',args[idx])\n elif '%*'not in line:\n if idx =0:\n \n next=line[marker+2:].lstrip()\n self.cmdqueue.insert(0,next)\n line=line[:marker].rstrip()\n \n \n line=self._replace_convenience_variables(line)\n \n return line\n \n def onecmd(self,line):\n ''\n\n\n\n\n \n if not self.commands_defining:\n self._validate_file_mtime()\n if line.startswith('_pdbcmd'):\n command,arg,line=self.parseline(line)\n if hasattr(self,command):\n return getattr(self,command)(arg)\n return cmd.Cmd.onecmd(self,line)\n else:\n return self.handle_command_def(line)\n \n def handle_command_def(self,line):\n ''\n cmd,arg,line=self.parseline(line)\n if not cmd:\n return False\n if cmd =='silent':\n self.commands_silent[self.commands_bnum]=True\n return False\n elif cmd =='end':\n return True\n cmdlist=self.commands[self.commands_bnum]\n if arg:\n cmdlist.append(cmd+' '+arg)\n else:\n cmdlist.append(cmd)\n \n try:\n func=getattr(self,'do_'+cmd)\n except AttributeError:\n func=self.default\n \n if func.__name__ in self.commands_resuming:\n self.commands_doprompt[self.commands_bnum]=False\n return True\n return False\n \n \n \n def message(self,msg,end='\\n'):\n print(msg,end=end,file=self.stdout)\n \n def error(self,msg):\n print('***',msg,file=self.stdout)\n \n \n \n def set_convenience_variable(self,frame,name,value):\n if '__pdb_convenience_variables'not in frame.f_globals:\n frame.f_globals['__pdb_convenience_variables']={}\n frame.f_globals['__pdb_convenience_variables'][name]=value\n \n \n \n \n def completenames(self,text,line,begidx,endidx):\n \n \n commands=super().completenames(text,line,begidx,endidx)\n for alias in self.aliases:\n if alias.startswith(text):\n commands.append(alias)\n if commands:\n return commands\n else:\n expressions=self._complete_expression(text,line,begidx,endidx)\n if expressions:\n return expressions\n return self.completedefault(text,line,begidx,endidx)\n \n def _complete_location(self,text,line,begidx,endidx):\n \n if line.strip().endswith((':',',')):\n \n return[]\n \n try:\n ret=self._complete_expression(text,line,begidx,endidx)\n except Exception:\n ret=[]\n \n globs=glob.glob(glob.escape(text)+'*')\n for fn in globs:\n if os.path.isdir(fn):\n ret.append(fn+'/')\n elif os.path.isfile(fn)and fn.lower().endswith(('.py','.pyw')):\n ret.append(fn+':')\n return ret\n \n def _complete_bpnumber(self,text,line,begidx,endidx):\n \n \n \n return[str(i)for i,bp in enumerate(bdb.Breakpoint.bpbynumber)\n if bp is not None and str(i).startswith(text)]\n \n def _complete_expression(self,text,line,begidx,endidx):\n \n if not self.curframe:\n return[]\n \n \n \n ns={**self.curframe.f_globals,**self.curframe_locals}\n if text.startswith(\"$\"):\n \n conv_vars=self.curframe.f_globals.get('__pdb_convenience_variables',{})\n return[f\"${name}\"for name in conv_vars if name.startswith(text[1:])]\n if '.'in text:\n \n \n \n dotted=text.split('.')\n try:\n obj=ns[dotted[0]]\n for part in dotted[1:-1]:\n obj=getattr(obj,part)\n except(KeyError,AttributeError):\n return[]\n prefix='.'.join(dotted[:-1])+'.'\n return[prefix+n for n in dir(obj)if n.startswith(dotted[-1])]\n else:\n \n return[n for n in ns.keys()if n.startswith(text)]\n \n def completedefault(self,text,line,begidx,endidx):\n if text.startswith(\"$\"):\n \n conv_vars=self.curframe.f_globals.get('__pdb_convenience_variables',{})\n return[f\"${name}\"for name in conv_vars if name.startswith(text[1:])]\n \n \n state=0\n matches=[]\n completer=Completer(self.curframe.f_globals |self.curframe_locals)\n while(match :=completer.complete(text,state))is not None:\n matches.append(match)\n state +=1\n return matches\n \n \n \n def _pdbcmd_print_frame_status(self,arg):\n self.print_stack_entry(self.stack[self.curindex])\n self._show_display()\n \n \n \n \n \n def do_commands(self,arg):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not arg:\n bnum=len(bdb.Breakpoint.bpbynumber)-1\n else:\n try:\n bnum=int(arg)\n except:\n self._print_invalid_arg(arg)\n return\n try:\n self.get_bpbynumber(bnum)\n except ValueError as err:\n self.error('cannot set commands: %s'%err)\n return\n \n self.commands_bnum=bnum\n \n if bnum in self.commands:\n old_command_defs=(self.commands[bnum],\n self.commands_doprompt[bnum],\n self.commands_silent[bnum])\n else:\n old_command_defs=None\n self.commands[bnum]=[]\n self.commands_doprompt[bnum]=True\n self.commands_silent[bnum]=False\n \n prompt_back=self.prompt\n self.prompt='(com) '\n self.commands_defining=True\n try:\n self.cmdloop()\n except KeyboardInterrupt:\n \n if old_command_defs:\n self.commands[bnum]=old_command_defs[0]\n self.commands_doprompt[bnum]=old_command_defs[1]\n self.commands_silent[bnum]=old_command_defs[2]\n else:\n del self.commands[bnum]\n del self.commands_doprompt[bnum]\n del self.commands_silent[bnum]\n self.error('command definition aborted, old commands restored')\n finally:\n self.commands_defining=False\n self.prompt=prompt_back\n \n complete_commands=_complete_bpnumber\n \n def do_break(self,arg,temporary=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not arg:\n if self.breaks:\n self.message(\"Num Type Disp Enb Where\")\n for bp in bdb.Breakpoint.bpbynumber:\n if bp:\n self.message(bp.bpformat())\n return\n \n \n filename=None\n lineno=None\n cond=None\n comma=arg.find(',')\n if comma >0:\n \n cond=arg[comma+1:].lstrip()\n if err :=self._compile_error_message(cond):\n self.error('Invalid condition %s: %r'%(cond,err))\n return\n arg=arg[:comma].rstrip()\n \n colon=arg.rfind(':')\n funcname=None\n if colon >=0:\n filename=arg[:colon].rstrip()\n f=self.lookupmodule(filename)\n if not f:\n self.error('%r not found from sys.path'%filename)\n return\n else:\n filename=f\n arg=arg[colon+1:].lstrip()\n try:\n lineno=int(arg)\n except ValueError:\n self.error('Bad lineno: %s'%arg)\n return\n else:\n \n try:\n lineno=int(arg)\n except ValueError:\n try:\n func=eval(arg,\n self.curframe.f_globals,\n self.curframe_locals)\n except:\n func=arg\n try:\n if hasattr(func,'__func__'):\n func=func.__func__\n code=func.__code__\n \n \n funcname=code.co_name\n lineno=find_first_executable_line(code)\n filename=code.co_filename\n except:\n \n (ok,filename,ln)=self.lineinfo(arg)\n if not ok:\n self.error('The specified object %r is not a function '\n 'or was not found along sys.path.'%arg)\n return\n funcname=ok\n lineno=int(ln)\n if not filename:\n filename=self.defaultFile()\n \n line=self.checkline(filename,lineno)\n if line:\n \n err=self.set_break(filename,line,temporary,cond,funcname)\n if err:\n self.error(err)\n else:\n bp=self.get_breaks(filename,line)[-1]\n self.message(\"Breakpoint %d at %s:%d\"%\n (bp.number,bp.file,bp.line))\n \n \n def defaultFile(self):\n ''\n filename=self.curframe.f_code.co_filename\n if filename ==''and self.mainpyfile:\n filename=self.mainpyfile\n return filename\n \n do_b=do_break\n \n complete_break=_complete_location\n complete_b=_complete_location\n \n def do_tbreak(self,arg):\n ''\n\n\n\n \n self.do_break(arg,1)\n \n complete_tbreak=_complete_location\n \n def lineinfo(self,identifier):\n failed=(None,None,None)\n \n idstring=identifier.split(\"'\")\n if len(idstring)==1:\n \n id=idstring[0].strip()\n elif len(idstring)==3:\n \n id=idstring[1].strip()\n else:\n return failed\n if id =='':return failed\n parts=id.split('.')\n \n if parts[0]=='self':\n del parts[0]\n if len(parts)==0:\n return failed\n \n fname=self.defaultFile()\n if len(parts)==1:\n item=parts[0]\n else:\n \n \n f=self.lookupmodule(parts[0])\n if f:\n fname=f\n item=parts[1]\n answer=find_function(item,self.canonic(fname))\n return answer or failed\n \n def checkline(self,filename,lineno):\n ''\n\n\n\n \n \n \n frame=getattr(self,'curframe',None)\n globs=frame.f_globals if frame else None\n line=linecache.getline(filename,lineno,globs)\n if not line:\n self.message('End of file')\n return 0\n line=line.strip()\n \n if(not line or(line[0]=='#')or\n (line[:3]=='\"\"\"')or line[:3]==\"'''\"):\n self.error('Blank or comment')\n return 0\n return lineno\n \n def do_enable(self,arg):\n ''\n\n\n\n \n args=arg.split()\n for i in args:\n try:\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else:\n bp.enable()\n self.message('Enabled %s'%bp)\n \n complete_enable=_complete_bpnumber\n \n def do_disable(self,arg):\n ''\n\n\n\n\n\n\n \n args=arg.split()\n for i in args:\n try:\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else:\n bp.disable()\n self.message('Disabled %s'%bp)\n \n complete_disable=_complete_bpnumber\n \n def do_condition(self,arg):\n ''\n\n\n\n\n\n \n args=arg.split(' ',1)\n try:\n cond=args[1]\n if err :=self._compile_error_message(cond):\n self.error('Invalid condition %s: %r'%(cond,err))\n return\n except IndexError:\n cond=None\n try:\n bp=self.get_bpbynumber(args[0].strip())\n except IndexError:\n self.error('Breakpoint number expected')\n except ValueError as err:\n self.error(err)\n else:\n bp.cond=cond\n if not cond:\n self.message('Breakpoint %d is now unconditional.'%bp.number)\n else:\n self.message('New condition set for breakpoint %d.'%bp.number)\n \n complete_condition=_complete_bpnumber\n \n def do_ignore(self,arg):\n ''\n\n\n\n\n\n\n\n \n args=arg.split()\n if not args:\n self.error('Breakpoint number expected')\n return\n if len(args)==1:\n count=0\n elif len(args)==2:\n try:\n count=int(args[1])\n except ValueError:\n self._print_invalid_arg(arg)\n return\n else:\n self._print_invalid_arg(arg)\n return\n try:\n bp=self.get_bpbynumber(args[0].strip())\n except ValueError as err:\n self.error(err)\n else:\n bp.ignore=count\n if count >0:\n if count >1:\n countstr='%d crossings'%count\n else:\n countstr='1 crossing'\n self.message('Will ignore next %s of breakpoint %d.'%\n (countstr,bp.number))\n else:\n self.message('Will stop next time breakpoint %d is reached.'\n %bp.number)\n \n complete_ignore=_complete_bpnumber\n \n def do_clear(self,arg):\n ''\n\n\n\n\n\n \n if not arg:\n try:\n reply=input('Clear all breaks? ')\n except EOFError:\n reply='no'\n reply=reply.strip().lower()\n if reply in('y','yes'):\n bplist=[bp for bp in bdb.Breakpoint.bpbynumber if bp]\n self.clear_all_breaks()\n for bp in bplist:\n self.message('Deleted %s'%bp)\n return\n if ':'in arg:\n \n i=arg.rfind(':')\n filename=arg[:i]\n arg=arg[i+1:]\n try:\n lineno=int(arg)\n except ValueError:\n err=\"Invalid line number (%s)\"%arg\n else:\n bplist=self.get_breaks(filename,lineno)[:]\n err=self.clear_break(filename,lineno)\n if err:\n self.error(err)\n else:\n for bp in bplist:\n self.message('Deleted %s'%bp)\n return\n numberlist=arg.split()\n for i in numberlist:\n try:\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else:\n self.clear_bpbynumber(i)\n self.message('Deleted %s'%bp)\n do_cl=do_clear\n \n complete_clear=_complete_location\n complete_cl=_complete_location\n \n def do_where(self,arg):\n ''\n\n\n\n\n \n if arg:\n self._print_invalid_arg(arg)\n return\n self.print_stack_trace()\n do_w=do_where\n do_bt=do_where\n \n def _select_frame(self,number):\n assert 0 <=number \"if ix ==self._chained_exception_index else \" \"\n rep=repr(exc)\n if len(rep)>80:\n rep=rep[:77]+\"...\"\n indicator=(\n \" -\"\n if self._chained_exceptions[ix].__traceback__ is None\n else f\"{ix:>3}\"\n )\n self.message(f\"{prompt} {indicator} {rep}\")\n else:\n try:\n number=int(arg)\n except ValueError:\n self.error(\"Argument must be an integer\")\n return\n if 0 <=number =2:\n self.error('No help for %r; please do not run Python with -OO '\n 'if you need command help'%arg)\n return\n if command.__doc__ is None:\n self.error('No help for %r; __doc__ string missing'%arg)\n return\n self.message(self._help_message_from_doc(command.__doc__))\n \n do_h=do_help\n \n def help_exec(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self.message((self.help_exec.__doc__ or '').strip())\n \n def help_pdb(self):\n help()\n \n \n \n def lookupmodule(self,filename):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not filename.endswith('.py'):\n \n filename=filename.replace('.',os.sep)+'.py'\n \n if os.path.isabs(filename):\n if os.path.exists(filename):\n return filename\n return None\n \n for dirname in sys.path:\n while os.path.islink(dirname):\n dirname=os.readlink(dirname)\n fullname=os.path.join(dirname,filename)\n if os.path.exists(fullname):\n return fullname\n return None\n \n def _run(self,target:_ExecutableTarget):\n \n \n \n \n \n self._wait_for_mainpyfile=True\n self._user_requested_quit=False\n \n self.mainpyfile=self.canonic(target.filename)\n \n \n \n \n import __main__\n __main__.__dict__.clear()\n __main__.__dict__.update(target.namespace)\n \n \n \n self._file_mtime_table.clear()\n \n self.run(target.code)\n \n def _format_exc(self,exc:BaseException):\n return traceback.format_exception_only(exc)[-1].strip()\n \n def _compile_error_message(self,expr):\n ''\n try:\n compile(expr,\"\",\"eval\")\n except SyntaxError as exc:\n return _rstr(self._format_exc(exc))\n return \"\"\n \n def _getsourcelines(self,obj):\n \n \n \n \n \n lines,lineno=inspect.getsourcelines(obj)\n lineno=max(1,lineno)\n return lines,lineno\n \n def _help_message_from_doc(self,doc,usage_only=False):\n lines=[line.strip()for line in doc.rstrip().splitlines()]\n if not lines:\n return \"No help message found.\"\n if \"\"in lines:\n usage_end=lines.index(\"\")\n else:\n usage_end=1\n formatted=[]\n indent=\" \"*len(self.prompt)\n for i,line in enumerate(lines):\n if i ==0:\n prefix=\"Usage: \"\n elif i 0:\n self.commit_frame(force=True)\n self.current_frame=None\n \n def commit_frame(self,force=False):\n if self.current_frame:\n f=self.current_frame\n if f.tell()>=self._FRAME_SIZE_TARGET or force:\n data=f.getbuffer()\n write=self.file_write\n if len(data)>=self._FRAME_SIZE_MIN:\n \n \n \n \n write(FRAME+pack(\"':\n raise AttributeError(\"Can't get local attribute {!r} on {!r}\"\n .format(name,obj))\n try:\n parent=obj\n obj=getattr(obj,subpath)\n except AttributeError:\n raise AttributeError(\"Can't get attribute {!r} on {!r}\"\n .format(name,obj))from None\n return obj,parent\n \ndef whichmodule(obj,name):\n ''\n module_name=getattr(obj,'__module__',None)\n if module_name is not None:\n return module_name\n \n \n for module_name,module in sys.modules.copy().items():\n if(module_name =='__main__'\n or module_name =='__mp_main__'\n or module is None):\n continue\n try:\n if _getattribute(module,name)[0]is obj:\n return module_name\n except AttributeError:\n pass\n return '__main__'\n \ndef encode_long(x):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if x ==0:\n return b''\n nbytes=(x.bit_length()>>3)+1\n result=x.to_bytes(nbytes,byteorder='little',signed=True)\n if x <0 and nbytes >1:\n if result[-1]==0xff and(result[-2]&0x80)!=0:\n result=result[:-1]\n return result\n \ndef decode_long(data):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return int.from_bytes(data,byteorder='little',signed=True)\n \n \n_NoValue=object()\n\n\n\nclass _Pickler:\n\n def __init__(self,file,protocol=None,*,fix_imports=True,\n buffer_callback=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if protocol is None:\n protocol=DEFAULT_PROTOCOL\n if protocol <0:\n protocol=HIGHEST_PROTOCOL\n elif not 0 <=protocol <=HIGHEST_PROTOCOL:\n raise ValueError(\"pickle protocol must be <= %d\"%HIGHEST_PROTOCOL)\n if buffer_callback is not None and protocol <5:\n raise ValueError(\"buffer_callback needs protocol >= 5\")\n self._buffer_callback=buffer_callback\n try:\n self._file_write=file.write\n except AttributeError:\n raise TypeError(\"file must have a 'write' attribute\")\n self.framer=_Framer(self._file_write)\n self.write=self.framer.write\n self._write_large_bytes=self.framer.write_large_bytes\n self.memo={}\n self.proto=int(protocol)\n self.bin=protocol >=1\n self.fast=0\n self.fix_imports=fix_imports and protocol <3\n \n def clear_memo(self):\n ''\n\n\n\n\n\n \n self.memo.clear()\n \n def dump(self,obj):\n ''\n \n \n if not hasattr(self,\"_file_write\"):\n raise PicklingError(\"Pickler.__init__() was not called by \"\n \"%s.__init__()\"%(self.__class__.__name__,))\n if self.proto >=2:\n self.write(PROTO+pack(\"=4:\n self.framer.start_framing()\n self.save(obj)\n self.write(STOP)\n self.framer.end_framing()\n \n def memoize(self,obj):\n ''\n \n \n \n \n \n \n \n \n \n \n \n \n \n if self.fast:\n return\n assert id(obj)not in self.memo\n idx=len(self.memo)\n self.write(self.put(idx))\n self.memo[id(obj)]=idx,obj\n \n \n def put(self,idx):\n if self.proto >=4:\n return MEMOIZE\n elif self.bin:\n if idx <256:\n return BINPUT+pack(\"=2 and func_name ==\"__newobj_ex__\":\n cls,args,kwargs=args\n if not hasattr(cls,\"__new__\"):\n raise PicklingError(\"args[0] from {} args has no __new__\"\n .format(func_name))\n if obj is not None and cls is not obj.__class__:\n raise PicklingError(\"args[0] from {} args has the wrong class\"\n .format(func_name))\n if self.proto >=4:\n save(cls)\n save(args)\n save(kwargs)\n write(NEWOBJ_EX)\n else:\n func=partial(cls.__new__,cls,*args,**kwargs)\n save(func)\n save(())\n write(REDUCE)\n elif self.proto >=2 and func_name ==\"__newobj__\":\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n cls=args[0]\n if not hasattr(cls,\"__new__\"):\n raise PicklingError(\n \"args[0] from __newobj__ args has no __new__\")\n if obj is not None and cls is not obj.__class__:\n raise PicklingError(\n \"args[0] from __newobj__ args has the wrong class\")\n args=args[1:]\n save(cls)\n save(args)\n write(NEWOBJ)\n else:\n save(func)\n save(args)\n write(REDUCE)\n \n if obj is not None:\n \n \n \n if id(obj)in self.memo:\n write(POP+self.get(self.memo[id(obj)][0]))\n else:\n self.memoize(obj)\n \n \n \n \n \n \n if listitems is not None:\n self._batch_appends(listitems)\n \n if dictitems is not None:\n self._batch_setitems(dictitems)\n \n if state is not None:\n if state_setter is None:\n save(state)\n write(BUILD)\n else:\n \n \n \n \n save(state_setter)\n save(obj)\n save(state)\n write(TUPLE2)\n \n write(REDUCE)\n \n \n \n \n write(POP)\n \n \n \n dispatch={}\n \n def save_none(self,obj):\n self.write(NONE)\n dispatch[type(None)]=save_none\n \n def save_bool(self,obj):\n if self.proto >=2:\n self.write(NEWTRUE if obj else NEWFALSE)\n else:\n self.write(TRUE if obj else FALSE)\n dispatch[bool]=save_bool\n \n def save_long(self,obj):\n if self.bin:\n \n \n \n \n if obj >=0:\n if obj <=0xff:\n self.write(BININT1+pack(\"=2:\n encoded=encode_long(obj)\n n=len(encoded)\n if n <256:\n self.write(LONG1+pack(\"d',obj))\n else:\n self.write(FLOAT+repr(obj).encode(\"ascii\")+b'\\n')\n dispatch[float]=save_float\n \n def _save_bytes_no_memo(self,obj):\n \n \n assert self.proto >=3\n n=len(obj)\n if n <=0xff:\n self.write(SHORT_BINBYTES+pack(\"0xffffffff and self.proto >=4:\n self._write_large_bytes(BINBYTES8+pack(\"=self.framer._FRAME_SIZE_TARGET:\n self._write_large_bytes(BINBYTES+pack(\"=5\n n=len(obj)\n if n >=self.framer._FRAME_SIZE_TARGET:\n self._write_large_bytes(BYTEARRAY8+pack(\"= 5\")\n with obj.raw()as m:\n if not m.contiguous:\n raise PicklingError(\"PickleBuffer can not be pickled when \"\n \"pointing to a non-contiguous buffer\")\n in_band=True\n if self._buffer_callback is not None:\n in_band=bool(self._buffer_callback(obj))\n if in_band:\n \n \n buf=m.tobytes()\n in_memo=id(buf)in self.memo\n if m.readonly:\n if in_memo:\n self._save_bytes_no_memo(buf)\n else:\n self.save_bytes(buf)\n else:\n if in_memo:\n self._save_bytearray_no_memo(buf)\n else:\n self.save_bytearray(buf)\n else:\n \n self.write(NEXT_BUFFER)\n if m.readonly:\n self.write(READONLY_BUFFER)\n \n dispatch[PickleBuffer]=save_picklebuffer\n \n def save_str(self,obj):\n if self.bin:\n encoded=obj.encode('utf-8','surrogatepass')\n n=len(encoded)\n if n <=0xff and self.proto >=4:\n self.write(SHORT_BINUNICODE+pack(\"0xffffffff and self.proto >=4:\n self._write_large_bytes(BINUNICODE8+pack(\"=self.framer._FRAME_SIZE_TARGET:\n self._write_large_bytes(BINUNICODE+pack(\"=2:\n for element in obj:\n save(element)\n \n if id(obj)in memo:\n get=self.get(memo[id(obj)][0])\n self.write(POP *n+get)\n else:\n self.write(_tuplesize2code[n])\n self.memoize(obj)\n return\n \n \n \n write=self.write\n write(MARK)\n for element in obj:\n save(element)\n \n if id(obj)in memo:\n \n \n \n \n \n \n \n get=self.get(memo[id(obj)][0])\n if self.bin:\n write(POP_MARK+get)\n else:\n write(POP *(n+1)+get)\n return\n \n \n write(TUPLE)\n self.memoize(obj)\n \n dispatch[tuple]=save_tuple\n \n def save_list(self,obj):\n if self.bin:\n self.write(EMPTY_LIST)\n else:\n self.write(MARK+LIST)\n \n self.memoize(obj)\n self._batch_appends(obj)\n \n dispatch[list]=save_list\n \n _BATCHSIZE=1000\n \n def _batch_appends(self,items):\n \n save=self.save\n write=self.write\n \n if not self.bin:\n for x in items:\n save(x)\n write(APPEND)\n return\n \n it=iter(items)\n while True:\n tmp=list(islice(it,self._BATCHSIZE))\n n=len(tmp)\n if n >1:\n write(MARK)\n for x in tmp:\n save(x)\n write(APPENDS)\n elif n:\n save(tmp[0])\n write(APPEND)\n \n if n 1:\n write(MARK)\n for k,v in tmp:\n save(k)\n save(v)\n write(SETITEMS)\n elif n:\n k,v=tmp[0]\n save(k)\n save(v)\n write(SETITEM)\n \n if n 0:\n write(MARK)\n for item in batch:\n save(item)\n write(ADDITEMS)\n if n =2:\n code=_extension_registry.get((module_name,name))\n if code:\n assert code >0\n if code <=0xff:\n write(EXT1+pack(\"=4:\n self.save(module_name)\n self.save(name)\n write(STACK_GLOBAL)\n elif parent is not module:\n self.save_reduce(getattr,(parent,lastname))\n elif self.proto >=3:\n write(GLOBAL+bytes(module_name,\"utf-8\")+b'\\n'+\n bytes(name,\"utf-8\")+b'\\n')\n else:\n if self.fix_imports:\n r_name_mapping=_compat_pickle.REVERSE_NAME_MAPPING\n r_import_mapping=_compat_pickle.REVERSE_IMPORT_MAPPING\n if(module_name,name)in r_name_mapping:\n module_name,name=r_name_mapping[(module_name,name)]\n elif module_name in r_import_mapping:\n module_name=r_import_mapping[module_name]\n try:\n write(GLOBAL+bytes(module_name,\"ascii\")+b'\\n'+\n bytes(name,\"ascii\")+b'\\n')\n except UnicodeEncodeError:\n raise PicklingError(\n \"can't pickle global identifier '%s.%s' using \"\n \"pickle protocol %i\"%(module,name,self.proto))from None\n \n self.memoize(obj)\n \n def save_type(self,obj):\n if obj is type(None):\n return self.save_reduce(type,(None,),obj=obj)\n elif obj is type(NotImplemented):\n return self.save_reduce(type,(NotImplemented,),obj=obj)\n elif obj is type(...):\n return self.save_reduce(type,(...,),obj=obj)\n return self.save_global(obj)\n \n dispatch[FunctionType]=save_global\n dispatch[type]=save_type\n \n \n \n \nclass _Unpickler:\n\n def __init__(self,file,*,fix_imports=True,\n encoding=\"ASCII\",errors=\"strict\",buffers=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._buffers=iter(buffers)if buffers is not None else None\n self._file_readline=file.readline\n self._file_read=file.read\n self.memo={}\n self.encoding=encoding\n self.errors=errors\n self.proto=0\n self.fix_imports=fix_imports\n \n def load(self):\n ''\n\n\n \n \n \n if not hasattr(self,\"_file_read\"):\n raise UnpicklingError(\"Unpickler.__init__() was not called by \"\n \"%s.__init__()\"%(self.__class__.__name__,))\n self._unframer=_Unframer(self._file_read,self._file_readline)\n self.read=self._unframer.read\n self.readinto=self._unframer.readinto\n self.readline=self._unframer.readline\n self.metastack=[]\n self.stack=[]\n self.append=self.stack.append\n self.proto=0\n read=self.read\n dispatch=self.dispatch\n try:\n while True:\n key=read(1)\n if not key:\n raise EOFError\n assert isinstance(key,bytes_types)\n dispatch[key[0]](self)\n except _Stop as stopinst:\n return stopinst.value\n \n \n def pop_mark(self):\n items=self.stack\n self.stack=self.metastack.pop()\n self.append=self.stack.append\n return items\n \n def persistent_load(self,pid):\n raise UnpicklingError(\"unsupported persistent id encountered\")\n \n dispatch={}\n \n def load_proto(self):\n proto=self.read(1)[0]\n if not 0 <=proto <=HIGHEST_PROTOCOL:\n raise ValueError(\"unsupported pickle protocol: %d\"%proto)\n self.proto=proto\n dispatch[PROTO[0]]=load_proto\n \n def load_frame(self):\n frame_size,=unpack('sys.maxsize:\n raise ValueError(\"frame size > sys.maxsize: %d\"%frame_size)\n self._unframer.load_frame(frame_size)\n dispatch[FRAME[0]]=load_frame\n \n def load_persid(self):\n try:\n pid=self.readline()[:-1].decode(\"ascii\")\n except UnicodeDecodeError:\n raise UnpicklingError(\n \"persistent IDs in protocol 0 must be ASCII strings\")\n self.append(self.persistent_load(pid))\n dispatch[PERSID[0]]=load_persid\n \n def load_binpersid(self):\n pid=self.stack.pop()\n self.append(self.persistent_load(pid))\n dispatch[BINPERSID[0]]=load_binpersid\n \n def load_none(self):\n self.append(None)\n dispatch[NONE[0]]=load_none\n \n def load_false(self):\n self.append(False)\n dispatch[NEWFALSE[0]]=load_false\n \n def load_true(self):\n self.append(True)\n dispatch[NEWTRUE[0]]=load_true\n \n def load_int(self):\n data=self.readline()\n if data ==FALSE[1:]:\n val=False\n elif data ==TRUE[1:]:\n val=True\n else:\n val=int(data,0)\n self.append(val)\n dispatch[INT[0]]=load_int\n \n def load_binint(self):\n self.append(unpack('d',self.read(8))[0])\n dispatch[BINFLOAT[0]]=load_binfloat\n \n def _decode_string(self,value):\n \n \n \n if self.encoding ==\"bytes\":\n return value\n else:\n return value.decode(self.encoding,self.errors)\n \n def load_string(self):\n data=self.readline()[:-1]\n \n if len(data)>=2 and data[0]==data[-1]and data[0]in b'\"\\'':\n data=data[1:-1]\n else:\n raise UnpicklingError(\"the STRING opcode argument must be quoted\")\n self.append(self._decode_string(codecs.escape_decode(data)[0]))\n dispatch[STRING[0]]=load_string\n \n def load_binstring(self):\n \n len,=unpack('maxsize:\n raise UnpicklingError(\"BINBYTES exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n self.append(self.read(len))\n dispatch[BINBYTES[0]]=load_binbytes\n \n def load_unicode(self):\n self.append(str(self.readline()[:-1],'raw-unicode-escape'))\n dispatch[UNICODE[0]]=load_unicode\n \n def load_binunicode(self):\n len,=unpack('maxsize:\n raise UnpicklingError(\"BINUNICODE exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n self.append(str(self.read(len),'utf-8','surrogatepass'))\n dispatch[BINUNICODE[0]]=load_binunicode\n \n def load_binunicode8(self):\n len,=unpack('maxsize:\n raise UnpicklingError(\"BINUNICODE8 exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n self.append(str(self.read(len),'utf-8','surrogatepass'))\n dispatch[BINUNICODE8[0]]=load_binunicode8\n \n def load_binbytes8(self):\n len,=unpack('maxsize:\n raise UnpicklingError(\"BINBYTES8 exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n self.append(self.read(len))\n dispatch[BINBYTES8[0]]=load_binbytes8\n \n def load_bytearray8(self):\n len,=unpack('maxsize:\n raise UnpicklingError(\"BYTEARRAY8 exceeds system's maximum size \"\n \"of %d bytes\"%maxsize)\n b=bytearray(len)\n self.readinto(b)\n self.append(b)\n dispatch[BYTEARRAY8[0]]=load_bytearray8\n \n def load_next_buffer(self):\n if self._buffers is None:\n raise UnpicklingError(\"pickle stream refers to out-of-band data \"\n \"but no *buffers* argument was given\")\n try:\n buf=next(self._buffers)\n except StopIteration:\n raise UnpicklingError(\"not enough out-of-band buffers\")\n self.append(buf)\n dispatch[NEXT_BUFFER[0]]=load_next_buffer\n \n def load_readonly_buffer(self):\n buf=self.stack[-1]\n with memoryview(buf)as m:\n if not m.readonly:\n self.stack[-1]=m.toreadonly()\n dispatch[READONLY_BUFFER[0]]=load_readonly_buffer\n \n def load_short_binstring(self):\n len=self.read(1)[0]\n data=self.read(len)\n self.append(self._decode_string(data))\n dispatch[SHORT_BINSTRING[0]]=load_short_binstring\n \n def load_short_binbytes(self):\n len=self.read(1)[0]\n self.append(self.read(len))\n dispatch[SHORT_BINBYTES[0]]=load_short_binbytes\n \n def load_short_binunicode(self):\n len=self.read(1)[0]\n self.append(str(self.read(len),'utf-8','surrogatepass'))\n dispatch[SHORT_BINUNICODE[0]]=load_short_binunicode\n \n def load_tuple(self):\n items=self.pop_mark()\n self.append(tuple(items))\n dispatch[TUPLE[0]]=load_tuple\n \n def load_empty_tuple(self):\n self.append(())\n dispatch[EMPTY_TUPLE[0]]=load_empty_tuple\n \n def load_tuple1(self):\n self.stack[-1]=(self.stack[-1],)\n dispatch[TUPLE1[0]]=load_tuple1\n \n def load_tuple2(self):\n self.stack[-2:]=[(self.stack[-2],self.stack[-1])]\n dispatch[TUPLE2[0]]=load_tuple2\n \n def load_tuple3(self):\n self.stack[-3:]=[(self.stack[-3],self.stack[-2],self.stack[-1])]\n dispatch[TUPLE3[0]]=load_tuple3\n \n def load_empty_list(self):\n self.append([])\n dispatch[EMPTY_LIST[0]]=load_empty_list\n \n def load_empty_dictionary(self):\n self.append({})\n dispatch[EMPTY_DICT[0]]=load_empty_dictionary\n \n def load_empty_set(self):\n self.append(set())\n dispatch[EMPTY_SET[0]]=load_empty_set\n \n def load_frozenset(self):\n items=self.pop_mark()\n self.append(frozenset(items))\n dispatch[FROZENSET[0]]=load_frozenset\n \n def load_list(self):\n items=self.pop_mark()\n self.append(items)\n dispatch[LIST[0]]=load_list\n \n def load_dict(self):\n items=self.pop_mark()\n d={items[i]:items[i+1]\n for i in range(0,len(items),2)}\n self.append(d)\n dispatch[DICT[0]]=load_dict\n \n \n \n \n \n \n def _instantiate(self,klass,args):\n if(args or not isinstance(klass,type)or\n hasattr(klass,\"__getinitargs__\")):\n try:\n value=klass(*args)\n except TypeError as err:\n raise TypeError(\"in constructor for %s: %s\"%\n (klass.__name__,str(err)),err.__traceback__)\n else:\n value=klass.__new__(klass)\n self.append(value)\n \n def load_inst(self):\n module=self.readline()[:-1].decode(\"ascii\")\n name=self.readline()[:-1].decode(\"ascii\")\n klass=self.find_class(module,name)\n self._instantiate(klass,self.pop_mark())\n dispatch[INST[0]]=load_inst\n \n def load_obj(self):\n \n args=self.pop_mark()\n cls=args.pop(0)\n self._instantiate(cls,args)\n dispatch[OBJ[0]]=load_obj\n \n def load_newobj(self):\n args=self.stack.pop()\n cls=self.stack.pop()\n obj=cls.__new__(cls,*args)\n self.append(obj)\n dispatch[NEWOBJ[0]]=load_newobj\n \n def load_newobj_ex(self):\n kwargs=self.stack.pop()\n args=self.stack.pop()\n cls=self.stack.pop()\n obj=cls.__new__(cls,*args,**kwargs)\n self.append(obj)\n dispatch[NEWOBJ_EX[0]]=load_newobj_ex\n \n def load_global(self):\n module=self.readline()[:-1].decode(\"utf-8\")\n name=self.readline()[:-1].decode(\"utf-8\")\n klass=self.find_class(module,name)\n self.append(klass)\n dispatch[GLOBAL[0]]=load_global\n \n def load_stack_global(self):\n name=self.stack.pop()\n module=self.stack.pop()\n if type(name)is not str or type(module)is not str:\n raise UnpicklingError(\"STACK_GLOBAL requires str\")\n self.append(self.find_class(module,name))\n dispatch[STACK_GLOBAL[0]]=load_stack_global\n \n def load_ext1(self):\n code=self.read(1)[0]\n self.get_extension(code)\n dispatch[EXT1[0]]=load_ext1\n \n def load_ext2(self):\n code,=unpack('=4:\n return _getattribute(sys.modules[module],name)[0]\n else:\n return getattr(sys.modules[module],name)\n \n def load_reduce(self):\n stack=self.stack\n args=stack.pop()\n func=stack[-1]\n stack[-1]=func(*args)\n dispatch[REDUCE[0]]=load_reduce\n \n def load_pop(self):\n if self.stack:\n del self.stack[-1]\n else:\n self.pop_mark()\n dispatch[POP[0]]=load_pop\n \n def load_pop_mark(self):\n self.pop_mark()\n dispatch[POP_MARK[0]]=load_pop_mark\n \n def load_dup(self):\n self.append(self.stack[-1])\n dispatch[DUP[0]]=load_dup\n \n def load_get(self):\n i=int(self.readline()[:-1])\n try:\n self.append(self.memo[i])\n except KeyError:\n msg=f'Memo value not found at index {i}'\n raise UnpicklingError(msg)from None\n dispatch[GET[0]]=load_get\n \n def load_binget(self):\n i=self.read(1)[0]\n try:\n self.append(self.memo[i])\n except KeyError as exc:\n msg=f'Memo value not found at index {i}'\n raise UnpicklingError(msg)from None\n dispatch[BINGET[0]]=load_binget\n \n def load_long_binget(self):\n i,=unpack('maxsize:\n raise ValueError(\"negative LONG_BINPUT argument\")\n self.memo[i]=self.stack[-1]\n dispatch[LONG_BINPUT[0]]=load_long_binput\n \n def load_memoize(self):\n memo=self.memo\n memo[len(memo)]=self.stack[-1]\n dispatch[MEMOIZE[0]]=load_memoize\n \n def load_append(self):\n stack=self.stack\n value=stack.pop()\n list=stack[-1]\n list.append(value)\n dispatch[APPEND[0]]=load_append\n \n def load_appends(self):\n items=self.pop_mark()\n list_obj=self.stack[-1]\n try:\n extend=list_obj.extend\n except AttributeError:\n pass\n else:\n extend(items)\n return\n \n \n \n append=list_obj.append\n for item in items:\n append(item)\n dispatch[APPENDS[0]]=load_appends\n \n def load_setitem(self):\n stack=self.stack\n value=stack.pop()\n key=stack.pop()\n dict=stack[-1]\n dict[key]=value\n dispatch[SETITEM[0]]=load_setitem\n \n def load_setitems(self):\n items=self.pop_mark()\n dict=self.stack[-1]\n for i in range(0,len(items),2):\n dict[items[i]]=items[i+1]\n dispatch[SETITEMS[0]]=load_setitems\n \n def load_additems(self):\n items=self.pop_mark()\n set_obj=self.stack[-1]\n if isinstance(set_obj,set):\n set_obj.update(items)\n else:\n add=set_obj.add\n for item in items:\n add(item)\n dispatch[ADDITEMS[0]]=load_additems\n \n def load_build(self):\n stack=self.stack\n state=stack.pop()\n inst=stack[-1]\n setstate=getattr(inst,\"__setstate__\",_NoValue)\n if setstate is not _NoValue:\n setstate(state)\n return\n slotstate=None\n if isinstance(state,tuple)and len(state)==2:\n state,slotstate=state\n if state:\n inst_dict=inst.__dict__\n intern=sys.intern\n for k,v in state.items():\n if type(k)is str:\n inst_dict[intern(k)]=v\n else:\n inst_dict[k]=v\n if slotstate:\n for k,v in slotstate.items():\n setattr(inst,k,v)\n dispatch[BUILD[0]]=load_build\n \n def load_mark(self):\n self.metastack.append(self.stack)\n self.stack=[]\n self.append=self.stack.append\n dispatch[MARK[0]]=load_mark\n \n def load_stop(self):\n value=self.stack.pop()\n raise _Stop(value)\n dispatch[STOP[0]]=load_stop\n \n \n \n \ndef _dump(obj,file,protocol=None,*,fix_imports=True,buffer_callback=None):\n _Pickler(file,protocol,fix_imports=fix_imports,\n buffer_callback=buffer_callback).dump(obj)\n \ndef _dumps(obj,protocol=None,*,fix_imports=True,buffer_callback=None):\n f=io.BytesIO()\n _Pickler(f,protocol,fix_imports=fix_imports,\n buffer_callback=buffer_callback).dump(obj)\n res=f.getvalue()\n assert isinstance(res,bytes_types)\n return res\n \ndef _load(file,*,fix_imports=True,encoding=\"ASCII\",errors=\"strict\",\nbuffers=None):\n return _Unpickler(file,fix_imports=fix_imports,buffers=buffers,\n encoding=encoding,errors=errors).load()\n \ndef _loads(s,/,*,fix_imports=True,encoding=\"ASCII\",errors=\"strict\",\nbuffers=None):\n if isinstance(s,str):\n raise TypeError(\"Can't load pickle from unicode string\")\n file=io.BytesIO(s)\n return _Unpickler(file,fix_imports=fix_imports,buffers=buffers,\n encoding=encoding,errors=errors).load()\n \n \ntry:\n from _pickle import(\n PickleError,\n PicklingError,\n UnpicklingError,\n Pickler,\n Unpickler,\n dump,\n dumps,\n load,\n loads\n )\nexcept ImportError:\n Pickler,Unpickler=_Pickler,_Unpickler\n dump,dumps,load,loads=_dump,_dumps,_load,_loads\n \n \ndef _test():\n import doctest\n return doctest.testmod()\n \nif __name__ ==\"__main__\":\n import argparse\n parser=argparse.ArgumentParser(\n description='display contents of the pickle files')\n parser.add_argument(\n 'pickle_file',\n nargs='*',help='the pickle file')\n parser.add_argument(\n '-t','--test',action='store_true',\n help='run self-test suite')\n parser.add_argument(\n '-v',action='store_true',\n help='run verbosely; only affects self-test run')\n args=parser.parse_args()\n if args.test:\n _test()\n else:\n if not args.pickle_file:\n parser.print_help()\n else:\n import pprint\n for fn in args.pickle_file:\n if fn =='-':\n obj=load(sys.stdin.buffer)\n else:\n with open(fn,'rb')as f:\n obj=load(f)\n pprint.pprint(obj)\n", ["_compat_pickle", "_pickle", "argparse", "codecs", "copyreg", "doctest", "functools", "io", "itertools", "pprint", "re", "struct", "sys", "types"]], "pkgutil": [".py", "''\n\nfrom collections import namedtuple\nfrom functools import singledispatch as simplegeneric\nimport importlib\nimport importlib.util\nimport importlib.machinery\nimport os\nimport os.path\nimport sys\nfrom types import ModuleType\nimport warnings\n\n__all__=[\n'get_importer','iter_importers','get_loader','find_loader',\n'walk_packages','iter_modules','get_data',\n'read_code','extend_path',\n'ModuleInfo',\n]\n\n\nModuleInfo=namedtuple('ModuleInfo','module_finder name ispkg')\nModuleInfo.__doc__='A namedtuple with minimal info about a module.'\n\n\ndef read_code(stream):\n\n\n import marshal\n \n magic=stream.read(4)\n if magic !=importlib.util.MAGIC_NUMBER:\n return None\n \n stream.read(12)\n return marshal.load(stream)\n \n \ndef walk_packages(path=None,prefix='',onerror=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def seen(p,m={}):\n if p in m:\n return True\n m[p]=True\n \n for info in iter_modules(path,prefix):\n yield info\n \n if info.ispkg:\n try:\n __import__(info.name)\n except ImportError:\n if onerror is not None:\n onerror(info.name)\n except Exception:\n if onerror is not None:\n onerror(info.name)\n else:\n raise\n else:\n path=getattr(sys.modules[info.name],'__path__',None)or[]\n \n \n path=[p for p in path if not seen(p)]\n \n yield from walk_packages(path,info.name+'.',onerror)\n \n \ndef iter_modules(path=None,prefix=''):\n ''\n\n\n\n\n\n\n\n \n if path is None:\n importers=iter_importers()\n elif isinstance(path,str):\n raise ValueError(\"path must be None or list of paths to look for \"\n \"modules in\")\n else:\n importers=map(get_importer,path)\n \n yielded={}\n for i in importers:\n for name,ispkg in iter_importer_modules(i,prefix):\n if name not in yielded:\n yielded[name]=1\n yield ModuleInfo(i,name,ispkg)\n \n \n@simplegeneric\ndef iter_importer_modules(importer,prefix=''):\n if not hasattr(importer,'iter_modules'):\n return[]\n return importer.iter_modules(prefix)\n \n \n \ndef _iter_file_finder_modules(importer,prefix=''):\n if importer.path is None or not os.path.isdir(importer.path):\n return\n \n yielded={}\n import inspect\n try:\n filenames=os.listdir(importer.path)\n except OSError:\n \n filenames=[]\n filenames.sort()\n \n for fn in filenames:\n modname=inspect.getmodulename(fn)\n if modname =='__init__'or modname in yielded:\n continue\n \n path=os.path.join(importer.path,fn)\n ispkg=False\n \n if not modname and os.path.isdir(path)and '.'not in fn:\n modname=fn\n try:\n dircontents=os.listdir(path)\n except OSError:\n \n dircontents=[]\n for fn in dircontents:\n subname=inspect.getmodulename(fn)\n if subname =='__init__':\n ispkg=True\n break\n else:\n continue\n \n if modname and '.'not in modname:\n yielded[modname]=1\n yield prefix+modname,ispkg\n \niter_importer_modules.register(\nimportlib.machinery.FileFinder,_iter_file_finder_modules)\n\n\ntry:\n import zipimport\n from zipimport import zipimporter\n \n def iter_zipimport_modules(importer,prefix=''):\n dirlist=sorted(zipimport._zip_directory_cache[importer.archive])\n _prefix=importer.prefix\n plen=len(_prefix)\n yielded={}\n import inspect\n for fn in dirlist:\n if not fn.startswith(_prefix):\n continue\n \n fn=fn[plen:].split(os.sep)\n \n if len(fn)==2 and fn[1].startswith('__init__.py'):\n if fn[0]not in yielded:\n yielded[fn[0]]=1\n yield prefix+fn[0],True\n \n if len(fn)!=1:\n continue\n \n modname=inspect.getmodulename(fn[0])\n if modname =='__init__':\n continue\n \n if modname and '.'not in modname and modname not in yielded:\n yielded[modname]=1\n yield prefix+modname,False\n \n iter_importer_modules.register(zipimporter,iter_zipimport_modules)\n \nexcept ImportError:\n pass\n \n \ndef get_importer(path_item):\n ''\n\n\n\n\n\n\n \n path_item=os.fsdecode(path_item)\n try:\n importer=sys.path_importer_cache[path_item]\n except KeyError:\n for path_hook in sys.path_hooks:\n try:\n importer=path_hook(path_item)\n sys.path_importer_cache.setdefault(path_item,importer)\n break\n except ImportError:\n pass\n else:\n importer=None\n return importer\n \n \ndef iter_importers(fullname=\"\"):\n ''\n\n\n\n\n\n\n\n\n\n \n if fullname.startswith('.'):\n msg=\"Relative module name {!r} not supported\".format(fullname)\n raise ImportError(msg)\n if '.'in fullname:\n \n pkg_name=fullname.rpartition(\".\")[0]\n pkg=importlib.import_module(pkg_name)\n path=getattr(pkg,'__path__',None)\n if path is None:\n return\n else:\n yield from sys.meta_path\n path=sys.path\n for item in path:\n yield get_importer(item)\n \n \ndef get_loader(module_or_name):\n ''\n\n\n\n\n \n warnings._deprecated(\"pkgutil.get_loader\",\n f\"{warnings._DEPRECATED_MSG}; \"\n \"use importlib.util.find_spec() instead\",\n remove=(3,14))\n if module_or_name in sys.modules:\n module_or_name=sys.modules[module_or_name]\n if module_or_name is None:\n return None\n if isinstance(module_or_name,ModuleType):\n module=module_or_name\n loader=getattr(module,'__loader__',None)\n if loader is not None:\n return loader\n if getattr(module,'__spec__',None)is None:\n return None\n fullname=module.__name__\n else:\n fullname=module_or_name\n return find_loader(fullname)\n \n \ndef find_loader(fullname):\n ''\n\n\n\n\n \n warnings._deprecated(\"pkgutil.find_loader\",\n f\"{warnings._DEPRECATED_MSG}; \"\n \"use importlib.util.find_spec() instead\",\n remove=(3,14))\n if fullname.startswith('.'):\n msg=\"Relative module name {!r} not supported\".format(fullname)\n raise ImportError(msg)\n try:\n spec=importlib.util.find_spec(fullname)\n except(ImportError,AttributeError,TypeError,ValueError)as ex:\n \n \n \n msg=\"Error while finding loader for {!r} ({}: {})\"\n raise ImportError(msg.format(fullname,type(ex),ex))from ex\n return spec.loader if spec is not None else None\n \n \ndef extend_path(path,name):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not isinstance(path,list):\n \n \n return path\n \n sname_pkg=name+\".pkg\"\n \n path=path[:]\n \n parent_package,_,final_name=name.rpartition('.')\n if parent_package:\n try:\n search_path=sys.modules[parent_package].__path__\n except(KeyError,AttributeError):\n \n \n return path\n else:\n search_path=sys.path\n \n for dir in search_path:\n if not isinstance(dir,str):\n continue\n \n finder=get_importer(dir)\n if finder is not None:\n portions=[]\n if hasattr(finder,'find_spec'):\n spec=finder.find_spec(final_name)\n if spec is not None:\n portions=spec.submodule_search_locations or[]\n \n elif hasattr(finder,'find_loader'):\n _,portions=finder.find_loader(final_name)\n \n for portion in portions:\n \n \n if portion not in path:\n path.append(portion)\n \n \n \n pkgfile=os.path.join(dir,sname_pkg)\n if os.path.isfile(pkgfile):\n try:\n f=open(pkgfile)\n except OSError as msg:\n sys.stderr.write(\"Can't open %s: %s\\n\"%\n (pkgfile,msg))\n else:\n with f:\n for line in f:\n line=line.rstrip('\\n')\n if not line or line.startswith('#'):\n continue\n path.append(line)\n \n return path\n \n \ndef get_data(package,resource):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n spec=importlib.util.find_spec(package)\n if spec is None:\n return None\n loader=spec.loader\n if loader is None or not hasattr(loader,'get_data'):\n return None\n \n mod=(sys.modules.get(package)or\n importlib._bootstrap._load(spec))\n if mod is None or not hasattr(mod,'__file__'):\n return None\n \n \n \n \n parts=resource.split('/')\n parts.insert(0,os.path.dirname(mod.__file__))\n resource_name=os.path.join(*parts)\n return loader.get_data(resource_name)\n \n \n_NAME_PATTERN=None\n\ndef resolve_name(name):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _NAME_PATTERN\n if _NAME_PATTERN is None:\n \n import re\n dotted_words=r'(?!\\d)(\\w+)(\\.(?!\\d)(\\w+))*'\n _NAME_PATTERN=re.compile(f'^(?P{dotted_words})'\n f'(?P:(?P{dotted_words})?)?$',\n re.UNICODE)\n \n m=_NAME_PATTERN.match(name)\n if not m:\n raise ValueError(f'invalid format: {name !r}')\n gd=m.groupdict()\n if gd.get('cln'):\n \n mod=importlib.import_module(gd['pkg'])\n parts=gd.get('obj')\n parts=parts.split('.')if parts else[]\n else:\n \n parts=name.split('.')\n modname=parts.pop(0)\n \n mod=importlib.import_module(modname)\n while parts:\n p=parts[0]\n s=f'{modname}.{p}'\n try:\n mod=importlib.import_module(s)\n parts.pop(0)\n modname=s\n except ImportError:\n break\n \n \n \n result=mod\n for p in parts:\n result=getattr(result,p)\n return result\n", ["collections", "functools", "importlib", "importlib.machinery", "importlib.util", "inspect", "marshal", "os", "os.path", "re", "sys", "types", "warnings", "zipimport"]], "platform": [".py", "''\n\n\n\nfrom browser import self as window\n\ndef architecture(*args,**kw):\n return \"\",window.navigator.platform\n \ndef machine(*args,**kw):\n return ''\n \ndef node(*args,**kw):\n return ''\n \ndef platform(*args,**kw):\n return window.navigator.platform\n \ndef processor(*args,**kw):\n return ''\n \ndef python_build():\n return('.'.join(map(str,__BRYTHON__.implementation[:-1])),\n __BRYTHON__.compiled_date)\n \ndef python_compiler():\n return ''\n \ndef python_branch():\n return ''\n \ndef python_implementation():\n return 'Brython'\n \ndef python_revision():\n return ''\n \ndef python_version():\n return '.'.join(map(str,__BRYTHON__.version_info[:3]))\n \ndef python_version_tuple():\n return __BRYTHON__.version_info[:3]\n \ndef release():\n return ''\n \ndef system():\n return window.navigator.platform\n \ndef system_alias(*args,**kw):\n return window.navigator.platform\n \ndef uname():\n from collections import namedtuple\n klass=namedtuple('uname_result',\n 'system node release version machine processor')\n return klass(window.navigator.platform,'','','','','')\n", ["browser", "collections"]], "posixpath": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ncurdir='.'\npardir='..'\nextsep='.'\nsep='/'\npathsep=':'\ndefpath='/bin:/usr/bin'\naltsep=None\ndevnull='/dev/null'\n\nimport os\nimport sys\nimport stat\nimport genericpath\nfrom genericpath import *\n\n__all__=[\"normcase\",\"isabs\",\"join\",\"splitdrive\",\"splitroot\",\"split\",\"splitext\",\n\"basename\",\"dirname\",\"commonprefix\",\"getsize\",\"getmtime\",\n\"getatime\",\"getctime\",\"islink\",\"exists\",\"lexists\",\"isdir\",\"isfile\",\n\"ismount\",\"expanduser\",\"expandvars\",\"normpath\",\"abspath\",\n\"samefile\",\"sameopenfile\",\"samestat\",\n\"curdir\",\"pardir\",\"sep\",\"pathsep\",\"defpath\",\"altsep\",\"extsep\",\n\"devnull\",\"realpath\",\"supports_unicode_filenames\",\"relpath\",\n\"commonpath\",\"isjunction\"]\n\n\ndef _get_sep(path):\n if isinstance(path,bytes):\n return b'/'\n else:\n return '/'\n \n \n \n \n \n \ndef normcase(s):\n ''\n return os.fspath(s)\n \n \n \n \n \ndef isabs(s):\n ''\n s=os.fspath(s)\n sep=_get_sep(s)\n return s.startswith(sep)\n \n \n \n \n \n \ndef join(a,*p):\n ''\n\n\n \n a=os.fspath(a)\n sep=_get_sep(a)\n path=a\n try:\n if not p:\n path[:0]+sep\n for b in map(os.fspath,p):\n if b.startswith(sep):\n path=b\n elif not path or path.endswith(sep):\n path +=b\n else:\n path +=sep+b\n except(TypeError,AttributeError,BytesWarning):\n genericpath._check_arg_types('join',a,*p)\n raise\n return path\n \n \n \n \n \n \n \ndef split(p):\n ''\n \n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n head,tail=p[:i],p[i:]\n if head and head !=sep *len(head):\n head=head.rstrip(sep)\n return head,tail\n \n \n \n \n \n \n \ndef splitext(p):\n p=os.fspath(p)\n if isinstance(p,bytes):\n sep=b'/'\n extsep=b'.'\n else:\n sep='/'\n extsep='.'\n return genericpath._splitext(p,sep,None,extsep)\nsplitext.__doc__=genericpath._splitext.__doc__\n\n\n\n\ndef splitdrive(p):\n ''\n \n p=os.fspath(p)\n return p[:0],p\n \n \ndef splitroot(p):\n ''\n\n\n\n\n\n\n\n \n p=os.fspath(p)\n if isinstance(p,bytes):\n sep=b'/'\n empty=b''\n else:\n sep='/'\n empty=''\n if p[:1]!=sep:\n \n return empty,empty,p\n elif p[1:2]!=sep or p[2:3]==sep:\n \n return empty,sep,p[1:]\n else:\n \n \n return empty,p[:2],p[2:]\n \n \n \n \ndef basename(p):\n ''\n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n return p[i:]\n \n \n \n \ndef dirname(p):\n ''\n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n head=p[:i]\n if head and head !=sep *len(head):\n head=head.rstrip(sep)\n return head\n \n \n \n \ndef isjunction(path):\n ''\n \n os.fspath(path)\n return False\n \n \n \n \ndef lexists(path):\n ''\n try:\n os.lstat(path)\n except(OSError,ValueError):\n return False\n return True\n \n \n \n \n \ndef ismount(path):\n ''\n try:\n s1=os.lstat(path)\n except(OSError,ValueError):\n \n return False\n else:\n \n if stat.S_ISLNK(s1.st_mode):\n return False\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n parent=join(path,b'..')\n else:\n parent=join(path,'..')\n parent=realpath(parent)\n try:\n s2=os.lstat(parent)\n except(OSError,ValueError):\n return False\n \n dev1=s1.st_dev\n dev2=s2.st_dev\n if dev1 !=dev2:\n return True\n ino1=s1.st_ino\n ino2=s2.st_ino\n if ino1 ==ino2:\n return True\n return False\n \n \n \n \n \n \n \n \n \n \n \ndef expanduser(path):\n ''\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n tilde=b'~'\n else:\n tilde='~'\n if not path.startswith(tilde):\n return path\n sep=_get_sep(path)\n i=path.find(sep,1)\n if i <0:\n i=len(path)\n if i ==1:\n if 'HOME'not in os.environ:\n try:\n import pwd\n except ImportError:\n \n return path\n try:\n userhome=pwd.getpwuid(os.getuid()).pw_dir\n except KeyError:\n \n \n return path\n else:\n userhome=os.environ['HOME']\n else:\n try:\n import pwd\n except ImportError:\n \n return path\n name=path[1:i]\n if isinstance(name,bytes):\n name=str(name,'ASCII')\n try:\n pwent=pwd.getpwnam(name)\n except KeyError:\n \n \n return path\n userhome=pwent.pw_dir\n \n if userhome is None and sys.platform ==\"vxworks\":\n return path\n if isinstance(path,bytes):\n userhome=os.fsencode(userhome)\n root=b'/'\n else:\n root='/'\n userhome=userhome.rstrip(root)\n return(userhome+path[i:])or root\n \n \n \n \n \n \n_varprog=None\n_varprogb=None\n\ndef expandvars(path):\n ''\n \n path=os.fspath(path)\n global _varprog,_varprogb\n if isinstance(path,bytes):\n if b'$'not in path:\n return path\n if not _varprogb:\n import re\n _varprogb=re.compile(br'\\$(\\w+|\\{[^}]*\\})',re.ASCII)\n search=_varprogb.search\n start=b'{'\n end=b'}'\n environ=getattr(os,'environb',None)\n else:\n if '$'not in path:\n return path\n if not _varprog:\n import re\n _varprog=re.compile(r'\\$(\\w+|\\{[^}]*\\})',re.ASCII)\n search=_varprog.search\n start='{'\n end='}'\n environ=os.environ\n i=0\n while True:\n m=search(path,i)\n if not m:\n break\n i,j=m.span(0)\n name=m.group(1)\n if name.startswith(start)and name.endswith(end):\n name=name[1:-1]\n try:\n if environ is None:\n value=os.fsencode(os.environ[os.fsdecode(name)])\n else:\n value=environ[name]\n except KeyError:\n i=j\n else:\n tail=path[j:]\n path=path[:i]+value\n i=len(path)\n path +=tail\n return path\n \n \n \n \n \n \ntry:\n from posix import _path_normpath\n \nexcept ImportError:\n def normpath(path):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n sep=b'/'\n empty=b''\n dot=b'.'\n dotdot=b'..'\n else:\n sep='/'\n empty=''\n dot='.'\n dotdot='..'\n if path ==empty:\n return dot\n _,initial_slashes,path=splitroot(path)\n comps=path.split(sep)\n new_comps=[]\n for comp in comps:\n if comp in(empty,dot):\n continue\n if(comp !=dotdot or(not initial_slashes and not new_comps)or\n (new_comps and new_comps[-1]==dotdot)):\n new_comps.append(comp)\n elif new_comps:\n new_comps.pop()\n comps=new_comps\n path=initial_slashes+sep.join(comps)\n return path or dot\n \nelse:\n def normpath(path):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n return os.fsencode(_path_normpath(os.fsdecode(path)))or b\".\"\n return _path_normpath(path)or \".\"\n \n \ndef abspath(path):\n ''\n path=os.fspath(path)\n if not isabs(path):\n if isinstance(path,bytes):\n cwd=os.getcwdb()\n else:\n cwd=os.getcwd()\n path=join(cwd,path)\n return normpath(path)\n \n \n \n \n \ndef realpath(filename,*,strict=False):\n ''\n \n filename=os.fspath(filename)\n path,ok=_joinrealpath(filename[:0],filename,strict,{})\n return abspath(path)\n \n \n \ndef _joinrealpath(path,rest,strict,seen):\n if isinstance(path,bytes):\n sep=b'/'\n curdir=b'.'\n pardir=b'..'\n else:\n sep='/'\n curdir='.'\n pardir='..'\n \n if isabs(rest):\n rest=rest[1:]\n path=sep\n \n while rest:\n name,_,rest=rest.partition(sep)\n if not name or name ==curdir:\n \n continue\n if name ==pardir:\n \n if path:\n path,name=split(path)\n if name ==pardir:\n path=join(path,pardir,pardir)\n else:\n path=pardir\n continue\n newpath=join(path,name)\n try:\n st=os.lstat(newpath)\n except OSError:\n if strict:\n raise\n is_link=False\n else:\n is_link=stat.S_ISLNK(st.st_mode)\n if not is_link:\n path=newpath\n continue\n \n if newpath in seen:\n \n path=seen[newpath]\n if path is not None:\n \n continue\n \n if strict:\n \n os.stat(newpath)\n else:\n \n return join(newpath,rest),False\n seen[newpath]=None\n path,ok=_joinrealpath(path,os.readlink(newpath),strict,seen)\n if not ok:\n return join(path,rest),False\n seen[newpath]=path\n \n return path,True\n \n \nsupports_unicode_filenames=(sys.platform =='darwin')\n\ndef relpath(path,start=None):\n ''\n \n if not path:\n raise ValueError(\"no path specified\")\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n curdir=b'.'\n sep=b'/'\n pardir=b'..'\n else:\n curdir='.'\n sep='/'\n pardir='..'\n \n if start is None:\n start=curdir\n else:\n start=os.fspath(start)\n \n try:\n start_list=[x for x in abspath(start).split(sep)if x]\n path_list=[x for x in abspath(path).split(sep)if x]\n \n i=len(commonprefix([start_list,path_list]))\n \n rel_list=[pardir]*(len(start_list)-i)+path_list[i:]\n if not rel_list:\n return curdir\n return join(*rel_list)\n except(TypeError,AttributeError,BytesWarning,DeprecationWarning):\n genericpath._check_arg_types('relpath',path,start)\n raise\n \n \n \n \n \n \n \ndef commonpath(paths):\n ''\n \n if not paths:\n raise ValueError('commonpath() arg is an empty sequence')\n \n paths=tuple(map(os.fspath,paths))\n if isinstance(paths[0],bytes):\n sep=b'/'\n curdir=b'.'\n else:\n sep='/'\n curdir='.'\n \n try:\n split_paths=[path.split(sep)for path in paths]\n \n try:\n isabs,=set(p[:1]==sep for p in paths)\n except ValueError:\n raise ValueError(\"Can't mix absolute and relative paths\")from None\n \n split_paths=[[c for c in s if c and c !=curdir]for s in split_paths]\n s1=min(split_paths)\n s2=max(split_paths)\n common=s1\n for i,c in enumerate(s1):\n if c !=s2[i]:\n common=s1[:i]\n break\n \n prefix=sep if isabs else sep[:0]\n return prefix+sep.join(common)\n except(TypeError,AttributeError):\n genericpath._check_arg_types('commonpath',*paths)\n raise\n \n", ["genericpath", "os", "posix", "pwd", "re", "stat", "sys"]], "pprint": [".py", "\n\n\n\n\n\n\n\n\n\n\"\"\"Support to pretty-print lists, tuples, & dictionaries recursively.\n\nVery simple, but useful, especially in debugging data structures.\n\nClasses\n-------\n\nPrettyPrinter()\n Handle pretty-printing operations onto a stream using a configured\n set of formatting parameters.\n\nFunctions\n---------\n\npformat()\n Format a Python object into a pretty-printed representation.\n\npprint()\n Pretty-print a Python object to a stream [default is sys.stdout].\n\nsaferepr()\n Generate a 'standard' repr()-like value, but protect against recursive\n data structures.\n\n\"\"\"\n\nimport collections as _collections\nimport dataclasses as _dataclasses\nimport re\nimport sys as _sys\nimport types as _types\nfrom io import StringIO as _StringIO\n\n__all__=[\"pprint\",\"pformat\",\"isreadable\",\"isrecursive\",\"saferepr\",\n\"PrettyPrinter\",\"pp\"]\n\n\ndef pprint(object,stream=None,indent=1,width=80,depth=None,*,\ncompact=False,sort_dicts=True,underscore_numbers=False):\n ''\n printer=PrettyPrinter(\n stream=stream,indent=indent,width=width,depth=depth,\n compact=compact,sort_dicts=sort_dicts,\n underscore_numbers=underscore_numbers)\n printer.pprint(object)\n \ndef pformat(object,indent=1,width=80,depth=None,*,\ncompact=False,sort_dicts=True,underscore_numbers=False):\n ''\n return PrettyPrinter(indent=indent,width=width,depth=depth,\n compact=compact,sort_dicts=sort_dicts,\n underscore_numbers=underscore_numbers).pformat(object)\n \ndef pp(object,*args,sort_dicts=False,**kwargs):\n ''\n pprint(object,*args,sort_dicts=sort_dicts,**kwargs)\n \ndef saferepr(object):\n ''\n return PrettyPrinter()._safe_repr(object,{},None,0)[0]\n \ndef isreadable(object):\n ''\n return PrettyPrinter()._safe_repr(object,{},None,0)[1]\n \ndef isrecursive(object):\n ''\n return PrettyPrinter()._safe_repr(object,{},None,0)[2]\n \nclass _safe_key:\n ''\n\n\n\n\n\n\n \n \n __slots__=['obj']\n \n def __init__(self,obj):\n self.obj=obj\n \n def __lt__(self,other):\n try:\n return self.obj = 0')\n if depth is not None and depth <=0:\n raise ValueError('depth must be > 0')\n if not width:\n raise ValueError('width must be != 0')\n self._depth=depth\n self._indent_per_level=indent\n self._width=width\n if stream is not None:\n self._stream=stream\n else:\n self._stream=_sys.stdout\n self._compact=bool(compact)\n self._sort_dicts=sort_dicts\n self._underscore_numbers=underscore_numbers\n \n def pprint(self,object):\n if self._stream is not None:\n self._format(object,self._stream,0,0,{},0)\n self._stream.write(\"\\n\")\n \n def pformat(self,object):\n sio=_StringIO()\n self._format(object,sio,0,0,{},0)\n return sio.getvalue()\n \n def isrecursive(self,object):\n return self.format(object,{},0,0)[2]\n \n def isreadable(self,object):\n s,readable,recursive=self.format(object,{},0,0)\n return readable and not recursive\n \n def _format(self,object,stream,indent,allowance,context,level):\n objid=id(object)\n if objid in context:\n stream.write(_recursion(object))\n self._recursive=True\n self._readable=False\n return\n rep=self._repr(object,context,level)\n max_width=self._width -indent -allowance\n if len(rep)>max_width:\n p=self._dispatch.get(type(object).__repr__,None)\n if p is not None:\n context[objid]=1\n p(self,object,stream,indent,allowance,context,level+1)\n del context[objid]\n return\n elif(_dataclasses.is_dataclass(object)and\n not isinstance(object,type)and\n object.__dataclass_params__.repr and\n \n hasattr(object.__repr__,\"__wrapped__\")and\n \"__create_fn__\"in object.__repr__.__wrapped__.__qualname__):\n context[objid]=1\n self._pprint_dataclass(object,stream,indent,allowance,context,level+1)\n del context[objid]\n return\n stream.write(rep)\n \n def _pprint_dataclass(self,object,stream,indent,allowance,context,level):\n cls_name=object.__class__.__name__\n indent +=len(cls_name)+1\n items=[(f.name,getattr(object,f.name))for f in _dataclasses.fields(object)if f.repr]\n stream.write(cls_name+'(')\n self._format_namespace_items(items,stream,indent,allowance,context,level)\n stream.write(')')\n \n _dispatch={}\n \n def _pprint_dict(self,object,stream,indent,allowance,context,level):\n write=stream.write\n write('{')\n if self._indent_per_level >1:\n write((self._indent_per_level -1)*' ')\n length=len(object)\n if length:\n if self._sort_dicts:\n items=sorted(object.items(),key=_safe_tuple)\n else:\n items=object.items()\n self._format_dict_items(items,stream,indent,allowance+1,\n context,level)\n write('}')\n \n _dispatch[dict.__repr__]=_pprint_dict\n \n def _pprint_ordered_dict(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n self._format(list(object.items()),stream,\n indent+len(cls.__name__)+1,allowance+1,\n context,level)\n stream.write(')')\n \n _dispatch[_collections.OrderedDict.__repr__]=_pprint_ordered_dict\n \n def _pprint_list(self,object,stream,indent,allowance,context,level):\n stream.write('[')\n self._format_items(object,stream,indent,allowance+1,\n context,level)\n stream.write(']')\n \n _dispatch[list.__repr__]=_pprint_list\n \n def _pprint_tuple(self,object,stream,indent,allowance,context,level):\n stream.write('(')\n endchar=',)'if len(object)==1 else ')'\n self._format_items(object,stream,indent,allowance+len(endchar),\n context,level)\n stream.write(endchar)\n \n _dispatch[tuple.__repr__]=_pprint_tuple\n \n def _pprint_set(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n typ=object.__class__\n if typ is set:\n stream.write('{')\n endchar='}'\n else:\n stream.write(typ.__name__+'({')\n endchar='})'\n indent +=len(typ.__name__)+1\n object=sorted(object,key=_safe_key)\n self._format_items(object,stream,indent,allowance+len(endchar),\n context,level)\n stream.write(endchar)\n \n _dispatch[set.__repr__]=_pprint_set\n _dispatch[frozenset.__repr__]=_pprint_set\n \n def _pprint_str(self,object,stream,indent,allowance,context,level):\n write=stream.write\n if not len(object):\n write(repr(object))\n return\n chunks=[]\n lines=object.splitlines(True)\n if level ==1:\n indent +=1\n allowance +=1\n max_width1=max_width=self._width -indent\n for i,line in enumerate(lines):\n rep=repr(line)\n if i ==len(lines)-1:\n max_width1 -=allowance\n if len(rep)<=max_width1:\n chunks.append(rep)\n else:\n \n parts=re.findall(r'\\S*\\s*',line)\n assert parts\n assert not parts[-1]\n parts.pop()\n max_width2=max_width\n current=''\n for j,part in enumerate(parts):\n candidate=current+part\n if j ==len(parts)-1 and i ==len(lines)-1:\n max_width2 -=allowance\n if len(repr(candidate))>max_width2:\n if current:\n chunks.append(repr(current))\n current=part\n else:\n current=candidate\n if current:\n chunks.append(repr(current))\n if len(chunks)==1:\n write(rep)\n return\n if level ==1:\n write('(')\n for i,rep in enumerate(chunks):\n if i >0:\n write('\\n'+' '*indent)\n write(rep)\n if level ==1:\n write(')')\n \n _dispatch[str.__repr__]=_pprint_str\n \n def _pprint_bytes(self,object,stream,indent,allowance,context,level):\n write=stream.write\n if len(object)<=4:\n write(repr(object))\n return\n parens=level ==1\n if parens:\n indent +=1\n allowance +=1\n write('(')\n delim=''\n for rep in _wrap_bytes_repr(object,self._width -indent,allowance):\n write(delim)\n write(rep)\n if not delim:\n delim='\\n'+' '*indent\n if parens:\n write(')')\n \n _dispatch[bytes.__repr__]=_pprint_bytes\n \n def _pprint_bytearray(self,object,stream,indent,allowance,context,level):\n write=stream.write\n write('bytearray(')\n self._pprint_bytes(bytes(object),stream,indent+10,\n allowance+1,context,level+1)\n write(')')\n \n _dispatch[bytearray.__repr__]=_pprint_bytearray\n \n def _pprint_mappingproxy(self,object,stream,indent,allowance,context,level):\n stream.write('mappingproxy(')\n self._format(object.copy(),stream,indent+13,allowance+1,\n context,level)\n stream.write(')')\n \n _dispatch[_types.MappingProxyType.__repr__]=_pprint_mappingproxy\n \n def _pprint_simplenamespace(self,object,stream,indent,allowance,context,level):\n if type(object)is _types.SimpleNamespace:\n \n \n cls_name='namespace'\n else:\n cls_name=object.__class__.__name__\n indent +=len(cls_name)+1\n items=object.__dict__.items()\n stream.write(cls_name+'(')\n self._format_namespace_items(items,stream,indent,allowance,context,level)\n stream.write(')')\n \n _dispatch[_types.SimpleNamespace.__repr__]=_pprint_simplenamespace\n \n def _format_dict_items(self,items,stream,indent,allowance,context,\n level):\n write=stream.write\n indent +=self._indent_per_level\n delimnl=',\\n'+' '*indent\n last_index=len(items)-1\n for i,(key,ent)in enumerate(items):\n last=i ==last_index\n rep=self._repr(key,context,level)\n write(rep)\n write(': ')\n self._format(ent,stream,indent+len(rep)+2,\n allowance if last else 1,\n context,level)\n if not last:\n write(delimnl)\n \n def _format_namespace_items(self,items,stream,indent,allowance,context,level):\n write=stream.write\n delimnl=',\\n'+' '*indent\n last_index=len(items)-1\n for i,(key,ent)in enumerate(items):\n last=i ==last_index\n write(key)\n write('=')\n if id(ent)in context:\n \n \n write(\"...\")\n else:\n self._format(ent,stream,indent+len(key)+1,\n allowance if last else 1,\n context,level)\n if not last:\n write(delimnl)\n \n def _format_items(self,items,stream,indent,allowance,context,level):\n write=stream.write\n indent +=self._indent_per_level\n if self._indent_per_level >1:\n write((self._indent_per_level -1)*' ')\n delimnl=',\\n'+' '*indent\n delim=''\n width=max_width=self._width -indent+1\n it=iter(items)\n try:\n next_ent=next(it)\n except StopIteration:\n return\n last=False\n while not last:\n ent=next_ent\n try:\n next_ent=next(it)\n except StopIteration:\n last=True\n max_width -=allowance\n width -=allowance\n if self._compact:\n rep=self._repr(ent,context,level)\n w=len(rep)+2\n if width =w:\n width -=w\n write(delim)\n delim=', '\n write(rep)\n continue\n write(delim)\n delim=delimnl\n self._format(ent,stream,indent,\n allowance if last else 1,\n context,level)\n \n def _repr(self,object,context,level):\n repr,readable,recursive=self.format(object,context.copy(),\n self._depth,level)\n if not readable:\n self._readable=False\n if recursive:\n self._recursive=True\n return repr\n \n def format(self,object,context,maxlevels,level):\n ''\n\n\n \n return self._safe_repr(object,context,maxlevels,level)\n \n def _pprint_default_dict(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n rdf=self._repr(object.default_factory,context,level)\n cls=object.__class__\n indent +=len(cls.__name__)+1\n stream.write('%s(%s,\\n%s'%(cls.__name__,rdf,' '*indent))\n self._pprint_dict(object,stream,indent,allowance+1,context,level)\n stream.write(')')\n \n _dispatch[_collections.defaultdict.__repr__]=_pprint_default_dict\n \n def _pprint_counter(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'({')\n if self._indent_per_level >1:\n stream.write((self._indent_per_level -1)*' ')\n items=object.most_common()\n self._format_dict_items(items,stream,\n indent+len(cls.__name__)+1,allowance+2,\n context,level)\n stream.write('})')\n \n _dispatch[_collections.Counter.__repr__]=_pprint_counter\n \n def _pprint_chain_map(self,object,stream,indent,allowance,context,level):\n if not len(object.maps):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n indent +=len(cls.__name__)+1\n for i,m in enumerate(object.maps):\n if i ==len(object.maps)-1:\n self._format(m,stream,indent,allowance+1,context,level)\n stream.write(')')\n else:\n self._format(m,stream,indent,1,context,level)\n stream.write(',\\n'+' '*indent)\n \n _dispatch[_collections.ChainMap.__repr__]=_pprint_chain_map\n \n def _pprint_deque(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n indent +=len(cls.__name__)+1\n stream.write('[')\n if object.maxlen is None:\n self._format_items(object,stream,indent,allowance+2,\n context,level)\n stream.write('])')\n else:\n self._format_items(object,stream,indent,2,\n context,level)\n rml=self._repr(object.maxlen,context,level)\n stream.write('],\\n%smaxlen=%s)'%(' '*indent,rml))\n \n _dispatch[_collections.deque.__repr__]=_pprint_deque\n \n def _pprint_user_dict(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserDict.__repr__]=_pprint_user_dict\n \n def _pprint_user_list(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserList.__repr__]=_pprint_user_list\n \n def _pprint_user_string(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserString.__repr__]=_pprint_user_string\n \n def _safe_repr(self,object,context,maxlevels,level):\n \n typ=type(object)\n if typ in _builtin_scalars:\n return repr(object),True,False\n \n r=getattr(typ,\"__repr__\",None)\n \n if issubclass(typ,int)and r is int.__repr__:\n if self._underscore_numbers:\n return f\"{object:_d}\",True,False\n else:\n return repr(object),True,False\n \n if issubclass(typ,dict)and r is dict.__repr__:\n if not object:\n return \"{}\",True,False\n objid=id(object)\n if maxlevels and level >=maxlevels:\n return \"{...}\",False,objid in context\n if objid in context:\n return _recursion(object),False,True\n context[objid]=1\n readable=True\n recursive=False\n components=[]\n append=components.append\n level +=1\n if self._sort_dicts:\n items=sorted(object.items(),key=_safe_tuple)\n else:\n items=object.items()\n for k,v in items:\n krepr,kreadable,krecur=self.format(\n k,context,maxlevels,level)\n vrepr,vreadable,vrecur=self.format(\n v,context,maxlevels,level)\n append(\"%s: %s\"%(krepr,vrepr))\n readable=readable and kreadable and vreadable\n if krecur or vrecur:\n recursive=True\n del context[objid]\n return \"{%s}\"%\", \".join(components),readable,recursive\n \n if(issubclass(typ,list)and r is list.__repr__)or\\\n (issubclass(typ,tuple)and r is tuple.__repr__):\n if issubclass(typ,list):\n if not object:\n return \"[]\",True,False\n format=\"[%s]\"\n elif len(object)==1:\n format=\"(%s,)\"\n else:\n if not object:\n return \"()\",True,False\n format=\"(%s)\"\n objid=id(object)\n if maxlevels and level >=maxlevels:\n return format %\"...\",False,objid in context\n if objid in context:\n return _recursion(object),False,True\n context[objid]=1\n readable=True\n recursive=False\n components=[]\n append=components.append\n level +=1\n for o in object:\n orepr,oreadable,orecur=self.format(\n o,context,maxlevels,level)\n append(orepr)\n if not oreadable:\n readable=False\n if orecur:\n recursive=True\n del context[objid]\n return format %\", \".join(components),readable,recursive\n \n rep=repr(object)\n return rep,(rep and not rep.startswith('<')),False\n \n_builtin_scalars=frozenset({str,bytes,bytearray,float,complex,\nbool,type(None)})\n\ndef _recursion(object):\n return(\"\"\n %(type(object).__name__,id(object)))\n \n \ndef _wrap_bytes_repr(object,width,allowance):\n current=b''\n last=len(object)//4 *4\n for i in range(0,len(object),4):\n part=object[i:i+4]\n candidate=current+part\n if i ==last:\n width -=allowance\n if len(repr(candidate))>width:\n if current:\n yield repr(current)\n current=part\n else:\n current=candidate\n if current:\n yield repr(current)\n", ["collections", "dataclasses", "io", "re", "sys", "types"]], "profile": [".py", "#! /usr/bin/env python3\n\n\n\n\n\n\n\n\"\"\"Class for profiling Python code.\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport importlib.machinery\nimport io\nimport sys\nimport time\nimport marshal\n\n__all__=[\"run\",\"runctx\",\"Profile\"]\n\n\n\n\n\n\n\n\n\nclass _Utils:\n ''\n\n\n \n \n def __init__(self,profiler):\n self.profiler=profiler\n \n def run(self,statement,filename,sort):\n prof=self.profiler()\n try:\n prof.run(statement)\n except SystemExit:\n pass\n finally:\n self._show(prof,filename,sort)\n \n def runctx(self,statement,globals,locals,filename,sort):\n prof=self.profiler()\n try:\n prof.runctx(statement,globals,locals)\n except SystemExit:\n pass\n finally:\n self._show(prof,filename,sort)\n \n def _show(self,prof,filename,sort):\n if filename is not None:\n prof.dump_stats(filename)\n else:\n prof.print_stats(sort)\n \n \n \n \n \n \n \ndef run(statement,filename=None,sort=-1):\n ''\n\n\n\n\n\n\n\n\n \n return _Utils(Profile).run(statement,filename,sort)\n \ndef runctx(statement,globals,locals,filename=None,sort=-1):\n ''\n\n\n\n \n return _Utils(Profile).runctx(statement,globals,locals,filename,sort)\n \n \nclass Profile:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n bias=0\n \n def __init__(self,timer=None,bias=None):\n self.timings={}\n self.cur=None\n self.cmd=\"\"\n self.c_func_name=\"\"\n \n if bias is None:\n bias=self.bias\n self.bias=bias\n \n if not timer:\n self.timer=self.get_time=time.process_time\n self.dispatcher=self.trace_dispatch_i\n else:\n self.timer=timer\n t=self.timer()\n try:\n length=len(t)\n except TypeError:\n self.get_time=timer\n self.dispatcher=self.trace_dispatch_i\n else:\n if length ==2:\n self.dispatcher=self.trace_dispatch\n else:\n self.dispatcher=self.trace_dispatch_l\n \n \n \n \n \n def get_time_timer(timer=timer,sum=sum):\n return sum(timer())\n self.get_time=get_time_timer\n self.t=self.get_time()\n self.simulate_call('profiler')\n \n \n \n def trace_dispatch(self,frame,event,arg):\n timer=self.timer\n t=timer()\n t=t[0]+t[1]-self.t -self.bias\n \n if event ==\"c_call\":\n self.c_func_name=arg.__name__\n \n if self.dispatch[event](self,frame,t):\n t=timer()\n self.t=t[0]+t[1]\n else:\n r=timer()\n self.t=r[0]+r[1]-t\n \n \n \n \n def trace_dispatch_i(self,frame,event,arg):\n timer=self.timer\n t=timer()-self.t -self.bias\n \n if event ==\"c_call\":\n self.c_func_name=arg.__name__\n \n if self.dispatch[event](self,frame,t):\n self.t=timer()\n else:\n self.t=timer()-t\n \n \n \n \n def trace_dispatch_mac(self,frame,event,arg):\n timer=self.timer\n t=timer()/60.0 -self.t -self.bias\n \n if event ==\"c_call\":\n self.c_func_name=arg.__name__\n \n if self.dispatch[event](self,frame,t):\n self.t=timer()/60.0\n else:\n self.t=timer()/60.0 -t\n \n \n \n def trace_dispatch_l(self,frame,event,arg):\n get_time=self.get_time\n t=get_time()-self.t -self.bias\n \n if event ==\"c_call\":\n self.c_func_name=arg.__name__\n \n if self.dispatch[event](self,frame,t):\n self.t=get_time()\n else:\n self.t=get_time()-t\n \n \n \n \n \n \n \n \n def trace_dispatch_exception(self,frame,t):\n rpt,rit,ret,rfn,rframe,rcur=self.cur\n if(rframe is not frame)and rcur:\n return self.trace_dispatch_return(rframe,t)\n self.cur=rpt,rit+t,ret,rfn,rframe,rcur\n return 1\n \n \n def trace_dispatch_call(self,frame,t):\n if self.cur and frame.f_back is not self.cur[-2]:\n rpt,rit,ret,rfn,rframe,rcur=self.cur\n if not isinstance(rframe,Profile.fake_frame):\n assert rframe.f_back is frame.f_back,(\"Bad call\",rfn,\n rframe,rframe.f_back,\n frame,frame.f_back)\n self.trace_dispatch_return(rframe,0)\n assert(self.cur is None or\\\n frame.f_back is self.cur[-2]),(\"Bad call\",\n self.cur[-3])\n fcode=frame.f_code\n fn=(fcode.co_filename,fcode.co_firstlineno,fcode.co_name)\n self.cur=(t,0,0,fn,frame,self.cur)\n timings=self.timings\n if fn in timings:\n cc,ns,tt,ct,callers=timings[fn]\n timings[fn]=cc,ns+1,tt,ct,callers\n else:\n timings[fn]=0,0,0,0,{}\n return 1\n \n def trace_dispatch_c_call(self,frame,t):\n fn=(\"\",0,self.c_func_name)\n self.cur=(t,0,0,fn,frame,self.cur)\n timings=self.timings\n if fn in timings:\n cc,ns,tt,ct,callers=timings[fn]\n timings[fn]=cc,ns+1,tt,ct,callers\n else:\n timings[fn]=0,0,0,0,{}\n return 1\n \n def trace_dispatch_return(self,frame,t):\n if frame is not self.cur[-2]:\n assert frame is self.cur[-2].f_back,(\"Bad return\",self.cur[-3])\n self.trace_dispatch_return(self.cur[-2],0)\n \n \n \n \n rpt,rit,ret,rfn,frame,rcur=self.cur\n rit=rit+t\n frame_total=rit+ret\n \n ppt,pit,pet,pfn,pframe,pcur=rcur\n self.cur=ppt,pit+rpt,pet+frame_total,pfn,pframe,pcur\n \n timings=self.timings\n cc,ns,tt,ct,callers=timings[rfn]\n if not ns:\n \n \n \n \n ct=ct+frame_total\n cc=cc+1\n \n if pfn in callers:\n callers[pfn]=callers[pfn]+1\n \n \n \n else:\n callers[pfn]=1\n \n timings[rfn]=cc,ns -1,tt+rit,ct,callers\n \n return 1\n \n \n dispatch={\n \"call\":trace_dispatch_call,\n \"exception\":trace_dispatch_exception,\n \"return\":trace_dispatch_return,\n \"c_call\":trace_dispatch_c_call,\n \"c_exception\":trace_dispatch_return,\n \"c_return\":trace_dispatch_return,\n }\n \n \n \n \n \n \n \n \n def set_cmd(self,cmd):\n if self.cur[-1]:return\n self.cmd=cmd\n self.simulate_call(cmd)\n \n class fake_code:\n def __init__(self,filename,line,name):\n self.co_filename=filename\n self.co_line=line\n self.co_name=name\n self.co_firstlineno=0\n \n def __repr__(self):\n return repr((self.co_filename,self.co_line,self.co_name))\n \n class fake_frame:\n def __init__(self,code,prior):\n self.f_code=code\n self.f_back=prior\n \n def simulate_call(self,name):\n code=self.fake_code('profile',0,name)\n if self.cur:\n pframe=self.cur[-2]\n else:\n pframe=None\n frame=self.fake_frame(code,pframe)\n self.dispatch['call'](self,frame,0)\n \n \n \n \n def simulate_cmd_complete(self):\n get_time=self.get_time\n t=get_time()-self.t\n while self.cur[-1]:\n \n \n self.dispatch['return'](self,self.cur[-2],t)\n t=0\n self.t=get_time()-t\n \n \n def print_stats(self,sort=-1):\n import pstats\n if not isinstance(sort,tuple):\n sort=(sort,)\n pstats.Stats(self).strip_dirs().sort_stats(*sort).print_stats()\n \n def dump_stats(self,file):\n with open(file,'wb')as f:\n self.create_stats()\n marshal.dump(self.stats,f)\n \n def create_stats(self):\n self.simulate_cmd_complete()\n self.snapshot_stats()\n \n def snapshot_stats(self):\n self.stats={}\n for func,(cc,ns,tt,ct,callers)in self.timings.items():\n callers=callers.copy()\n nc=0\n for callcnt in callers.values():\n nc +=callcnt\n self.stats[func]=cc,nc,tt,ct,callers\n \n \n \n \n \n def run(self,cmd):\n import __main__\n dict=__main__.__dict__\n return self.runctx(cmd,dict,dict)\n \n def runctx(self,cmd,globals,locals):\n self.set_cmd(cmd)\n sys.setprofile(self.dispatcher)\n try:\n exec(cmd,globals,locals)\n finally:\n sys.setprofile(None)\n return self\n \n \n def runcall(self,func,/,*args,**kw):\n self.set_cmd(repr(func))\n sys.setprofile(self.dispatcher)\n try:\n return func(*args,**kw)\n finally:\n sys.setprofile(None)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def calibrate(self,m,verbose=0):\n if self.__class__ is not Profile:\n raise TypeError(\"Subclasses must override .calibrate().\")\n \n saved_bias=self.bias\n self.bias=0\n try:\n return self._calibrate_inner(m,verbose)\n finally:\n self.bias=saved_bias\n \n def _calibrate_inner(self,m,verbose):\n get_time=self.get_time\n \n \n \n \n \n \n \n def f1(n):\n for i in range(n):\n x=1\n \n def f(m,f1=f1):\n for i in range(m):\n f1(100)\n \n f(m)\n \n \n t0=get_time()\n f(m)\n t1=get_time()\n elapsed_noprofile=t1 -t0\n if verbose:\n print(\"elapsed time without profiling =\",elapsed_noprofile)\n \n \n \n \n p=Profile()\n t0=get_time()\n p.runctx('f(m)',globals(),locals())\n t1=get_time()\n elapsed_profile=t1 -t0\n if verbose:\n print(\"elapsed time with profiling =\",elapsed_profile)\n \n \n total_calls=0.0\n reported_time=0.0\n for(filename,line,funcname),(cc,ns,tt,ct,callers)in\\\n p.timings.items():\n if funcname in(\"f\",\"f1\"):\n total_calls +=cc\n reported_time +=tt\n \n if verbose:\n print(\"'CPU seconds' profiler reported =\",reported_time)\n print(\"total # calls =\",total_calls)\n if total_calls !=m+1:\n raise ValueError(\"internal error: total calls = %d\"%total_calls)\n \n \n \n \n \n mean=(reported_time -elapsed_noprofile)/2.0 /total_calls\n if verbose:\n print(\"mean stopwatch overhead per profile event =\",mean)\n return mean\n \n \n \ndef main():\n import os\n from optparse import OptionParser\n \n usage=\"profile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ...\"\n parser=OptionParser(usage=usage)\n parser.allow_interspersed_args=False\n parser.add_option('-o','--outfile',dest=\"outfile\",\n help=\"Save stats to \",default=None)\n parser.add_option('-m',dest=\"module\",action=\"store_true\",\n help=\"Profile a library module.\",default=False)\n parser.add_option('-s','--sort',dest=\"sort\",\n help=\"Sort order when printing to stdout, based on pstats.Stats class\",\n default=-1)\n \n if not sys.argv[1:]:\n parser.print_usage()\n sys.exit(2)\n \n (options,args)=parser.parse_args()\n sys.argv[:]=args\n \n \n \n if options.outfile is not None:\n options.outfile=os.path.abspath(options.outfile)\n \n if len(args)>0:\n if options.module:\n import runpy\n code=\"run_module(modname, run_name='__main__')\"\n globs={\n 'run_module':runpy.run_module,\n 'modname':args[0]\n }\n else:\n progname=args[0]\n sys.path.insert(0,os.path.dirname(progname))\n with io.open_code(progname)as fp:\n code=compile(fp.read(),progname,'exec')\n spec=importlib.machinery.ModuleSpec(name='__main__',loader=None,\n origin=progname)\n globs={\n '__spec__':spec,\n '__file__':spec.origin,\n '__name__':spec.name,\n '__package__':None,\n '__cached__':None,\n }\n try:\n runctx(code,globs,None,options.outfile,options.sort)\n except BrokenPipeError as exc:\n \n sys.stdout=None\n sys.exit(exc.errno)\n else:\n parser.print_usage()\n return parser\n \n \nif __name__ =='__main__':\n main()\n", ["__main__", "importlib.machinery", "io", "marshal", "optparse", "os", "pstats", "runpy", "sys", "time"]], "pwd": [".py", "\ndef getpwuid():\n pass\n", []], "pyclbr": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport ast\nimport sys\nimport importlib.util\n\n__all__=[\"readmodule\",\"readmodule_ex\",\"Class\",\"Function\"]\n\n_modules={}\n\n\nclass _Object:\n ''\n def __init__(self,module,name,file,lineno,end_lineno,parent):\n self.module=module\n self.name=name\n self.file=file\n self.lineno=lineno\n self.end_lineno=end_lineno\n self.parent=parent\n self.children={}\n if parent is not None:\n parent.children[name]=self\n \n \n \nclass Function(_Object):\n ''\n def __init__(self,module,name,file,lineno,\n parent=None,is_async=False,*,end_lineno=None):\n super().__init__(module,name,file,lineno,end_lineno,parent)\n self.is_async=is_async\n if isinstance(parent,Class):\n parent.methods[name]=lineno\n \n \nclass Class(_Object):\n ''\n def __init__(self,module,name,super_,file,lineno,\n parent=None,*,end_lineno=None):\n super().__init__(module,name,file,lineno,end_lineno,parent)\n self.super=super_ or[]\n self.methods={}\n \n \n \n \ndef _nest_function(ob,func_name,lineno,end_lineno,is_async=False):\n ''\n return Function(ob.module,func_name,ob.file,lineno,\n parent=ob,is_async=is_async,end_lineno=end_lineno)\n \ndef _nest_class(ob,class_name,lineno,end_lineno,super=None):\n ''\n return Class(ob.module,class_name,super,ob.file,lineno,\n parent=ob,end_lineno=end_lineno)\n \n \ndef readmodule(module,path=None):\n ''\n\n\n \n \n res={}\n for key,value in _readmodule(module,path or[]).items():\n if isinstance(value,Class):\n res[key]=value\n return res\n \ndef readmodule_ex(module,path=None):\n ''\n\n\n\n\n \n return _readmodule(module,path or[])\n \n \ndef _readmodule(module,path,inpackage=None):\n ''\n\n\n\n\n\n \n \n if inpackage is not None:\n fullmodule=\"%s.%s\"%(inpackage,module)\n else:\n fullmodule=module\n \n \n if fullmodule in _modules:\n return _modules[fullmodule]\n \n \n tree={}\n \n \n if module in sys.builtin_module_names and inpackage is None:\n _modules[module]=tree\n return tree\n \n \n i=module.rfind('.')\n if i >=0:\n package=module[:i]\n submodule=module[i+1:]\n parent=_readmodule(package,path,inpackage)\n if inpackage is not None:\n package=\"%s.%s\"%(inpackage,package)\n if not '__path__'in parent:\n raise ImportError('No package named {}'.format(package))\n return _readmodule(submodule,parent['__path__'],package)\n \n \n f=None\n if inpackage is not None:\n search_path=path\n else:\n search_path=path+sys.path\n spec=importlib.util._find_spec_from_path(fullmodule,search_path)\n if spec is None:\n raise ModuleNotFoundError(f\"no module named {fullmodule !r}\",name=fullmodule)\n _modules[fullmodule]=tree\n \n if spec.submodule_search_locations is not None:\n tree['__path__']=spec.submodule_search_locations\n try:\n source=spec.loader.get_source(fullmodule)\n except(AttributeError,ImportError):\n \n return tree\n else:\n if source is None:\n return tree\n \n fname=spec.loader.get_filename(fullmodule)\n return _create_tree(fullmodule,path,fname,source,tree,inpackage)\n \n \nclass _ModuleBrowser(ast.NodeVisitor):\n def __init__(self,module,path,file,tree,inpackage):\n self.path=path\n self.tree=tree\n self.file=file\n self.module=module\n self.inpackage=inpackage\n self.stack=[]\n \n def visit_ClassDef(self,node):\n bases=[]\n for base in node.bases:\n name=ast.unparse(base)\n if name in self.tree:\n \n bases.append(self.tree[name])\n elif len(names :=name.split(\".\"))>1:\n \n \n *_,module,class_=names\n if module in _modules:\n bases.append(_modules[module].get(class_,name))\n else:\n bases.append(name)\n \n parent=self.stack[-1]if self.stack else None\n class_=Class(self.module,node.name,bases,self.file,node.lineno,\n parent=parent,end_lineno=node.end_lineno)\n if parent is None:\n self.tree[node.name]=class_\n self.stack.append(class_)\n self.generic_visit(node)\n self.stack.pop()\n \n def visit_FunctionDef(self,node,*,is_async=False):\n parent=self.stack[-1]if self.stack else None\n function=Function(self.module,node.name,self.file,node.lineno,\n parent,is_async,end_lineno=node.end_lineno)\n if parent is None:\n self.tree[node.name]=function\n self.stack.append(function)\n self.generic_visit(node)\n self.stack.pop()\n \n def visit_AsyncFunctionDef(self,node):\n self.visit_FunctionDef(node,is_async=True)\n \n def visit_Import(self,node):\n if node.col_offset !=0:\n return\n \n for module in node.names:\n try:\n try:\n _readmodule(module.name,self.path,self.inpackage)\n except ImportError:\n _readmodule(module.name,[])\n except(ImportError,SyntaxError):\n \n \n continue\n \n def visit_ImportFrom(self,node):\n if node.col_offset !=0:\n return\n try:\n module=\".\"*node.level\n if node.module:\n module +=node.module\n module=_readmodule(module,self.path,self.inpackage)\n except(ImportError,SyntaxError):\n return\n \n for name in node.names:\n if name.name in module:\n self.tree[name.asname or name.name]=module[name.name]\n elif name.name ==\"*\":\n for import_name,import_value in module.items():\n if import_name.startswith(\"_\"):\n continue\n self.tree[import_name]=import_value\n \n \ndef _create_tree(fullmodule,path,fname,source,tree,inpackage):\n mbrowser=_ModuleBrowser(fullmodule,path,fname,tree,inpackage)\n mbrowser.visit(ast.parse(source))\n return mbrowser.tree\n \n \ndef _main():\n ''\n import os\n try:\n mod=sys.argv[1]\n except:\n mod=__file__\n if os.path.exists(mod):\n path=[os.path.dirname(mod)]\n mod=os.path.basename(mod)\n if mod.lower().endswith(\".py\"):\n mod=mod[:-3]\n else:\n path=[]\n tree=readmodule_ex(mod,path)\n lineno_key=lambda a:getattr(a,'lineno',0)\n objs=sorted(tree.values(),key=lineno_key,reverse=True)\n indent_level=2\n while objs:\n obj=objs.pop()\n if isinstance(obj,list):\n \n continue\n if not hasattr(obj,'indent'):\n obj.indent=0\n \n if isinstance(obj,_Object):\n new_objs=sorted(obj.children.values(),\n key=lineno_key,reverse=True)\n for ob in new_objs:\n ob.indent=obj.indent+indent_level\n objs.extend(new_objs)\n if isinstance(obj,Class):\n print(\"{}class {} {} {}\"\n .format(' '*obj.indent,obj.name,obj.super,obj.lineno))\n elif isinstance(obj,Function):\n print(\"{}def {} {}\".format(' '*obj.indent,obj.name,obj.lineno))\n \nif __name__ ==\"__main__\":\n _main()\n", ["ast", "importlib.util", "os", "sys"]], "pydoc": [".py", "#!/usr/bin/env python3\n''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['help']\n__author__=\"Ka-Ping Yee \"\n__date__=\"26 February 2001\"\n\n__credits__=\"\"\"Guido van Rossum, for an excellent programming language.\nTommy Burnette, the original creator of manpy.\nPaul Prescod, for all his work on onlinehelp.\nRichard Chamberlain, for the first implementation of textdoc.\n\"\"\"\n\n\n\n\n\n\n\n\nimport __future__\nimport builtins\nimport importlib._bootstrap\nimport importlib._bootstrap_external\nimport importlib.machinery\nimport importlib.util\nimport inspect\nimport io\nimport os\nimport pkgutil\nimport platform\nimport re\nimport sys\nimport sysconfig\nimport time\nimport tokenize\nimport urllib.parse\nimport warnings\nfrom collections import deque\nfrom reprlib import Repr\nfrom traceback import format_exception_only\n\n\n\n\ndef pathdirs():\n ''\n dirs=[]\n normdirs=[]\n for dir in sys.path:\n dir=os.path.abspath(dir or '.')\n normdir=os.path.normcase(dir)\n if normdir not in normdirs and os.path.isdir(dir):\n dirs.append(dir)\n normdirs.append(normdir)\n return dirs\n \ndef _findclass(func):\n cls=sys.modules.get(func.__module__)\n if cls is None:\n return None\n for name in func.__qualname__.split('.')[:-1]:\n cls=getattr(cls,name)\n if not inspect.isclass(cls):\n return None\n return cls\n \ndef _finddoc(obj):\n if inspect.ismethod(obj):\n name=obj.__func__.__name__\n self=obj.__self__\n if(inspect.isclass(self)and\n getattr(getattr(self,name,None),'__func__')is obj.__func__):\n \n cls=self\n else:\n cls=self.__class__\n elif inspect.isfunction(obj):\n name=obj.__name__\n cls=_findclass(obj)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif inspect.isbuiltin(obj):\n name=obj.__name__\n self=obj.__self__\n if(inspect.isclass(self)and\n self.__qualname__+'.'+name ==obj.__qualname__):\n \n cls=self\n else:\n cls=self.__class__\n \n elif isinstance(obj,property):\n func=obj.fget\n name=func.__name__\n cls=_findclass(func)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif inspect.ismethoddescriptor(obj)or inspect.isdatadescriptor(obj):\n name=obj.__name__\n cls=obj.__objclass__\n if getattr(cls,name)is not obj:\n return None\n if inspect.ismemberdescriptor(obj):\n slots=getattr(cls,'__slots__',None)\n if isinstance(slots,dict)and name in slots:\n return slots[name]\n else:\n return None\n for base in cls.__mro__:\n try:\n doc=_getowndoc(getattr(base,name))\n except AttributeError:\n continue\n if doc is not None:\n return doc\n return None\n \ndef _getowndoc(obj):\n ''\n \n try:\n doc=object.__getattribute__(obj,'__doc__')\n if doc is None:\n return None\n if obj is not type:\n typedoc=type(obj).__doc__\n if isinstance(typedoc,str)and typedoc ==doc:\n return None\n return doc\n except AttributeError:\n return None\n \ndef _getdoc(object):\n ''\n\n\n\n \n doc=_getowndoc(object)\n if doc is None:\n try:\n doc=_finddoc(object)\n except(AttributeError,TypeError):\n return None\n if not isinstance(doc,str):\n return None\n return inspect.cleandoc(doc)\n \ndef getdoc(object):\n ''\n result=_getdoc(object)or inspect.getcomments(object)\n return result and re.sub('^ *\\n','',result.rstrip())or ''\n \ndef splitdoc(doc):\n ''\n lines=doc.strip().split('\\n')\n if len(lines)==1:\n return lines[0],''\n elif len(lines)>=2 and not lines[1].rstrip():\n return lines[0],'\\n'.join(lines[2:])\n return '','\\n'.join(lines)\n \ndef classname(object,modname):\n ''\n name=object.__name__\n if object.__module__ !=modname:\n name=object.__module__+'.'+name\n return name\n \ndef isdata(object):\n ''\n return not(inspect.ismodule(object)or inspect.isclass(object)or\n inspect.isroutine(object)or inspect.isframe(object)or\n inspect.istraceback(object)or inspect.iscode(object))\n \ndef replace(text,*pairs):\n ''\n while pairs:\n text=pairs[1].join(text.split(pairs[0]))\n pairs=pairs[2:]\n return text\n \ndef cram(text,maxlen):\n ''\n if len(text)>maxlen:\n pre=max(0,(maxlen -3)//2)\n post=max(0,maxlen -3 -pre)\n return text[:pre]+'...'+text[len(text)-post:]\n return text\n \n_re_stripid=re.compile(r' at 0x[0-9a-f]{6,16}(>+)$',re.IGNORECASE)\ndef stripid(text):\n ''\n \n return _re_stripid.sub(r'\\1',text)\n \ndef _is_bound_method(fn):\n ''\n\n\n \n if inspect.ismethod(fn):\n return True\n if inspect.isbuiltin(fn):\n self=getattr(fn,'__self__',None)\n return not(inspect.ismodule(self)or(self is None))\n return False\n \n \ndef allmethods(cl):\n methods={}\n for key,value in inspect.getmembers(cl,inspect.isroutine):\n methods[key]=1\n for base in cl.__bases__:\n methods.update(allmethods(base))\n for key in methods.keys():\n methods[key]=getattr(cl,key)\n return methods\n \ndef _split_list(s,predicate):\n ''\n\n\n\n\n \n \n yes=[]\n no=[]\n for x in s:\n if predicate(x):\n yes.append(x)\n else:\n no.append(x)\n return yes,no\n \n_future_feature_names=set(__future__.all_feature_names)\n\ndef visiblename(name,all=None,obj=None):\n ''\n \n \n if name in{'__author__','__builtins__','__cached__','__credits__',\n '__date__','__doc__','__file__','__spec__',\n '__loader__','__module__','__name__','__package__',\n '__path__','__qualname__','__slots__','__version__'}:\n return 0\n \n if name.startswith('__')and name.endswith('__'):return 1\n \n if name.startswith('_')and hasattr(obj,'_fields'):\n return True\n \n if obj is not __future__ and name in _future_feature_names:\n if isinstance(getattr(obj,name,None),__future__._Feature):\n return False\n if all is not None:\n \n return name in all\n else:\n return not name.startswith('_')\n \ndef classify_class_attrs(object):\n ''\n results=[]\n for(name,kind,cls,value)in inspect.classify_class_attrs(object):\n if inspect.isdatadescriptor(value):\n kind='data descriptor'\n if isinstance(value,property)and value.fset is None:\n kind='readonly property'\n results.append((name,kind,cls,value))\n return results\n \ndef sort_attributes(attrs,object):\n ''\n \n \n fields=getattr(object,'_fields',[])\n try:\n field_order={name:i -len(fields)for(i,name)in enumerate(fields)}\n except TypeError:\n field_order={}\n keyfunc=lambda attr:(field_order.get(attr[0],0),attr[0])\n attrs.sort(key=keyfunc)\n \n \n \ndef ispackage(path):\n ''\n if os.path.isdir(path):\n for ext in('.py','.pyc'):\n if os.path.isfile(os.path.join(path,'__init__'+ext)):\n return True\n return False\n \ndef source_synopsis(file):\n line=file.readline()\n while line[:1]=='#'or not line.strip():\n line=file.readline()\n if not line:break\n line=line.strip()\n if line[:4]=='r\"\"\"':line=line[1:]\n if line[:3]=='\"\"\"':\n line=line[3:]\n if line[-1:]=='\\\\':line=line[:-1]\n while not line.strip():\n line=file.readline()\n if not line:break\n result=line.split('\"\"\"')[0].strip()\n else:result=None\n return result\n \ndef synopsis(filename,cache={}):\n ''\n mtime=os.stat(filename).st_mtime\n lastupdate,result=cache.get(filename,(None,None))\n if lastupdate is None or lastupdate ','>')\n \n def repr(self,object):\n return Repr.repr(self,object)\n \n def repr1(self,x,level):\n if hasattr(type(x),'__name__'):\n methodname='repr_'+'_'.join(type(x).__name__.split())\n if hasattr(self,methodname):\n return getattr(self,methodname)(x,level)\n return self.escape(cram(stripid(repr(x)),self.maxother))\n \n def repr_string(self,x,level):\n test=cram(x,self.maxstring)\n testrepr=repr(test)\n if '\\\\'in test and '\\\\'not in replace(testrepr,r'\\\\',''):\n \n \n return 'r'+testrepr[0]+self.escape(test)+testrepr[0]\n return re.sub(r'((\\\\[\\\\abfnrtv\\'\"]|\\\\[0-9]..|\\\\x..|\\\\u....)+)',\n r'\\1',\n self.escape(testrepr))\n \n repr_str=repr_string\n \n def repr_instance(self,x,level):\n try:\n return self.escape(cram(stripid(repr(x)),self.maxstring))\n except:\n return self.escape('<%s instance>'%x.__class__.__name__)\n \n repr_unicode=repr_string\n \nclass HTMLDoc(Doc):\n ''\n \n \n \n _repr_instance=HTMLRepr()\n repr=_repr_instance.repr\n escape=_repr_instance.escape\n \n def page(self,title,contents):\n ''\n return '''\\\n\n\n\n\nPython: %s\n\n%s\n'''%(title,contents)\n \n def heading(self,title,extras=''):\n ''\n return '''\n\n\n\n
 
%s
%s
\n '''%(title,extras or ' ')\n \n def section(self,title,cls,contents,width=6,\n prelude='',marginalia=None,gap=' '):\n ''\n if marginalia is None:\n marginalia=''+' '*width+''\n result='''

\n\n\n\n '''%(cls,title)\n if prelude:\n result=result+'''\n\n\n'''%(cls,marginalia,cls,prelude,gap)\n else:\n result=result+'''\n'''%(cls,marginalia,gap)\n \n return result+'\\n
 
%s
%s%s
%s
%s%s%s
'%contents\n \n def bigsection(self,title,*args):\n ''\n title='%s'%title\n return self.section(title,*args)\n \n def preformat(self,text):\n ''\n text=self.escape(text.expandtabs())\n return replace(text,'\\n\\n','\\n \\n','\\n\\n','\\n \\n',\n ' ',' ','\\n','
\\n')\n \n def multicolumn(self,list,format):\n ''\n result=''\n rows=(len(list)+3)//4\n for col in range(4):\n result=result+''\n for i in range(rows *col,rows *col+rows):\n if i \\n'\n result=result+''\n return '%s
'%result\n \n def grey(self,text):return '%s'%text\n \n def namelink(self,name,*dicts):\n ''\n for dict in dicts:\n if name in dict:\n return '
%s'%(dict[name],name)\n return name\n \n def classlink(self,object,modname):\n ''\n name,module=object.__name__,sys.modules.get(object.__module__)\n if hasattr(module,name)and getattr(module,name)is object:\n return '%s'%(\n module.__name__,name,classname(object,modname))\n return classname(object,modname)\n \n def modulelink(self,object):\n ''\n return '%s'%(object.__name__,object.__name__)\n \n def modpkglink(self,modpkginfo):\n ''\n name,path,ispackage,shadowed=modpkginfo\n if shadowed:\n return self.grey(name)\n if path:\n url='%s.%s.html'%(path,name)\n else:\n url='%s.html'%name\n if ispackage:\n text='%s (package)'%name\n else:\n text=name\n return '%s'%(url,text)\n \n def filelink(self,url,path):\n ''\n return '%s'%(url,path)\n \n def markup(self,text,escape=None,funcs={},classes={},methods={}):\n ''\n \n escape=escape or self.escape\n results=[]\n here=0\n pattern=re.compile(r'\\b((http|https|ftp)://\\S+[\\w/]|'\n r'RFC[- ]?(\\d+)|'\n r'PEP[- ]?(\\d+)|'\n r'(self\\.)?(\\w+))')\n while match :=pattern.search(text,here):\n start,end=match.span()\n results.append(escape(text[here:start]))\n \n all,scheme,rfc,pep,selfdot,name=match.groups()\n if scheme:\n url=escape(all).replace('\"','"')\n results.append('%s'%(url,url))\n elif rfc:\n url='https://www.rfc-editor.org/rfc/rfc%d.txt'%int(rfc)\n results.append('%s'%(url,escape(all)))\n elif pep:\n url='https://peps.python.org/pep-%04d/'%int(pep)\n results.append('%s'%(url,escape(all)))\n elif selfdot:\n \n \n if text[end:end+1]=='(':\n results.append('self.'+self.namelink(name,methods))\n else:\n results.append('self.%s'%name)\n elif text[end:end+1]=='(':\n results.append(self.namelink(name,methods,funcs,classes))\n else:\n results.append(self.namelink(name,classes))\n here=end\n results.append(escape(text[here:]))\n return ''.join(results)\n \n \n \n def formattree(self,tree,modname,parent=None):\n ''\n result=''\n for entry in tree:\n if isinstance(entry,tuple):\n c,bases=entry\n result=result+'

'\n result=result+self.classlink(c,modname)\n if bases and bases !=(parent,):\n parents=[]\n for base in bases:\n parents.append(self.classlink(base,modname))\n result=result+'('+', '.join(parents)+')'\n result=result+'\\n
'\n elif isinstance(entry,list):\n result=result+'
\\n%s
\\n'%self.formattree(\n entry,modname,c)\n return '
\\n%s
\\n'%result\n \n def docmodule(self,object,name=None,mod=None,*ignored):\n ''\n name=object.__name__\n try:\n all=object.__all__\n except AttributeError:\n all=None\n parts=name.split('.')\n links=[]\n for i in range(len(parts)-1):\n links.append(\n '%s'%\n ('.'.join(parts[:i+1]),parts[i]))\n linkedname='.'.join(links+parts[-1:])\n head='%s'%linkedname\n try:\n path=inspect.getabsfile(object)\n url=urllib.parse.quote(path)\n filelink=self.filelink(url,path)\n except TypeError:\n filelink='(built-in)'\n info=[]\n if hasattr(object,'__version__'):\n version=str(object.__version__)\n if version[:11]=='$'+'Revision: 'and version[-1:]=='$':\n version=version[11:-1].strip()\n info.append('version %s'%self.escape(version))\n if hasattr(object,'__date__'):\n info.append(self.escape(str(object.__date__)))\n if info:\n head=head+' (%s)'%', '.join(info)\n docloc=self.getdocloc(object)\n if docloc is not None:\n docloc='
Module Reference'%locals()\n else:\n docloc=''\n result=self.heading(head,'index
'+filelink+docloc)\n \n modules=inspect.getmembers(object,inspect.ismodule)\n \n classes,cdict=[],{}\n for key,value in inspect.getmembers(object,inspect.isclass):\n \n if(all is not None or\n (inspect.getmodule(value)or object)is object):\n if visiblename(key,all,object):\n classes.append((key,value))\n cdict[key]=cdict[value]='#'+key\n for key,value in classes:\n for base in value.__bases__:\n key,modname=base.__name__,base.__module__\n module=sys.modules.get(modname)\n if modname !=name and module and hasattr(module,key):\n if getattr(module,key)is base:\n if not key in cdict:\n cdict[key]=cdict[base]=modname+'.html#'+key\n funcs,fdict=[],{}\n for key,value in inspect.getmembers(object,inspect.isroutine):\n \n if(all is not None or\n inspect.isbuiltin(value)or inspect.getmodule(value)is object):\n if visiblename(key,all,object):\n funcs.append((key,value))\n fdict[key]='#-'+key\n if inspect.isfunction(value):fdict[value]=fdict[key]\n data=[]\n for key,value in inspect.getmembers(object,isdata):\n if visiblename(key,all,object):\n data.append((key,value))\n \n doc=self.markup(getdoc(object),self.preformat,fdict,cdict)\n doc=doc and '%s'%doc\n result=result+'

%s

\\n'%doc\n \n if hasattr(object,'__path__'):\n modpkgs=[]\n for importer,modname,ispkg in pkgutil.iter_modules(object.__path__):\n modpkgs.append((modname,name,ispkg,0))\n modpkgs.sort()\n contents=self.multicolumn(modpkgs,self.modpkglink)\n result=result+self.bigsection(\n 'Package Contents','pkg-content',contents)\n elif modules:\n contents=self.multicolumn(\n modules,lambda t:self.modulelink(t[1]))\n result=result+self.bigsection(\n 'Modules','pkg-content',contents)\n \n if classes:\n classlist=[value for(key,value)in classes]\n contents=[\n self.formattree(inspect.getclasstree(classlist,1),name)]\n for key,value in classes:\n contents.append(self.document(value,key,name,fdict,cdict))\n result=result+self.bigsection(\n 'Classes','index',' '.join(contents))\n if funcs:\n contents=[]\n for key,value in funcs:\n contents.append(self.document(value,key,name,fdict,cdict))\n result=result+self.bigsection(\n 'Functions','functions',' '.join(contents))\n if data:\n contents=[]\n for key,value in data:\n contents.append(self.document(value,key))\n result=result+self.bigsection(\n 'Data','data','
\\n'.join(contents))\n if hasattr(object,'__author__'):\n contents=self.markup(str(object.__author__),self.preformat)\n result=result+self.bigsection('Author','author',contents)\n if hasattr(object,'__credits__'):\n contents=self.markup(str(object.__credits__),self.preformat)\n result=result+self.bigsection('Credits','credits',contents)\n \n return result\n \n def docclass(self,object,name=None,mod=None,funcs={},classes={},\n *ignored):\n ''\n realname=object.__name__\n name=name or realname\n bases=object.__bases__\n \n contents=[]\n push=contents.append\n \n \n class HorizontalRule:\n def __init__(self):\n self.needone=0\n def maybe(self):\n if self.needone:\n push('
\\n')\n self.needone=1\n hr=HorizontalRule()\n \n \n mro=deque(inspect.getmro(object))\n if len(mro)>2:\n hr.maybe()\n push('
Method resolution order:
\\n')\n for base in mro:\n push('
%s
\\n'%self.classlink(base,\n object.__module__))\n push('
\\n')\n \n def spill(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n try:\n value=getattr(object,name)\n except Exception:\n \n \n push(self.docdata(value,name,mod))\n else:\n push(self.document(value,name,mod,\n funcs,classes,mdict,object))\n push('\\n')\n return attrs\n \n def spilldescriptors(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n push(self.docdata(value,name,mod))\n return attrs\n \n def spilldata(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n base=self.docother(getattr(object,name),name,mod)\n doc=getdoc(value)\n if not doc:\n push('
%s
\\n'%base)\n else:\n doc=self.markup(getdoc(value),self.preformat,\n funcs,classes,mdict)\n doc='
%s'%doc\n push('
%s%s
\\n'%(base,doc))\n push('\\n')\n return attrs\n \n attrs=[(name,kind,cls,value)\n for name,kind,cls,value in classify_class_attrs(object)\n if visiblename(name,obj=object)]\n \n mdict={}\n for key,kind,homecls,value in attrs:\n mdict[key]=anchor='#'+name+'-'+key\n try:\n value=getattr(object,name)\n except Exception:\n \n \n pass\n try:\n \n \n mdict[value]=anchor\n except TypeError:\n pass\n \n while attrs:\n if mro:\n thisclass=mro.popleft()\n else:\n thisclass=attrs[0][2]\n attrs,inherited=_split_list(attrs,lambda t:t[2]is thisclass)\n \n if object is not builtins.object and thisclass is builtins.object:\n attrs=inherited\n continue\n elif thisclass is object:\n tag='defined here'\n else:\n tag='inherited from %s'%self.classlink(thisclass,\n object.__module__)\n tag +=':
\\n'\n \n sort_attributes(attrs,object)\n \n \n attrs=spill('Methods %s'%tag,attrs,\n lambda t:t[1]=='method')\n attrs=spill('Class methods %s'%tag,attrs,\n lambda t:t[1]=='class method')\n attrs=spill('Static methods %s'%tag,attrs,\n lambda t:t[1]=='static method')\n attrs=spilldescriptors(\"Readonly properties %s\"%tag,attrs,\n lambda t:t[1]=='readonly property')\n attrs=spilldescriptors('Data descriptors %s'%tag,attrs,\n lambda t:t[1]=='data descriptor')\n attrs=spilldata('Data and other attributes %s'%tag,attrs,\n lambda t:t[1]=='data')\n assert attrs ==[]\n attrs=inherited\n \n contents=''.join(contents)\n \n if name ==realname:\n title='class %s'%(\n name,realname)\n else:\n title='%s = class %s'%(\n name,name,realname)\n if bases:\n parents=[]\n for base in bases:\n parents.append(self.classlink(base,object.__module__))\n title=title+'(%s)'%', '.join(parents)\n \n decl=''\n try:\n signature=inspect.signature(object)\n except(ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if argspec and argspec !='()':\n decl=name+self.escape(argspec)+'\\n\\n'\n \n doc=getdoc(object)\n if decl:\n doc=decl+(doc or '')\n doc=self.markup(doc,self.preformat,funcs,classes,mdict)\n doc=doc and '%s
 
'%doc\n \n return self.section(title,'title',contents,3,doc)\n \n def formatvalue(self,object):\n ''\n return self.grey('='+self.repr(object))\n \n def docroutine(self,object,name=None,mod=None,\n funcs={},classes={},methods={},cl=None):\n ''\n realname=object.__name__\n name=name or realname\n anchor=(cl and cl.__name__ or '')+'-'+name\n note=''\n skipdocs=0\n if _is_bound_method(object):\n imclass=object.__self__.__class__\n if cl:\n if imclass is not cl:\n note=' from '+self.classlink(imclass,mod)\n else:\n if object.__self__ is not None:\n note=' method of %s instance'%self.classlink(\n object.__self__.__class__,mod)\n else:\n note=' unbound %s method'%self.classlink(imclass,mod)\n \n if(inspect.iscoroutinefunction(object)or\n inspect.isasyncgenfunction(object)):\n asyncqualifier='async '\n else:\n asyncqualifier=''\n \n if name ==realname:\n title='%s'%(anchor,realname)\n else:\n if cl and inspect.getattr_static(cl,realname,[])is object:\n reallink='%s'%(\n cl.__name__+'-'+realname,realname)\n skipdocs=1\n else:\n reallink=realname\n title='%s = %s'%(\n anchor,name,reallink)\n argspec=None\n if inspect.isroutine(object):\n try:\n signature=inspect.signature(object)\n except(ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if realname =='':\n title='%s lambda '%name\n \n \n \n argspec=argspec[1:-1]\n if not argspec:\n argspec='(...)'\n \n decl=asyncqualifier+title+self.escape(argspec)+(note and\n self.grey('%s'%note))\n \n if skipdocs:\n return '
%s
\\n'%decl\n else:\n doc=self.markup(\n getdoc(object),self.preformat,funcs,classes,methods)\n doc=doc and '
%s
'%doc\n return '
%s
%s
\\n'%(decl,doc)\n \n def docdata(self,object,name=None,mod=None,cl=None):\n ''\n results=[]\n push=results.append\n \n if name:\n push('
%s
\\n'%name)\n doc=self.markup(getdoc(object),self.preformat)\n if doc:\n push('
%s
\\n'%doc)\n push('
\\n')\n \n return ''.join(results)\n \n docproperty=docdata\n \n def docother(self,object,name=None,mod=None,*ignored):\n ''\n lhs=name and '%s = '%name or ''\n return lhs+self.repr(object)\n \n def index(self,dir,shadowed=None):\n ''\n modpkgs=[]\n if shadowed is None:shadowed={}\n for importer,name,ispkg in pkgutil.iter_modules([dir]):\n if any((0xD800 <=ord(ch)<=0xDFFF)for ch in name):\n \n continue\n modpkgs.append((name,'',ispkg,name in shadowed))\n shadowed[name]=1\n \n modpkgs.sort()\n contents=self.multicolumn(modpkgs,self.modpkglink)\n return self.bigsection(dir,'index',contents)\n \n \n \nclass TextRepr(Repr):\n ''\n def __init__(self):\n Repr.__init__(self)\n self.maxlist=self.maxtuple=20\n self.maxdict=10\n self.maxstring=self.maxother=100\n \n def repr1(self,x,level):\n if hasattr(type(x),'__name__'):\n methodname='repr_'+'_'.join(type(x).__name__.split())\n if hasattr(self,methodname):\n return getattr(self,methodname)(x,level)\n return cram(stripid(repr(x)),self.maxother)\n \n def repr_string(self,x,level):\n test=cram(x,self.maxstring)\n testrepr=repr(test)\n if '\\\\'in test and '\\\\'not in replace(testrepr,r'\\\\',''):\n \n \n return 'r'+testrepr[0]+test+testrepr[0]\n return testrepr\n \n repr_str=repr_string\n \n def repr_instance(self,x,level):\n try:\n return cram(stripid(repr(x)),self.maxstring)\n except:\n return '<%s instance>'%x.__class__.__name__\n \nclass TextDoc(Doc):\n ''\n \n \n \n _repr_instance=TextRepr()\n repr=_repr_instance.repr\n \n def bold(self,text):\n ''\n return ''.join(ch+'\\b'+ch for ch in text)\n \n def indent(self,text,prefix=' '):\n ''\n if not text:return ''\n lines=[(prefix+line).rstrip()for line in text.split('\\n')]\n return '\\n'.join(lines)\n \n def section(self,title,contents):\n ''\n clean_contents=self.indent(contents).rstrip()\n return self.bold(title)+'\\n'+clean_contents+'\\n\\n'\n \n \n \n def formattree(self,tree,modname,parent=None,prefix=''):\n ''\n result=''\n for entry in tree:\n if isinstance(entry,tuple):\n c,bases=entry\n result=result+prefix+classname(c,modname)\n if bases and bases !=(parent,):\n parents=(classname(c,modname)for c in bases)\n result=result+'(%s)'%', '.join(parents)\n result=result+'\\n'\n elif isinstance(entry,list):\n result=result+self.formattree(\n entry,modname,c,prefix+' ')\n return result\n \n def docmodule(self,object,name=None,mod=None):\n ''\n name=object.__name__\n synop,desc=splitdoc(getdoc(object))\n result=self.section('NAME',name+(synop and ' - '+synop))\n all=getattr(object,'__all__',None)\n docloc=self.getdocloc(object)\n if docloc is not None:\n result=result+self.section('MODULE REFERENCE',docloc+\"\"\"\n\nThe following documentation is automatically generated from the Python\nsource files. It may be incomplete, incorrect or include features that\nare considered implementation detail and may vary between Python\nimplementations. When in doubt, consult the module reference at the\nlocation listed above.\n\"\"\")\n \n if desc:\n result=result+self.section('DESCRIPTION',desc)\n \n classes=[]\n for key,value in inspect.getmembers(object,inspect.isclass):\n \n if(all is not None\n or(inspect.getmodule(value)or object)is object):\n if visiblename(key,all,object):\n classes.append((key,value))\n funcs=[]\n for key,value in inspect.getmembers(object,inspect.isroutine):\n \n if(all is not None or\n inspect.isbuiltin(value)or inspect.getmodule(value)is object):\n if visiblename(key,all,object):\n funcs.append((key,value))\n data=[]\n for key,value in inspect.getmembers(object,isdata):\n if visiblename(key,all,object):\n data.append((key,value))\n \n modpkgs=[]\n modpkgs_names=set()\n if hasattr(object,'__path__'):\n for importer,modname,ispkg in pkgutil.iter_modules(object.__path__):\n modpkgs_names.add(modname)\n if ispkg:\n modpkgs.append(modname+' (package)')\n else:\n modpkgs.append(modname)\n \n modpkgs.sort()\n result=result+self.section(\n 'PACKAGE CONTENTS','\\n'.join(modpkgs))\n \n \n submodules=[]\n for key,value in inspect.getmembers(object,inspect.ismodule):\n if value.__name__.startswith(name+'.')and key not in modpkgs_names:\n submodules.append(key)\n if submodules:\n submodules.sort()\n result=result+self.section(\n 'SUBMODULES','\\n'.join(submodules))\n \n if classes:\n classlist=[value for key,value in classes]\n contents=[self.formattree(\n inspect.getclasstree(classlist,1),name)]\n for key,value in classes:\n contents.append(self.document(value,key,name))\n result=result+self.section('CLASSES','\\n'.join(contents))\n \n if funcs:\n contents=[]\n for key,value in funcs:\n contents.append(self.document(value,key,name))\n result=result+self.section('FUNCTIONS','\\n'.join(contents))\n \n if data:\n contents=[]\n for key,value in data:\n contents.append(self.docother(value,key,name,maxlen=70))\n result=result+self.section('DATA','\\n'.join(contents))\n \n if hasattr(object,'__version__'):\n version=str(object.__version__)\n if version[:11]=='$'+'Revision: 'and version[-1:]=='$':\n version=version[11:-1].strip()\n result=result+self.section('VERSION',version)\n if hasattr(object,'__date__'):\n result=result+self.section('DATE',str(object.__date__))\n if hasattr(object,'__author__'):\n result=result+self.section('AUTHOR',str(object.__author__))\n if hasattr(object,'__credits__'):\n result=result+self.section('CREDITS',str(object.__credits__))\n try:\n file=inspect.getabsfile(object)\n except TypeError:\n file='(built-in)'\n result=result+self.section('FILE',file)\n return result\n \n def docclass(self,object,name=None,mod=None,*ignored):\n ''\n realname=object.__name__\n name=name or realname\n bases=object.__bases__\n \n def makename(c,m=object.__module__):\n return classname(c,m)\n \n if name ==realname:\n title='class '+self.bold(realname)\n else:\n title=self.bold(name)+' = class '+realname\n if bases:\n parents=map(makename,bases)\n title=title+'(%s)'%', '.join(parents)\n \n contents=[]\n push=contents.append\n \n try:\n signature=inspect.signature(object)\n except(ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if argspec and argspec !='()':\n push(name+argspec+'\\n')\n \n doc=getdoc(object)\n if doc:\n push(doc+'\\n')\n \n \n mro=deque(inspect.getmro(object))\n if len(mro)>2:\n push(\"Method resolution order:\")\n for base in mro:\n push(' '+makename(base))\n push('')\n \n \n subclasses=sorted(\n (str(cls.__name__)for cls in type.__subclasses__(object)\n if not cls.__name__.startswith(\"_\")and cls.__module__ ==\"builtins\"),\n key=str.lower\n )\n no_of_subclasses=len(subclasses)\n MAX_SUBCLASSES_TO_DISPLAY=4\n if subclasses:\n push(\"Built-in subclasses:\")\n for subclassname in subclasses[:MAX_SUBCLASSES_TO_DISPLAY]:\n push(' '+subclassname)\n if no_of_subclasses >MAX_SUBCLASSES_TO_DISPLAY:\n push(' ... and '+\n str(no_of_subclasses -MAX_SUBCLASSES_TO_DISPLAY)+\n ' other subclasses')\n push('')\n \n \n class HorizontalRule:\n def __init__(self):\n self.needone=0\n def maybe(self):\n if self.needone:\n push('-'*70)\n self.needone=1\n hr=HorizontalRule()\n \n def spill(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n try:\n value=getattr(object,name)\n except Exception:\n \n \n push(self.docdata(value,name,mod))\n else:\n push(self.document(value,\n name,mod,object))\n return attrs\n \n def spilldescriptors(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n push(self.docdata(value,name,mod))\n return attrs\n \n def spilldata(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n doc=getdoc(value)\n try:\n obj=getattr(object,name)\n except AttributeError:\n obj=homecls.__dict__[name]\n push(self.docother(obj,name,mod,maxlen=70,doc=doc)+\n '\\n')\n return attrs\n \n attrs=[(name,kind,cls,value)\n for name,kind,cls,value in classify_class_attrs(object)\n if visiblename(name,obj=object)]\n \n while attrs:\n if mro:\n thisclass=mro.popleft()\n else:\n thisclass=attrs[0][2]\n attrs,inherited=_split_list(attrs,lambda t:t[2]is thisclass)\n \n if object is not builtins.object and thisclass is builtins.object:\n attrs=inherited\n continue\n elif thisclass is object:\n tag=\"defined here\"\n else:\n tag=\"inherited from %s\"%classname(thisclass,\n object.__module__)\n \n sort_attributes(attrs,object)\n \n \n attrs=spill(\"Methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='method')\n attrs=spill(\"Class methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='class method')\n attrs=spill(\"Static methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='static method')\n attrs=spilldescriptors(\"Readonly properties %s:\\n\"%tag,attrs,\n lambda t:t[1]=='readonly property')\n attrs=spilldescriptors(\"Data descriptors %s:\\n\"%tag,attrs,\n lambda t:t[1]=='data descriptor')\n attrs=spilldata(\"Data and other attributes %s:\\n\"%tag,attrs,\n lambda t:t[1]=='data')\n \n assert attrs ==[]\n attrs=inherited\n \n contents='\\n'.join(contents)\n if not contents:\n return title+'\\n'\n return title+'\\n'+self.indent(contents.rstrip(),' | ')+'\\n'\n \n def formatvalue(self,object):\n ''\n return '='+self.repr(object)\n \n def docroutine(self,object,name=None,mod=None,cl=None):\n ''\n realname=object.__name__\n name=name or realname\n note=''\n skipdocs=0\n if _is_bound_method(object):\n imclass=object.__self__.__class__\n if cl:\n if imclass is not cl:\n note=' from '+classname(imclass,mod)\n else:\n if object.__self__ is not None:\n note=' method of %s instance'%classname(\n object.__self__.__class__,mod)\n else:\n note=' unbound %s method'%classname(imclass,mod)\n \n if(inspect.iscoroutinefunction(object)or\n inspect.isasyncgenfunction(object)):\n asyncqualifier='async '\n else:\n asyncqualifier=''\n \n if name ==realname:\n title=self.bold(realname)\n else:\n if cl and inspect.getattr_static(cl,realname,[])is object:\n skipdocs=1\n title=self.bold(name)+' = '+realname\n argspec=None\n \n if inspect.isroutine(object):\n try:\n signature=inspect.signature(object)\n except(ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if realname =='':\n title=self.bold(name)+' lambda '\n \n \n \n argspec=argspec[1:-1]\n if not argspec:\n argspec='(...)'\n decl=asyncqualifier+title+argspec+note\n \n if skipdocs:\n return decl+'\\n'\n else:\n doc=getdoc(object)or ''\n return decl+'\\n'+(doc and self.indent(doc).rstrip()+'\\n')\n \n def docdata(self,object,name=None,mod=None,cl=None):\n ''\n results=[]\n push=results.append\n \n if name:\n push(self.bold(name))\n push('\\n')\n doc=getdoc(object)or ''\n if doc:\n push(self.indent(doc))\n push('\\n')\n return ''.join(results)\n \n docproperty=docdata\n \n def docother(self,object,name=None,mod=None,parent=None,maxlen=None,doc=None):\n ''\n repr=self.repr(object)\n if maxlen:\n line=(name and name+' = 'or '')+repr\n chop=maxlen -len(line)\n if chop <0:repr=repr[:chop]+'...'\n line=(name and self.bold(name)+' = 'or '')+repr\n if not doc:\n doc=getdoc(object)\n if doc:\n line +='\\n'+self.indent(str(doc))+'\\n'\n return line\n \nclass _PlainTextDoc(TextDoc):\n ''\n def bold(self,text):\n return text\n \n \n \ndef pager(text):\n ''\n global pager\n pager=getpager()\n pager(text)\n \ndef getpager():\n ''\n if not hasattr(sys.stdin,\"isatty\"):\n return plainpager\n if not hasattr(sys.stdout,\"isatty\"):\n return plainpager\n if not sys.stdin.isatty()or not sys.stdout.isatty():\n return plainpager\n if sys.platform ==\"emscripten\":\n return plainpager\n use_pager=os.environ.get('MANPAGER')or os.environ.get('PAGER')\n if use_pager:\n if sys.platform =='win32':\n return lambda text:tempfilepager(plain(text),use_pager)\n elif os.environ.get('TERM')in('dumb','emacs'):\n return lambda text:pipepager(plain(text),use_pager)\n else:\n return lambda text:pipepager(text,use_pager)\n if os.environ.get('TERM')in('dumb','emacs'):\n return plainpager\n if sys.platform =='win32':\n return lambda text:tempfilepager(plain(text),'more <')\n if hasattr(os,'system')and os.system('(less) 2>/dev/null')==0:\n return lambda text:pipepager(text,'less')\n \n import tempfile\n (fd,filename)=tempfile.mkstemp()\n os.close(fd)\n try:\n if hasattr(os,'system')and os.system('more \"%s\"'%filename)==0:\n return lambda text:pipepager(text,'more')\n else:\n return ttypager\n finally:\n os.unlink(filename)\n \ndef plain(text):\n ''\n return re.sub('.\\b','',text)\n \ndef pipepager(text,cmd):\n ''\n import subprocess\n proc=subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE,\n errors='backslashreplace')\n try:\n with proc.stdin as pipe:\n try:\n pipe.write(text)\n except KeyboardInterrupt:\n \n \n pass\n except OSError:\n pass\n while True:\n try:\n proc.wait()\n break\n except KeyboardInterrupt:\n \n \n pass\n \ndef tempfilepager(text,cmd):\n ''\n import tempfile\n with tempfile.TemporaryDirectory()as tempdir:\n filename=os.path.join(tempdir,'pydoc.out')\n with open(filename,'w',errors='backslashreplace',\n encoding=os.device_encoding(0)if\n sys.platform =='win32'else None\n )as file:\n file.write(text)\n os.system(cmd+' \"'+filename+'\"')\n \ndef _escape_stdout(text):\n\n encoding=getattr(sys.stdout,'encoding',None)or 'utf-8'\n return text.encode(encoding,'backslashreplace').decode(encoding)\n \ndef ttypager(text):\n ''\n lines=plain(_escape_stdout(text)).split('\\n')\n try:\n import tty\n fd=sys.stdin.fileno()\n old=tty.tcgetattr(fd)\n tty.setcbreak(fd)\n getchar=lambda:sys.stdin.read(1)\n except(ImportError,AttributeError,io.UnsupportedOperation):\n tty=None\n getchar=lambda:sys.stdin.readline()[:-1][:1]\n \n try:\n try:\n h=int(os.environ.get('LINES',0))\n except ValueError:\n h=0\n if h <=1:\n h=25\n r=inc=h -1\n sys.stdout.write('\\n'.join(lines[:inc])+'\\n')\n while lines[r:]:\n sys.stdout.write('-- more --')\n sys.stdout.flush()\n c=getchar()\n \n if c in('q','Q'):\n sys.stdout.write('\\r \\r')\n break\n elif c in('\\r','\\n'):\n sys.stdout.write('\\r \\r'+lines[r]+'\\n')\n r=r+1\n continue\n if c in('b','B','\\x1b'):\n r=r -inc -inc\n if r <0:r=0\n sys.stdout.write('\\n'+'\\n'.join(lines[r:r+inc])+'\\n')\n r=r+inc\n \n finally:\n if tty:\n tty.tcsetattr(fd,tty.TCSAFLUSH,old)\n \ndef plainpager(text):\n ''\n sys.stdout.write(plain(_escape_stdout(text)))\n \ndef describe(thing):\n ''\n if inspect.ismodule(thing):\n if thing.__name__ in sys.builtin_module_names:\n return 'built-in module '+thing.__name__\n if hasattr(thing,'__path__'):\n return 'package '+thing.__name__\n else:\n return 'module '+thing.__name__\n if inspect.isbuiltin(thing):\n return 'built-in function '+thing.__name__\n if inspect.isgetsetdescriptor(thing):\n return 'getset descriptor %s.%s.%s'%(\n thing.__objclass__.__module__,thing.__objclass__.__name__,\n thing.__name__)\n if inspect.ismemberdescriptor(thing):\n return 'member descriptor %s.%s.%s'%(\n thing.__objclass__.__module__,thing.__objclass__.__name__,\n thing.__name__)\n if inspect.isclass(thing):\n return 'class '+thing.__name__\n if inspect.isfunction(thing):\n return 'function '+thing.__name__\n if inspect.ismethod(thing):\n return 'method '+thing.__name__\n return type(thing).__name__\n \ndef locate(path,forceload=0):\n ''\n parts=[part for part in path.split('.')if part]\n module,n=None,0\n while n >','&',\n '|','^','~','<','>','<=','>=','==','!=','<>'),\n 'COMPARISON':('<','>','<=','>=','==','!=','<>'),\n 'UNARY':('-','~'),\n 'AUGMENTEDASSIGNMENT':('+=','-=','*=','/=','%=','&=','|=',\n '^=','<<=','>>=','**=','//='),\n 'BITWISE':('<<','>>','&','|','^','~'),\n 'COMPLEX':('j','J')\n }\n symbols={\n '%':'OPERATORS FORMATTING',\n '**':'POWER',\n ',':'TUPLES LISTS FUNCTIONS',\n '.':'ATTRIBUTES FLOAT MODULES OBJECTS',\n '...':'ELLIPSIS',\n ':':'SLICINGS DICTIONARYLITERALS',\n '@':'def class',\n '\\\\':'STRINGS',\n '_':'PRIVATENAMES',\n '__':'PRIVATENAMES SPECIALMETHODS',\n '`':'BACKQUOTES',\n '(':'TUPLES FUNCTIONS CALLS',\n ')':'TUPLES FUNCTIONS CALLS',\n '[':'LISTS SUBSCRIPTS SLICINGS',\n ']':'LISTS SUBSCRIPTS SLICINGS'\n }\n for topic,symbols_ in _symbols_inverse.items():\n for symbol in symbols_:\n topics=symbols.get(symbol,topic)\n if topic not in topics:\n topics=topics+' '+topic\n symbols[symbol]=topics\n del topic,symbols_,symbol,topics\n \n topics={\n 'TYPES':('types','STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '\n 'FUNCTIONS CLASSES MODULES FILES inspect'),\n 'STRINGS':('strings','str UNICODE SEQUENCES STRINGMETHODS '\n 'FORMATTING TYPES'),\n 'STRINGMETHODS':('string-methods','STRINGS FORMATTING'),\n 'FORMATTING':('formatstrings','OPERATORS'),\n 'UNICODE':('strings','encodings unicode SEQUENCES STRINGMETHODS '\n 'FORMATTING TYPES'),\n 'NUMBERS':('numbers','INTEGER FLOAT COMPLEX TYPES'),\n 'INTEGER':('integers','int range'),\n 'FLOAT':('floating','float math'),\n 'COMPLEX':('imaginary','complex cmath'),\n 'SEQUENCES':('typesseq','STRINGMETHODS FORMATTING range LISTS'),\n 'MAPPINGS':'DICTIONARIES',\n 'FUNCTIONS':('typesfunctions','def TYPES'),\n 'METHODS':('typesmethods','class def CLASSES TYPES'),\n 'CODEOBJECTS':('bltin-code-objects','compile FUNCTIONS TYPES'),\n 'TYPEOBJECTS':('bltin-type-objects','types TYPES'),\n 'FRAMEOBJECTS':'TYPES',\n 'TRACEBACKS':'TYPES',\n 'NONE':('bltin-null-object',''),\n 'ELLIPSIS':('bltin-ellipsis-object','SLICINGS'),\n 'SPECIALATTRIBUTES':('specialattrs',''),\n 'CLASSES':('types','class SPECIALMETHODS PRIVATENAMES'),\n 'MODULES':('typesmodules','import'),\n 'PACKAGES':'import',\n 'EXPRESSIONS':('operator-summary','lambda or and not in is BOOLEAN '\n 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '\n 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '\n 'LISTS DICTIONARIES'),\n 'OPERATORS':'EXPRESSIONS',\n 'PRECEDENCE':'EXPRESSIONS',\n 'OBJECTS':('objects','TYPES'),\n 'SPECIALMETHODS':('specialnames','BASICMETHODS ATTRIBUTEMETHODS '\n 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '\n 'NUMBERMETHODS CLASSES'),\n 'BASICMETHODS':('customization','hash repr str SPECIALMETHODS'),\n 'ATTRIBUTEMETHODS':('attribute-access','ATTRIBUTES SPECIALMETHODS'),\n 'CALLABLEMETHODS':('callable-types','CALLS SPECIALMETHODS'),\n 'SEQUENCEMETHODS':('sequence-types','SEQUENCES SEQUENCEMETHODS '\n 'SPECIALMETHODS'),\n 'MAPPINGMETHODS':('sequence-types','MAPPINGS SPECIALMETHODS'),\n 'NUMBERMETHODS':('numeric-types','NUMBERS AUGMENTEDASSIGNMENT '\n 'SPECIALMETHODS'),\n 'EXECUTION':('execmodel','NAMESPACES DYNAMICFEATURES EXCEPTIONS'),\n 'NAMESPACES':('naming','global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),\n 'DYNAMICFEATURES':('dynamic-features',''),\n 'SCOPING':'NAMESPACES',\n 'FRAMES':'NAMESPACES',\n 'EXCEPTIONS':('exceptions','try except finally raise'),\n 'CONVERSIONS':('conversions',''),\n 'IDENTIFIERS':('identifiers','keywords SPECIALIDENTIFIERS'),\n 'SPECIALIDENTIFIERS':('id-classes',''),\n 'PRIVATENAMES':('atom-identifiers',''),\n 'LITERALS':('atom-literals','STRINGS NUMBERS TUPLELITERALS '\n 'LISTLITERALS DICTIONARYLITERALS'),\n 'TUPLES':'SEQUENCES',\n 'TUPLELITERALS':('exprlists','TUPLES LITERALS'),\n 'LISTS':('typesseq-mutable','LISTLITERALS'),\n 'LISTLITERALS':('lists','LISTS LITERALS'),\n 'DICTIONARIES':('typesmapping','DICTIONARYLITERALS'),\n 'DICTIONARYLITERALS':('dict','DICTIONARIES LITERALS'),\n 'ATTRIBUTES':('attribute-references','getattr hasattr setattr ATTRIBUTEMETHODS'),\n 'SUBSCRIPTS':('subscriptions','SEQUENCEMETHODS'),\n 'SLICINGS':('slicings','SEQUENCEMETHODS'),\n 'CALLS':('calls','EXPRESSIONS'),\n 'POWER':('power','EXPRESSIONS'),\n 'UNARY':('unary','EXPRESSIONS'),\n 'BINARY':('binary','EXPRESSIONS'),\n 'SHIFTING':('shifting','EXPRESSIONS'),\n 'BITWISE':('bitwise','EXPRESSIONS'),\n 'COMPARISON':('comparisons','EXPRESSIONS BASICMETHODS'),\n 'BOOLEAN':('booleans','EXPRESSIONS TRUTHVALUE'),\n 'ASSERTION':'assert',\n 'ASSIGNMENT':('assignment','AUGMENTEDASSIGNMENT'),\n 'AUGMENTEDASSIGNMENT':('augassign','NUMBERMETHODS'),\n 'DELETION':'del',\n 'RETURNING':'return',\n 'IMPORTING':'import',\n 'CONDITIONAL':'if',\n 'LOOPING':('compound','for while break continue'),\n 'TRUTHVALUE':('truth','if while and or not BASICMETHODS'),\n 'DEBUGGING':('debugger','pdb'),\n 'CONTEXTMANAGERS':('context-managers','with'),\n }\n \n def __init__(self,input=None,output=None):\n self._input=input\n self._output=output\n \n @property\n def input(self):\n return self._input or sys.stdin\n \n @property\n def output(self):\n return self._output or sys.stdout\n \n def __repr__(self):\n if inspect.stack()[1][3]=='?':\n self()\n return ''\n return '<%s.%s instance>'%(self.__class__.__module__,\n self.__class__.__qualname__)\n \n _GoInteractive=object()\n def __call__(self,request=_GoInteractive):\n if request is not self._GoInteractive:\n try:\n self.help(request)\n except ImportError as err:\n self.output.write(f'{err}\\n')\n else:\n self.intro()\n self.interact()\n self.output.write('''\nYou are now leaving help and returning to the Python interpreter.\nIf you want to ask for help on a particular object directly from the\ninterpreter, you can type \"help(object)\". Executing \"help('string')\"\nhas the same effect as typing a particular string at the help> prompt.\n''')\n \n def interact(self):\n self.output.write('\\n')\n while True:\n try:\n request=self.getline('help> ')\n if not request:break\n except(KeyboardInterrupt,EOFError):\n break\n request=request.strip()\n \n \n \n if(len(request)>2 and request[0]==request[-1]in(\"'\",'\"')\n and request[0]not in request[1:-1]):\n request=request[1:-1]\n if request.lower()in('q','quit'):break\n if request =='help':\n self.intro()\n else:\n self.help(request)\n \n def getline(self,prompt):\n ''\n if self.input is sys.stdin:\n return input(prompt)\n else:\n self.output.write(prompt)\n self.output.flush()\n return self.input.readline()\n \n def help(self,request):\n if isinstance(request,str):\n request=request.strip()\n if request =='keywords':self.listkeywords()\n elif request =='symbols':self.listsymbols()\n elif request =='topics':self.listtopics()\n elif request =='modules':self.listmodules()\n elif request[:8]=='modules ':\n self.listmodules(request.split()[1])\n elif request in self.symbols:self.showsymbol(request)\n elif request in['True','False','None']:\n \n doc(eval(request),'Help on %s:')\n elif request in self.keywords:self.showtopic(request)\n elif request in self.topics:self.showtopic(request)\n elif request:doc(request,'Help on %s:',output=self._output)\n else:doc(str,'Help on %s:',output=self._output)\n elif isinstance(request,Helper):self()\n else:doc(request,'Help on %s:',output=self._output)\n self.output.write('\\n')\n \n def intro(self):\n self.output.write('''\nWelcome to Python {0}'s help utility!\n\nIf this is your first time using Python, you should definitely check out\nthe tutorial on the internet at https://docs.python.org/{0}/tutorial/.\n\nEnter the name of any module, keyword, or topic to get help on writing\nPython programs and using Python modules. To quit this help utility and\nreturn to the interpreter, just type \"quit\".\n\nTo get a list of available modules, keywords, symbols, or topics, type\n\"modules\", \"keywords\", \"symbols\", or \"topics\". Each module also comes\nwith a one-line summary of what it does; to list the modules whose name\nor summary contain a given string such as \"spam\", type \"modules spam\".\n'''.format('%d.%d'%sys.version_info[:2]))\n \n def list(self,items,columns=4,width=80):\n items=list(sorted(items))\n colw=width //columns\n rows=(len(items)+columns -1)//columns\n for row in range(rows):\n for col in range(columns):\n i=col *rows+row\n if i =0:\n callback(None,modname,desc)\n \n for importer,modname,ispkg in pkgutil.walk_packages(onerror=onerror):\n if self.quit:\n break\n \n if key is None:\n callback(None,modname,'')\n else:\n try:\n spec=importer.find_spec(modname)\n except SyntaxError:\n \n continue\n loader=spec.loader\n if hasattr(loader,'get_source'):\n try:\n source=loader.get_source(modname)\n except Exception:\n if onerror:\n onerror(modname)\n continue\n desc=source_synopsis(io.StringIO(source))or ''\n if hasattr(loader,'get_filename'):\n path=loader.get_filename(modname)\n else:\n path=None\n else:\n try:\n module=importlib._bootstrap._load(spec)\n except ImportError:\n if onerror:\n onerror(modname)\n continue\n desc=module.__doc__.splitlines()[0]if module.__doc__ else ''\n path=getattr(module,'__file__',None)\n name=modname+' - '+desc\n if name.lower().find(key)>=0:\n callback(path,modname,desc)\n \n if completer:\n completer()\n \ndef apropos(key):\n ''\n def callback(path,modname,desc):\n if modname[-9:]=='.__init__':\n modname=modname[:-9]+' (package)'\n print(modname,desc and '- '+desc)\n def onerror(modname):\n pass\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n ModuleScanner().run(callback,key,onerror=onerror)\n \n \n \ndef _start_server(urlhandler,hostname,port):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n import http.server\n import email.message\n import select\n import threading\n \n class DocHandler(http.server.BaseHTTPRequestHandler):\n \n def do_GET(self):\n ''\n\n\n\n \n if self.path.endswith('.css'):\n content_type='text/css'\n else:\n content_type='text/html'\n self.send_response(200)\n self.send_header('Content-Type','%s; charset=UTF-8'%content_type)\n self.end_headers()\n self.wfile.write(self.urlhandler(\n self.path,content_type).encode('utf-8'))\n \n def log_message(self,*args):\n \n pass\n \n class DocServer(http.server.HTTPServer):\n \n def __init__(self,host,port,callback):\n self.host=host\n self.address=(self.host,port)\n self.callback=callback\n self.base.__init__(self,self.address,self.handler)\n self.quit=False\n \n def serve_until_quit(self):\n while not self.quit:\n rd,wr,ex=select.select([self.socket.fileno()],[],[],1)\n if rd:\n self.handle_request()\n self.server_close()\n \n def server_activate(self):\n self.base.server_activate(self)\n if self.callback:\n self.callback(self)\n \n class ServerThread(threading.Thread):\n \n def __init__(self,urlhandler,host,port):\n self.urlhandler=urlhandler\n self.host=host\n self.port=int(port)\n threading.Thread.__init__(self)\n self.serving=False\n self.error=None\n \n def run(self):\n ''\n try:\n DocServer.base=http.server.HTTPServer\n DocServer.handler=DocHandler\n DocHandler.MessageClass=email.message.Message\n DocHandler.urlhandler=staticmethod(self.urlhandler)\n docsvr=DocServer(self.host,self.port,self.ready)\n self.docserver=docsvr\n docsvr.serve_until_quit()\n except Exception as err:\n self.error=err\n \n def ready(self,server):\n self.serving=True\n self.host=server.host\n self.port=server.server_port\n self.url='http://%s:%d/'%(self.host,self.port)\n \n def stop(self):\n ''\n self.docserver.quit=True\n self.join()\n \n \n self.docserver=None\n self.serving=False\n self.url=None\n \n thread=ServerThread(urlhandler,hostname,port)\n thread.start()\n \n \n while not thread.error and not thread.serving:\n time.sleep(.01)\n return thread\n \n \ndef _url_handler(url,content_type=\"text/html\"):\n ''\n\n\n\n\n\n\n \n class _HTMLDoc(HTMLDoc):\n \n def page(self,title,contents):\n ''\n css_path=\"pydoc_data/_pydoc.css\"\n css_link=(\n ''%\n css_path)\n return '''\\\n\n\n\n\nPydoc: %s\n%s%s
%s
\n'''%(title,css_link,html_navbar(),contents)\n \n \n html=_HTMLDoc()\n \n def html_navbar():\n version=html.escape(\"%s [%s, %s]\"%(platform.python_version(),\n platform.python_build()[0],\n platform.python_compiler()))\n return \"\"\"\n
\n Python %s
%s\n
\n
\n \n
\n
\n \n \n
 \n
\n \n \n
\n
\n
\n \"\"\"%(version,html.escape(platform.platform(terse=True)))\n \n def html_index():\n ''\n \n def bltinlink(name):\n return '%s'%(name,name)\n \n heading=html.heading(\n 'Index of Modules'\n )\n names=[name for name in sys.builtin_module_names\n if name !='__main__']\n contents=html.multicolumn(names,bltinlink)\n contents=[heading,'

'+html.bigsection(\n 'Built-in Modules','index',contents)]\n \n seen={}\n for dir in sys.path:\n contents.append(html.index(dir,seen))\n \n contents.append(\n '

pydoc by Ka-Ping Yee'\n '<ping@lfw.org>

')\n return 'Index of Modules',''.join(contents)\n \n def html_search(key):\n ''\n \n search_result=[]\n \n def callback(path,modname,desc):\n if modname[-9:]=='.__init__':\n modname=modname[:-9]+' (package)'\n search_result.append((modname,desc and '- '+desc))\n \n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n def onerror(modname):\n pass\n ModuleScanner().run(callback,key,onerror=onerror)\n \n \n def bltinlink(name):\n return '%s'%(name,name)\n \n results=[]\n heading=html.heading(\n 'Search Results',\n )\n for name,desc in search_result:\n results.append(bltinlink(name)+desc)\n contents=heading+html.bigsection(\n 'key = %s'%key,'index','
'.join(results))\n return 'Search Results',contents\n \n def html_topics():\n ''\n \n def bltinlink(name):\n return '%s'%(name,name)\n \n heading=html.heading(\n 'INDEX',\n )\n names=sorted(Helper.topics.keys())\n \n contents=html.multicolumn(names,bltinlink)\n contents=heading+html.bigsection(\n 'Topics','index',contents)\n return 'Topics',contents\n \n def html_keywords():\n ''\n heading=html.heading(\n 'INDEX',\n )\n names=sorted(Helper.keywords.keys())\n \n def bltinlink(name):\n return '%s'%(name,name)\n \n contents=html.multicolumn(names,bltinlink)\n contents=heading+html.bigsection(\n 'Keywords','index',contents)\n return 'Keywords',contents\n \n def html_topicpage(topic):\n ''\n buf=io.StringIO()\n htmlhelp=Helper(buf,buf)\n contents,xrefs=htmlhelp._gettopic(topic)\n if topic in htmlhelp.keywords:\n title='KEYWORD'\n else:\n title='TOPIC'\n heading=html.heading(\n '%s'%title,\n )\n contents='
%s
'%html.markup(contents)\n contents=html.bigsection(topic,'index',contents)\n if xrefs:\n xrefs=sorted(xrefs.split())\n \n def bltinlink(name):\n return '%s'%(name,name)\n \n xrefs=html.multicolumn(xrefs,bltinlink)\n xrefs=html.section('Related help topics: ','index',xrefs)\n return('%s %s'%(title,topic),\n ''.join((heading,contents,xrefs)))\n \n def html_getobj(url):\n obj=locate(url,forceload=1)\n if obj is None and url !='None':\n raise ValueError('could not find object')\n title=describe(obj)\n content=html.document(obj,url)\n return title,content\n \n def html_error(url,exc):\n heading=html.heading(\n 'Error',\n )\n contents='
'.join(html.escape(line)for line in\n format_exception_only(type(exc),exc))\n contents=heading+html.bigsection(url,'error',contents)\n return \"Error - %s\"%url,contents\n \n def get_html_page(url):\n ''\n complete_url=url\n if url.endswith('.html'):\n url=url[:-5]\n try:\n if url in(\"\",\"index\"):\n title,content=html_index()\n elif url ==\"topics\":\n title,content=html_topics()\n elif url ==\"keywords\":\n title,content=html_keywords()\n elif '='in url:\n op,_,url=url.partition('=')\n if op ==\"search?key\":\n title,content=html_search(url)\n elif op ==\"topic?key\":\n \n try:\n title,content=html_topicpage(url)\n except ValueError:\n title,content=html_getobj(url)\n elif op ==\"get?key\":\n \n if url in(\"\",\"index\"):\n title,content=html_index()\n else:\n try:\n title,content=html_getobj(url)\n except ValueError:\n title,content=html_topicpage(url)\n else:\n raise ValueError('bad pydoc url')\n else:\n title,content=html_getobj(url)\n except Exception as exc:\n \n title,content=html_error(complete_url,exc)\n return html.page(title,content)\n \n if url.startswith('/'):\n url=url[1:]\n if content_type =='text/css':\n path_here=os.path.dirname(os.path.realpath(__file__))\n css_path=os.path.join(path_here,url)\n with open(css_path)as fp:\n return ''.join(fp.readlines())\n elif content_type =='text/html':\n return get_html_page(url)\n \n raise TypeError('unknown content type %r for url %s'%(content_type,url))\n \n \ndef browse(port=0,*,open_browser=True,hostname='localhost'):\n ''\n\n\n\n \n import webbrowser\n serverthread=_start_server(_url_handler,hostname,port)\n if serverthread.error:\n print(serverthread.error)\n return\n if serverthread.serving:\n server_help_msg='Server commands: [b]rowser, [q]uit'\n if open_browser:\n webbrowser.open(serverthread.url)\n try:\n print('Server ready at',serverthread.url)\n print(server_help_msg)\n while serverthread.serving:\n cmd=input('server> ')\n cmd=cmd.lower()\n if cmd =='q':\n break\n elif cmd =='b':\n webbrowser.open(serverthread.url)\n else:\n print(server_help_msg)\n except(KeyboardInterrupt,EOFError):\n print()\n finally:\n if serverthread.serving:\n serverthread.stop()\n print('Server stopped')\n \n \n \n \ndef ispath(x):\n return isinstance(x,str)and x.find(os.sep)>=0\n \ndef _get_revised_path(given_path,argv0):\n ''\n\n\n\n\n \n \n \n \n \n \n \n if ''in given_path or os.curdir in given_path or os.getcwd()in given_path:\n return None\n \n \n \n stdlib_dir=os.path.dirname(__file__)\n script_dir=os.path.dirname(argv0)\n revised_path=given_path.copy()\n if script_dir in given_path and not os.path.samefile(script_dir,stdlib_dir):\n revised_path.remove(script_dir)\n revised_path.insert(0,os.getcwd())\n return revised_path\n \n \n \ndef _adjust_cli_sys_path():\n ''\n\n\n \n revised_path=_get_revised_path(sys.path,sys.argv[0])\n if revised_path is not None:\n sys.path[:]=revised_path\n \n \ndef cli():\n ''\n import getopt\n class BadUsage(Exception):pass\n \n _adjust_cli_sys_path()\n \n try:\n opts,args=getopt.getopt(sys.argv[1:],'bk:n:p:w')\n writing=False\n start_server=False\n open_browser=False\n port=0\n hostname='localhost'\n for opt,val in opts:\n if opt =='-b':\n start_server=True\n open_browser=True\n if opt =='-k':\n apropos(val)\n return\n if opt =='-p':\n start_server=True\n port=val\n if opt =='-w':\n writing=True\n if opt =='-n':\n start_server=True\n hostname=val\n \n if start_server:\n browse(port,hostname=hostname,open_browser=open_browser)\n return\n \n if not args:raise BadUsage\n for arg in args:\n if ispath(arg)and not os.path.exists(arg):\n print('file %r does not exist'%arg)\n sys.exit(1)\n try:\n if ispath(arg)and os.path.isfile(arg):\n arg=importfile(arg)\n if writing:\n if ispath(arg)and os.path.isdir(arg):\n writedocs(arg)\n else:\n writedoc(arg)\n else:\n help.help(arg)\n except(ImportError,ErrorDuringImport)as value:\n print(value)\n sys.exit(1)\n \n except(getopt.error,BadUsage):\n cmd=os.path.splitext(os.path.basename(sys.argv[0]))[0]\n print(\"\"\"pydoc - the Python documentation tool\n\n{cmd} ...\n Show text documentation on something. may be the name of a\n Python keyword, topic, function, module, or package, or a dotted\n reference to a class or function within a module or module in a\n package. If contains a '{sep}', it is used as the path to a\n Python source file to document. If name is 'keywords', 'topics',\n or 'modules', a listing of these things is displayed.\n\n{cmd} -k \n Search for a keyword in the synopsis lines of all available modules.\n\n{cmd} -n \n Start an HTTP server with the given hostname (default: localhost).\n\n{cmd} -p \n Start an HTTP server on the given port on the local machine. Port\n number 0 can be used to get an arbitrary unused port.\n\n{cmd} -b\n Start an HTTP server on an arbitrary unused port and open a web browser\n to interactively browse documentation. This option can be used in\n combination with -n and/or -p.\n\n{cmd} -w ...\n Write out the HTML documentation for a module to a file in the current\n directory. If contains a '{sep}', it is treated as a filename; if\n it names a directory, documentation is written for all the contents.\n\"\"\".format(cmd=cmd,sep=os.sep))\n \nif __name__ =='__main__':\n cli()\n", ["__future__", "builtins", "collections", "email.message", "getopt", "http.server", "importlib._bootstrap", "importlib._bootstrap_external", "importlib.machinery", "importlib.util", "inspect", "io", "os", "pkgutil", "platform", "pydoc_data.topics", "re", "reprlib", "select", "subprocess", "sys", "sysconfig", "tempfile", "textwrap", "threading", "time", "tokenize", "traceback", "tty", "urllib.parse", "warnings", "webbrowser"]], "py_compile": [".py", "''\n\n\n\n\nimport enum\nimport importlib._bootstrap_external\nimport importlib.machinery\nimport importlib.util\nimport os\nimport os.path\nimport sys\nimport traceback\n\n__all__=[\"compile\",\"main\",\"PyCompileError\",\"PycInvalidationMode\"]\n\n\nclass PyCompileError(Exception):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,exc_type,exc_value,file,msg=''):\n exc_type_name=exc_type.__name__\n if exc_type is SyntaxError:\n tbtext=''.join(traceback.format_exception_only(\n exc_type,exc_value))\n errmsg=tbtext.replace('File \"\"','File \"%s\"'%file)\n else:\n errmsg=\"Sorry: %s: %s\"%(exc_type_name,exc_value)\n \n Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)\n \n self.exc_type_name=exc_type_name\n self.exc_value=exc_value\n self.file=file\n self.msg=msg or errmsg\n \n def __str__(self):\n return self.msg\n \n \nclass PycInvalidationMode(enum.Enum):\n TIMESTAMP=1\n CHECKED_HASH=2\n UNCHECKED_HASH=3\n \n \ndef _get_default_invalidation_mode():\n if os.environ.get('SOURCE_DATE_EPOCH'):\n return PycInvalidationMode.CHECKED_HASH\n else:\n return PycInvalidationMode.TIMESTAMP\n \n \ndef compile(file,cfile=None,dfile=None,doraise=False,optimize=-1,\ninvalidation_mode=None,quiet=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if invalidation_mode is None:\n invalidation_mode=_get_default_invalidation_mode()\n if cfile is None:\n if optimize >=0:\n optimization=optimize if optimize >=1 else ''\n cfile=importlib.util.cache_from_source(file,\n optimization=optimization)\n else:\n cfile=importlib.util.cache_from_source(file)\n if os.path.islink(cfile):\n msg=('{} is a symlink and will be changed into a regular file if '\n 'import writes a byte-compiled file to it')\n raise FileExistsError(msg.format(cfile))\n elif os.path.exists(cfile)and not os.path.isfile(cfile):\n msg=('{} is a non-regular file and will be changed into a regular '\n 'one if import writes a byte-compiled file to it')\n raise FileExistsError(msg.format(cfile))\n loader=importlib.machinery.SourceFileLoader('',file)\n source_bytes=loader.get_data(file)\n try:\n code=loader.source_to_code(source_bytes,dfile or file,\n _optimize=optimize)\n except Exception as err:\n py_exc=PyCompileError(err.__class__,err,dfile or file)\n if quiet <2:\n if doraise:\n raise py_exc\n else:\n sys.stderr.write(py_exc.msg+'\\n')\n return\n try:\n dirname=os.path.dirname(cfile)\n if dirname:\n os.makedirs(dirname)\n except FileExistsError:\n pass\n if invalidation_mode ==PycInvalidationMode.TIMESTAMP:\n source_stats=loader.path_stats(file)\n bytecode=importlib._bootstrap_external._code_to_timestamp_pyc(\n code,source_stats['mtime'],source_stats['size'])\n else:\n source_hash=importlib.util.source_hash(source_bytes)\n bytecode=importlib._bootstrap_external._code_to_hash_pyc(\n code,\n source_hash,\n (invalidation_mode ==PycInvalidationMode.CHECKED_HASH),\n )\n mode=importlib._bootstrap_external._calc_mode(file)\n importlib._bootstrap_external._write_atomic(cfile,bytecode,mode)\n return cfile\n \n \ndef main():\n import argparse\n \n description='A simple command-line interface for py_compile module.'\n parser=argparse.ArgumentParser(description=description)\n parser.add_argument(\n '-q','--quiet',\n action='store_true',\n help='Suppress error output',\n )\n parser.add_argument(\n 'filenames',\n nargs='+',\n help='Files to compile',\n )\n args=parser.parse_args()\n if args.filenames ==['-']:\n filenames=[filename.rstrip('\\n')for filename in sys.stdin.readlines()]\n else:\n filenames=args.filenames\n for filename in filenames:\n try:\n compile(filename,doraise=True)\n except PyCompileError as error:\n if args.quiet:\n parser.exit(1)\n else:\n parser.exit(1,error.msg)\n except OSError as error:\n if args.quiet:\n parser.exit(1)\n else:\n parser.exit(1,str(error))\n \n \nif __name__ ==\"__main__\":\n main()\n", ["argparse", "enum", "importlib._bootstrap_external", "importlib.machinery", "importlib.util", "os", "os.path", "sys", "traceback"]], "queue": [".py", "''\n\nimport threading\nimport types\nfrom collections import deque\nfrom heapq import heappush,heappop\nfrom time import monotonic as time\ntry:\n from _queue import SimpleQueue\nexcept ImportError:\n SimpleQueue=None\n \n__all__=[\n'Empty',\n'Full',\n'ShutDown',\n'Queue',\n'PriorityQueue',\n'LifoQueue',\n'SimpleQueue',\n]\n\n\ntry:\n from _queue import Empty\nexcept ImportError:\n class Empty(Exception):\n ''\n pass\n \nclass Full(Exception):\n ''\n pass\n \n \nclass ShutDown(Exception):\n ''\n \n \nclass Queue:\n ''\n\n\n \n \n def __init__(self,maxsize=0):\n self.maxsize=maxsize\n self._init(maxsize)\n \n \n \n \n \n self.mutex=threading.Lock()\n \n \n \n self.not_empty=threading.Condition(self.mutex)\n \n \n \n self.not_full=threading.Condition(self.mutex)\n \n \n \n self.all_tasks_done=threading.Condition(self.mutex)\n self.unfinished_tasks=0\n \n \n self.is_shutdown=False\n \n def task_done(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n with self.all_tasks_done:\n unfinished=self.unfinished_tasks -1\n if unfinished <=0:\n if unfinished <0:\n raise ValueError('task_done() called too many times')\n self.all_tasks_done.notify_all()\n self.unfinished_tasks=unfinished\n \n def join(self):\n ''\n\n\n\n\n\n\n \n with self.all_tasks_done:\n while self.unfinished_tasks:\n self.all_tasks_done.wait()\n \n def qsize(self):\n ''\n with self.mutex:\n return self._qsize()\n \n def empty(self):\n ''\n\n\n\n\n\n\n\n\n \n with self.mutex:\n return not self._qsize()\n \n def full(self):\n ''\n\n\n\n\n\n \n with self.mutex:\n return 0 0:\n if not block:\n if self._qsize()>=self.maxsize:\n raise Full\n elif timeout is None:\n while self._qsize()>=self.maxsize:\n self.not_full.wait()\n if self.is_shutdown:\n raise ShutDown\n elif timeout <0:\n raise ValueError(\"'timeout' must be a non-negative number\")\n else:\n endtime=time()+timeout\n while self._qsize()>=self.maxsize:\n remaining=endtime -time()\n if remaining <=0.0:\n raise Full\n self.not_full.wait(remaining)\n if self.is_shutdown:\n raise ShutDown\n self._put(item)\n self.unfinished_tasks +=1\n self.not_empty.notify()\n \n def get(self,block=True,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n with self.not_empty:\n if self.is_shutdown and not self._qsize():\n raise ShutDown\n if not block:\n if not self._qsize():\n raise Empty\n elif timeout is None:\n while not self._qsize():\n self.not_empty.wait()\n if self.is_shutdown and not self._qsize():\n raise ShutDown\n elif timeout <0:\n raise ValueError(\"'timeout' must be a non-negative number\")\n else:\n endtime=time()+timeout\n while not self._qsize():\n remaining=endtime -time()\n if remaining <=0.0:\n raise Empty\n self.not_empty.wait(remaining)\n if self.is_shutdown and not self._qsize():\n raise ShutDown\n item=self._get()\n self.not_full.notify()\n return item\n \n def put_nowait(self,item):\n ''\n\n\n\n \n return self.put(item,block=False)\n \n def get_nowait(self):\n ''\n\n\n\n \n return self.get(block=False)\n \n def shutdown(self,immediate=False):\n ''\n\n\n\n\n\n\n\n \n with self.mutex:\n self.is_shutdown=True\n if immediate:\n while self._qsize():\n self._get()\n if self.unfinished_tasks >0:\n self.unfinished_tasks -=1\n \n self.all_tasks_done.notify_all()\n \n self.not_empty.notify_all()\n self.not_full.notify_all()\n \n \n \n \n \n \n def _init(self,maxsize):\n self.queue=deque()\n \n def _qsize(self):\n return len(self.queue)\n \n \n def _put(self,item):\n self.queue.append(item)\n \n \n def _get(self):\n return self.queue.popleft()\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \nclass PriorityQueue(Queue):\n ''\n\n\n \n \n def _init(self,maxsize):\n self.queue=[]\n \n def _qsize(self):\n return len(self.queue)\n \n def _put(self,item):\n heappush(self.queue,item)\n \n def _get(self):\n return heappop(self.queue)\n \n \nclass LifoQueue(Queue):\n ''\n \n def _init(self,maxsize):\n self.queue=[]\n \n def _qsize(self):\n return len(self.queue)\n \n def _put(self,item):\n self.queue.append(item)\n \n def _get(self):\n return self.queue.pop()\n \n \nclass _PySimpleQueue:\n ''\n\n\n \n \n \n \n \n \n def __init__(self):\n self._queue=deque()\n self._count=threading.Semaphore(0)\n \n def put(self,item,block=True,timeout=None):\n ''\n\n\n\n \n self._queue.append(item)\n self._count.release()\n \n def get(self,block=True,timeout=None):\n ''\n\n\n\n\n\n\n\n\n \n if timeout is not None and timeout <0:\n raise ValueError(\"'timeout' must be a non-negative number\")\n if not self._count.acquire(block,timeout):\n raise Empty\n return self._queue.popleft()\n \n def put_nowait(self,item):\n ''\n\n\n\n \n return self.put(item,block=False)\n \n def get_nowait(self):\n ''\n\n\n\n \n return self.get(block=False)\n \n def empty(self):\n ''\n return len(self._queue)==0\n \n def qsize(self):\n ''\n return len(self._queue)\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \nif SimpleQueue is None:\n SimpleQueue=_PySimpleQueue\n", ["_queue", "collections", "heapq", "threading", "time", "types"]], "quopri": [".py", "#! /usr/bin/env python3\n\n\"\"\"Conversions to/from quoted-printable transport encoding as per RFC 1521.\"\"\"\n\n\n\n__all__=[\"encode\",\"decode\",\"encodestring\",\"decodestring\"]\n\nESCAPE=b'='\nMAXLINESIZE=76\nHEX=b'0123456789ABCDEF'\nEMPTYSTRING=b''\n\ntry:\n from binascii import a2b_qp,b2a_qp\nexcept ImportError:\n a2b_qp=None\n b2a_qp=None\n \n \ndef needsquoting(c,quotetabs,header):\n ''\n\n\n\n\n \n assert isinstance(c,bytes)\n if c in b' \\t':\n return quotetabs\n \n if c ==b'_':\n return header\n return c ==ESCAPE or not(b' '<=c <=b'~')\n \ndef quote(c):\n ''\n assert isinstance(c,bytes)and len(c)==1\n c=ord(c)\n return ESCAPE+bytes((HEX[c //16],HEX[c %16]))\n \n \n \ndef encode(input,output,quotetabs,header=False):\n ''\n\n\n\n\n\n \n \n if b2a_qp is not None:\n data=input.read()\n odata=b2a_qp(data,quotetabs=quotetabs,header=header)\n output.write(odata)\n return\n \n def write(s,output=output,lineEnd=b'\\n'):\n \n \n if s and s[-1:]in b' \\t':\n output.write(s[:-1]+quote(s[-1:])+lineEnd)\n elif s ==b'.':\n output.write(quote(s)+lineEnd)\n else:\n output.write(s+lineEnd)\n \n prevline=None\n while line :=input.readline():\n outline=[]\n \n stripped=b''\n if line[-1:]==b'\\n':\n line=line[:-1]\n stripped=b'\\n'\n \n for c in line:\n c=bytes((c,))\n if needsquoting(c,quotetabs,header):\n c=quote(c)\n if header and c ==b' ':\n outline.append(b'_')\n else:\n outline.append(c)\n \n if prevline is not None:\n write(prevline)\n \n \n thisline=EMPTYSTRING.join(outline)\n while len(thisline)>MAXLINESIZE:\n \n \n write(thisline[:MAXLINESIZE -1],lineEnd=b'=\\n')\n thisline=thisline[MAXLINESIZE -1:]\n \n prevline=thisline\n \n if prevline is not None:\n write(prevline,lineEnd=stripped)\n \ndef encodestring(s,quotetabs=False,header=False):\n if b2a_qp is not None:\n return b2a_qp(s,quotetabs=quotetabs,header=header)\n from io import BytesIO\n infp=BytesIO(s)\n outfp=BytesIO()\n encode(infp,outfp,quotetabs,header)\n return outfp.getvalue()\n \n \n \ndef decode(input,output,header=False):\n ''\n\n \n \n if a2b_qp is not None:\n data=input.read()\n odata=a2b_qp(data,header=header)\n output.write(odata)\n return\n \n new=b''\n while line :=input.readline():\n i,n=0,len(line)\n if n >0 and line[n -1:n]==b'\\n':\n partial=0 ;n=n -1\n \n while n >0 and line[n -1:n]in b\" \\t\\r\":\n n=n -1\n else:\n partial=1\n while i =n:\n r=getrandbits(k)\n return r\n \n def _randbelow_without_getrandbits(self,n,maxsize=1 <=maxsize:\n _warn(\"Underlying random() generator does not supply \\n\"\n \"enough bits to choose from a population range this large.\\n\"\n \"To remove the range limitation, add a getrandbits() method.\")\n return _floor(random()*n)\n rem=maxsize %n\n limit=(maxsize -rem)/maxsize\n r=random()\n while r >=limit:\n r=random()\n return _floor(r *maxsize)%n\n \n _randbelow=_randbelow_with_getrandbits\n \n \n \n \n \n \n \n \n \n \n \n \n def randbytes(self,n):\n ''\n return self.getrandbits(n *8).to_bytes(n,'little')\n \n \n \n \n def randrange(self,start,stop=None,step=_ONE):\n ''\n\n\n\n\n \n \n \n \n istart=_index(start)\n if stop is None:\n \n \n if step is not _ONE:\n raise TypeError(\"Missing a non-None stop argument\")\n if istart >0:\n return self._randbelow(istart)\n raise ValueError(\"empty range for randrange()\")\n \n \n istop=_index(stop)\n width=istop -istart\n istep=_index(step)\n \n if istep ==1:\n if width >0:\n return istart+self._randbelow(width)\n raise ValueError(f\"empty range in randrange({start}, {stop})\")\n \n \n if istep >0:\n n=(width+istep -1)//istep\n elif istep <0:\n n=(width+istep+1)//istep\n else:\n raise ValueError(\"zero step for randrange()\")\n if n <=0:\n raise ValueError(f\"empty range in randrange({start}, {stop}, {step})\")\n return istart+istep *self._randbelow(n)\n \n def randint(self,a,b):\n ''\n \n \n return self.randrange(a,b+1)\n \n \n \n \n def choice(self,seq):\n ''\n \n \n \n if not len(seq):\n raise IndexError('Cannot choose from an empty sequence')\n return seq[self._randbelow(len(seq))]\n \n def shuffle(self,x):\n ''\n \n randbelow=self._randbelow\n for i in reversed(range(1,len(x))):\n \n j=randbelow(i+1)\n x[i],x[j]=x[j],x[i]\n \n def sample(self,population,k,*,counts=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if not isinstance(population,_Sequence):\n raise TypeError(\"Population must be a sequence. \"\n \"For dicts or sets, use sorted(d).\")\n n=len(population)\n if counts is not None:\n cum_counts=list(_accumulate(counts))\n if len(cum_counts)!=n:\n raise ValueError('The number of counts does not match the population')\n total=cum_counts.pop()\n if not isinstance(total,int):\n raise TypeError('Counts must be integers')\n if total <=0:\n raise ValueError('Total of counts must be greater than zero')\n selections=self.sample(range(total),k=k)\n bisect=_bisect\n return[population[bisect(cum_counts,s)]for s in selections]\n randbelow=self._randbelow\n if not 0 <=k <=n:\n raise ValueError(\"Sample larger than population or is negative\")\n result=[None]*k\n setsize=21\n if k >5:\n setsize +=4 **_ceil(_log(k *3,4))\n if n <=setsize:\n \n \n pool=list(population)\n for i in range(k):\n j=randbelow(n -i)\n result[i]=pool[j]\n pool[j]=pool[n -i -1]\n else:\n selected=set()\n selected_add=selected.add\n for i in range(k):\n j=randbelow(n)\n while j in selected:\n j=randbelow(n)\n selected_add(j)\n result[i]=population[j]\n return result\n \n def choices(self,population,weights=None,*,cum_weights=None,k=1):\n ''\n\n\n\n\n \n random=self.random\n n=len(population)\n if cum_weights is None:\n if weights is None:\n floor=_floor\n n +=0.0\n return[population[floor(random()*n)]for i in _repeat(None,k)]\n try:\n cum_weights=list(_accumulate(weights))\n except TypeError:\n if not isinstance(weights,int):\n raise\n k=weights\n raise TypeError(\n f'The number of choices must be a keyword argument: {k=}'\n )from None\n elif weights is not None:\n raise TypeError('Cannot specify both weights and cumulative weights')\n if len(cum_weights)!=n:\n raise ValueError('The number of weights does not match the population')\n total=cum_weights[-1]+0.0\n if total <=0.0:\n raise ValueError('Total of weights must be greater than zero')\n if not _isfinite(total):\n raise ValueError('Total of weights must be finite')\n bisect=_bisect\n hi=n -1\n return[population[bisect(cum_weights,random()*total,0,hi)]\n for i in _repeat(None,k)]\n \n \n \n \n def uniform(self,a,b):\n ''\n return a+(b -a)*self.random()\n \n def triangular(self,low=0.0,high=1.0,mode=None):\n ''\n\n\n\n\n\n\n \n u=self.random()\n try:\n c=0.5 if mode is None else(mode -low)/(high -low)\n except ZeroDivisionError:\n return low\n if u >c:\n u=1.0 -u\n c=1.0 -c\n low,high=high,low\n return low+(high -low)*_sqrt(u *c)\n \n def normalvariate(self,mu=0.0,sigma=1.0):\n ''\n\n\n\n \n \n \n \n \n \n random=self.random\n while True:\n u1=random()\n u2=1.0 -random()\n z=NV_MAGICCONST *(u1 -0.5)/u2\n zz=z *z /4.0\n if zz <=-_log(u2):\n break\n return mu+z *sigma\n \n def gauss(self,mu=0.0,sigma=1.0):\n ''\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n random=self.random\n z=self.gauss_next\n self.gauss_next=None\n if z is None:\n x2pi=random()*TWOPI\n g2rad=_sqrt(-2.0 *_log(1.0 -random()))\n z=_cos(x2pi)*g2rad\n self.gauss_next=_sin(x2pi)*g2rad\n \n return mu+z *sigma\n \n def lognormvariate(self,mu,sigma):\n ''\n\n\n\n\n\n \n return _exp(self.normalvariate(mu,sigma))\n \n def expovariate(self,lambd=1.0):\n ''\n\n\n\n\n\n\n\n \n \n \n \n \n \n return -_log(1.0 -self.random())/lambd\n \n def vonmisesvariate(self,mu,kappa):\n ''\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n random=self.random\n if kappa <=1e-6:\n return TWOPI *random()\n \n s=0.5 /kappa\n r=s+_sqrt(1.0+s *s)\n \n while True:\n u1=random()\n z=_cos(_pi *u1)\n \n d=z /(r+z)\n u2=random()\n if u2 <1.0 -d *d or u2 <=(1.0 -d)*_exp(d):\n break\n \n q=1.0 /r\n f=(q+z)/(1.0+q *z)\n u3=random()\n if u3 >0.5:\n theta=(mu+_acos(f))%TWOPI\n else:\n theta=(mu -_acos(f))%TWOPI\n \n return theta\n \n def gammavariate(self,alpha,beta):\n ''\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n if alpha <=0.0 or beta <=0.0:\n raise ValueError('gammavariate: alpha and beta must be > 0.0')\n \n random=self.random\n if alpha >1.0:\n \n \n \n \n \n ainv=_sqrt(2.0 *alpha -1.0)\n bbb=alpha -LOG4\n ccc=alpha+ainv\n \n while True:\n u1=random()\n if not 1e-7 =0.0 or r >=_log(z):\n return x *beta\n \n elif alpha ==1.0:\n \n return -_log(1.0 -random())*beta\n \n else:\n \n \n while True:\n u=random()\n b=(_e+alpha)/_e\n p=b *u\n if p <=1.0:\n x=p **(1.0 /alpha)\n else:\n x=-_log((b -p)/alpha)\n u1=random()\n if p >1.0:\n if u1 <=x **(alpha -1.0):\n break\n elif u1 <=_exp(-x):\n break\n return x *beta\n \n def betavariate(self,alpha,beta):\n ''\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n y=self.gammavariate(alpha,1.0)\n if y:\n return y /(y+self.gammavariate(beta,1.0))\n return 0.0\n \n def paretovariate(self,alpha):\n ''\n \n \n u=1.0 -self.random()\n return u **(-1.0 /alpha)\n \n def weibullvariate(self,alpha,beta):\n ''\n\n\n\n \n \n \n u=1.0 -self.random()\n return alpha *(-_log(u))**(1.0 /beta)\n \n \n \n \n def binomialvariate(self,n=1,p=0.5):\n ''\n\n\n\n\n\n\n\n\n \n \n if n <0:\n raise ValueError(\"n must be non-negative\")\n if p <=0.0 or p >=1.0:\n if p ==0.0:\n return 0\n if p ==1.0:\n return n\n raise ValueError(\"p must be in the range 0.0 <= p <= 1.0\")\n \n random=self.random\n \n \n if n ==1:\n return _index(random()0.5:\n return n -self.binomialvariate(n,1.0 -p)\n \n if n *p <10.0:\n \n \n x=y=0\n c=_log2(1.0 -p)\n if not c:\n return x\n while True:\n y +=_floor(_log2(random())/c)+1\n if y >n:\n return x\n x +=1\n \n \n \n assert n *p >=10.0 and p <=0.5\n setup_complete=False\n \n spq=_sqrt(n *p *(1.0 -p))\n b=1.15+2.53 *spq\n a=-0.0873+0.0248 *b+0.01 *p\n c=n *p+0.5\n vr=0.92 -4.2 /b\n \n while True:\n \n u=random()\n u -=0.5\n us=0.5 -_fabs(u)\n k=_floor((2.0 *a /us+b)*u+c)\n if k <0 or k >n:\n continue\n \n \n \n v=random()\n if us >=0.07 and v <=vr:\n return k\n \n \n \n \n if not setup_complete:\n alpha=(2.83+5.1 /b)*spq\n lpq=_log(p /(1.0 -p))\n m=_floor((n+1)*p)\n h=_lgamma(m+1)+_lgamma(n -m+1)\n setup_complete=True\n v *=alpha /(a /(us *us)+b)\n if _log(v)<=h -_lgamma(k+1)-_lgamma(n -k+1)+(k -m)*lpq:\n return k\n \n \n \n \n \n \nclass SystemRandom(Random):\n ''\n\n\n\n\n\n \n \n def random(self):\n ''\n return(int.from_bytes(_urandom(7))>>3)*RECIP_BPF\n \n def getrandbits(self,k):\n ''\n if k <0:\n raise ValueError('number of bits must be non-negative')\n numbytes=(k+7)//8\n x=int.from_bytes(_urandom(numbytes))\n return x >>(numbytes *8 -k)\n \n def randbytes(self,n):\n ''\n \n \n return _urandom(n)\n \n def seed(self,*args,**kwds):\n ''\n return None\n \n def _notimplemented(self,*args,**kwds):\n ''\n raise NotImplementedError('System entropy source does not have state.')\n getstate=setstate=_notimplemented\n \n \n \n \n \n \n \n \n \n_inst=Random()\nseed=_inst.seed\nrandom=_inst.random\nuniform=_inst.uniform\ntriangular=_inst.triangular\nrandint=_inst.randint\nchoice=_inst.choice\nrandrange=_inst.randrange\nsample=_inst.sample\nshuffle=_inst.shuffle\nchoices=_inst.choices\nnormalvariate=_inst.normalvariate\nlognormvariate=_inst.lognormvariate\nexpovariate=_inst.expovariate\nvonmisesvariate=_inst.vonmisesvariate\ngammavariate=_inst.gammavariate\ngauss=_inst.gauss\nbetavariate=_inst.betavariate\nbinomialvariate=_inst.binomialvariate\nparetovariate=_inst.paretovariate\nweibullvariate=_inst.weibullvariate\ngetstate=_inst.getstate\nsetstate=_inst.setstate\ngetrandbits=_inst.getrandbits\nrandbytes=_inst.randbytes\n\n\n\n\n\ndef _test_generator(n,func,args):\n from statistics import stdev,fmean as mean\n from time import perf_counter\n \n t0=perf_counter()\n data=[func(*args)for i in _repeat(None,n)]\n t1=perf_counter()\n \n xbar=mean(data)\n sigma=stdev(data,xbar)\n low=min(data)\n high=max(data)\n \n print(f'{t1 -t0:.3f} sec, {n} times {func.__name__}{args !r}')\n print('avg %g, stddev %g, min %g, max %g\\n'%(xbar,sigma,low,high))\n \n \ndef _test(N=10_000):\n _test_generator(N,random,())\n _test_generator(N,normalvariate,(0.0,1.0))\n _test_generator(N,lognormvariate,(0.0,1.0))\n _test_generator(N,vonmisesvariate,(0.0,1.0))\n _test_generator(N,binomialvariate,(15,0.60))\n _test_generator(N,binomialvariate,(100,0.75))\n _test_generator(N,gammavariate,(0.01,1.0))\n _test_generator(N,gammavariate,(0.1,1.0))\n _test_generator(N,gammavariate,(0.1,2.0))\n _test_generator(N,gammavariate,(0.5,1.0))\n _test_generator(N,gammavariate,(0.9,1.0))\n _test_generator(N,gammavariate,(1.0,1.0))\n _test_generator(N,gammavariate,(2.0,1.0))\n _test_generator(N,gammavariate,(20.0,1.0))\n _test_generator(N,gammavariate,(200.0,1.0))\n _test_generator(N,gauss,(0.0,1.0))\n _test_generator(N,betavariate,(3.0,3.0))\n _test_generator(N,triangular,(0.0,1.0,1.0 /3.0))\n \n \n \n \n \nif hasattr(_os,\"fork\"):\n _os.register_at_fork(after_in_child=_inst.seed)\n \n \nif __name__ =='__main__':\n _test()\n \n", ["_collections_abc", "_random", "_sha512", "bisect", "hashlib", "itertools", "math", "operator", "os", "statistics", "time", "warnings"]], "re": [".py", "import enum\n\n\nclass _compiler:\n SRE_FLAG_IGNORECASE=2\n SRE_FLAG_LOCALE=4\n SRE_FLAG_MULTILINE=8\n SRE_FLAG_DOTALL=16\n SRE_FLAG_UNICODE=32\n SRE_FLAG_VERBOSE=64\n SRE_FLAG_DEBUG=128\n SRE_FLAG_ASCII=256\n SRE_INFO_PREFIX=1\n SRE_INFO_LITERAL=2\n SRE_INFO_CHARSET=4\n \n@enum.global_enum\n@enum._simple_enum(enum.IntFlag,boundary=enum.KEEP)\nclass RegexFlag:\n NOFLAG=0\n ASCII=A=_compiler.SRE_FLAG_ASCII\n IGNORECASE=I=_compiler.SRE_FLAG_IGNORECASE\n LOCALE=L=_compiler.SRE_FLAG_LOCALE\n UNICODE=U=_compiler.SRE_FLAG_UNICODE\n MULTILINE=M=_compiler.SRE_FLAG_MULTILINE\n DOTALL=S=_compiler.SRE_FLAG_DOTALL\n VERBOSE=X=_compiler.SRE_FLAG_VERBOSE\n \n \n DEBUG=_compiler.SRE_FLAG_DEBUG\n __str__=object.__str__\n _numeric_repr_=hex\n \n \nfrom python_re import *\nfrom browser import console\n\n\nimport python_re\n_compile=python_re._compile\n_reconstructor=python_re._reconstructor\n\npython_re._reconstructor.__module__='re'\n", ["browser", "enum", "python_re"]], "re1": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nr\"\"\"Support for regular expressions (RE).\n\nThis module provides regular expression matching operations similar to\nthose found in Perl. It supports both 8-bit and Unicode strings; both\nthe pattern and the strings being processed can contain null bytes and\ncharacters outside the US ASCII range.\n\nRegular expressions can contain both special and ordinary characters.\nMost ordinary characters, like \"A\", \"a\", or \"0\", are the simplest\nregular expressions; they simply match themselves. You can\nconcatenate ordinary characters, so last matches the string 'last'.\n\nThe special characters are:\n \".\" Matches any character except a newline.\n \"^\" Matches the start of the string.\n \"$\" Matches the end of the string or just before the newline at\n the end of the string.\n \"*\" Matches 0 or more (greedy) repetitions of the preceding RE.\n Greedy means that it will match as many repetitions as possible.\n \"+\" Matches 1 or more (greedy) repetitions of the preceding RE.\n \"?\" Matches 0 or 1 (greedy) of the preceding RE.\n *?,+?,?? Non-greedy versions of the previous three special characters.\n {m,n} Matches from m to n repetitions of the preceding RE.\n {m,n}? Non-greedy version of the above.\n \"\\\\\" Either escapes special characters or signals a special sequence.\n [] Indicates a set of characters.\n A \"^\" as the first character indicates a complementing set.\n \"|\" A|B, creates an RE that will match either A or B.\n (...) Matches the RE inside the parentheses.\n The contents can be retrieved or matched later in the string.\n (?aiLmsux) The letters set the corresponding flags defined below.\n (?:...) Non-grouping version of regular parentheses.\n (?P...) The substring matched by the group is accessible by name.\n (?P=name) Matches the text matched earlier by the group named name.\n (?#...) A comment; ignored.\n (?=...) Matches if ... matches next, but doesn't consume the string.\n (?!...) Matches if ... doesn't match next.\n (?<=...) Matches if preceded by ... (must be fixed length).\n (?1:\n res=f'~({res})'\n else:\n res=f'~{res}'\n return res\n __str__=object.__str__\nglobals().update(RegexFlag.__members__)\n\n\nerror=sre_compile.error\n\n\n\n\ndef match(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).match(string)\n \ndef fullmatch(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).fullmatch(string)\n \ndef search(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).search(string)\n \ndef sub(pattern,repl,string,count=0,flags=0):\n ''\n\n\n\n\n \n return _compile(pattern,flags).sub(repl,string,count)\n \ndef subn(pattern,repl,string,count=0,flags=0):\n ''\n\n\n\n\n\n\n \n return _compile(pattern,flags).subn(repl,string,count)\n \ndef split(pattern,string,maxsplit=0,flags=0):\n ''\n\n\n\n\n\n \n return _compile(pattern,flags).split(string,maxsplit)\n \ndef findall(pattern,string,flags=0):\n ''\n\n\n\n\n\n \n return _compile(pattern,flags).findall(string)\n \ndef finditer(pattern,string,flags=0):\n ''\n\n\n \n return _compile(pattern,flags).finditer(string)\n \ndef compile(pattern,flags=0):\n ''\n return _compile(pattern,flags)\n \ndef purge():\n ''\n _cache.clear()\n _compile_repl.cache_clear()\n \ndef template(pattern,flags=0):\n ''\n return _compile(pattern,flags |T)\n \n \n \n \n \n \n_special_chars_map={i:'\\\\'+chr(i)for i in b'()[]{}?*+-|^$\\\\.&~# \\t\\n\\r\\v\\f'}\n\ndef escape(pattern):\n ''\n\n \n if isinstance(pattern,str):\n return pattern.translate(_special_chars_map)\n else:\n pattern=str(pattern,'latin1')\n return pattern.translate(_special_chars_map).encode('latin1')\n \nPattern=type(sre_compile.compile('',0))\nMatch=type(sre_compile.compile('',0).match(''))\n\n\n\n\n_cache={}\n\n_MAXCACHE=512\ndef _compile(pattern,flags):\n\n if isinstance(flags,RegexFlag):\n flags=flags.value\n try:\n return _cache[type(pattern),pattern,flags]\n except KeyError:\n pass\n if isinstance(pattern,Pattern):\n if flags:\n raise ValueError(\n \"cannot process flags argument with a compiled pattern\")\n return pattern\n if not sre_compile.isstring(pattern):\n raise TypeError(\"first argument must be string or compiled pattern\")\n p=sre_compile.compile(pattern,flags)\n if not(flags&DEBUG):\n if len(_cache)>=_MAXCACHE:\n \n try:\n del _cache[next(iter(_cache))]\n except(StopIteration,RuntimeError,KeyError):\n pass\n _cache[type(pattern),pattern,flags]=p\n return p\n \n@functools.lru_cache(_MAXCACHE)\ndef _compile_repl(repl,pattern):\n\n return sre_parse.parse_template(repl,pattern)\n \ndef _expand(pattern,match,template):\n\n template=sre_parse.parse_template(template,pattern)\n return sre_parse.expand_template(template,match)\n \ndef _subx(pattern,template):\n\n template=_compile_repl(template,pattern)\n if not template[0]and len(template[1])==1:\n \n return template[1][0]\n def filter(match,template=template):\n return sre_parse.expand_template(template,match)\n return filter\n \n \n \nimport copyreg\n\ndef _pickle(p):\n return _compile,(p.pattern,p.flags)\n \ncopyreg.pickle(Pattern,_pickle,_compile)\n\n\n\n\nclass Scanner:\n def __init__(self,lexicon,flags=0):\n from sre_constants import BRANCH,SUBPATTERN\n if isinstance(flags,RegexFlag):\n flags=flags.value\n self.lexicon=lexicon\n \n p=[]\n s=sre_parse.State()\n s.flags=flags\n for phrase,action in lexicon:\n gid=s.opengroup()\n p.append(sre_parse.SubPattern(s,[\n (SUBPATTERN,(gid,0,0,sre_parse.parse(phrase,flags))),\n ]))\n s.closegroup(gid,p[-1])\n p=sre_parse.SubPattern(s,[(BRANCH,(None,p))])\n self.scanner=sre_compile.compile(p)\n def scan(self,string):\n result=[]\n append=result.append\n match=self.scanner.scanner(string).match\n i=0\n while True:\n m=match()\n if not m:\n break\n j=m.end()\n if i ==j:\n break\n action=self.lexicon[m.lastindex -1][1]\n if callable(action):\n self.match=m\n action=action(self,m.group())\n if action is not None:\n append(action)\n i=j\n return result,string[i:]\n", ["_locale", "copyreg", "enum", "functools", "sre_compile", "sre_constants", "sre_parse"]], "reprlib": [".py", "''\n\n__all__=[\"Repr\",\"repr\",\"recursive_repr\"]\n\nimport builtins\nfrom itertools import islice\nfrom _thread import get_ident\n\ndef recursive_repr(fillvalue='...'):\n ''\n \n def decorating_function(user_function):\n repr_running=set()\n \n def wrapper(self):\n key=id(self),get_ident()\n if key in repr_running:\n return fillvalue\n repr_running.add(key)\n try:\n result=user_function(self)\n finally:\n repr_running.discard(key)\n return result\n \n \n wrapper.__module__=getattr(user_function,'__module__')\n wrapper.__doc__=getattr(user_function,'__doc__')\n wrapper.__name__=getattr(user_function,'__name__')\n wrapper.__qualname__=getattr(user_function,'__qualname__')\n wrapper.__annotations__=getattr(user_function,'__annotations__',{})\n wrapper.__type_params__=getattr(user_function,'__type_params__',())\n wrapper.__wrapped__=user_function\n return wrapper\n \n return decorating_function\n \nclass Repr:\n\n def __init__(\n self,*,maxlevel=6,maxtuple=6,maxlist=6,maxarray=5,maxdict=4,\n maxset=6,maxfrozenset=6,maxdeque=6,maxstring=30,maxlong=40,\n maxother=30,fillvalue='...',indent=None,\n ):\n self.maxlevel=maxlevel\n self.maxtuple=maxtuple\n self.maxlist=maxlist\n self.maxarray=maxarray\n self.maxdict=maxdict\n self.maxset=maxset\n self.maxfrozenset=maxfrozenset\n self.maxdeque=maxdeque\n self.maxstring=maxstring\n self.maxlong=maxlong\n self.maxother=maxother\n self.fillvalue=fillvalue\n self.indent=indent\n \n def repr(self,x):\n return self.repr1(x,self.maxlevel)\n \n def repr1(self,x,level):\n typename=type(x).__name__\n if ' 'in typename:\n parts=typename.split()\n typename='_'.join(parts)\n if hasattr(self,'repr_'+typename):\n return getattr(self,'repr_'+typename)(x,level)\n else:\n return self.repr_instance(x,level)\n \n def _join(self,pieces,level):\n if self.indent is None:\n return ', '.join(pieces)\n if not pieces:\n return ''\n indent=self.indent\n if isinstance(indent,int):\n if indent <0:\n raise ValueError(\n f'Repr.indent cannot be negative int (was {indent !r})'\n )\n indent *=' '\n try:\n sep=',\\n'+(self.maxlevel -level+1)*indent\n except TypeError as error:\n raise TypeError(\n f'Repr.indent must be a str, int or None, not {type(indent)}'\n )from error\n return sep.join(('',*pieces,''))[1:-len(indent)or None]\n \n def _repr_iterable(self,x,level,left,right,maxiter,trail=''):\n n=len(x)\n if level <=0 and n:\n s=self.fillvalue\n else:\n newlevel=level -1\n repr1=self.repr1\n pieces=[repr1(elem,newlevel)for elem in islice(x,maxiter)]\n if n >maxiter:\n pieces.append(self.fillvalue)\n s=self._join(pieces,level)\n if n ==1 and trail and self.indent is None:\n right=trail+right\n return '%s%s%s'%(left,s,right)\n \n def repr_tuple(self,x,level):\n return self._repr_iterable(x,level,'(',')',self.maxtuple,',')\n \n def repr_list(self,x,level):\n return self._repr_iterable(x,level,'[',']',self.maxlist)\n \n def repr_array(self,x,level):\n if not x:\n return \"array('%s')\"%x.typecode\n header=\"array('%s', [\"%x.typecode\n return self._repr_iterable(x,level,header,'])',self.maxarray)\n \n def repr_set(self,x,level):\n if not x:\n return 'set()'\n x=_possibly_sorted(x)\n return self._repr_iterable(x,level,'{','}',self.maxset)\n \n def repr_frozenset(self,x,level):\n if not x:\n return 'frozenset()'\n x=_possibly_sorted(x)\n return self._repr_iterable(x,level,'frozenset({','})',\n self.maxfrozenset)\n \n def repr_deque(self,x,level):\n return self._repr_iterable(x,level,'deque([','])',self.maxdeque)\n \n def repr_dict(self,x,level):\n n=len(x)\n if n ==0:\n return '{}'\n if level <=0:\n return '{'+self.fillvalue+'}'\n newlevel=level -1\n repr1=self.repr1\n pieces=[]\n for key in islice(_possibly_sorted(x),self.maxdict):\n keyrepr=repr1(key,newlevel)\n valrepr=repr1(x[key],newlevel)\n pieces.append('%s: %s'%(keyrepr,valrepr))\n if n >self.maxdict:\n pieces.append(self.fillvalue)\n s=self._join(pieces,level)\n return '{%s}'%(s,)\n \n def repr_str(self,x,level):\n s=builtins.repr(x[:self.maxstring])\n if len(s)>self.maxstring:\n i=max(0,(self.maxstring -3)//2)\n j=max(0,self.maxstring -3 -i)\n s=builtins.repr(x[:i]+x[len(x)-j:])\n s=s[:i]+self.fillvalue+s[len(s)-j:]\n return s\n \n def repr_int(self,x,level):\n s=builtins.repr(x)\n if len(s)>self.maxlong:\n i=max(0,(self.maxlong -3)//2)\n j=max(0,self.maxlong -3 -i)\n s=s[:i]+self.fillvalue+s[len(s)-j:]\n return s\n \n def repr_instance(self,x,level):\n try:\n s=builtins.repr(x)\n \n \n except Exception:\n return '<%s instance at %#x>'%(x.__class__.__name__,id(x))\n if len(s)>self.maxother:\n i=max(0,(self.maxother -3)//2)\n j=max(0,self.maxother -3 -i)\n s=s[:i]+self.fillvalue+s[len(s)-j:]\n return s\n \n \ndef _possibly_sorted(x):\n\n\n\n try:\n return sorted(x)\n except Exception:\n return list(x)\n \naRepr=Repr()\nrepr=aRepr.repr\n", ["_thread", "builtins", "itertools"]], "secrets": [".py", "''\n\n\n\n\n\n\n\n__all__=['choice','randbelow','randbits','SystemRandom',\n'token_bytes','token_hex','token_urlsafe',\n'compare_digest',\n]\n\n\nimport base64\n\nfrom hmac import compare_digest\nfrom random import SystemRandom\n\n_sysrand=SystemRandom()\n\nrandbits=_sysrand.getrandbits\nchoice=_sysrand.choice\n\ndef randbelow(exclusive_upper_bound):\n ''\n if exclusive_upper_bound <=0:\n raise ValueError(\"Upper bound must be positive.\")\n return _sysrand._randbelow(exclusive_upper_bound)\n \nDEFAULT_ENTROPY=32\n\ndef token_bytes(nbytes=None):\n ''\n\n\n\n\n\n\n\n \n if nbytes is None:\n nbytes=DEFAULT_ENTROPY\n return _sysrand.randbytes(nbytes)\n \ndef token_hex(nbytes=None):\n ''\n\n\n\n\n\n\n\n\n \n return token_bytes(nbytes).hex()\n \ndef token_urlsafe(nbytes=None):\n ''\n\n\n\n\n\n\n\n \n tok=token_bytes(nbytes)\n return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')\n", ["base64", "hmac", "random"]], "select": [".py", "''\n\n\n\n\nimport errno\nimport os\n\nclass error(Exception):\n pass\n \nALL=None\n\n_exception_map={}\n\ndef _map_exception(exc,circumstance=ALL):\n try:\n mapped_exception=_exception_map[(exc.__class__,circumstance)]\n mapped_exception.java_exception=exc\n return mapped_exception\n except KeyError:\n return error(-1,'Unmapped java exception: <%s:%s>'%(exc.toString(),circumstance))\n \nPOLLIN=1\nPOLLOUT=2\n\n\n\n\n\nPOLLPRI=4\nPOLLERR=8\nPOLLHUP=16\nPOLLNVAL=32\n\ndef _getselectable(selectable_object):\n try:\n channel=selectable_object.getchannel()\n except:\n try:\n channel=selectable_object.fileno().getChannel()\n except:\n raise TypeError(\"Object '%s' is not watchable\"%selectable_object,\n errno.ENOTSOCK)\n \n return channel\n \n \nclass Selector:\n\n def close(self):\n pass\n \n def keys(self):\n return[]\n \n def select(self,timeout=None):\n return[]\n \n def selectedKeys(self):\n class SelectedKeys:\n def iterator(self):\n return[]\n return SelectedKeys()\n \n def selectNow(self,timeout=None):\n return[]\n \nclass poll:\n\n def __init__(self):\n self.selector=Selector()\n self.chanmap={}\n self.unconnected_sockets=[]\n \n def _register_channel(self,socket_object,channel,mask):\n jmask=0\n if mask&POLLIN:\n \n if channel.validOps()&OP_ACCEPT:\n jmask=OP_ACCEPT\n else:\n jmask=OP_READ\n if mask&POLLOUT:\n if channel.validOps()&OP_WRITE:\n jmask |=OP_WRITE\n if channel.validOps()&OP_CONNECT:\n jmask |=OP_CONNECT\n selectionkey=channel.register(self.selector,jmask)\n self.chanmap[channel]=(socket_object,selectionkey)\n \n def _check_unconnected_sockets(self):\n temp_list=[]\n for socket_object,mask in self.unconnected_sockets:\n channel=_getselectable(socket_object)\n if channel is not None:\n self._register_channel(socket_object,channel,mask)\n else:\n temp_list.append((socket_object,mask))\n self.unconnected_sockets=temp_list\n \n def register(self,socket_object,mask=POLLIN |POLLOUT |POLLPRI):\n try:\n channel=_getselectable(socket_object)\n if channel is None:\n \n \n self.unconnected_sockets.append((socket_object,mask))\n return\n self._register_channel(socket_object,channel,mask)\n except BaseException as exc:\n raise _map_exception(exc)\n \n def unregister(self,socket_object):\n try:\n channel=_getselectable(socket_object)\n self.chanmap[channel][1].cancel()\n del self.chanmap[channel]\n except BaseException as exc:\n raise _map_exception(exc)\n \n def _dopoll(self,timeout):\n if timeout is None or timeout <0:\n self.selector.select()\n else:\n try:\n timeout=int(timeout)\n if not timeout:\n self.selector.selectNow()\n else:\n \n self.selector.select(timeout)\n except ValueError as vx:\n raise error(\"poll timeout must be a number of milliseconds or None\",errno.EINVAL)\n \n return self.selector.selectedKeys()\n \n def poll(self,timeout=None):\n return[]\n \n def _deregister_all(self):\n try:\n for k in self.selector.keys():\n k.cancel()\n \n self.selector.selectNow()\n except BaseException as exc:\n raise _map_exception(exc)\n \n def close(self):\n try:\n self._deregister_all()\n self.selector.close()\n except BaseException as exc:\n raise _map_exception(exc)\n \ndef _calcselecttimeoutvalue(value):\n if value is None:\n return None\n try:\n floatvalue=float(value)\n except Exception as x:\n raise TypeError(\"Select timeout value must be a number or None\")\n if value <0:\n raise error(\"Select timeout value cannot be negative\",errno.EINVAL)\n if floatvalue <0.000001:\n return 0\n return int(floatvalue *1000)\n \n \n \n \nclass poll_object_cache:\n\n def __init__(self):\n self.is_windows=os.name =='nt'\n if self.is_windows:\n self.poll_object_queue=Queue.Queue()\n import atexit\n atexit.register(self.finalize)\n \n def get_poll_object(self):\n if not self.is_windows:\n return poll()\n try:\n return self.poll_object_queue.get(False)\n except Queue.Empty:\n return poll()\n \n def release_poll_object(self,pobj):\n if self.is_windows:\n pobj._deregister_all()\n self.poll_object_queue.put(pobj)\n else:\n pobj.close()\n \n def finalize(self):\n if self.is_windows:\n while True:\n try:\n p=self.poll_object_queue.get(False)\n p.close()\n except Queue.Empty:\n return\n \n_poll_object_cache=poll_object_cache()\n\ndef native_select(read_fd_list,write_fd_list,outofband_fd_list,timeout=None):\n timeout=_calcselecttimeoutvalue(timeout)\n \n pobj=_poll_object_cache.get_poll_object()\n try:\n registered_for_read={}\n \n for fd in read_fd_list:\n pobj.register(fd,POLLIN)\n registered_for_read[fd]=1\n \n for fd in write_fd_list:\n if fd in registered_for_read:\n \n pobj.register(fd,POLLIN |POLLOUT)\n else:\n pobj.register(fd,POLLOUT)\n results=pobj.poll(timeout)\n \n read_ready_list,write_ready_list,oob_ready_list=[],[],[]\n for fd,mask in results:\n if mask&POLLIN:\n read_ready_list.append(fd)\n if mask&POLLOUT:\n write_ready_list.append(fd)\n return read_ready_list,write_ready_list,oob_ready_list\n finally:\n _poll_object_cache.release_poll_object(pobj)\n \nselect=native_select\n\ndef cpython_compatible_select(read_fd_list,write_fd_list,outofband_fd_list,timeout=None):\n\n\n modified_channels=[]\n try:\n for socket_list in[read_fd_list,write_fd_list,outofband_fd_list]:\n for s in socket_list:\n channel=_getselectable(s)\n if channel.isBlocking():\n modified_channels.append(channel)\n channel.configureBlocking(0)\n return native_select(read_fd_list,write_fd_list,outofband_fd_list,timeout)\n finally:\n for channel in modified_channels:\n channel.configureBlocking(1)\n", ["atexit", "errno", "os"]], "selectors": [".py", "''\n\n\n\n\n\n\nfrom abc import ABCMeta,abstractmethod\nfrom collections import namedtuple\nfrom collections.abc import Mapping\nimport math\nimport select\nimport sys\n\n\n\nEVENT_READ=(1 <<0)\nEVENT_WRITE=(1 <<1)\n\n\ndef _fileobj_to_fd(fileobj):\n ''\n\n\n\n\n\n\n\n\n\n \n if isinstance(fileobj,int):\n fd=fileobj\n else:\n try:\n fd=int(fileobj.fileno())\n except(AttributeError,TypeError,ValueError):\n raise ValueError(\"Invalid file object: \"\n \"{!r}\".format(fileobj))from None\n if fd <0:\n raise ValueError(\"Invalid file descriptor: {}\".format(fd))\n return fd\n \n \nSelectorKey=namedtuple('SelectorKey',['fileobj','fd','events','data'])\n\nSelectorKey.__doc__=\"\"\"SelectorKey(fileobj, fd, events, data)\n\n Object used to associate a file object to its backing\n file descriptor, selected event mask, and attached data.\n\"\"\"\nSelectorKey.fileobj.__doc__='File object registered.'\nSelectorKey.fd.__doc__='Underlying file descriptor.'\nSelectorKey.events.__doc__='Events that must be waited for on this file object.'\nSelectorKey.data.__doc__=('''Optional opaque data associated to this file object.\nFor example, this could be used to store a per-client session ID.''')\n\n\nclass _SelectorMapping(Mapping):\n ''\n \n def __init__(self,selector):\n self._selector=selector\n \n def __len__(self):\n return len(self._selector._fd_to_key)\n \n def get(self,fileobj,default=None):\n fd=self._selector._fileobj_lookup(fileobj)\n return self._selector._fd_to_key.get(fd,default)\n \n def __getitem__(self,fileobj):\n fd=self._selector._fileobj_lookup(fileobj)\n key=self._selector._fd_to_key.get(fd)\n if key is None:\n raise KeyError(\"{!r} is not registered\".format(fileobj))\n return key\n \n def __iter__(self):\n return iter(self._selector._fd_to_key)\n \n \nclass BaseSelector(metaclass=ABCMeta):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n @abstractmethod\n def register(self,fileobj,events,data=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def unregister(self,fileobj):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def modify(self,fileobj,events,data=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self.unregister(fileobj)\n return self.register(fileobj,events,data)\n \n @abstractmethod\n def select(self,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def close(self):\n ''\n\n\n \n pass\n \n def get_key(self,fileobj):\n ''\n\n\n\n \n mapping=self.get_map()\n if mapping is None:\n raise RuntimeError('Selector is closed')\n try:\n return mapping[fileobj]\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n \n @abstractmethod\n def get_map(self):\n ''\n raise NotImplementedError\n \n def __enter__(self):\n return self\n \n def __exit__(self,*args):\n self.close()\n \n \nclass _BaseSelectorImpl(BaseSelector):\n ''\n \n def __init__(self):\n \n self._fd_to_key={}\n \n self._map=_SelectorMapping(self)\n \n def _fileobj_lookup(self,fileobj):\n ''\n\n\n\n\n\n\n \n try:\n return _fileobj_to_fd(fileobj)\n except ValueError:\n \n for key in self._fd_to_key.values():\n if key.fileobj is fileobj:\n return key.fd\n \n raise\n \n def register(self,fileobj,events,data=None):\n if(not events)or(events&~(EVENT_READ |EVENT_WRITE)):\n raise ValueError(\"Invalid events: {!r}\".format(events))\n \n key=SelectorKey(fileobj,self._fileobj_lookup(fileobj),events,data)\n \n if key.fd in self._fd_to_key:\n raise KeyError(\"{!r} (FD {}) is already registered\"\n .format(fileobj,key.fd))\n \n self._fd_to_key[key.fd]=key\n return key\n \n def unregister(self,fileobj):\n try:\n key=self._fd_to_key.pop(self._fileobj_lookup(fileobj))\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n return key\n \n def modify(self,fileobj,events,data=None):\n try:\n key=self._fd_to_key[self._fileobj_lookup(fileobj)]\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n if events !=key.events:\n self.unregister(fileobj)\n key=self.register(fileobj,events,data)\n elif data !=key.data:\n \n key=key._replace(data=data)\n self._fd_to_key[key.fd]=key\n return key\n \n def close(self):\n self._fd_to_key.clear()\n self._map=None\n \n def get_map(self):\n return self._map\n \n \n \nclass SelectSelector(_BaseSelectorImpl):\n ''\n \n def __init__(self):\n super().__init__()\n self._readers=set()\n self._writers=set()\n \n def register(self,fileobj,events,data=None):\n key=super().register(fileobj,events,data)\n if events&EVENT_READ:\n self._readers.add(key.fd)\n if events&EVENT_WRITE:\n self._writers.add(key.fd)\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n self._readers.discard(key.fd)\n self._writers.discard(key.fd)\n return key\n \n if sys.platform =='win32':\n def _select(self,r,w,_,timeout=None):\n r,w,x=select.select(r,w,w,timeout)\n return r,w+x,[]\n else:\n _select=select.select\n \n def select(self,timeout=None):\n timeout=None if timeout is None else max(timeout,0)\n ready=[]\n try:\n r,w,_=self._select(self._readers,self._writers,[],timeout)\n except InterruptedError:\n return ready\n r=frozenset(r)\n w=frozenset(w)\n rw=r |w\n fd_to_key_get=self._fd_to_key.get\n for fd in rw:\n key=fd_to_key_get(fd)\n if key:\n events=((fd in r and EVENT_READ)\n |(fd in w and EVENT_WRITE))\n ready.append((key,events&key.events))\n return ready\n \n \nclass _PollLikeSelector(_BaseSelectorImpl):\n ''\n _selector_cls=None\n _EVENT_READ=None\n _EVENT_WRITE=None\n \n def __init__(self):\n super().__init__()\n self._selector=self._selector_cls()\n \n def register(self,fileobj,events,data=None):\n key=super().register(fileobj,events,data)\n poller_events=((events&EVENT_READ and self._EVENT_READ)\n |(events&EVENT_WRITE and self._EVENT_WRITE))\n try:\n self._selector.register(key.fd,poller_events)\n except:\n super().unregister(fileobj)\n raise\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n try:\n self._selector.unregister(key.fd)\n except OSError:\n \n \n pass\n return key\n \n def modify(self,fileobj,events,data=None):\n try:\n key=self._fd_to_key[self._fileobj_lookup(fileobj)]\n except KeyError:\n raise KeyError(f\"{fileobj !r} is not registered\")from None\n \n changed=False\n if events !=key.events:\n selector_events=((events&EVENT_READ and self._EVENT_READ)\n |(events&EVENT_WRITE and self._EVENT_WRITE))\n try:\n self._selector.modify(key.fd,selector_events)\n except:\n super().unregister(fileobj)\n raise\n changed=True\n if data !=key.data:\n changed=True\n \n if changed:\n key=key._replace(events=events,data=data)\n self._fd_to_key[key.fd]=key\n return key\n \n def select(self,timeout=None):\n \n \n if timeout is None:\n timeout=None\n elif timeout <=0:\n timeout=0\n else:\n \n \n timeout=math.ceil(timeout *1e3)\n ready=[]\n try:\n fd_event_list=self._selector.poll(timeout)\n except InterruptedError:\n return ready\n \n fd_to_key_get=self._fd_to_key.get\n for fd,event in fd_event_list:\n key=fd_to_key_get(fd)\n if key:\n events=((event&~self._EVENT_READ and EVENT_WRITE)\n |(event&~self._EVENT_WRITE and EVENT_READ))\n ready.append((key,events&key.events))\n return ready\n \n \nif hasattr(select,'poll'):\n\n class PollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.poll\n _EVENT_READ=select.POLLIN\n _EVENT_WRITE=select.POLLOUT\n \n \nif hasattr(select,'epoll'):\n\n _NOT_EPOLLIN=~select.EPOLLIN\n _NOT_EPOLLOUT=~select.EPOLLOUT\n \n class EpollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.epoll\n _EVENT_READ=select.EPOLLIN\n _EVENT_WRITE=select.EPOLLOUT\n \n def fileno(self):\n return self._selector.fileno()\n \n def select(self,timeout=None):\n if timeout is None:\n timeout=-1\n elif timeout <=0:\n timeout=0\n else:\n \n \n timeout=math.ceil(timeout *1e3)*1e-3\n \n \n \n \n max_ev=len(self._fd_to_key)or 1\n \n ready=[]\n try:\n fd_event_list=self._selector.poll(timeout,max_ev)\n except InterruptedError:\n return ready\n \n fd_to_key=self._fd_to_key\n for fd,event in fd_event_list:\n key=fd_to_key.get(fd)\n if key:\n events=((event&_NOT_EPOLLIN and EVENT_WRITE)\n |(event&_NOT_EPOLLOUT and EVENT_READ))\n ready.append((key,events&key.events))\n return ready\n \n def close(self):\n self._selector.close()\n super().close()\n \n \nif hasattr(select,'devpoll'):\n\n class DevpollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.devpoll\n _EVENT_READ=select.POLLIN\n _EVENT_WRITE=select.POLLOUT\n \n def fileno(self):\n return self._selector.fileno()\n \n def close(self):\n self._selector.close()\n super().close()\n \n \nif hasattr(select,'kqueue'):\n\n class KqueueSelector(_BaseSelectorImpl):\n ''\n \n def __init__(self):\n super().__init__()\n self._selector=select.kqueue()\n self._max_events=0\n \n def fileno(self):\n return self._selector.fileno()\n \n def register(self,fileobj,events,data=None):\n key=super().register(fileobj,events,data)\n try:\n if events&EVENT_READ:\n kev=select.kevent(key.fd,select.KQ_FILTER_READ,\n select.KQ_EV_ADD)\n self._selector.control([kev],0,0)\n self._max_events +=1\n if events&EVENT_WRITE:\n kev=select.kevent(key.fd,select.KQ_FILTER_WRITE,\n select.KQ_EV_ADD)\n self._selector.control([kev],0,0)\n self._max_events +=1\n except:\n super().unregister(fileobj)\n raise\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n if key.events&EVENT_READ:\n kev=select.kevent(key.fd,select.KQ_FILTER_READ,\n select.KQ_EV_DELETE)\n self._max_events -=1\n try:\n self._selector.control([kev],0,0)\n except OSError:\n \n \n pass\n if key.events&EVENT_WRITE:\n kev=select.kevent(key.fd,select.KQ_FILTER_WRITE,\n select.KQ_EV_DELETE)\n self._max_events -=1\n try:\n self._selector.control([kev],0,0)\n except OSError:\n \n pass\n return key\n \n def select(self,timeout=None):\n timeout=None if timeout is None else max(timeout,0)\n \n \n \n max_ev=self._max_events or 1\n ready=[]\n try:\n kev_list=self._selector.control(None,max_ev,timeout)\n except InterruptedError:\n return ready\n \n fd_to_key_get=self._fd_to_key.get\n for kev in kev_list:\n fd=kev.ident\n flag=kev.filter\n key=fd_to_key_get(fd)\n if key:\n events=((flag ==select.KQ_FILTER_READ and EVENT_READ)\n |(flag ==select.KQ_FILTER_WRITE and EVENT_WRITE))\n ready.append((key,events&key.events))\n return ready\n \n def close(self):\n self._selector.close()\n super().close()\n \n \ndef _can_use(method):\n ''\n \n \n selector=getattr(select,method,None)\n if selector is None:\n \n return False\n \n \n try:\n selector_obj=selector()\n if method =='poll':\n \n selector_obj.poll(0)\n else:\n \n selector_obj.close()\n return True\n except OSError:\n return False\n \n \n \n \n \nif _can_use('kqueue'):\n DefaultSelector=KqueueSelector\nelif _can_use('epoll'):\n DefaultSelector=EpollSelector\nelif _can_use('devpoll'):\n DefaultSelector=DevpollSelector\nelif _can_use('poll'):\n DefaultSelector=PollSelector\nelse:\n DefaultSelector=SelectSelector\n", ["abc", "collections", "collections.abc", "math", "select", "sys"]], "shlex": [".py", "''\n\n\n\n\n\n\n\n\nimport os\nimport re\nimport sys\nfrom collections import deque\n\nfrom io import StringIO\n\n__all__=[\"shlex\",\"split\",\"quote\",\"join\"]\n\nclass shlex:\n ''\n def __init__(self,instream=None,infile=None,posix=False,\n punctuation_chars=False):\n if isinstance(instream,str):\n instream=StringIO(instream)\n if instream is not None:\n self.instream=instream\n self.infile=infile\n else:\n self.instream=sys.stdin\n self.infile=None\n self.posix=posix\n if posix:\n self.eof=None\n else:\n self.eof=''\n self.commenters='#'\n self.wordchars=('abcdfeghijklmnopqrstuvwxyz'\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')\n if self.posix:\n self.wordchars +=('\u00df\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef\u00f0\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u00f9\u00fa\u00fb\u00fc\u00fd\u00fe\u00ff'\n '\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf\u00d0\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d8\u00d9\u00da\u00db\u00dc\u00dd\u00de')\n self.whitespace=' \\t\\r\\n'\n self.whitespace_split=False\n self.quotes='\\'\"'\n self.escape='\\\\'\n self.escapedquotes='\"'\n self.state=' '\n self.pushback=deque()\n self.lineno=1\n self.debug=0\n self.token=''\n self.filestack=deque()\n self.source=None\n if not punctuation_chars:\n punctuation_chars=''\n elif punctuation_chars is True:\n punctuation_chars='();<>|&'\n self._punctuation_chars=punctuation_chars\n if punctuation_chars:\n \n self._pushback_chars=deque()\n \n self.wordchars +='~-./*?='\n \n t=self.wordchars.maketrans(dict.fromkeys(punctuation_chars))\n self.wordchars=self.wordchars.translate(t)\n \n @property\n def punctuation_chars(self):\n return self._punctuation_chars\n \n def push_token(self,tok):\n ''\n if self.debug >=1:\n print(\"shlex: pushing token \"+repr(tok))\n self.pushback.appendleft(tok)\n \n def push_source(self,newstream,newfile=None):\n ''\n if isinstance(newstream,str):\n newstream=StringIO(newstream)\n self.filestack.appendleft((self.infile,self.instream,self.lineno))\n self.infile=newfile\n self.instream=newstream\n self.lineno=1\n if self.debug:\n if newfile is not None:\n print('shlex: pushing to file %s'%(self.infile,))\n else:\n print('shlex: pushing to stream %s'%(self.instream,))\n \n def pop_source(self):\n ''\n self.instream.close()\n (self.infile,self.instream,self.lineno)=self.filestack.popleft()\n if self.debug:\n print('shlex: popping to %s, line %d'\\\n %(self.instream,self.lineno))\n self.state=' '\n \n def get_token(self):\n ''\n if self.pushback:\n tok=self.pushback.popleft()\n if self.debug >=1:\n print(\"shlex: popping token \"+repr(tok))\n return tok\n \n raw=self.read_token()\n \n if self.source is not None:\n while raw ==self.source:\n spec=self.sourcehook(self.read_token())\n if spec:\n (newfile,newstream)=spec\n self.push_source(newstream,newfile)\n raw=self.get_token()\n \n while raw ==self.eof:\n if not self.filestack:\n return self.eof\n else:\n self.pop_source()\n raw=self.get_token()\n \n if self.debug >=1:\n if raw !=self.eof:\n print(\"shlex: token=\"+repr(raw))\n else:\n print(\"shlex: token=EOF\")\n return raw\n \n def read_token(self):\n quoted=False\n escapedstate=' '\n while True:\n if self.punctuation_chars and self._pushback_chars:\n nextchar=self._pushback_chars.pop()\n else:\n nextchar=self.instream.read(1)\n if nextchar =='\\n':\n self.lineno +=1\n if self.debug >=3:\n print(\"shlex: in state %r I see character: %r\"%(self.state,\n nextchar))\n if self.state is None:\n self.token=''\n break\n elif self.state ==' ':\n if not nextchar:\n self.state=None\n break\n elif nextchar in self.whitespace:\n if self.debug >=2:\n print(\"shlex: I see whitespace in whitespace state\")\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n elif nextchar in self.commenters:\n self.instream.readline()\n self.lineno +=1\n elif self.posix and nextchar in self.escape:\n escapedstate='a'\n self.state=nextchar\n elif nextchar in self.wordchars:\n self.token=nextchar\n self.state='a'\n elif nextchar in self.punctuation_chars:\n self.token=nextchar\n self.state='c'\n elif nextchar in self.quotes:\n if not self.posix:\n self.token=nextchar\n self.state=nextchar\n elif self.whitespace_split:\n self.token=nextchar\n self.state='a'\n else:\n self.token=nextchar\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n elif self.state in self.quotes:\n quoted=True\n if not nextchar:\n if self.debug >=2:\n print(\"shlex: I see EOF in quotes state\")\n \n raise ValueError(\"No closing quotation\")\n if nextchar ==self.state:\n if not self.posix:\n self.token +=nextchar\n self.state=' '\n break\n else:\n self.state='a'\n elif(self.posix and nextchar in self.escape and self.state\n in self.escapedquotes):\n escapedstate=self.state\n self.state=nextchar\n else:\n self.token +=nextchar\n elif self.state in self.escape:\n if not nextchar:\n if self.debug >=2:\n print(\"shlex: I see EOF in escape state\")\n \n raise ValueError(\"No escaped character\")\n \n \n if(escapedstate in self.quotes and\n nextchar !=self.state and nextchar !=escapedstate):\n self.token +=self.state\n self.token +=nextchar\n self.state=escapedstate\n elif self.state in('a','c'):\n if not nextchar:\n self.state=None\n break\n elif nextchar in self.whitespace:\n if self.debug >=2:\n print(\"shlex: I see whitespace in word state\")\n self.state=' '\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n elif nextchar in self.commenters:\n self.instream.readline()\n self.lineno +=1\n if self.posix:\n self.state=' '\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n elif self.state =='c':\n if nextchar in self.punctuation_chars:\n self.token +=nextchar\n else:\n if nextchar not in self.whitespace:\n self._pushback_chars.append(nextchar)\n self.state=' '\n break\n elif self.posix and nextchar in self.quotes:\n self.state=nextchar\n elif self.posix and nextchar in self.escape:\n escapedstate='a'\n self.state=nextchar\n elif(nextchar in self.wordchars or nextchar in self.quotes\n or(self.whitespace_split and\n nextchar not in self.punctuation_chars)):\n self.token +=nextchar\n else:\n if self.punctuation_chars:\n self._pushback_chars.append(nextchar)\n else:\n self.pushback.appendleft(nextchar)\n if self.debug >=2:\n print(\"shlex: I see punctuation in word state\")\n self.state=' '\n if self.token or(self.posix and quoted):\n break\n else:\n continue\n result=self.token\n self.token=''\n if self.posix and not quoted and result =='':\n result=None\n if self.debug >1:\n if result:\n print(\"shlex: raw token=\"+repr(result))\n else:\n print(\"shlex: raw token=EOF\")\n return result\n \n def sourcehook(self,newfile):\n ''\n if newfile[0]=='\"':\n newfile=newfile[1:-1]\n \n if isinstance(self.infile,str)and not os.path.isabs(newfile):\n newfile=os.path.join(os.path.dirname(self.infile),newfile)\n return(newfile,open(newfile,\"r\"))\n \n def error_leader(self,infile=None,lineno=None):\n ''\n if infile is None:\n infile=self.infile\n if lineno is None:\n lineno=self.lineno\n return \"\\\"%s\\\", line %d: \"%(infile,lineno)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n token=self.get_token()\n if token ==self.eof:\n raise StopIteration\n return token\n \ndef split(s,comments=False,posix=True):\n ''\n if s is None:\n raise ValueError(\"s argument must not be None\")\n lex=shlex(s,posix=posix)\n lex.whitespace_split=True\n if not comments:\n lex.commenters=''\n return list(lex)\n \n \ndef join(split_command):\n ''\n return ' '.join(quote(arg)for arg in split_command)\n \n \n_find_unsafe=re.compile(r'[^\\w@%+=:,./-]',re.ASCII).search\n\ndef quote(s):\n ''\n if not s:\n return \"''\"\n if _find_unsafe(s)is None:\n return s\n \n \n \n return \"'\"+s.replace(\"'\",\"'\\\"'\\\"'\")+\"'\"\n \n \ndef _print_tokens(lexer):\n while tt :=lexer.get_token():\n print(\"Token: \"+repr(tt))\n \nif __name__ =='__main__':\n if len(sys.argv)==1:\n _print_tokens(shlex())\n else:\n fn=sys.argv[1]\n with open(fn)as f:\n _print_tokens(shlex(f,fn))\n", ["collections", "io", "os", "re", "sys"]], "shutil": [".py", "''\n\n\n\n\n\nimport os\nimport sys\nimport stat\nimport fnmatch\nimport collections\nimport errno\n\ntry:\n import zlib\n del zlib\n _ZLIB_SUPPORTED=True\nexcept ImportError:\n _ZLIB_SUPPORTED=False\n \ntry:\n import bz2\n del bz2\n _BZ2_SUPPORTED=True\nexcept ImportError:\n _BZ2_SUPPORTED=False\n \ntry:\n import lzma\n del lzma\n _LZMA_SUPPORTED=True\nexcept ImportError:\n _LZMA_SUPPORTED=False\n \n_WINDOWS=os.name =='nt'\nposix=nt=None\nif os.name =='posix':\n import posix\nelif _WINDOWS:\n import nt\n \nif sys.platform =='win32':\n import _winapi\nelse:\n _winapi=None\n \nCOPY_BUFSIZE=1024 *1024 if _WINDOWS else 64 *1024\n\n\n_USE_CP_SENDFILE=(hasattr(os,\"sendfile\")\nand sys.platform.startswith((\"linux\",\"android\")))\n_HAS_FCOPYFILE=posix and hasattr(posix,\"_fcopyfile\")\n\n\n_WIN_DEFAULT_PATHEXT=\".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC\"\n\n__all__=[\"copyfileobj\",\"copyfile\",\"copymode\",\"copystat\",\"copy\",\"copy2\",\n\"copytree\",\"move\",\"rmtree\",\"Error\",\"SpecialFileError\",\n\"ExecError\",\"make_archive\",\"get_archive_formats\",\n\"register_archive_format\",\"unregister_archive_format\",\n\"get_unpack_formats\",\"register_unpack_format\",\n\"unregister_unpack_format\",\"unpack_archive\",\n\"ignore_patterns\",\"chown\",\"which\",\"get_terminal_size\",\n\"SameFileError\"]\n\n\nclass Error(OSError):\n pass\n \nclass SameFileError(Error):\n ''\n \nclass SpecialFileError(OSError):\n ''\n \n \nclass ExecError(OSError):\n ''\n \nclass ReadError(OSError):\n ''\n \nclass RegistryError(Exception):\n ''\n \n \nclass _GiveupOnFastCopy(Exception):\n ''\n\n \n \ndef _fastcopy_fcopyfile(fsrc,fdst,flags):\n ''\n\n \n try:\n infd=fsrc.fileno()\n outfd=fdst.fileno()\n except Exception as err:\n raise _GiveupOnFastCopy(err)\n \n try:\n posix._fcopyfile(infd,outfd,flags)\n except OSError as err:\n err.filename=fsrc.name\n err.filename2=fdst.name\n if err.errno in{errno.EINVAL,errno.ENOTSUP}:\n raise _GiveupOnFastCopy(err)\n else:\n raise err from None\n \ndef _fastcopy_sendfile(fsrc,fdst):\n ''\n\n\n \n \n \n \n \n \n \n \n \n \n global _USE_CP_SENDFILE\n try:\n infd=fsrc.fileno()\n outfd=fdst.fileno()\n except Exception as err:\n raise _GiveupOnFastCopy(err)\n \n \n \n \n \n \n try:\n blocksize=max(os.fstat(infd).st_size,2 **23)\n except OSError:\n blocksize=2 **27\n \n \n if sys.maxsize <2 **32:\n blocksize=min(blocksize,2 **30)\n \n offset=0\n while True:\n try:\n sent=os.sendfile(outfd,infd,offset,blocksize)\n except OSError as err:\n \n err.filename=fsrc.name\n err.filename2=fdst.name\n \n if err.errno ==errno.ENOTSOCK:\n \n \n \n _USE_CP_SENDFILE=False\n raise _GiveupOnFastCopy(err)\n \n if err.errno ==errno.ENOSPC:\n raise err from None\n \n \n if offset ==0 and os.lseek(outfd,0,os.SEEK_CUR)==0:\n raise _GiveupOnFastCopy(err)\n \n raise err\n else:\n if sent ==0:\n break\n offset +=sent\n \ndef _copyfileobj_readinto(fsrc,fdst,length=COPY_BUFSIZE):\n ''\n\n\n \n \n fsrc_readinto=fsrc.readinto\n fdst_write=fdst.write\n with memoryview(bytearray(length))as mv:\n while True:\n n=fsrc_readinto(mv)\n if not n:\n break\n elif n 0:\n _copyfileobj_readinto(fsrc,fdst,min(file_size,COPY_BUFSIZE))\n return dst\n \n copyfileobj(fsrc,fdst)\n \n \n except IsADirectoryError as e:\n if not os.path.exists(dst):\n raise FileNotFoundError(f'Directory does not exist: {dst}')from e\n else:\n raise\n \n return dst\n \ndef copymode(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n \n sys.audit(\"shutil.copymode\",src,dst)\n \n if not follow_symlinks and _islink(src)and os.path.islink(dst):\n if hasattr(os,'lchmod'):\n stat_func,chmod_func=os.lstat,os.lchmod\n else:\n return\n else:\n stat_func=_stat\n if os.name =='nt'and os.path.islink(dst):\n def chmod_func(*args):\n os.chmod(*args,follow_symlinks=True)\n else:\n chmod_func=os.chmod\n \n st=stat_func(src)\n chmod_func(dst,stat.S_IMODE(st.st_mode))\n \nif hasattr(os,'listxattr'):\n def _copyxattr(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n \n \n try:\n names=os.listxattr(src,follow_symlinks=follow_symlinks)\n except OSError as e:\n if e.errno not in(errno.ENOTSUP,errno.ENODATA,errno.EINVAL):\n raise\n return\n for name in names:\n try:\n value=os.getxattr(src,name,follow_symlinks=follow_symlinks)\n os.setxattr(dst,name,value,follow_symlinks=follow_symlinks)\n except OSError as e:\n if e.errno not in(errno.EPERM,errno.ENOTSUP,errno.ENODATA,\n errno.EINVAL,errno.EACCES):\n raise\nelse:\n def _copyxattr(*args,**kwargs):\n pass\n \ndef copystat(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.copystat\",src,dst)\n \n def _nop(*args,ns=None,follow_symlinks=None):\n pass\n \n \n follow=follow_symlinks or not(_islink(src)and os.path.islink(dst))\n if follow:\n \n def lookup(name):\n return getattr(os,name,_nop)\n else:\n \n \n def lookup(name):\n fn=getattr(os,name,_nop)\n if fn in os.supports_follow_symlinks:\n return fn\n return _nop\n \n if isinstance(src,os.DirEntry):\n st=src.stat(follow_symlinks=follow)\n else:\n st=lookup(\"stat\")(src,follow_symlinks=follow)\n mode=stat.S_IMODE(st.st_mode)\n lookup(\"utime\")(dst,ns=(st.st_atime_ns,st.st_mtime_ns),\n follow_symlinks=follow)\n \n \n _copyxattr(src,dst,follow_symlinks=follow)\n try:\n lookup(\"chmod\")(dst,mode,follow_symlinks=follow)\n except NotImplementedError:\n \n \n \n \n \n \n \n \n \n \n pass\n if hasattr(st,'st_flags'):\n try:\n lookup(\"chflags\")(dst,st.st_flags,follow_symlinks=follow)\n except OSError as why:\n for err in 'EOPNOTSUPP','ENOTSUP':\n if hasattr(errno,err)and why.errno ==getattr(errno,err):\n break\n else:\n raise\n \ndef copy(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n\n\n\n\n \n if os.path.isdir(dst):\n dst=os.path.join(dst,os.path.basename(src))\n copyfile(src,dst,follow_symlinks=follow_symlinks)\n copymode(src,dst,follow_symlinks=follow_symlinks)\n return dst\n \ndef copy2(src,dst,*,follow_symlinks=True):\n ''\n\n\n\n\n\n\n\n\n \n if os.path.isdir(dst):\n dst=os.path.join(dst,os.path.basename(src))\n \n if hasattr(_winapi,\"CopyFile2\"):\n src_=os.fsdecode(src)\n dst_=os.fsdecode(dst)\n flags=_winapi.COPY_FILE_ALLOW_DECRYPTED_DESTINATION\n if not follow_symlinks:\n flags |=_winapi.COPY_FILE_COPY_SYMLINK\n try:\n _winapi.CopyFile2(src_,dst_,flags)\n return dst\n except OSError as exc:\n if(exc.winerror ==_winapi.ERROR_PRIVILEGE_NOT_HELD\n and not follow_symlinks):\n \n \n pass\n elif exc.winerror ==_winapi.ERROR_ACCESS_DENIED:\n \n \n pass\n else:\n raise\n \n copyfile(src,dst,follow_symlinks=follow_symlinks)\n copystat(src,dst,follow_symlinks=follow_symlinks)\n return dst\n \ndef ignore_patterns(*patterns):\n ''\n\n\n \n def _ignore_patterns(path,names):\n ignored_names=[]\n for pattern in patterns:\n ignored_names.extend(fnmatch.filter(names,pattern))\n return set(ignored_names)\n return _ignore_patterns\n \ndef _copytree(entries,src,dst,symlinks,ignore,copy_function,\nignore_dangling_symlinks,dirs_exist_ok=False):\n if ignore is not None:\n ignored_names=ignore(os.fspath(src),[x.name for x in entries])\n else:\n ignored_names=()\n \n os.makedirs(dst,exist_ok=dirs_exist_ok)\n errors=[]\n use_srcentry=copy_function is copy2 or copy_function is copy\n \n for srcentry in entries:\n if srcentry.name in ignored_names:\n continue\n srcname=os.path.join(src,srcentry.name)\n dstname=os.path.join(dst,srcentry.name)\n srcobj=srcentry if use_srcentry else srcname\n try:\n is_symlink=srcentry.is_symlink()\n if is_symlink and os.name =='nt':\n \n \n lstat=srcentry.stat(follow_symlinks=False)\n if lstat.st_reparse_tag ==stat.IO_REPARSE_TAG_MOUNT_POINT:\n is_symlink=False\n if is_symlink:\n linkto=os.readlink(srcname)\n if symlinks:\n \n \n \n os.symlink(linkto,dstname)\n copystat(srcobj,dstname,follow_symlinks=not symlinks)\n else:\n \n if not os.path.exists(linkto)and ignore_dangling_symlinks:\n continue\n \n if srcentry.is_dir():\n copytree(srcobj,dstname,symlinks,ignore,\n copy_function,ignore_dangling_symlinks,\n dirs_exist_ok)\n else:\n copy_function(srcobj,dstname)\n elif srcentry.is_dir():\n copytree(srcobj,dstname,symlinks,ignore,copy_function,\n ignore_dangling_symlinks,dirs_exist_ok)\n else:\n \n copy_function(srcobj,dstname)\n \n \n except Error as err:\n errors.extend(err.args[0])\n except OSError as why:\n errors.append((srcname,dstname,str(why)))\n try:\n copystat(src,dst)\n except OSError as why:\n \n if getattr(why,'winerror',None)is None:\n errors.append((src,dst,str(why)))\n if errors:\n raise Error(errors)\n return dst\n \ndef copytree(src,dst,symlinks=False,ignore=None,copy_function=copy2,\nignore_dangling_symlinks=False,dirs_exist_ok=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.copytree\",src,dst)\n with os.scandir(src)as itr:\n entries=list(itr)\n return _copytree(entries=entries,src=src,dst=dst,symlinks=symlinks,\n ignore=ignore,copy_function=copy_function,\n ignore_dangling_symlinks=ignore_dangling_symlinks,\n dirs_exist_ok=dirs_exist_ok)\n \nif hasattr(os.stat_result,'st_file_attributes'):\n def _rmtree_islink(st):\n return(stat.S_ISLNK(st.st_mode)or\n (st.st_file_attributes&stat.FILE_ATTRIBUTE_REPARSE_POINT\n and st.st_reparse_tag ==stat.IO_REPARSE_TAG_MOUNT_POINT))\nelse:\n def _rmtree_islink(st):\n return stat.S_ISLNK(st.st_mode)\n \n \ndef _rmtree_unsafe(path,onexc):\n try:\n with os.scandir(path)as scandir_it:\n entries=list(scandir_it)\n except FileNotFoundError:\n return\n except OSError as err:\n onexc(os.scandir,path,err)\n entries=[]\n for entry in entries:\n fullname=entry.path\n try:\n is_dir=entry.is_dir(follow_symlinks=False)\n except FileNotFoundError:\n continue\n except OSError:\n is_dir=False\n \n if is_dir and not entry.is_junction():\n try:\n if entry.is_symlink():\n \n \n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.path.islink,fullname,err)\n continue\n _rmtree_unsafe(fullname,onexc)\n else:\n try:\n os.unlink(fullname)\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.unlink,fullname,err)\n try:\n os.rmdir(path)\n except FileNotFoundError:\n pass\n except OSError as err:\n onexc(os.rmdir,path,err)\n \n \ndef _rmtree_safe_fd(topfd,path,onexc):\n try:\n with os.scandir(topfd)as scandir_it:\n entries=list(scandir_it)\n except FileNotFoundError:\n return\n except OSError as err:\n err.filename=path\n onexc(os.scandir,path,err)\n return\n for entry in entries:\n fullname=os.path.join(path,entry.name)\n try:\n is_dir=entry.is_dir(follow_symlinks=False)\n except FileNotFoundError:\n continue\n except OSError:\n is_dir=False\n else:\n if is_dir:\n try:\n orig_st=entry.stat(follow_symlinks=False)\n is_dir=stat.S_ISDIR(orig_st.st_mode)\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.lstat,fullname,err)\n continue\n if is_dir:\n try:\n dirfd=os.open(entry.name,os.O_RDONLY |os.O_NONBLOCK,dir_fd=topfd)\n dirfd_closed=False\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.open,fullname,err)\n else:\n try:\n if os.path.samestat(orig_st,os.fstat(dirfd)):\n _rmtree_safe_fd(dirfd,fullname,onexc)\n try:\n os.close(dirfd)\n except OSError as err:\n \n dirfd_closed=True\n onexc(os.close,fullname,err)\n dirfd_closed=True\n try:\n os.rmdir(entry.name,dir_fd=topfd)\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.rmdir,fullname,err)\n else:\n try:\n \n \n \n raise OSError(\"Cannot call rmtree on a symbolic \"\n \"link\")\n except OSError as err:\n onexc(os.path.islink,fullname,err)\n finally:\n if not dirfd_closed:\n try:\n os.close(dirfd)\n except OSError as err:\n onexc(os.close,fullname,err)\n else:\n try:\n os.unlink(entry.name,dir_fd=topfd)\n except FileNotFoundError:\n continue\n except OSError as err:\n onexc(os.unlink,fullname,err)\n \n_use_fd_functions=({os.open,os.stat,os.unlink,os.rmdir}<=\nos.supports_dir_fd and\nos.scandir in os.supports_fd and\nos.stat in os.supports_follow_symlinks)\n\ndef rmtree(path,ignore_errors=False,onerror=None,*,onexc=None,dir_fd=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n sys.audit(\"shutil.rmtree\",path,dir_fd)\n if ignore_errors:\n def onexc(*args):\n pass\n elif onerror is None and onexc is None:\n def onexc(*args):\n raise\n elif onexc is None:\n if onerror is None:\n def onexc(*args):\n raise\n else:\n \n def onexc(*args):\n func,path,exc=args\n if exc is None:\n exc_info=None,None,None\n else:\n exc_info=type(exc),exc,exc.__traceback__\n return onerror(func,path,exc_info)\n \n if _use_fd_functions:\n \n if isinstance(path,bytes):\n path=os.fsdecode(path)\n \n \n try:\n orig_st=os.lstat(path,dir_fd=dir_fd)\n except OSError as err:\n onexc(os.lstat,path,err)\n return\n try:\n fd=os.open(path,os.O_RDONLY |os.O_NONBLOCK,dir_fd=dir_fd)\n fd_closed=False\n except OSError as err:\n onexc(os.open,path,err)\n return\n try:\n if os.path.samestat(orig_st,os.fstat(fd)):\n _rmtree_safe_fd(fd,path,onexc)\n try:\n os.close(fd)\n except OSError as err:\n \n fd_closed=True\n onexc(os.close,path,err)\n fd_closed=True\n try:\n os.rmdir(path,dir_fd=dir_fd)\n except OSError as err:\n onexc(os.rmdir,path,err)\n else:\n try:\n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except OSError as err:\n onexc(os.path.islink,path,err)\n finally:\n if not fd_closed:\n try:\n os.close(fd)\n except OSError as err:\n onexc(os.close,path,err)\n else:\n if dir_fd is not None:\n raise NotImplementedError(\"dir_fd unavailable on this platform\")\n try:\n st=os.lstat(path)\n except OSError as err:\n onexc(os.lstat,path,err)\n return\n try:\n if _rmtree_islink(st):\n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except OSError as err:\n onexc(os.path.islink,path,err)\n \n return\n return _rmtree_unsafe(path,onexc)\n \n \n \nrmtree.avoids_symlink_attacks=_use_fd_functions\n\ndef _basename(path):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n path=os.fspath(path)\n sep=os.path.sep+(os.path.altsep or '')\n return os.path.basename(path.rstrip(sep))\n \ndef move(src,dst,copy_function=copy2):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.move\",src,dst)\n real_dst=dst\n if os.path.isdir(dst):\n if _samefile(src,dst)and not os.path.islink(src):\n \n \n os.rename(src,dst)\n return\n \n \n \n real_dst=os.path.join(dst,_basename(src))\n \n if os.path.exists(real_dst):\n raise Error(\"Destination path '%s' already exists\"%real_dst)\n try:\n os.rename(src,real_dst)\n except OSError:\n if os.path.islink(src):\n linkto=os.readlink(src)\n os.symlink(linkto,real_dst)\n os.unlink(src)\n elif os.path.isdir(src):\n if _destinsrc(src,dst):\n raise Error(\"Cannot move a directory '%s' into itself\"\n \" '%s'.\"%(src,dst))\n if(_is_immutable(src)\n or(not os.access(src,os.W_OK)and os.listdir(src)\n and sys.platform =='darwin')):\n raise PermissionError(\"Cannot move the non-empty directory \"\n \"'%s': Lacking write permission to '%s'.\"\n %(src,src))\n copytree(src,real_dst,copy_function=copy_function,\n symlinks=True)\n rmtree(src)\n else:\n copy_function(src,real_dst)\n os.unlink(src)\n return real_dst\n \ndef _destinsrc(src,dst):\n src=os.path.abspath(src)\n dst=os.path.abspath(dst)\n if not src.endswith(os.path.sep):\n src +=os.path.sep\n if not dst.endswith(os.path.sep):\n dst +=os.path.sep\n return dst.startswith(src)\n \ndef _is_immutable(src):\n st=_stat(src)\n immutable_states=[stat.UF_IMMUTABLE,stat.SF_IMMUTABLE]\n return hasattr(st,'st_flags')and st.st_flags in immutable_states\n \ndef _get_gid(name):\n ''\n if name is None:\n return None\n \n try:\n from grp import getgrnam\n except ImportError:\n return None\n \n try:\n result=getgrnam(name)\n except KeyError:\n result=None\n if result is not None:\n return result[2]\n return None\n \ndef _get_uid(name):\n ''\n if name is None:\n return None\n \n try:\n from pwd import getpwnam\n except ImportError:\n return None\n \n try:\n result=getpwnam(name)\n except KeyError:\n result=None\n if result is not None:\n return result[2]\n return None\n \ndef _make_tarball(base_name,base_dir,compress=\"gzip\",verbose=0,dry_run=0,\nowner=None,group=None,logger=None,root_dir=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if compress is None:\n tar_compression=''\n elif _ZLIB_SUPPORTED and compress =='gzip':\n tar_compression='gz'\n elif _BZ2_SUPPORTED and compress =='bzip2':\n tar_compression='bz2'\n elif _LZMA_SUPPORTED and compress =='xz':\n tar_compression='xz'\n else:\n raise ValueError(\"bad value for 'compress', or compression format not \"\n \"supported : {0}\".format(compress))\n \n import tarfile\n \n compress_ext='.'+tar_compression if compress else ''\n archive_name=base_name+'.tar'+compress_ext\n archive_dir=os.path.dirname(archive_name)\n \n if archive_dir and not os.path.exists(archive_dir):\n if logger is not None:\n logger.info(\"creating %s\",archive_dir)\n if not dry_run:\n os.makedirs(archive_dir)\n \n \n if logger is not None:\n logger.info('Creating tar archive')\n \n uid=_get_uid(owner)\n gid=_get_gid(group)\n \n def _set_uid_gid(tarinfo):\n if gid is not None:\n tarinfo.gid=gid\n tarinfo.gname=group\n if uid is not None:\n tarinfo.uid=uid\n tarinfo.uname=owner\n return tarinfo\n \n if not dry_run:\n tar=tarfile.open(archive_name,'w|%s'%tar_compression)\n arcname=base_dir\n if root_dir is not None:\n base_dir=os.path.join(root_dir,base_dir)\n try:\n tar.add(base_dir,arcname,filter=_set_uid_gid)\n finally:\n tar.close()\n \n if root_dir is not None:\n archive_name=os.path.abspath(archive_name)\n return archive_name\n \ndef _make_zipfile(base_name,base_dir,verbose=0,dry_run=0,\nlogger=None,owner=None,group=None,root_dir=None):\n ''\n\n\n\n \n import zipfile\n \n zip_filename=base_name+\".zip\"\n archive_dir=os.path.dirname(base_name)\n \n if archive_dir and not os.path.exists(archive_dir):\n if logger is not None:\n logger.info(\"creating %s\",archive_dir)\n if not dry_run:\n os.makedirs(archive_dir)\n \n if logger is not None:\n logger.info(\"creating '%s' and adding '%s' to it\",\n zip_filename,base_dir)\n \n if not dry_run:\n with zipfile.ZipFile(zip_filename,\"w\",\n compression=zipfile.ZIP_DEFLATED)as zf:\n arcname=os.path.normpath(base_dir)\n if root_dir is not None:\n base_dir=os.path.join(root_dir,base_dir)\n base_dir=os.path.normpath(base_dir)\n if arcname !=os.curdir:\n zf.write(base_dir,arcname)\n if logger is not None:\n logger.info(\"adding '%s'\",base_dir)\n for dirpath,dirnames,filenames in os.walk(base_dir):\n arcdirpath=dirpath\n if root_dir is not None:\n arcdirpath=os.path.relpath(arcdirpath,root_dir)\n arcdirpath=os.path.normpath(arcdirpath)\n for name in sorted(dirnames):\n path=os.path.join(dirpath,name)\n arcname=os.path.join(arcdirpath,name)\n zf.write(path,arcname)\n if logger is not None:\n logger.info(\"adding '%s'\",path)\n for name in filenames:\n path=os.path.join(dirpath,name)\n path=os.path.normpath(path)\n if os.path.isfile(path):\n arcname=os.path.join(arcdirpath,name)\n zf.write(path,arcname)\n if logger is not None:\n logger.info(\"adding '%s'\",path)\n \n if root_dir is not None:\n zip_filename=os.path.abspath(zip_filename)\n return zip_filename\n \n_make_tarball.supports_root_dir=True\n_make_zipfile.supports_root_dir=True\n\n\n\n\n\n_ARCHIVE_FORMATS={\n'tar':(_make_tarball,[('compress',None)],\n\"uncompressed tar file\"),\n}\n\nif _ZLIB_SUPPORTED:\n _ARCHIVE_FORMATS['gztar']=(_make_tarball,[('compress','gzip')],\n \"gzip'ed tar-file\")\n _ARCHIVE_FORMATS['zip']=(_make_zipfile,[],\"ZIP file\")\n \nif _BZ2_SUPPORTED:\n _ARCHIVE_FORMATS['bztar']=(_make_tarball,[('compress','bzip2')],\n \"bzip2'ed tar-file\")\n \nif _LZMA_SUPPORTED:\n _ARCHIVE_FORMATS['xztar']=(_make_tarball,[('compress','xz')],\n \"xz'ed tar-file\")\n \ndef get_archive_formats():\n ''\n\n\n \n formats=[(name,registry[2])for name,registry in\n _ARCHIVE_FORMATS.items()]\n formats.sort()\n return formats\n \ndef register_archive_format(name,function,extra_args=None,description=''):\n ''\n\n\n\n\n\n\n \n if extra_args is None:\n extra_args=[]\n if not callable(function):\n raise TypeError('The %s object is not callable'%function)\n if not isinstance(extra_args,(tuple,list)):\n raise TypeError('extra_args needs to be a sequence')\n for element in extra_args:\n if not isinstance(element,(tuple,list))or len(element)!=2:\n raise TypeError('extra_args elements are : (arg_name, value)')\n \n _ARCHIVE_FORMATS[name]=(function,extra_args,description)\n \ndef unregister_archive_format(name):\n del _ARCHIVE_FORMATS[name]\n \ndef make_archive(base_name,format,root_dir=None,base_dir=None,verbose=0,\ndry_run=0,owner=None,group=None,logger=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.make_archive\",base_name,format,root_dir,base_dir)\n try:\n format_info=_ARCHIVE_FORMATS[format]\n except KeyError:\n raise ValueError(\"unknown archive format '%s'\"%format)from None\n \n kwargs={'dry_run':dry_run,'logger':logger,\n 'owner':owner,'group':group}\n \n func=format_info[0]\n for arg,val in format_info[1]:\n kwargs[arg]=val\n \n if base_dir is None:\n base_dir=os.curdir\n \n supports_root_dir=getattr(func,'supports_root_dir',False)\n save_cwd=None\n if root_dir is not None:\n stmd=os.stat(root_dir).st_mode\n if not stat.S_ISDIR(stmd):\n raise NotADirectoryError(errno.ENOTDIR,'Not a directory',root_dir)\n \n if supports_root_dir:\n \n base_name=os.fspath(base_name)\n kwargs['root_dir']=root_dir\n else:\n save_cwd=os.getcwd()\n if logger is not None:\n logger.debug(\"changing into '%s'\",root_dir)\n base_name=os.path.abspath(base_name)\n if not dry_run:\n os.chdir(root_dir)\n \n try:\n filename=func(base_name,base_dir,**kwargs)\n finally:\n if save_cwd is not None:\n if logger is not None:\n logger.debug(\"changing back to '%s'\",save_cwd)\n os.chdir(save_cwd)\n \n return filename\n \n \ndef get_unpack_formats():\n ''\n\n\n\n \n formats=[(name,info[0],info[3])for name,info in\n _UNPACK_FORMATS.items()]\n formats.sort()\n return formats\n \ndef _check_unpack_options(extensions,function,extra_args):\n ''\n \n existing_extensions={}\n for name,info in _UNPACK_FORMATS.items():\n for ext in info[0]:\n existing_extensions[ext]=name\n \n for extension in extensions:\n if extension in existing_extensions:\n msg='%s is already registered for \"%s\"'\n raise RegistryError(msg %(extension,\n existing_extensions[extension]))\n \n if not callable(function):\n raise TypeError('The registered function must be a callable')\n \n \ndef register_unpack_format(name,extensions,function,extra_args=None,\ndescription=''):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if extra_args is None:\n extra_args=[]\n _check_unpack_options(extensions,function,extra_args)\n _UNPACK_FORMATS[name]=extensions,function,extra_args,description\n \ndef unregister_unpack_format(name):\n ''\n del _UNPACK_FORMATS[name]\n \ndef _ensure_directory(path):\n ''\n dirname=os.path.dirname(path)\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n \ndef _unpack_zipfile(filename,extract_dir):\n ''\n \n import zipfile\n \n if not zipfile.is_zipfile(filename):\n raise ReadError(\"%s is not a zip file\"%filename)\n \n zip=zipfile.ZipFile(filename)\n try:\n for info in zip.infolist():\n name=info.filename\n \n \n if name.startswith('/')or '..'in name:\n continue\n \n targetpath=os.path.join(extract_dir,*name.split('/'))\n if not targetpath:\n continue\n \n _ensure_directory(targetpath)\n if not name.endswith('/'):\n \n with zip.open(name,'r')as source,\\\n open(targetpath,'wb')as target:\n copyfileobj(source,target)\n finally:\n zip.close()\n \ndef _unpack_tarfile(filename,extract_dir,*,filter=None):\n ''\n \n import tarfile\n try:\n tarobj=tarfile.open(filename)\n except tarfile.TarError:\n raise ReadError(\n \"%s is not a compressed or uncompressed tar file\"%filename)\n try:\n tarobj.extractall(extract_dir,filter=filter)\n finally:\n tarobj.close()\n \n \n \n \n \n \n_UNPACK_FORMATS={\n'tar':(['.tar'],_unpack_tarfile,[],\"uncompressed tar file\"),\n'zip':(['.zip'],_unpack_zipfile,[],\"ZIP file\"),\n}\n\nif _ZLIB_SUPPORTED:\n _UNPACK_FORMATS['gztar']=(['.tar.gz','.tgz'],_unpack_tarfile,[],\n \"gzip'ed tar-file\")\n \nif _BZ2_SUPPORTED:\n _UNPACK_FORMATS['bztar']=(['.tar.bz2','.tbz2'],_unpack_tarfile,[],\n \"bzip2'ed tar-file\")\n \nif _LZMA_SUPPORTED:\n _UNPACK_FORMATS['xztar']=(['.tar.xz','.txz'],_unpack_tarfile,[],\n \"xz'ed tar-file\")\n \ndef _find_unpack_format(filename):\n for name,info in _UNPACK_FORMATS.items():\n for extension in info[0]:\n if filename.endswith(extension):\n return name\n return None\n \ndef unpack_archive(filename,extract_dir=None,format=None,*,filter=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sys.audit(\"shutil.unpack_archive\",filename,extract_dir,format)\n \n if extract_dir is None:\n extract_dir=os.getcwd()\n \n extract_dir=os.fspath(extract_dir)\n filename=os.fspath(filename)\n \n if filter is None:\n filter_kwargs={}\n else:\n filter_kwargs={'filter':filter}\n if format is not None:\n try:\n format_info=_UNPACK_FORMATS[format]\n except KeyError:\n raise ValueError(\"Unknown unpack format '{0}'\".format(format))from None\n \n func=format_info[1]\n func(filename,extract_dir,**dict(format_info[2]),**filter_kwargs)\n else:\n \n format=_find_unpack_format(filename)\n if format is None:\n raise ReadError(\"Unknown archive format '{0}'\".format(filename))\n \n func=_UNPACK_FORMATS[format][1]\n kwargs=dict(_UNPACK_FORMATS[format][2])|filter_kwargs\n func(filename,extract_dir,**kwargs)\n \n \nif hasattr(os,'statvfs'):\n\n __all__.append('disk_usage')\n _ntuple_diskusage=collections.namedtuple('usage','total used free')\n _ntuple_diskusage.total.__doc__='Total space in bytes'\n _ntuple_diskusage.used.__doc__='Used space in bytes'\n _ntuple_diskusage.free.__doc__='Free space in bytes'\n \n def disk_usage(path):\n ''\n\n\n\n \n st=os.statvfs(path)\n free=st.f_bavail *st.f_frsize\n total=st.f_blocks *st.f_frsize\n used=(st.f_blocks -st.f_bfree)*st.f_frsize\n return _ntuple_diskusage(total,used,free)\n \nelif _WINDOWS:\n\n __all__.append('disk_usage')\n _ntuple_diskusage=collections.namedtuple('usage','total used free')\n \n def disk_usage(path):\n ''\n\n\n\n \n total,free=nt._getdiskusage(path)\n used=total -free\n return _ntuple_diskusage(total,used,free)\n \n \ndef chown(path,user=None,group=None,*,dir_fd=None,follow_symlinks=True):\n ''\n\n\n\n\n\n\n\n\n\n\n \n sys.audit('shutil.chown',path,user,group)\n \n if user is None and group is None:\n raise ValueError(\"user and/or group must be set\")\n \n _user=user\n _group=group\n \n \n if user is None:\n _user=-1\n \n elif isinstance(user,str):\n _user=_get_uid(user)\n if _user is None:\n raise LookupError(\"no such user: {!r}\".format(user))\n \n if group is None:\n _group=-1\n elif not isinstance(group,int):\n _group=_get_gid(group)\n if _group is None:\n raise LookupError(\"no such group: {!r}\".format(group))\n \n os.chown(path,_user,_group,dir_fd=dir_fd,\n follow_symlinks=follow_symlinks)\n \ndef get_terminal_size(fallback=(80,24)):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n try:\n columns=int(os.environ['COLUMNS'])\n except(KeyError,ValueError):\n columns=0\n \n try:\n lines=int(os.environ['LINES'])\n except(KeyError,ValueError):\n lines=0\n \n \n if columns <=0 or lines <=0:\n try:\n size=os.get_terminal_size(sys.__stdout__.fileno())\n except(AttributeError,ValueError,OSError):\n \n \n size=os.terminal_size(fallback)\n if columns <=0:\n columns=size.columns or fallback[0]\n if lines <=0:\n lines=size.lines or fallback[1]\n \n return os.terminal_size((columns,lines))\n \n \n \n \n \ndef _access_check(fn,mode):\n return(os.path.exists(fn)and os.access(fn,mode)\n and not os.path.isdir(fn))\n \n \ndef _win_path_needs_curdir(cmd,mode):\n ''\n\n\n\n \n return(not(mode&os.X_OK))or _winapi.NeedCurrentDirectoryForExePath(\n os.fsdecode(cmd))\n \n \ndef which(cmd,mode=os.F_OK |os.X_OK,path=None):\n ''\n\n\n\n\n\n\n\n \n use_bytes=isinstance(cmd,bytes)\n \n \n \n \n dirname,cmd=os.path.split(cmd)\n if dirname:\n path=[dirname]\n else:\n if path is None:\n path=os.environ.get(\"PATH\",None)\n if path is None:\n try:\n path=os.confstr(\"CS_PATH\")\n except(AttributeError,ValueError):\n \n path=os.defpath\n \n \n \n \n \n if not path:\n return None\n \n if use_bytes:\n path=os.fsencode(path)\n path=path.split(os.fsencode(os.pathsep))\n else:\n path=os.fsdecode(path)\n path=path.split(os.pathsep)\n \n if sys.platform ==\"win32\"and _win_path_needs_curdir(cmd,mode):\n curdir=os.curdir\n if use_bytes:\n curdir=os.fsencode(curdir)\n path.insert(0,curdir)\n \n if sys.platform ==\"win32\":\n \n pathext_source=os.getenv(\"PATHEXT\")or _WIN_DEFAULT_PATHEXT\n pathext=[ext for ext in pathext_source.split(os.pathsep)if ext]\n \n if use_bytes:\n pathext=[os.fsencode(ext)for ext in pathext]\n \n files=([cmd]+[cmd+ext for ext in pathext])\n \n \n \n \n \n \n suffix=os.path.splitext(files[0])[1].upper()\n if mode&os.X_OK and not any(suffix ==ext.upper()for ext in pathext):\n files.append(files.pop(0))\n else:\n \n \n files=[cmd]\n \n seen=set()\n for dir in path:\n normdir=os.path.normcase(dir)\n if not normdir in seen:\n seen.add(normdir)\n for thefile in files:\n name=os.path.join(dir,thefile)\n if _access_check(name,mode):\n return name\n return None\n", ["_winapi", "bz2", "collections", "errno", "fnmatch", "grp", "lzma", "nt", "os", "posix", "pwd", "stat", "sys", "tarfile", "zipfile", "zlib"]], "signal": [".py", "import _signal\nfrom _signal import *\nfrom enum import IntEnum as _IntEnum\n\n_globals=globals()\n\n_IntEnum._convert_(\n'Signals',__name__,\nlambda name:\nname.isupper()\nand(name.startswith('SIG')and not name.startswith('SIG_'))\nor name.startswith('CTRL_'))\n\n_IntEnum._convert_(\n'Handlers',__name__,\nlambda name:name in('SIG_DFL','SIG_IGN'))\n\nif 'pthread_sigmask'in _globals:\n _IntEnum._convert_(\n 'Sigmasks',__name__,\n lambda name:name in('SIG_BLOCK','SIG_UNBLOCK','SIG_SETMASK'))\n \n \ndef _int_to_enum(value,enum_klass):\n ''\n\n \n if not isinstance(value,int):\n return value\n try:\n return enum_klass(value)\n except ValueError:\n return value\n \n \ndef _enum_to_int(value):\n ''\n\n \n try:\n return int(value)\n except(ValueError,TypeError):\n return value\n \n \n \n \n \n \ndef _wraps(wrapped):\n def decorator(wrapper):\n wrapper.__doc__=wrapped.__doc__\n return wrapper\n return decorator\n \n@_wraps(_signal.signal)\ndef signal(signalnum,handler):\n handler=_signal.signal(_enum_to_int(signalnum),_enum_to_int(handler))\n return _int_to_enum(handler,Handlers)\n \n \n@_wraps(_signal.getsignal)\ndef getsignal(signalnum):\n handler=_signal.getsignal(signalnum)\n return _int_to_enum(handler,Handlers)\n \n \nif 'pthread_sigmask'in _globals:\n @_wraps(_signal.pthread_sigmask)\n def pthread_sigmask(how,mask):\n sigs_set=_signal.pthread_sigmask(how,mask)\n return set(_int_to_enum(x,Signals)for x in sigs_set)\n \n \nif 'sigpending'in _globals:\n @_wraps(_signal.sigpending)\n def sigpending():\n return{_int_to_enum(x,Signals)for x in _signal.sigpending()}\n \n \nif 'sigwait'in _globals:\n @_wraps(_signal.sigwait)\n def sigwait(sigset):\n retsig=_signal.sigwait(sigset)\n return _int_to_enum(retsig,Signals)\n \n \nif 'valid_signals'in _globals:\n @_wraps(_signal.valid_signals)\n def valid_signals():\n return{_int_to_enum(x,Signals)for x in _signal.valid_signals()}\n \n \ndel _globals,_wraps\n", ["_signal", "enum"]], "site": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport os\nimport builtins\nimport _sitebuiltins\nimport io\nimport stat\n\n\nPREFIXES=[sys.prefix,sys.exec_prefix]\n\n\nENABLE_USER_SITE=None\n\n\n\n\nUSER_SITE=None\nUSER_BASE=None\n\n\ndef _trace(message):\n if sys.flags.verbose:\n print(message,file=sys.stderr)\n \n \ndef makepath(*paths):\n dir=os.path.join(*paths)\n try:\n dir=os.path.abspath(dir)\n except OSError:\n pass\n return dir,os.path.normcase(dir)\n \n \ndef abs_paths():\n ''\n for m in set(sys.modules.values()):\n loader_module=None\n try:\n loader_module=m.__loader__.__module__\n except AttributeError:\n try:\n loader_module=m.__spec__.loader.__module__\n except AttributeError:\n pass\n if loader_module not in{'_frozen_importlib','_frozen_importlib_external'}:\n continue\n try:\n m.__file__=os.path.abspath(m.__file__)\n except(AttributeError,OSError,TypeError):\n pass\n try:\n m.__cached__=os.path.abspath(m.__cached__)\n except(AttributeError,OSError,TypeError):\n pass\n \n \ndef removeduppaths():\n ''\n \n \n \n L=[]\n known_paths=set()\n for dir in sys.path:\n \n \n \n dir,dircase=makepath(dir)\n if dircase not in known_paths:\n L.append(dir)\n known_paths.add(dircase)\n sys.path[:]=L\n return known_paths\n \n \ndef _init_pathinfo():\n ''\n d=set()\n for item in sys.path:\n try:\n if os.path.exists(item):\n _,itemcase=makepath(item)\n d.add(itemcase)\n except TypeError:\n continue\n return d\n \n \ndef addpackage(sitedir,name,known_paths):\n ''\n\n\n \n if known_paths is None:\n known_paths=_init_pathinfo()\n reset=True\n else:\n reset=False\n fullname=os.path.join(sitedir,name)\n try:\n st=os.lstat(fullname)\n except OSError:\n return\n if((getattr(st,'st_flags',0)&stat.UF_HIDDEN)or\n (getattr(st,'st_file_attributes',0)&stat.FILE_ATTRIBUTE_HIDDEN)):\n _trace(f\"Skipping hidden .pth file: {fullname !r}\")\n return\n _trace(f\"Processing .pth file: {fullname !r}\")\n try:\n with io.open_code(fullname)as f:\n pth_content=f.read()\n except OSError:\n return\n \n try:\n pth_content=pth_content.decode()\n except UnicodeDecodeError:\n \n \n import locale\n pth_content=pth_content.decode(locale.getencoding())\n _trace(f\"Cannot read {fullname !r} as UTF-8. \"\n f\"Using fallback encoding {locale.getencoding()!r}\")\n \n for n,line in enumerate(pth_content.splitlines(),1):\n if line.startswith(\"#\"):\n continue\n if line.strip()==\"\":\n continue\n try:\n if line.startswith((\"import \",\"import\\t\")):\n exec(line)\n continue\n line=line.rstrip()\n dir,dircase=makepath(sitedir,line)\n if dircase not in known_paths and os.path.exists(dir):\n sys.path.append(dir)\n known_paths.add(dircase)\n except Exception as exc:\n print(f\"Error processing line {n:d} of {fullname}:\\n\",\n file=sys.stderr)\n import traceback\n for record in traceback.format_exception(exc):\n for line in record.splitlines():\n print(' '+line,file=sys.stderr)\n print(\"\\nRemainder of file ignored\",file=sys.stderr)\n break\n if reset:\n known_paths=None\n return known_paths\n \n \ndef addsitedir(sitedir,known_paths=None):\n ''\n \n _trace(f\"Adding directory: {sitedir !r}\")\n if known_paths is None:\n known_paths=_init_pathinfo()\n reset=True\n else:\n reset=False\n sitedir,sitedircase=makepath(sitedir)\n if not sitedircase in known_paths:\n sys.path.append(sitedir)\n known_paths.add(sitedircase)\n try:\n names=os.listdir(sitedir)\n except OSError:\n return\n names=[name for name in names\n if name.endswith(\".pth\")and not name.startswith(\".\")]\n for name in sorted(names):\n addpackage(sitedir,name,known_paths)\n if reset:\n known_paths=None\n return known_paths\n \n \ndef check_enableusersite():\n ''\n\n\n\n\n\n\n\n \n if sys.flags.no_user_site:\n return False\n \n if hasattr(os,\"getuid\")and hasattr(os,\"geteuid\"):\n \n if os.geteuid()!=os.getuid():\n return None\n if hasattr(os,\"getgid\")and hasattr(os,\"getegid\"):\n \n if os.getegid()!=os.getgid():\n return None\n \n return True\n \n \n \n \n \n \n \n \n \ndef _get_implementation():\n return 'Python'\n \n \ndef _getuserbase():\n env_base=os.environ.get(\"PYTHONUSERBASE\",None)\n if env_base:\n return env_base\n \n \n if sys.platform in{\"emscripten\",\"ios\",\"tvos\",\"vxworks\",\"wasi\",\"watchos\"}:\n return None\n \n def joinuser(*args):\n return os.path.expanduser(os.path.join(*args))\n \n if os.name ==\"nt\":\n base=os.environ.get(\"APPDATA\")or \"~\"\n return joinuser(base,_get_implementation())\n \n if sys.platform ==\"darwin\"and sys._framework:\n return joinuser(\"~\",\"Library\",sys._framework,\n \"%d.%d\"%sys.version_info[:2])\n \n return joinuser(\"~\",\".local\")\n \n \n \ndef _get_path(userbase):\n version=sys.version_info\n \n implementation=_get_implementation()\n implementation_lower=implementation.lower()\n if os.name =='nt':\n ver_nodot=sys.winver.replace('.','')\n return f'{userbase}\\\\{implementation}{ver_nodot}\\\\site-packages'\n \n if sys.platform =='darwin'and sys._framework:\n return f'{userbase}/lib/{implementation_lower}/site-packages'\n \n return f'{userbase}/lib/python{version[0]}.{version[1]}/site-packages'\n \n \ndef getuserbase():\n ''\n\n\n\n\n \n global USER_BASE\n if USER_BASE is None:\n USER_BASE=_getuserbase()\n return USER_BASE\n \n \ndef getusersitepackages():\n ''\n\n\n\n \n global USER_SITE,ENABLE_USER_SITE\n userbase=getuserbase()\n \n if USER_SITE is None:\n if userbase is None:\n ENABLE_USER_SITE=False\n else:\n USER_SITE=_get_path(userbase)\n \n return USER_SITE\n \ndef addusersitepackages(known_paths):\n ''\n\n\n\n \n \n \n _trace(\"Processing user site-packages\")\n user_site=getusersitepackages()\n \n if ENABLE_USER_SITE and os.path.isdir(user_site):\n addsitedir(user_site,known_paths)\n return known_paths\n \ndef getsitepackages(prefixes=None):\n ''\n\n\n\n\n \n sitepackages=[]\n seen=set()\n \n if prefixes is None:\n prefixes=PREFIXES\n \n for prefix in prefixes:\n if not prefix or prefix in seen:\n continue\n seen.add(prefix)\n \n implementation=_get_implementation().lower()\n ver=sys.version_info\n if os.sep =='/':\n libdirs=[sys.platlibdir]\n if sys.platlibdir !=\"lib\":\n libdirs.append(\"lib\")\n \n for libdir in libdirs:\n path=os.path.join(prefix,libdir,\n f\"{implementation}{ver[0]}.{ver[1]}\",\n \"site-packages\")\n sitepackages.append(path)\n else:\n sitepackages.append(prefix)\n sitepackages.append(os.path.join(prefix,\"Lib\",\"site-packages\"))\n return sitepackages\n \ndef addsitepackages(known_paths,prefixes=None):\n ''\n _trace(\"Processing global site-packages\")\n for sitedir in getsitepackages(prefixes):\n if os.path.isdir(sitedir):\n addsitedir(sitedir,known_paths)\n \n return known_paths\n \ndef setquit():\n ''\n\n\n\n\n \n if os.sep =='\\\\':\n eof='Ctrl-Z plus Return'\n else:\n eof='Ctrl-D (i.e. EOF)'\n \n builtins.quit=_sitebuiltins.Quitter('quit',eof)\n builtins.exit=_sitebuiltins.Quitter('exit',eof)\n \n \ndef setcopyright():\n ''\n builtins.copyright=_sitebuiltins._Printer(\"copyright\",sys.copyright)\n builtins.credits=_sitebuiltins._Printer(\"credits\",\"\"\"\\\n Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\n for supporting Python development. See www.python.org for more information.\"\"\")\n files,dirs=[],[]\n \n \n here=getattr(sys,'_stdlib_dir',None)\n if not here and hasattr(os,'__file__'):\n here=os.path.dirname(os.__file__)\n if here:\n files.extend([\"LICENSE.txt\",\"LICENSE\"])\n dirs.extend([os.path.join(here,os.pardir),here,os.curdir])\n builtins.license=_sitebuiltins._Printer(\n \"license\",\n \"See https://www.python.org/psf/license/\",\n files,dirs)\n \n \ndef sethelper():\n builtins.help=_sitebuiltins._Helper()\n \n \ndef gethistoryfile():\n ''\n\n\n \n if not sys.flags.ignore_environment:\n history=os.environ.get(\"PYTHON_HISTORY\")\n if history:\n return history\n return os.path.join(os.path.expanduser('~'),\n '.python_history')\n \n \ndef enablerlcompleter():\n ''\n\n \n sys.__interactivehook__=register_readline\n \n \ndef register_readline():\n ''\n\n\n\n\n\n \n import atexit\n try:\n import readline\n import rlcompleter\n import _pyrepl.readline\n import _pyrepl.unix_console\n except ImportError:\n return\n \n \n \n if readline.backend =='editline':\n readline.parse_and_bind('bind ^I rl_complete')\n else:\n readline.parse_and_bind('tab: complete')\n \n try:\n readline.read_init_file()\n except OSError:\n \n \n \n \n pass\n \n if readline.get_current_history_length()==0:\n \n \n \n \n \n \n history=gethistoryfile()\n try:\n if os.getenv(\"PYTHON_BASIC_REPL\"):\n readline.read_history_file(history)\n else:\n _pyrepl.readline.read_history_file(history)\n except(OSError,*_pyrepl.unix_console._error):\n pass\n \n def write_history():\n try:\n if os.getenv(\"PYTHON_BASIC_REPL\"):\n readline.write_history_file(history)\n else:\n _pyrepl.readline.write_history_file(history)\n except(FileNotFoundError,PermissionError):\n \n \n pass\n \n atexit.register(write_history)\n \n \ndef venv(known_paths):\n global PREFIXES,ENABLE_USER_SITE\n \n env=os.environ\n if sys.platform =='darwin'and '__PYVENV_LAUNCHER__'in env:\n executable=sys._base_executable=os.environ['__PYVENV_LAUNCHER__']\n else:\n executable=sys.executable\n exe_dir=os.path.dirname(os.path.abspath(executable))\n site_prefix=os.path.dirname(exe_dir)\n sys._home=None\n conf_basename='pyvenv.cfg'\n candidate_conf=next(\n (\n conffile for conffile in(\n os.path.join(exe_dir,conf_basename),\n os.path.join(site_prefix,conf_basename)\n )\n if os.path.isfile(conffile)\n ),\n None\n )\n \n if candidate_conf:\n virtual_conf=candidate_conf\n system_site=\"true\"\n \n \n with open(virtual_conf,encoding='utf-8')as f:\n for line in f:\n if '='in line:\n key,_,value=line.partition('=')\n key=key.strip().lower()\n value=value.strip()\n if key =='include-system-site-packages':\n system_site=value.lower()\n elif key =='home':\n sys._home=value\n \n sys.prefix=sys.exec_prefix=site_prefix\n \n \n addsitepackages(known_paths,[sys.prefix])\n \n \n \n if system_site ==\"true\":\n PREFIXES.insert(0,sys.prefix)\n else:\n PREFIXES=[sys.prefix]\n ENABLE_USER_SITE=False\n \n return known_paths\n \n \ndef execsitecustomize():\n ''\n try:\n try:\n import sitecustomize\n except ImportError as exc:\n if exc.name =='sitecustomize':\n pass\n else:\n raise\n except Exception as err:\n if sys.flags.verbose:\n sys.excepthook(*sys.exc_info())\n else:\n sys.stderr.write(\n \"Error in sitecustomize; set PYTHONVERBOSE for traceback:\\n\"\n \"%s: %s\\n\"%\n (err.__class__.__name__,err))\n \n \ndef execusercustomize():\n ''\n try:\n try:\n import usercustomize\n except ImportError as exc:\n if exc.name =='usercustomize':\n pass\n else:\n raise\n except Exception as err:\n if sys.flags.verbose:\n sys.excepthook(*sys.exc_info())\n else:\n sys.stderr.write(\n \"Error in usercustomize; set PYTHONVERBOSE for traceback:\\n\"\n \"%s: %s\\n\"%\n (err.__class__.__name__,err))\n \n \ndef main():\n ''\n\n\n\n \n global ENABLE_USER_SITE\n \n orig_path=sys.path[:]\n known_paths=removeduppaths()\n if orig_path !=sys.path:\n \n \n abs_paths()\n \n known_paths=venv(known_paths)\n if ENABLE_USER_SITE is None:\n ENABLE_USER_SITE=check_enableusersite()\n known_paths=addusersitepackages(known_paths)\n known_paths=addsitepackages(known_paths)\n setquit()\n setcopyright()\n sethelper()\n if not sys.flags.isolated:\n enablerlcompleter()\n execsitecustomize()\n if ENABLE_USER_SITE:\n execusercustomize()\n \n \n \nif not sys.flags.no_site:\n main()\n \ndef _script():\n help=\"\"\"\\\n %s [--user-base] [--user-site]\n\n Without arguments print some useful information\n With arguments print the value of USER_BASE and/or USER_SITE separated\n by '%s'.\n\n Exit codes with --user-base or --user-site:\n 0 - user site directory is enabled\n 1 - user site directory is disabled by user\n 2 - user site directory is disabled by super user\n or for security reasons\n >2 - unknown error\n \"\"\"\n args=sys.argv[1:]\n if not args:\n user_base=getuserbase()\n user_site=getusersitepackages()\n print(\"sys.path = [\")\n for dir in sys.path:\n print(\" %r,\"%(dir,))\n print(\"]\")\n def exists(path):\n if path is not None and os.path.isdir(path):\n return \"exists\"\n else:\n return \"doesn't exist\"\n print(f\"USER_BASE: {user_base !r} ({exists(user_base)})\")\n print(f\"USER_SITE: {user_site !r} ({exists(user_site)})\")\n print(f\"ENABLE_USER_SITE: {ENABLE_USER_SITE !r}\")\n sys.exit(0)\n \n buffer=[]\n if '--user-base'in args:\n buffer.append(USER_BASE)\n if '--user-site'in args:\n buffer.append(USER_SITE)\n \n if buffer:\n print(os.pathsep.join(buffer))\n if ENABLE_USER_SITE:\n sys.exit(0)\n elif ENABLE_USER_SITE is False:\n sys.exit(1)\n elif ENABLE_USER_SITE is None:\n sys.exit(2)\n else:\n sys.exit(3)\n else:\n import textwrap\n print(textwrap.dedent(help %(sys.argv[0],os.pathsep)))\n sys.exit(10)\n \nif __name__ =='__main__':\n _script()\n", ["_pyrepl.readline", "_pyrepl.unix_console", "_sitebuiltins", "atexit", "builtins", "io", "locale", "os", "readline", "rlcompleter", "sitecustomize", "stat", "sys", "textwrap", "traceback", "usercustomize"]], "socket": [".py", "\n\n\n\"\"\"\\\nThis module provides socket operations and some related functions.\nOn Unix, it supports IP (Internet Protocol) and Unix domain sockets.\nOn other systems, it only supports IP. Functions specific for a\nsocket are available as methods of the socket object.\n\nFunctions:\n\nsocket() -- create a new socket object\nsocketpair() -- create a pair of new socket objects [*]\nfromfd() -- create a socket object from an open file descriptor [*]\nsend_fds() -- Send file descriptor to the socket.\nrecv_fds() -- Receive file descriptors from the socket.\nfromshare() -- create a socket object from data received from socket.share() [*]\ngethostname() -- return the current hostname\ngethostbyname() -- map a hostname to its IP number\ngethostbyaddr() -- map an IP number or hostname to DNS info\ngetservbyname() -- map a service name and a protocol name to a port number\ngetprotobyname() -- map a protocol name (e.g. 'tcp') to a number\nntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order\nhtons(), htonl() -- convert 16, 32 bit int from host to network byte order\ninet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format\ninet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)\nsocket.getdefaulttimeout() -- get the default timeout value\nsocket.setdefaulttimeout() -- set the default timeout value\ncreate_connection() -- connects to an address, with an optional timeout and\n optional source address.\n\n [*] not available on all platforms!\n\nSpecial objects:\n\nSocketType -- type object for socket objects\nerror -- exception raised for I/O errors\nhas_ipv6 -- boolean value indicating if IPv6 is supported\n\nIntEnum constants:\n\nAF_INET, AF_UNIX -- socket domains (first argument to socket() call)\nSOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)\n\nInteger constants:\n\nMany other constants may be defined; these may be used in calls to\nthe setsockopt() and getsockopt() methods.\n\"\"\"\n\nimport _socket\nfrom _socket import *\n\nimport os,sys,io,selectors\nfrom enum import IntEnum,IntFlag\n\ntry:\n import errno\nexcept ImportError:\n errno=None\nEBADF=getattr(errno,'EBADF',9)\nEAGAIN=getattr(errno,'EAGAIN',11)\nEWOULDBLOCK=getattr(errno,'EWOULDBLOCK',11)\n\n__all__=[\"fromfd\",\"getfqdn\",\"create_connection\",\"create_server\",\n\"has_dualstack_ipv6\",\"AddressFamily\",\"SocketKind\"]\n__all__.extend(os._get_exports_list(_socket))\n\n\n\n\n\n\n\nIntEnum._convert_(\n'AddressFamily',\n__name__,\nlambda C:C.isupper()and C.startswith('AF_'))\n\nIntEnum._convert_(\n'SocketKind',\n__name__,\nlambda C:C.isupper()and C.startswith('SOCK_'))\n\nIntFlag._convert_(\n'MsgFlag',\n__name__,\nlambda C:C.isupper()and C.startswith('MSG_'))\n\nIntFlag._convert_(\n'AddressInfo',\n__name__,\nlambda C:C.isupper()and C.startswith('AI_'))\n\n_LOCALHOST='127.0.0.1'\n_LOCALHOST_V6='::1'\n\n\ndef _intenum_converter(value,enum_klass):\n ''\n\n\n \n try:\n return enum_klass(value)\n except ValueError:\n return value\n \n \n \nif sys.platform.lower().startswith(\"win\"):\n errorTab={}\n errorTab[6]=\"Specified event object handle is invalid.\"\n errorTab[8]=\"Insufficient memory available.\"\n errorTab[87]=\"One or more parameters are invalid.\"\n errorTab[995]=\"Overlapped operation aborted.\"\n errorTab[996]=\"Overlapped I/O event object not in signaled state.\"\n errorTab[997]=\"Overlapped operation will complete later.\"\n errorTab[10004]=\"The operation was interrupted.\"\n errorTab[10009]=\"A bad file handle was passed.\"\n errorTab[10013]=\"Permission denied.\"\n errorTab[10014]=\"A fault occurred on the network??\"\n errorTab[10022]=\"An invalid operation was attempted.\"\n errorTab[10024]=\"Too many open files.\"\n errorTab[10035]=\"The socket operation would block.\"\n errorTab[10036]=\"A blocking operation is already in progress.\"\n errorTab[10037]=\"Operation already in progress.\"\n errorTab[10038]=\"Socket operation on nonsocket.\"\n errorTab[10039]=\"Destination address required.\"\n errorTab[10040]=\"Message too long.\"\n errorTab[10041]=\"Protocol wrong type for socket.\"\n errorTab[10042]=\"Bad protocol option.\"\n errorTab[10043]=\"Protocol not supported.\"\n errorTab[10044]=\"Socket type not supported.\"\n errorTab[10045]=\"Operation not supported.\"\n errorTab[10046]=\"Protocol family not supported.\"\n errorTab[10047]=\"Address family not supported by protocol family.\"\n errorTab[10048]=\"The network address is in use.\"\n errorTab[10049]=\"Cannot assign requested address.\"\n errorTab[10050]=\"Network is down.\"\n errorTab[10051]=\"Network is unreachable.\"\n errorTab[10052]=\"Network dropped connection on reset.\"\n errorTab[10053]=\"Software caused connection abort.\"\n errorTab[10054]=\"The connection has been reset.\"\n errorTab[10055]=\"No buffer space available.\"\n errorTab[10056]=\"Socket is already connected.\"\n errorTab[10057]=\"Socket is not connected.\"\n errorTab[10058]=\"The network has been shut down.\"\n errorTab[10059]=\"Too many references.\"\n errorTab[10060]=\"The operation timed out.\"\n errorTab[10061]=\"Connection refused.\"\n errorTab[10062]=\"Cannot translate name.\"\n errorTab[10063]=\"The name is too long.\"\n errorTab[10064]=\"The host is down.\"\n errorTab[10065]=\"The host is unreachable.\"\n errorTab[10066]=\"Directory not empty.\"\n errorTab[10067]=\"Too many processes.\"\n errorTab[10068]=\"User quota exceeded.\"\n errorTab[10069]=\"Disk quota exceeded.\"\n errorTab[10070]=\"Stale file handle reference.\"\n errorTab[10071]=\"Item is remote.\"\n errorTab[10091]=\"Network subsystem is unavailable.\"\n errorTab[10092]=\"Winsock.dll version out of range.\"\n errorTab[10093]=\"Successful WSAStartup not yet performed.\"\n errorTab[10101]=\"Graceful shutdown in progress.\"\n errorTab[10102]=\"No more results from WSALookupServiceNext.\"\n errorTab[10103]=\"Call has been canceled.\"\n errorTab[10104]=\"Procedure call table is invalid.\"\n errorTab[10105]=\"Service provider is invalid.\"\n errorTab[10106]=\"Service provider failed to initialize.\"\n errorTab[10107]=\"System call failure.\"\n errorTab[10108]=\"Service not found.\"\n errorTab[10109]=\"Class type not found.\"\n errorTab[10110]=\"No more results from WSALookupServiceNext.\"\n errorTab[10111]=\"Call was canceled.\"\n errorTab[10112]=\"Database query was refused.\"\n errorTab[11001]=\"Host not found.\"\n errorTab[11002]=\"Nonauthoritative host not found.\"\n errorTab[11003]=\"This is a nonrecoverable error.\"\n errorTab[11004]=\"Valid name, no data record requested type.\"\n errorTab[11005]=\"QoS receivers.\"\n errorTab[11006]=\"QoS senders.\"\n errorTab[11007]=\"No QoS senders.\"\n errorTab[11008]=\"QoS no receivers.\"\n errorTab[11009]=\"QoS request confirmed.\"\n errorTab[11010]=\"QoS admission error.\"\n errorTab[11011]=\"QoS policy failure.\"\n errorTab[11012]=\"QoS bad style.\"\n errorTab[11013]=\"QoS bad object.\"\n errorTab[11014]=\"QoS traffic control error.\"\n errorTab[11015]=\"QoS generic error.\"\n errorTab[11016]=\"QoS service type error.\"\n errorTab[11017]=\"QoS flowspec error.\"\n errorTab[11018]=\"Invalid QoS provider buffer.\"\n errorTab[11019]=\"Invalid QoS filter style.\"\n errorTab[11020]=\"Invalid QoS filter style.\"\n errorTab[11021]=\"Incorrect QoS filter count.\"\n errorTab[11022]=\"Invalid QoS object length.\"\n errorTab[11023]=\"Incorrect QoS flow count.\"\n errorTab[11024]=\"Unrecognized QoS object.\"\n errorTab[11025]=\"Invalid QoS policy object.\"\n errorTab[11026]=\"Invalid QoS flow descriptor.\"\n errorTab[11027]=\"Invalid QoS provider-specific flowspec.\"\n errorTab[11028]=\"Invalid QoS provider-specific filterspec.\"\n errorTab[11029]=\"Invalid QoS shape discard mode object.\"\n errorTab[11030]=\"Invalid QoS shaping rate object.\"\n errorTab[11031]=\"Reserved policy QoS element type.\"\n __all__.append(\"errorTab\")\n \n \nclass _GiveupOnSendfile(Exception):pass\n\n\nclass socket(_socket.socket):\n\n ''\n \n __slots__=[\"__weakref__\",\"_io_refs\",\"_closed\"]\n \n def __init__(self,family=-1,type=-1,proto=-1,fileno=None):\n \n \n \n \n if fileno is None:\n if family ==-1:\n family=AF_INET\n if type ==-1:\n type=SOCK_STREAM\n if proto ==-1:\n proto=0\n _socket.socket.__init__(self,family,type,proto,fileno)\n self._io_refs=0\n self._closed=False\n \n def __enter__(self):\n return self\n \n def __exit__(self,*args):\n if not self._closed:\n self.close()\n \n def __repr__(self):\n ''\n\n \n closed=getattr(self,'_closed',False)\n s=\"<%s.%s%s fd=%i, family=%s, type=%s, proto=%i\"\\\n %(self.__class__.__module__,\n self.__class__.__qualname__,\n \" [closed]\"if closed else \"\",\n self.fileno(),\n self.family,\n self.type,\n self.proto)\n if not closed:\n try:\n laddr=self.getsockname()\n if laddr:\n s +=\", laddr=%s\"%str(laddr)\n except error:\n pass\n try:\n raddr=self.getpeername()\n if raddr:\n s +=\", raddr=%s\"%str(raddr)\n except error:\n pass\n s +='>'\n return s\n \n def __getstate__(self):\n raise TypeError(f\"cannot pickle {self.__class__.__name__ !r} object\")\n \n def dup(self):\n ''\n\n\n\n \n fd=dup(self.fileno())\n sock=self.__class__(self.family,self.type,self.proto,fileno=fd)\n sock.settimeout(self.gettimeout())\n return sock\n \n def accept(self):\n ''\n\n\n\n\n \n fd,addr=self._accept()\n sock=socket(self.family,self.type,self.proto,fileno=fd)\n \n \n \n if getdefaulttimeout()is None and self.gettimeout():\n sock.setblocking(True)\n return sock,addr\n \n def makefile(self,mode=\"r\",buffering=None,*,\n encoding=None,errors=None,newline=None):\n ''\n\n\n\n \n \n if not set(mode)<={\"r\",\"w\",\"b\"}:\n raise ValueError(\"invalid mode %r (only r, w, b allowed)\"%(mode,))\n writing=\"w\"in mode\n reading=\"r\"in mode or not writing\n assert reading or writing\n binary=\"b\"in mode\n rawmode=\"\"\n if reading:\n rawmode +=\"r\"\n if writing:\n rawmode +=\"w\"\n raw=SocketIO(self,rawmode)\n self._io_refs +=1\n if buffering is None:\n buffering=-1\n if buffering <0:\n buffering=io.DEFAULT_BUFFER_SIZE\n if buffering ==0:\n if not binary:\n raise ValueError(\"unbuffered streams must be binary\")\n return raw\n if reading and writing:\n buffer=io.BufferedRWPair(raw,raw,buffering)\n elif reading:\n buffer=io.BufferedReader(raw,buffering)\n else:\n assert writing\n buffer=io.BufferedWriter(raw,buffering)\n if binary:\n return buffer\n encoding=io.text_encoding(encoding)\n text=io.TextIOWrapper(buffer,encoding,errors,newline)\n text.mode=mode\n return text\n \n if hasattr(os,'sendfile'):\n \n def _sendfile_use_sendfile(self,file,offset=0,count=None):\n self._check_sendfile_params(file,offset,count)\n sockno=self.fileno()\n try:\n fileno=file.fileno()\n except(AttributeError,io.UnsupportedOperation)as err:\n raise _GiveupOnSendfile(err)\n try:\n fsize=os.fstat(fileno).st_size\n except OSError as err:\n raise _GiveupOnSendfile(err)\n if not fsize:\n return 0\n \n blocksize=min(count or fsize,2 **30)\n timeout=self.gettimeout()\n if timeout ==0:\n raise ValueError(\"non-blocking sockets are not supported\")\n \n \n \n if hasattr(selectors,'PollSelector'):\n selector=selectors.PollSelector()\n else:\n selector=selectors.SelectSelector()\n selector.register(sockno,selectors.EVENT_WRITE)\n \n total_sent=0\n \n selector_select=selector.select\n os_sendfile=os.sendfile\n try:\n while True:\n if timeout and not selector_select(timeout):\n raise TimeoutError('timed out')\n if count:\n blocksize=count -total_sent\n if blocksize <=0:\n break\n try:\n sent=os_sendfile(sockno,fileno,offset,blocksize)\n except BlockingIOError:\n if not timeout:\n \n \n selector_select()\n continue\n except OSError as err:\n if total_sent ==0:\n \n \n \n \n raise _GiveupOnSendfile(err)\n raise err from None\n else:\n if sent ==0:\n break\n offset +=sent\n total_sent +=sent\n return total_sent\n finally:\n if total_sent >0 and hasattr(file,'seek'):\n file.seek(offset)\n else:\n def _sendfile_use_sendfile(self,file,offset=0,count=None):\n raise _GiveupOnSendfile(\n \"os.sendfile() not available on this platform\")\n \n def _sendfile_use_send(self,file,offset=0,count=None):\n self._check_sendfile_params(file,offset,count)\n if self.gettimeout()==0:\n raise ValueError(\"non-blocking sockets are not supported\")\n if offset:\n file.seek(offset)\n blocksize=min(count,8192)if count else 8192\n total_sent=0\n \n file_read=file.read\n sock_send=self.send\n try:\n while True:\n if count:\n blocksize=min(count -total_sent,blocksize)\n if blocksize <=0:\n break\n data=memoryview(file_read(blocksize))\n if not data:\n break\n while True:\n try:\n sent=sock_send(data)\n except BlockingIOError:\n continue\n else:\n total_sent +=sent\n if sent 0 and hasattr(file,'seek'):\n file.seek(offset+total_sent)\n \n def _check_sendfile_params(self,file,offset,count):\n if 'b'not in getattr(file,'mode','b'):\n raise ValueError(\"file should be opened in binary mode\")\n if not self.type&SOCK_STREAM:\n raise ValueError(\"only SOCK_STREAM type sockets are supported\")\n if count is not None:\n if not isinstance(count,int):\n raise TypeError(\n \"count must be a positive integer (got {!r})\".format(count))\n if count <=0:\n raise ValueError(\n \"count must be a positive integer (got {!r})\".format(count))\n \n def sendfile(self,file,offset=0,count=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return self._sendfile_use_sendfile(file,offset,count)\n except _GiveupOnSendfile:\n return self._sendfile_use_send(file,offset,count)\n \n def _decref_socketios(self):\n if self._io_refs >0:\n self._io_refs -=1\n if self._closed:\n self.close()\n \n def _real_close(self,_ss=_socket.socket):\n \n _ss.close(self)\n \n def close(self):\n \n self._closed=True\n if self._io_refs <=0:\n self._real_close()\n \n def detach(self):\n ''\n\n\n\n\n \n self._closed=True\n return super().detach()\n \n @property\n def family(self):\n ''\n \n return _intenum_converter(super().family,AddressFamily)\n \n @property\n def type(self):\n ''\n \n return _intenum_converter(super().type,SocketKind)\n \n if os.name =='nt':\n def get_inheritable(self):\n return os.get_handle_inheritable(self.fileno())\n def set_inheritable(self,inheritable):\n os.set_handle_inheritable(self.fileno(),inheritable)\n else:\n def get_inheritable(self):\n return os.get_inheritable(self.fileno())\n def set_inheritable(self,inheritable):\n os.set_inheritable(self.fileno(),inheritable)\n get_inheritable.__doc__=\"Get the inheritable flag of the socket\"\n set_inheritable.__doc__=\"Set the inheritable flag of the socket\"\n \ndef fromfd(fd,family,type,proto=0):\n ''\n\n\n\n \n nfd=dup(fd)\n return socket(family,type,proto,nfd)\n \nif hasattr(_socket.socket,\"sendmsg\"):\n import array\n \n def send_fds(sock,buffers,fds,flags=0,address=None):\n ''\n\n\n \n return sock.sendmsg(buffers,[(_socket.SOL_SOCKET,\n _socket.SCM_RIGHTS,array.array(\"i\",fds))])\n __all__.append(\"send_fds\")\n \nif hasattr(_socket.socket,\"recvmsg\"):\n import array\n \n def recv_fds(sock,bufsize,maxfds,flags=0):\n ''\n\n\n\n\n \n \n fds=array.array(\"i\")\n msg,ancdata,flags,addr=sock.recvmsg(bufsize,\n _socket.CMSG_LEN(maxfds *fds.itemsize))\n for cmsg_level,cmsg_type,cmsg_data in ancdata:\n if(cmsg_level ==_socket.SOL_SOCKET and cmsg_type ==_socket.SCM_RIGHTS):\n fds.frombytes(cmsg_data[:\n len(cmsg_data)-(len(cmsg_data)%fds.itemsize)])\n \n return msg,list(fds),flags,addr\n __all__.append(\"recv_fds\")\n \nif hasattr(_socket.socket,\"share\"):\n def fromshare(info):\n ''\n\n\n\n \n return socket(0,0,0,info)\n __all__.append(\"fromshare\")\n \nif hasattr(_socket,\"socketpair\"):\n\n def socketpair(family=None,type=SOCK_STREAM,proto=0):\n ''\n\n\n\n\n\n \n if family is None:\n try:\n family=AF_UNIX\n except NameError:\n family=AF_INET\n a,b=_socket.socketpair(family,type,proto)\n a=socket(family,type,proto,a.detach())\n b=socket(family,type,proto,b.detach())\n return a,b\n \nelse:\n\n\n def socketpair(family=AF_INET,type=SOCK_STREAM,proto=0):\n if family ==AF_INET:\n host=_LOCALHOST\n elif family ==AF_INET6:\n host=_LOCALHOST_V6\n else:\n raise ValueError(\"Only AF_INET and AF_INET6 socket address families \"\n \"are supported\")\n if type !=SOCK_STREAM:\n raise ValueError(\"Only SOCK_STREAM socket type is supported\")\n if proto !=0:\n raise ValueError(\"Only protocol zero is supported\")\n \n \n \n lsock=socket(family,type,proto)\n try:\n lsock.bind((host,0))\n lsock.listen()\n \n addr,port=lsock.getsockname()[:2]\n csock=socket(family,type,proto)\n try:\n csock.setblocking(False)\n try:\n csock.connect((addr,port))\n except(BlockingIOError,InterruptedError):\n pass\n csock.setblocking(True)\n ssock,_=lsock.accept()\n except:\n csock.close()\n raise\n finally:\n lsock.close()\n return(ssock,csock)\n __all__.append(\"socketpair\")\n \nsocketpair.__doc__=\"\"\"socketpair([family[, type[, proto]]]) -> (socket object, socket object)\nCreate a pair of socket objects from the sockets returned by the platform\nsocketpair() function.\nThe arguments are the same as for socket() except the default family is AF_UNIX\nif defined on the platform; otherwise, the default is AF_INET.\n\"\"\"\n\n_blocking_errnos={EAGAIN,EWOULDBLOCK}\n\nclass SocketIO(io.RawIOBase):\n\n ''\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n def __init__(self,sock,mode):\n if mode not in(\"r\",\"w\",\"rw\",\"rb\",\"wb\",\"rwb\"):\n raise ValueError(\"invalid mode: %r\"%mode)\n io.RawIOBase.__init__(self)\n self._sock=sock\n if \"b\"not in mode:\n mode +=\"b\"\n self._mode=mode\n self._reading=\"r\"in mode\n self._writing=\"w\"in mode\n self._timeout_occurred=False\n \n def readinto(self,b):\n ''\n\n\n\n\n\n \n self._checkClosed()\n self._checkReadable()\n if self._timeout_occurred:\n raise OSError(\"cannot read from timed out object\")\n while True:\n try:\n return self._sock.recv_into(b)\n except timeout:\n self._timeout_occurred=True\n raise\n except error as e:\n if e.errno in _blocking_errnos:\n return None\n raise\n \n def write(self,b):\n ''\n\n\n\n \n self._checkClosed()\n self._checkWritable()\n try:\n return self._sock.send(b)\n except error as e:\n \n if e.errno in _blocking_errnos:\n return None\n raise\n \n def readable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return self._reading\n \n def writable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return self._writing\n \n def seekable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return super().seekable()\n \n def fileno(self):\n ''\n \n self._checkClosed()\n return self._sock.fileno()\n \n @property\n def name(self):\n if not self.closed:\n return self.fileno()\n else:\n return -1\n \n @property\n def mode(self):\n return self._mode\n \n def close(self):\n ''\n\n \n if self.closed:\n return\n io.RawIOBase.close(self)\n self._sock._decref_socketios()\n self._sock=None\n \n \ndef getfqdn(name=''):\n ''\n\n\n\n\n\n\n\n \n name=name.strip()\n if not name or name =='0.0.0.0':\n name=gethostname()\n try:\n hostname,aliases,ipaddrs=gethostbyaddr(name)\n except error:\n pass\n else:\n aliases.insert(0,hostname)\n for name in aliases:\n if '.'in name:\n break\n else:\n name=hostname\n return name\n \n \n_GLOBAL_DEFAULT_TIMEOUT=object()\n\ndef create_connection(address,timeout=_GLOBAL_DEFAULT_TIMEOUT,\nsource_address=None,*,all_errors=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n host,port=address\n exceptions=[]\n for res in getaddrinfo(host,port,0,SOCK_STREAM):\n af,socktype,proto,canonname,sa=res\n sock=None\n try:\n sock=socket(af,socktype,proto)\n if timeout is not _GLOBAL_DEFAULT_TIMEOUT:\n sock.settimeout(timeout)\n if source_address:\n sock.bind(source_address)\n sock.connect(sa)\n \n exceptions.clear()\n return sock\n \n except error as exc:\n if not all_errors:\n exceptions.clear()\n exceptions.append(exc)\n if sock is not None:\n sock.close()\n \n if len(exceptions):\n try:\n if not all_errors:\n raise exceptions[0]\n raise ExceptionGroup(\"create_connection failed\",exceptions)\n finally:\n \n exceptions.clear()\n else:\n raise error(\"getaddrinfo returns an empty list\")\n \n \ndef has_dualstack_ipv6():\n ''\n\n \n if not has_ipv6\\\n or not hasattr(_socket,'IPPROTO_IPV6')\\\n or not hasattr(_socket,'IPV6_V6ONLY'):\n return False\n try:\n with socket(AF_INET6,SOCK_STREAM)as sock:\n sock.setsockopt(IPPROTO_IPV6,IPV6_V6ONLY,0)\n return True\n except error:\n return False\n \n \ndef create_server(address,*,family=AF_INET,backlog=None,reuse_port=False,\ndualstack_ipv6=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if reuse_port and not hasattr(_socket,\"SO_REUSEPORT\"):\n raise ValueError(\"SO_REUSEPORT not supported on this platform\")\n if dualstack_ipv6:\n if not has_dualstack_ipv6():\n raise ValueError(\"dualstack_ipv6 not supported on this platform\")\n if family !=AF_INET6:\n raise ValueError(\"dualstack_ipv6 requires AF_INET6 family\")\n sock=socket(family,SOCK_STREAM)\n try:\n \n \n \n \n \n \n \n \n \n if os.name not in('nt','cygwin')and\\\n hasattr(_socket,'SO_REUSEADDR'):\n try:\n sock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)\n except error:\n \n \n pass\n if reuse_port:\n sock.setsockopt(SOL_SOCKET,SO_REUSEPORT,1)\n if has_ipv6 and family ==AF_INET6:\n if dualstack_ipv6:\n sock.setsockopt(IPPROTO_IPV6,IPV6_V6ONLY,0)\n elif hasattr(_socket,\"IPV6_V6ONLY\")and\\\n hasattr(_socket,\"IPPROTO_IPV6\"):\n sock.setsockopt(IPPROTO_IPV6,IPV6_V6ONLY,1)\n try:\n sock.bind(address)\n except error as err:\n msg='%s (while attempting to bind on address %r)'%\\\n (err.strerror,address)\n raise error(err.errno,msg)from None\n if backlog is None:\n sock.listen()\n else:\n sock.listen(backlog)\n return sock\n except error:\n sock.close()\n raise\n \n \ndef getaddrinfo(host,port,family=0,type=0,proto=0,flags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n addrlist=[]\n for res in _socket.getaddrinfo(host,port,family,type,proto,flags):\n af,socktype,proto,canonname,sa=res\n addrlist.append((_intenum_converter(af,AddressFamily),\n _intenum_converter(socktype,SocketKind),\n proto,canonname,sa))\n return addrlist\n", ["_socket", "array", "enum", "errno", "io", "os", "selectors", "sys"]], "sre_compile": [".py", "import warnings\nwarnings.warn(f\"module {__name__ !r} is deprecated\",\nDeprecationWarning,\nstacklevel=2)\n\nfrom re import _compiler as _\nglobals().update({k:v for k,v in vars(_).items()if k[:2]!='__'})\n", ["re", "warnings"]], "sre_constants": [".py", "import warnings\nwarnings.warn(f\"module {__name__ !r} is deprecated\",\nDeprecationWarning,\nstacklevel=2)\n\nfrom re import _constants as _\nglobals().update({k:v for k,v in vars(_).items()if k[:2]!='__'})\n", ["re", "warnings"]], "sre_parse": [".py", "import warnings\nwarnings.warn(f\"module {__name__ !r} is deprecated\",\nDeprecationWarning,\nstacklevel=2)\n\nfrom re import _parser as _\nglobals().update({k:v for k,v in vars(_).items()if k[:2]!='__'})\n", ["re", "warnings"]], "stat": [".py", "''\n\n\n\nimport sys\n\n\n\nST_MODE=0\nST_INO=1\nST_DEV=2\nST_NLINK=3\nST_UID=4\nST_GID=5\nST_SIZE=6\nST_ATIME=7\nST_MTIME=8\nST_CTIME=9\n\n\n\ndef S_IMODE(mode):\n ''\n\n \n return mode&0o7777\n \ndef S_IFMT(mode):\n ''\n\n \n return mode&0o170000\n \n \n \n \nS_IFDIR=0o040000\nS_IFCHR=0o020000\nS_IFBLK=0o060000\nS_IFREG=0o100000\nS_IFIFO=0o010000\nS_IFLNK=0o120000\nS_IFSOCK=0o140000\n\nS_IFDOOR=0\nS_IFPORT=0\nS_IFWHT=0\n\n\n\ndef S_ISDIR(mode):\n ''\n return S_IFMT(mode)==S_IFDIR\n \ndef S_ISCHR(mode):\n ''\n return S_IFMT(mode)==S_IFCHR\n \ndef S_ISBLK(mode):\n ''\n return S_IFMT(mode)==S_IFBLK\n \ndef S_ISREG(mode):\n ''\n return S_IFMT(mode)==S_IFREG\n \ndef S_ISFIFO(mode):\n ''\n return S_IFMT(mode)==S_IFIFO\n \ndef S_ISLNK(mode):\n ''\n return S_IFMT(mode)==S_IFLNK\n \ndef S_ISSOCK(mode):\n ''\n return S_IFMT(mode)==S_IFSOCK\n \ndef S_ISDOOR(mode):\n ''\n return False\n \ndef S_ISPORT(mode):\n ''\n return False\n \ndef S_ISWHT(mode):\n ''\n return False\n \n \n \nS_ISUID=0o4000\nS_ISGID=0o2000\nS_ENFMT=S_ISGID\nS_ISVTX=0o1000\nS_IREAD=0o0400\nS_IWRITE=0o0200\nS_IEXEC=0o0100\nS_IRWXU=0o0700\nS_IRUSR=0o0400\nS_IWUSR=0o0200\nS_IXUSR=0o0100\nS_IRWXG=0o0070\nS_IRGRP=0o0040\nS_IWGRP=0o0020\nS_IXGRP=0o0010\nS_IRWXO=0o0007\nS_IROTH=0o0004\nS_IWOTH=0o0002\nS_IXOTH=0o0001\n\n\nUF_SETTABLE=0x0000ffff\nUF_NODUMP=0x00000001\nUF_IMMUTABLE=0x00000002\nUF_APPEND=0x00000004\nUF_OPAQUE=0x00000008\nUF_NOUNLINK=0x00000010\nUF_COMPRESSED=0x00000020\nUF_TRACKED=0x00000040\nUF_DATAVAULT=0x00000080\nUF_HIDDEN=0x00008000\nSF_SETTABLE=0xffff0000\nSF_ARCHIVED=0x00010000\nSF_IMMUTABLE=0x00020000\nSF_APPEND=0x00040000\nSF_RESTRICTED=0x00080000\nSF_NOUNLINK=0x00100000\nSF_SNAPSHOT=0x00200000\nSF_FIRMLINK=0x00800000\nSF_DATALESS=0x40000000\n\n\n_filemode_table=(\n\n\n((S_IFLNK,\"l\"),\n(S_IFSOCK,\"s\"),\n(S_IFREG,\"-\"),\n(S_IFBLK,\"b\"),\n(S_IFDIR,\"d\"),\n(S_IFCHR,\"c\"),\n(S_IFIFO,\"p\")),\n\n((S_IRUSR,\"r\"),),\n((S_IWUSR,\"w\"),),\n((S_IXUSR |S_ISUID,\"s\"),\n(S_ISUID,\"S\"),\n(S_IXUSR,\"x\")),\n\n((S_IRGRP,\"r\"),),\n((S_IWGRP,\"w\"),),\n((S_IXGRP |S_ISGID,\"s\"),\n(S_ISGID,\"S\"),\n(S_IXGRP,\"x\")),\n\n((S_IROTH,\"r\"),),\n((S_IWOTH,\"w\"),),\n((S_IXOTH |S_ISVTX,\"t\"),\n(S_ISVTX,\"T\"),\n(S_IXOTH,\"x\"))\n)\n\ndef filemode(mode):\n ''\n perm=[]\n for index,table in enumerate(_filemode_table):\n for bit,char in table:\n if mode&bit ==bit:\n perm.append(char)\n break\n else:\n if index ==0:\n \n perm.append(\"?\")\n else:\n perm.append(\"-\")\n return \"\".join(perm)\n \n \n \n \n \nFILE_ATTRIBUTE_ARCHIVE=32\nFILE_ATTRIBUTE_COMPRESSED=2048\nFILE_ATTRIBUTE_DEVICE=64\nFILE_ATTRIBUTE_DIRECTORY=16\nFILE_ATTRIBUTE_ENCRYPTED=16384\nFILE_ATTRIBUTE_HIDDEN=2\nFILE_ATTRIBUTE_INTEGRITY_STREAM=32768\nFILE_ATTRIBUTE_NORMAL=128\nFILE_ATTRIBUTE_NOT_CONTENT_INDEXED=8192\nFILE_ATTRIBUTE_NO_SCRUB_DATA=131072\nFILE_ATTRIBUTE_OFFLINE=4096\nFILE_ATTRIBUTE_READONLY=1\nFILE_ATTRIBUTE_REPARSE_POINT=1024\nFILE_ATTRIBUTE_SPARSE_FILE=512\nFILE_ATTRIBUTE_SYSTEM=4\nFILE_ATTRIBUTE_TEMPORARY=256\nFILE_ATTRIBUTE_VIRTUAL=65536\n\n\n\ntry:\n from _stat import *\nexcept ImportError:\n pass\n", ["_stat", "sys"]], "statistics": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\n'NormalDist',\n'StatisticsError',\n'correlation',\n'covariance',\n'fmean',\n'geometric_mean',\n'harmonic_mean',\n'kde',\n'kde_random',\n'linear_regression',\n'mean',\n'median',\n'median_grouped',\n'median_high',\n'median_low',\n'mode',\n'multimode',\n'pstdev',\n'pvariance',\n'quantiles',\n'stdev',\n'variance',\n]\n\nimport math\nimport numbers\nimport random\nimport sys\n\nfrom fractions import Fraction\nfrom decimal import Decimal\nfrom itertools import count,groupby,repeat\nfrom bisect import bisect_left,bisect_right\nfrom math import hypot,sqrt,fabs,exp,erf,tau,log,fsum,sumprod\nfrom math import isfinite,isinf,pi,cos,sin,tan,cosh,asin,atan,acos\nfrom functools import reduce\nfrom operator import itemgetter\nfrom collections import Counter,namedtuple,defaultdict\n\n_SQRT2=sqrt(2.0)\n_random=random\n\n\n\nclass StatisticsError(ValueError):\n pass\n \n \n \n \ndef _sum(data):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n count=0\n types=set()\n types_add=types.add\n partials={}\n partials_get=partials.get\n for typ,values in groupby(data,type):\n types_add(typ)\n for n,d in map(_exact_ratio,values):\n count +=1\n partials[d]=partials_get(d,0)+n\n if None in partials:\n \n \n total=partials[None]\n assert not _isfinite(total)\n else:\n \n total=sum(Fraction(n,d)for d,n in partials.items())\n T=reduce(_coerce,types,int)\n return(T,total,count)\n \n \ndef _ss(data,c=None):\n ''\n\n\n\n\n\n\n \n if c is not None:\n T,ssd,count=_sum((d :=x -c)*d for x in data)\n return(T,ssd,c,count)\n count=0\n types=set()\n types_add=types.add\n sx_partials=defaultdict(int)\n sxx_partials=defaultdict(int)\n for typ,values in groupby(data,type):\n types_add(typ)\n for n,d in map(_exact_ratio,values):\n count +=1\n sx_partials[d]+=n\n sxx_partials[d]+=n *n\n if not count:\n ssd=c=Fraction(0)\n elif None in sx_partials:\n \n \n ssd=c=sx_partials[None]\n assert not _isfinite(ssd)\n else:\n sx=sum(Fraction(n,d)for d,n in sx_partials.items())\n sxx=sum(Fraction(n,d *d)for d,n in sxx_partials.items())\n \n \n ssd=(count *sxx -sx *sx)/count\n c=sx /count\n T=reduce(_coerce,types,int)\n return(T,ssd,c,count)\n \n \ndef _isfinite(x):\n try:\n return x.is_finite()\n except AttributeError:\n return math.isfinite(x)\n \n \ndef _coerce(T,S):\n ''\n\n\n\n \n \n assert T is not bool,\"initial type T is bool\"\n \n \n \n if T is S:return T\n \n if S is int or S is bool:return T\n if T is int:return S\n \n if issubclass(S,T):return S\n if issubclass(T,S):return T\n \n if issubclass(T,int):return S\n if issubclass(S,int):return T\n \n if issubclass(T,Fraction)and issubclass(S,float):\n return S\n if issubclass(T,float)and issubclass(S,Fraction):\n return T\n \n msg=\"don't know how to coerce %s and %s\"\n raise TypeError(msg %(T.__name__,S.__name__))\n \n \ndef _exact_ratio(x):\n ''\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n try:\n return x.as_integer_ratio()\n except AttributeError:\n pass\n except(OverflowError,ValueError):\n \n assert not _isfinite(x)\n return(x,None)\n try:\n \n return(x.numerator,x.denominator)\n except AttributeError:\n msg=f\"can't convert type '{type(x).__name__}' to numerator/denominator\"\n raise TypeError(msg)\n \n \ndef _convert(value,T):\n ''\n if type(value)is T:\n \n \n return value\n if issubclass(T,int)and value.denominator !=1:\n T=float\n try:\n \n return T(value)\n except TypeError:\n if issubclass(T,Decimal):\n return T(value.numerator)/T(value.denominator)\n else:\n raise\n \n \ndef _fail_neg(values,errmsg='negative value'):\n ''\n for x in values:\n if x <0:\n raise StatisticsError(errmsg)\n yield x\n \n \ndef _rank(data,/,*,key=None,reverse=False,ties='average',start=1)->list[float]:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n if ties !='average':\n raise ValueError(f'Unknown tie resolution method: {ties !r}')\n if key is not None:\n data=map(key,data)\n val_pos=sorted(zip(data,count()),reverse=reverse)\n i=start -1\n result=[0]*len(val_pos)\n for _,g in groupby(val_pos,key=itemgetter(0)):\n group=list(g)\n size=len(group)\n rank=i+(size+1)/2\n for value,orig_pos in group:\n result[orig_pos]=rank\n i +=size\n return result\n \n \ndef _integer_sqrt_of_frac_rto(n:int,m:int)->int:\n ''\n \n a=math.isqrt(n //m)\n return a |(a *a *m !=n)\n \n \n \n \n_sqrt_bit_width:int=2 *sys.float_info.mant_dig+3\n\n\ndef _float_sqrt_of_frac(n:int,m:int)->float:\n ''\n \n q=(n.bit_length()-m.bit_length()-_sqrt_bit_width)//2\n if q >=0:\n numerator=_integer_sqrt_of_frac_rto(n,m <<2 *q)<Decimal:\n ''\n \n \n \n if n <=0:\n if not n:\n return Decimal('0.0')\n n,m=-n,-m\n \n root=(Decimal(n)/Decimal(m)).sqrt()\n nr,dr=root.as_integer_ratio()\n \n plus=root.next_plus()\n np,dp=plus.as_integer_ratio()\n \n if 4 *n *(dr *dp)**2 >m *(dr *np+dp *nr)**2:\n return plus\n \n minus=root.next_minus()\n nm,dm=minus.as_integer_ratio()\n \n if 4 *n *(dr *dm)**2 0.0 or math.isnan(x):\n yield x\n elif x ==0.0:\n found_zero=True\n else:\n raise StatisticsError('No negative inputs allowed',x)\n total=fsum(map(log,count_positive(data)))\n if not n:\n raise StatisticsError('Must have a non-empty dataset')\n if math.isnan(total):\n return math.nan\n if found_zero:\n return math.nan if total ==math.inf else 0.0\n return exp(total /n)\n \n \ndef harmonic_mean(data,weights=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if iter(data)is data:\n data=list(data)\n errmsg='harmonic mean does not support negative values'\n n=len(data)\n if n <1:\n raise StatisticsError('harmonic_mean requires at least one data point')\n elif n ==1 and weights is None:\n x=data[0]\n if isinstance(x,(numbers.Real,Decimal)):\n if x <0:\n raise StatisticsError(errmsg)\n return x\n else:\n raise TypeError('unsupported type')\n if weights is None:\n weights=repeat(1,n)\n sum_weights=n\n else:\n if iter(weights)is weights:\n weights=list(weights)\n if len(weights)!=n:\n raise StatisticsError('Number of weights does not match data size')\n _,sum_weights,_=_sum(w for w in _fail_neg(weights,errmsg))\n try:\n data=_fail_neg(data,errmsg)\n T,total,count=_sum(w /x if w else 0 for w,x in zip(weights,data))\n except ZeroDivisionError:\n return 0\n if total <=0:\n raise StatisticsError('Weighted sum must be positive')\n return _convert(sum_weights /total,T)\n \n \ndef median(data):\n ''\n\n\n\n\n\n\n\n\n\n\n \n data=sorted(data)\n n=len(data)\n if n ==0:\n raise StatisticsError(\"no median for empty data\")\n if n %2 ==1:\n return data[n //2]\n else:\n i=n //2\n return(data[i -1]+data[i])/2\n \n \ndef median_low(data):\n ''\n\n\n\n\n\n\n\n\n\n \n data=sorted(data)\n n=len(data)\n if n ==0:\n raise StatisticsError(\"no median for empty data\")\n if n %2 ==1:\n return data[n //2]\n else:\n return data[n //2 -1]\n \n \ndef median_high(data):\n ''\n\n\n\n\n\n\n\n\n\n \n data=sorted(data)\n n=len(data)\n if n ==0:\n raise StatisticsError(\"no median for empty data\")\n return data[n //2]\n \n \ndef median_grouped(data,interval=1.0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n data=sorted(data)\n n=len(data)\n if not n:\n raise StatisticsError(\"no median for empty data\")\n \n \n \n x=data[n //2]\n \n \n \n i=bisect_left(data,x)\n j=bisect_right(data,x,lo=i)\n \n \n try:\n interval=float(interval)\n x=float(x)\n except ValueError:\n raise TypeError(f'Value cannot be converted to a float')\n \n \n \n L=x -interval /2.0\n cf=i\n f=j -i\n return L+interval *(n /2 -cf)/f\n \n \ndef mode(data):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n pairs=Counter(iter(data)).most_common(1)\n try:\n return pairs[0][0]\n except IndexError:\n raise StatisticsError('no mode for empty data')from None\n \n \ndef multimode(data):\n ''\n\n\n\n\n\n\n\n\n\n\n \n counts=Counter(iter(data))\n if not counts:\n return[]\n maxcount=max(counts.values())\n return[value for value,count in counts.items()if count ==maxcount]\n \n \ndef kde(data,h,kernel='normal',*,cumulative=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n n=len(data)\n if not n:\n raise StatisticsError('Empty data sequence')\n \n if not isinstance(data[0],(int,float)):\n raise TypeError('Data sequence must contain ints or floats')\n \n if h <=0.0:\n raise StatisticsError(f'Bandwidth h must be positive, not {h=!r}')\n \n match kernel:\n \n case 'normal'|'gauss':\n sqrt2pi=sqrt(2 *pi)\n sqrt2=sqrt(2)\n K=lambda t:exp(-1 /2 *t *t)/sqrt2pi\n W=lambda t:1 /2 *(1.0+erf(t /sqrt2))\n support=None\n \n case 'logistic':\n \n K=lambda t:1 /2 /(1.0+cosh(t))\n W=lambda t:1.0 -1.0 /(exp(t)+1.0)\n support=None\n \n case 'sigmoid':\n \n c1=1 /pi\n c2=2 /pi\n K=lambda t:c1 /cosh(t)\n W=lambda t:c2 *atan(exp(t))\n support=None\n \n case 'rectangular'|'uniform':\n K=lambda t:1 /2\n W=lambda t:1 /2 *t+1 /2\n support=1.0\n \n case 'triangular':\n K=lambda t:1.0 -abs(t)\n W=lambda t:t *t *(1 /2 if t <0.0 else -1 /2)+t+1 /2\n support=1.0\n \n case 'parabolic'|'epanechnikov':\n K=lambda t:3 /4 *(1.0 -t *t)\n W=lambda t:-1 /4 *t **3+3 /4 *t+1 /2\n support=1.0\n \n case 'quartic'|'biweight':\n K=lambda t:15 /16 *(1.0 -t *t)**2\n W=lambda t:3 /16 *t **5 -5 /8 *t **3+15 /16 *t+1 /2\n support=1.0\n \n case 'triweight':\n K=lambda t:35 /32 *(1.0 -t *t)**3\n W=lambda t:35 /32 *(-1 /7 *t **7+3 /5 *t **5 -t **3+t)+1 /2\n support=1.0\n \n case 'cosine':\n c1=pi /4\n c2=pi /2\n K=lambda t:c1 *cos(c2 *t)\n W=lambda t:1 /2 *sin(c2 *t)+1 /2\n support=1.0\n \n case _:\n raise StatisticsError(f'Unknown kernel name: {kernel !r}')\n \n if support is None:\n \n def pdf(x):\n n=len(data)\n return sum(K((x -x_i)/h)for x_i in data)/(n *h)\n \n def cdf(x):\n n=len(data)\n return sum(W((x -x_i)/h)for x_i in data)/n\n \n else:\n \n sample=sorted(data)\n bandwidth=h *support\n \n def pdf(x):\n nonlocal n,sample\n if len(data)!=n:\n sample=sorted(data)\n n=len(data)\n i=bisect_left(sample,x -bandwidth)\n j=bisect_right(sample,x+bandwidth)\n supported=sample[i:j]\n return sum(K((x -x_i)/h)for x_i in supported)/(n *h)\n \n def cdf(x):\n nonlocal n,sample\n if len(data)!=n:\n sample=sorted(data)\n n=len(data)\n i=bisect_left(sample,x -bandwidth)\n j=bisect_right(sample,x+bandwidth)\n supported=sample[i:j]\n return sum((W((x -x_i)/h)for x_i in supported),i)/n\n \n if cumulative:\n cdf.__doc__=f'CDF estimate with {h=!r} and {kernel=!r}'\n return cdf\n \n else:\n pdf.__doc__=f'PDF estimate with {h=!r} and {kernel=!r}'\n return pdf\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef quantiles(data,*,n=4,method='exclusive'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if n <1:\n raise StatisticsError('n must be at least 1')\n data=sorted(data)\n ld=len(data)\n if ld <2:\n if ld ==1:\n return data *(n -1)\n raise StatisticsError('must have at least one data point')\n \n if method =='inclusive':\n m=ld -1\n result=[]\n for i in range(1,n):\n j,delta=divmod(i *m,n)\n interpolated=(data[j]*(n -delta)+data[j+1]*delta)/n\n result.append(interpolated)\n return result\n \n if method =='exclusive':\n m=ld+1\n result=[]\n for i in range(1,n):\n j=i *m //n\n j=1 if j <1 else ld -1 if j >ld -1 else j\n delta=i *m -j *n\n interpolated=(data[j -1]*(n -delta)+data[j]*delta)/n\n result.append(interpolated)\n return result\n \n raise ValueError(f'Unknown method: {method !r}')\n \n \n \n \n \n \n \n \ndef variance(data,xbar=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n T,ss,c,n=_ss(data,xbar)\n if n <2:\n raise StatisticsError('variance requires at least two data points')\n return _convert(ss /(n -1),T)\n \n \ndef pvariance(data,mu=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n T,ss,c,n=_ss(data,mu)\n if n <1:\n raise StatisticsError('pvariance requires at least one data point')\n return _convert(ss /n,T)\n \n \ndef stdev(data,xbar=None):\n ''\n\n\n\n\n\n\n \n T,ss,c,n=_ss(data,xbar)\n if n <2:\n raise StatisticsError('stdev requires at least two data points')\n mss=ss /(n -1)\n if issubclass(T,Decimal):\n return _decimal_sqrt_of_frac(mss.numerator,mss.denominator)\n return _float_sqrt_of_frac(mss.numerator,mss.denominator)\n \n \ndef pstdev(data,mu=None):\n ''\n\n\n\n\n\n\n \n T,ss,c,n=_ss(data,mu)\n if n <1:\n raise StatisticsError('pstdev requires at least one data point')\n mss=ss /n\n if issubclass(T,Decimal):\n return _decimal_sqrt_of_frac(mss.numerator,mss.denominator)\n return _float_sqrt_of_frac(mss.numerator,mss.denominator)\n \n \ndef _mean_stdev(data):\n ''\n T,ss,xbar,n=_ss(data)\n if n <2:\n raise StatisticsError('stdev requires at least two data points')\n mss=ss /(n -1)\n try:\n return float(xbar),_float_sqrt_of_frac(mss.numerator,mss.denominator)\n except AttributeError:\n \n return float(xbar),float(xbar)/float(ss)\n \ndef _sqrtprod(x:float,y:float)->float:\n ''\n h=sqrt(x *y)\n if not isfinite(h):\n if isinf(h)and not isinf(x)and not isinf(y):\n \n scale=2.0 **-512\n return _sqrtprod(scale *x,scale *y)/scale\n return h\n if not h:\n if x and y:\n \n \n scale=2.0 **537\n return _sqrtprod(scale *x,scale *y)/scale\n return h\n \n \n d=sumprod((x,h),(y,-h))\n return h+d /(2.0 *h)\n \n \n \n \n \n \n \n \n \ndef covariance(x,y,/):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n n=len(x)\n if len(y)!=n:\n raise StatisticsError('covariance requires that both inputs have same number of data points')\n if n <2:\n raise StatisticsError('covariance requires at least two data points')\n xbar=fsum(x)/n\n ybar=fsum(y)/n\n sxy=sumprod((xi -xbar for xi in x),(yi -ybar for yi in y))\n return sxy /(n -1)\n \n \ndef correlation(x,y,/,*,method='linear'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n n=len(x)\n if len(y)!=n:\n raise StatisticsError('correlation requires that both inputs have same number of data points')\n if n <2:\n raise StatisticsError('correlation requires at least two data points')\n if method not in{'linear','ranked'}:\n raise ValueError(f'Unknown method: {method !r}')\n if method =='ranked':\n start=(n -1)/-2\n x=_rank(x,start=start)\n y=_rank(y,start=start)\n else:\n xbar=fsum(x)/n\n ybar=fsum(y)/n\n x=[xi -xbar for xi in x]\n y=[yi -ybar for yi in y]\n sxy=sumprod(x,y)\n sxx=sumprod(x,x)\n syy=sumprod(y,y)\n try:\n return sxy /_sqrtprod(sxx,syy)\n except ZeroDivisionError:\n raise StatisticsError('at least one of the inputs is constant')\n \n \nLinearRegression=namedtuple('LinearRegression',('slope','intercept'))\n\n\ndef linear_regression(x,y,/,*,proportional=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n n=len(x)\n if len(y)!=n:\n raise StatisticsError('linear regression requires that both inputs have same number of data points')\n if n <2:\n raise StatisticsError('linear regression requires at least two data points')\n if not proportional:\n xbar=fsum(x)/n\n ybar=fsum(y)/n\n x=[xi -xbar for xi in x]\n y=(yi -ybar for yi in y)\n sxy=sumprod(x,y)+0.0\n sxx=sumprod(x,x)\n try:\n slope=sxy /sxx\n except ZeroDivisionError:\n raise StatisticsError('x is constant')\n intercept=0.0 if proportional else ybar -slope *xbar\n return LinearRegression(slope=slope,intercept=intercept)\n \n \n \n \n \ndef _normal_dist_inv_cdf(p,mu,sigma):\n\n\n\n\n\n q=p -0.5\n if fabs(q)<=0.425:\n r=0.180625 -q *q\n \n num=(((((((2.50908_09287_30122_6727e+3 *r+\n 3.34305_75583_58812_8105e+4)*r+\n 6.72657_70927_00870_0853e+4)*r+\n 4.59219_53931_54987_1457e+4)*r+\n 1.37316_93765_50946_1125e+4)*r+\n 1.97159_09503_06551_4427e+3)*r+\n 1.33141_66789_17843_7745e+2)*r+\n 3.38713_28727_96366_6080e+0)*q\n den=(((((((5.22649_52788_52854_5610e+3 *r+\n 2.87290_85735_72194_2674e+4)*r+\n 3.93078_95800_09271_0610e+4)*r+\n 2.12137_94301_58659_5867e+4)*r+\n 5.39419_60214_24751_1077e+3)*r+\n 6.87187_00749_20579_0830e+2)*r+\n 4.23133_30701_60091_1252e+1)*r+\n 1.0)\n x=num /den\n return mu+(x *sigma)\n r=p if q <=0.0 else 1.0 -p\n r=sqrt(-log(r))\n if r <=5.0:\n r=r -1.6\n \n num=(((((((7.74545_01427_83414_07640e-4 *r+\n 2.27238_44989_26918_45833e-2)*r+\n 2.41780_72517_74506_11770e-1)*r+\n 1.27045_82524_52368_38258e+0)*r+\n 3.64784_83247_63204_60504e+0)*r+\n 5.76949_72214_60691_40550e+0)*r+\n 4.63033_78461_56545_29590e+0)*r+\n 1.42343_71107_49683_57734e+0)\n den=(((((((1.05075_00716_44416_84324e-9 *r+\n 5.47593_80849_95344_94600e-4)*r+\n 1.51986_66563_61645_71966e-2)*r+\n 1.48103_97642_74800_74590e-1)*r+\n 6.89767_33498_51000_04550e-1)*r+\n 1.67638_48301_83803_84940e+0)*r+\n 2.05319_16266_37758_82187e+0)*r+\n 1.0)\n else:\n r=r -5.0\n \n num=(((((((2.01033_43992_92288_13265e-7 *r+\n 2.71155_55687_43487_57815e-5)*r+\n 1.24266_09473_88078_43860e-3)*r+\n 2.65321_89526_57612_30930e-2)*r+\n 2.96560_57182_85048_91230e-1)*r+\n 1.78482_65399_17291_33580e+0)*r+\n 5.46378_49111_64114_36990e+0)*r+\n 6.65790_46435_01103_77720e+0)\n den=(((((((2.04426_31033_89939_78564e-15 *r+\n 1.42151_17583_16445_88870e-7)*r+\n 1.84631_83175_10054_68180e-5)*r+\n 7.86869_13114_56132_59100e-4)*r+\n 1.48753_61290_85061_48525e-2)*r+\n 1.36929_88092_27358_05310e-1)*r+\n 5.99832_20655_58879_37690e-1)*r+\n 1.0)\n x=num /den\n if q <0.0:\n x=-x\n return mu+(x *sigma)\n \n \n \ntry:\n from _statistics import _normal_dist_inv_cdf\nexcept ImportError:\n pass\n \n \nclass NormalDist:\n ''\n \n \n \n __slots__={\n '_mu':'Arithmetic mean of a normal distribution',\n '_sigma':'Standard deviation of a normal distribution',\n }\n \n def __init__(self,mu=0.0,sigma=1.0):\n ''\n if sigma <0.0:\n raise StatisticsError('sigma must be non-negative')\n self._mu=float(mu)\n self._sigma=float(sigma)\n \n @classmethod\n def from_samples(cls,data):\n ''\n return cls(*_mean_stdev(data))\n \n def samples(self,n,*,seed=None):\n ''\n rnd=random.random if seed is None else random.Random(seed).random\n inv_cdf=_normal_dist_inv_cdf\n mu=self._mu\n sigma=self._sigma\n return[inv_cdf(rnd(),mu,sigma)for _ in repeat(None,n)]\n \n def pdf(self,x):\n ''\n variance=self._sigma *self._sigma\n if not variance:\n raise StatisticsError('pdf() not defined when sigma is zero')\n diff=x -self._mu\n return exp(diff *diff /(-2.0 *variance))/sqrt(tau *variance)\n \n def cdf(self,x):\n ''\n if not self._sigma:\n raise StatisticsError('cdf() not defined when sigma is zero')\n return 0.5 *(1.0+erf((x -self._mu)/(self._sigma *_SQRT2)))\n \n def inv_cdf(self,p):\n ''\n\n\n\n\n\n\n\n \n if p <=0.0 or p >=1.0:\n raise StatisticsError('p must be in the range 0.0 < p < 1.0')\n return _normal_dist_inv_cdf(p,self._mu,self._sigma)\n \n def quantiles(self,n=4):\n ''\n\n\n\n\n\n\n \n return[self.inv_cdf(i /n)for i in range(1,n)]\n \n def overlap(self,other):\n ''\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n if not isinstance(other,NormalDist):\n raise TypeError('Expected another NormalDist instance')\n X,Y=self,other\n if(Y._sigma,Y._mu)<(X._sigma,X._mu):\n X,Y=Y,X\n X_var,Y_var=X.variance,Y.variance\n if not X_var or not Y_var:\n raise StatisticsError('overlap() not defined when sigma is zero')\n dv=Y_var -X_var\n dm=fabs(Y._mu -X._mu)\n if not dv:\n return 1.0 -erf(dm /(2.0 *X._sigma *_SQRT2))\n a=X._mu *Y_var -Y._mu *X_var\n b=X._sigma *Y._sigma *sqrt(dm *dm+dv *log(Y_var /X_var))\n x1=(a+b)/dv\n x2=(a -b)/dv\n return 1.0 -(fabs(Y.cdf(x1)-X.cdf(x1))+fabs(Y.cdf(x2)-X.cdf(x2)))\n \n def zscore(self,x):\n ''\n\n\n\n \n \n if not self._sigma:\n raise StatisticsError('zscore() not defined when sigma is zero')\n return(x -self._mu)/self._sigma\n \n @property\n def mean(self):\n ''\n return self._mu\n \n @property\n def median(self):\n ''\n return self._mu\n \n @property\n def mode(self):\n ''\n\n\n\n \n return self._mu\n \n @property\n def stdev(self):\n ''\n return self._sigma\n \n @property\n def variance(self):\n ''\n return self._sigma *self._sigma\n \n def __add__(x1,x2):\n ''\n\n\n\n\n\n\n\n \n if isinstance(x2,NormalDist):\n return NormalDist(x1._mu+x2._mu,hypot(x1._sigma,x2._sigma))\n return NormalDist(x1._mu+x2,x1._sigma)\n \n def __sub__(x1,x2):\n ''\n\n\n\n\n\n\n\n \n if isinstance(x2,NormalDist):\n return NormalDist(x1._mu -x2._mu,hypot(x1._sigma,x2._sigma))\n return NormalDist(x1._mu -x2,x1._sigma)\n \n def __mul__(x1,x2):\n ''\n\n\n\n \n return NormalDist(x1._mu *x2,x1._sigma *fabs(x2))\n \n def __truediv__(x1,x2):\n ''\n\n\n\n \n return NormalDist(x1._mu /x2,x1._sigma /fabs(x2))\n \n def __pos__(x1):\n ''\n return NormalDist(x1._mu,x1._sigma)\n \n def __neg__(x1):\n ''\n return NormalDist(-x1._mu,x1._sigma)\n \n __radd__=__add__\n \n def __rsub__(x1,x2):\n ''\n return -(x1 -x2)\n \n __rmul__=__mul__\n \n def __eq__(x1,x2):\n ''\n if not isinstance(x2,NormalDist):\n return NotImplemented\n return x1._mu ==x2._mu and x1._sigma ==x2._sigma\n \n def __hash__(self):\n ''\n return hash((self._mu,self._sigma))\n \n def __repr__(self):\n return f'{type(self).__name__}(mu={self._mu !r}, sigma={self._sigma !r})'\n \n def __getstate__(self):\n return self._mu,self._sigma\n \n def __setstate__(self,state):\n self._mu,self._sigma=state\n \n \n \n \ndef _newton_raphson(f_inv_estimate,f,f_prime,tolerance=1e-12):\n def f_inv(y):\n ''\n x=f_inv_estimate(y)\n while abs(diff :=f(x)-y)>tolerance:\n x -=diff /f_prime(x)\n return x\n return f_inv\n \ndef _quartic_invcdf_estimate(p):\n sign,p=(1.0,p)if p <=1 /2 else(-1.0,1.0 -p)\n x=(2.0 *p)**0.4258865685331 -1.0\n if p >=0.004 <0.499:\n x +=0.026818732 *sin(7.101753784 *p+2.73230839482953)\n return x *sign\n \n_quartic_invcdf=_newton_raphson(\nf_inv_estimate=_quartic_invcdf_estimate,\nf=lambda t:3 /16 *t **5 -5 /8 *t **3+15 /16 *t+1 /2,\nf_prime=lambda t:15 /16 *(1.0 -t *t)**2)\n\ndef _triweight_invcdf_estimate(p):\n sign,p=(1.0,p)if p <=1 /2 else(-1.0,1.0 -p)\n x=(2.0 *p)**0.3400218741872791 -1.0\n return x *sign\n \n_triweight_invcdf=_newton_raphson(\nf_inv_estimate=_triweight_invcdf_estimate,\nf=lambda t:35 /32 *(-1 /7 *t **7+3 /5 *t **5 -t **3+t)+1 /2,\nf_prime=lambda t:35 /32 *(1.0 -t *t)**3)\n\n_kernel_invcdfs={\n'normal':NormalDist().inv_cdf,\n'logistic':lambda p:log(p /(1 -p)),\n'sigmoid':lambda p:log(tan(p *pi /2)),\n'rectangular':lambda p:2 *p -1,\n'parabolic':lambda p:2 *cos((acos(2 *p -1)+pi)/3),\n'quartic':_quartic_invcdf,\n'triweight':_triweight_invcdf,\n'triangular':lambda p:sqrt(2 *p)-1 if p <1 /2 else 1 -sqrt(2 -2 *p),\n'cosine':lambda p:2 *asin(2 *p -1)/pi,\n}\n_kernel_invcdfs['gauss']=_kernel_invcdfs['normal']\n_kernel_invcdfs['uniform']=_kernel_invcdfs['rectangular']\n_kernel_invcdfs['epanechnikov']=_kernel_invcdfs['parabolic']\n_kernel_invcdfs['biweight']=_kernel_invcdfs['quartic']\n\ndef kde_random(data,h,kernel='normal',*,seed=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n n=len(data)\n if not n:\n raise StatisticsError('Empty data sequence')\n \n if not isinstance(data[0],(int,float)):\n raise TypeError('Data sequence must contain ints or floats')\n \n if h <=0.0:\n raise StatisticsError(f'Bandwidth h must be positive, not {h=!r}')\n \n kernel_invcdf=_kernel_invcdfs.get(kernel)\n if kernel_invcdf is None:\n raise StatisticsError(f'Unknown kernel name: {kernel !r}')\n \n prng=_random.Random(seed)\n random=prng.random\n choice=prng.choice\n \n def rand():\n return choice(data)+h *kernel_invcdf(random())\n \n rand.__doc__=f'Random KDE selection with {h=!r} and {kernel=!r}'\n \n return rand\n", ["_statistics", "bisect", "collections", "decimal", "fractions", "functools", "itertools", "math", "numbers", "operator", "random", "sys"]], "string": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\"ascii_letters\",\"ascii_lowercase\",\"ascii_uppercase\",\"capwords\",\n\"digits\",\"hexdigits\",\"octdigits\",\"printable\",\"punctuation\",\n\"whitespace\",\"Formatter\",\"Template\"]\n\nimport _string\n\n\nwhitespace=' \\t\\n\\r\\v\\f'\nascii_lowercase='abcdefghijklmnopqrstuvwxyz'\nascii_uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nascii_letters=ascii_lowercase+ascii_uppercase\ndigits='0123456789'\nhexdigits=digits+'abcdef'+'ABCDEF'\noctdigits='01234567'\npunctuation=r\"\"\"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\"\"\nprintable=digits+ascii_letters+punctuation+whitespace\n\n\n\n\ndef capwords(s,sep=None):\n ''\n\n\n\n\n\n\n\n\n \n return(sep or ' ').join(map(str.capitalize,s.split(sep)))\n \n \n \nimport re as _re\nfrom collections import ChainMap as _ChainMap\n\n_sentinel_dict={}\n\nclass Template:\n ''\n \n delimiter='$'\n \n \n \n \n idpattern=r'(?a:[_a-z][_a-z0-9]*)'\n braceidpattern=None\n flags=_re.IGNORECASE\n \n def __init_subclass__(cls):\n super().__init_subclass__()\n if 'pattern'in cls.__dict__:\n pattern=cls.pattern\n else:\n delim=_re.escape(cls.delimiter)\n id=cls.idpattern\n bid=cls.braceidpattern or cls.idpattern\n pattern=fr\"\"\"\n {delim}(?:\n (?P{delim}) | # Escape sequence of two delimiters\n (?P{id}) | # delimiter and a Python identifier\n {{(?P{bid})}} | # delimiter and a braced identifier\n (?P) # Other ill-formed delimiter exprs\n )\n \"\"\"\n cls.pattern=_re.compile(pattern,cls.flags |_re.VERBOSE)\n \n def __init__(self,template):\n self.template=template\n \n \n \n def _invalid(self,mo):\n i=mo.start('invalid')\n lines=self.template[:i].splitlines(keepends=True)\n if not lines:\n colno=1\n lineno=1\n else:\n colno=i -len(''.join(lines[:-1]))\n lineno=len(lines)\n raise ValueError('Invalid placeholder in string: line %d, col %d'%\n (lineno,colno))\n \n def substitute(self,mapping=_sentinel_dict,/,**kws):\n if mapping is _sentinel_dict:\n mapping=kws\n elif kws:\n mapping=_ChainMap(kws,mapping)\n \n def convert(mo):\n \n named=mo.group('named')or mo.group('braced')\n if named is not None:\n return str(mapping[named])\n if mo.group('escaped')is not None:\n return self.delimiter\n if mo.group('invalid')is not None:\n self._invalid(mo)\n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return self.pattern.sub(convert,self.template)\n \n def safe_substitute(self,mapping=_sentinel_dict,/,**kws):\n if mapping is _sentinel_dict:\n mapping=kws\n elif kws:\n mapping=_ChainMap(kws,mapping)\n \n def convert(mo):\n named=mo.group('named')or mo.group('braced')\n if named is not None:\n try:\n return str(mapping[named])\n except KeyError:\n return mo.group()\n if mo.group('escaped')is not None:\n return self.delimiter\n if mo.group('invalid')is not None:\n return mo.group()\n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return self.pattern.sub(convert,self.template)\n \n def is_valid(self):\n for mo in self.pattern.finditer(self.template):\n if mo.group('invalid')is not None:\n return False\n if(mo.group('named')is None\n and mo.group('braced')is None\n and mo.group('escaped')is None):\n \n \n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return True\n \n def get_identifiers(self):\n ids=[]\n for mo in self.pattern.finditer(self.template):\n named=mo.group('named')or mo.group('braced')\n if named is not None and named not in ids:\n \n ids.append(named)\n elif(named is None\n and mo.group('invalid')is None\n and mo.group('escaped')is None):\n \n \n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return ids\n \n \n \nTemplate.__init_subclass__()\n\n\n\n\n\n\n\n\n\n\n\n\nclass Formatter:\n def format(self,format_string,/,*args,**kwargs):\n return self.vformat(format_string,args,kwargs)\n \n def vformat(self,format_string,args,kwargs):\n used_args=set()\n result,_=self._vformat(format_string,args,kwargs,used_args,2)\n self.check_unused_args(used_args,args,kwargs)\n return result\n \n def _vformat(self,format_string,args,kwargs,used_args,recursion_depth,\n auto_arg_index=0):\n if recursion_depth <0:\n raise ValueError('Max string recursion exceeded')\n result=[]\n for literal_text,field_name,format_spec,conversion in\\\n self.parse(format_string):\n \n \n if literal_text:\n result.append(literal_text)\n \n \n if field_name is not None:\n \n \n \n \n if field_name =='':\n if auto_arg_index is False:\n raise ValueError('cannot switch from manual field '\n 'specification to automatic field '\n 'numbering')\n field_name=str(auto_arg_index)\n auto_arg_index +=1\n elif field_name.isdigit():\n if auto_arg_index:\n raise ValueError('cannot switch from manual field '\n 'specification to automatic field '\n 'numbering')\n \n \n auto_arg_index=False\n \n \n \n obj,arg_used=self.get_field(field_name,args,kwargs)\n used_args.add(arg_used)\n \n \n obj=self.convert_field(obj,conversion)\n \n \n format_spec,auto_arg_index=self._vformat(\n format_spec,args,kwargs,\n used_args,recursion_depth -1,\n auto_arg_index=auto_arg_index)\n \n \n result.append(self.format_field(obj,format_spec))\n \n return ''.join(result),auto_arg_index\n \n \n def get_value(self,key,args,kwargs):\n if isinstance(key,int):\n return args[key]\n else:\n return kwargs[key]\n \n \n def check_unused_args(self,used_args,args,kwargs):\n pass\n \n \n def format_field(self,value,format_spec):\n return format(value,format_spec)\n \n \n def convert_field(self,value,conversion):\n \n if conversion is None:\n return value\n elif conversion =='s':\n return str(value)\n elif conversion =='r':\n return repr(value)\n elif conversion =='a':\n return ascii(value)\n raise ValueError(\"Unknown conversion specifier {0!s}\".format(conversion))\n \n \n \n \n \n \n \n \n \n def parse(self,format_string):\n return _string.formatter_parser(format_string)\n \n \n \n \n \n \n \n def get_field(self,field_name,args,kwargs):\n first,rest=_string.formatter_field_name_split(field_name)\n \n obj=self.get_value(first,args,kwargs)\n \n \n \n for is_attr,i in rest:\n if is_attr:\n obj=getattr(obj,i)\n else:\n obj=obj[i]\n \n return obj,first\n", ["_string", "collections", "re"]], "stringprep": [".py", "\n''\n\n\n\n\n\nfrom unicodedata import ucd_3_2_0 as unicodedata\n\nassert unicodedata.unidata_version =='3.2.0'\n\ndef in_table_a1(code):\n if unicodedata.category(code)!='Cn':return False\n c=ord(code)\n if 0xFDD0 <=c <0xFDF0:return False\n return(c&0xFFFF)not in(0xFFFE,0xFFFF)\n \n \nb1_set=set([173,847,6150,6155,6156,6157,8203,8204,8205,8288,65279]+list(range(65024,65040)))\ndef in_table_b1(code):\n return ord(code)in b1_set\n \n \nb3_exceptions={\n0xb5:'\\u03bc',0xdf:'ss',0x130:'i\\u0307',0x149:'\\u02bcn',\n0x17f:'s',0x1f0:'j\\u030c',0x345:'\\u03b9',0x37a:' \\u03b9',\n0x390:'\\u03b9\\u0308\\u0301',0x3b0:'\\u03c5\\u0308\\u0301',0x3c2:'\\u03c3',0x3d0:'\\u03b2',\n0x3d1:'\\u03b8',0x3d2:'\\u03c5',0x3d3:'\\u03cd',0x3d4:'\\u03cb',\n0x3d5:'\\u03c6',0x3d6:'\\u03c0',0x3f0:'\\u03ba',0x3f1:'\\u03c1',\n0x3f2:'\\u03c3',0x3f5:'\\u03b5',0x587:'\\u0565\\u0582',0x1e96:'h\\u0331',\n0x1e97:'t\\u0308',0x1e98:'w\\u030a',0x1e99:'y\\u030a',0x1e9a:'a\\u02be',\n0x1e9b:'\\u1e61',0x1f50:'\\u03c5\\u0313',0x1f52:'\\u03c5\\u0313\\u0300',0x1f54:'\\u03c5\\u0313\\u0301',\n0x1f56:'\\u03c5\\u0313\\u0342',0x1f80:'\\u1f00\\u03b9',0x1f81:'\\u1f01\\u03b9',0x1f82:'\\u1f02\\u03b9',\n0x1f83:'\\u1f03\\u03b9',0x1f84:'\\u1f04\\u03b9',0x1f85:'\\u1f05\\u03b9',0x1f86:'\\u1f06\\u03b9',\n0x1f87:'\\u1f07\\u03b9',0x1f88:'\\u1f00\\u03b9',0x1f89:'\\u1f01\\u03b9',0x1f8a:'\\u1f02\\u03b9',\n0x1f8b:'\\u1f03\\u03b9',0x1f8c:'\\u1f04\\u03b9',0x1f8d:'\\u1f05\\u03b9',0x1f8e:'\\u1f06\\u03b9',\n0x1f8f:'\\u1f07\\u03b9',0x1f90:'\\u1f20\\u03b9',0x1f91:'\\u1f21\\u03b9',0x1f92:'\\u1f22\\u03b9',\n0x1f93:'\\u1f23\\u03b9',0x1f94:'\\u1f24\\u03b9',0x1f95:'\\u1f25\\u03b9',0x1f96:'\\u1f26\\u03b9',\n0x1f97:'\\u1f27\\u03b9',0x1f98:'\\u1f20\\u03b9',0x1f99:'\\u1f21\\u03b9',0x1f9a:'\\u1f22\\u03b9',\n0x1f9b:'\\u1f23\\u03b9',0x1f9c:'\\u1f24\\u03b9',0x1f9d:'\\u1f25\\u03b9',0x1f9e:'\\u1f26\\u03b9',\n0x1f9f:'\\u1f27\\u03b9',0x1fa0:'\\u1f60\\u03b9',0x1fa1:'\\u1f61\\u03b9',0x1fa2:'\\u1f62\\u03b9',\n0x1fa3:'\\u1f63\\u03b9',0x1fa4:'\\u1f64\\u03b9',0x1fa5:'\\u1f65\\u03b9',0x1fa6:'\\u1f66\\u03b9',\n0x1fa7:'\\u1f67\\u03b9',0x1fa8:'\\u1f60\\u03b9',0x1fa9:'\\u1f61\\u03b9',0x1faa:'\\u1f62\\u03b9',\n0x1fab:'\\u1f63\\u03b9',0x1fac:'\\u1f64\\u03b9',0x1fad:'\\u1f65\\u03b9',0x1fae:'\\u1f66\\u03b9',\n0x1faf:'\\u1f67\\u03b9',0x1fb2:'\\u1f70\\u03b9',0x1fb3:'\\u03b1\\u03b9',0x1fb4:'\\u03ac\\u03b9',\n0x1fb6:'\\u03b1\\u0342',0x1fb7:'\\u03b1\\u0342\\u03b9',0x1fbc:'\\u03b1\\u03b9',0x1fbe:'\\u03b9',\n0x1fc2:'\\u1f74\\u03b9',0x1fc3:'\\u03b7\\u03b9',0x1fc4:'\\u03ae\\u03b9',0x1fc6:'\\u03b7\\u0342',\n0x1fc7:'\\u03b7\\u0342\\u03b9',0x1fcc:'\\u03b7\\u03b9',0x1fd2:'\\u03b9\\u0308\\u0300',0x1fd3:'\\u03b9\\u0308\\u0301',\n0x1fd6:'\\u03b9\\u0342',0x1fd7:'\\u03b9\\u0308\\u0342',0x1fe2:'\\u03c5\\u0308\\u0300',0x1fe3:'\\u03c5\\u0308\\u0301',\n0x1fe4:'\\u03c1\\u0313',0x1fe6:'\\u03c5\\u0342',0x1fe7:'\\u03c5\\u0308\\u0342',0x1ff2:'\\u1f7c\\u03b9',\n0x1ff3:'\\u03c9\\u03b9',0x1ff4:'\\u03ce\\u03b9',0x1ff6:'\\u03c9\\u0342',0x1ff7:'\\u03c9\\u0342\\u03b9',\n0x1ffc:'\\u03c9\\u03b9',0x20a8:'rs',0x2102:'c',0x2103:'\\xb0c',\n0x2107:'\\u025b',0x2109:'\\xb0f',0x210b:'h',0x210c:'h',\n0x210d:'h',0x2110:'i',0x2111:'i',0x2112:'l',\n0x2115:'n',0x2116:'no',0x2119:'p',0x211a:'q',\n0x211b:'r',0x211c:'r',0x211d:'r',0x2120:'sm',\n0x2121:'tel',0x2122:'tm',0x2124:'z',0x2128:'z',\n0x212c:'b',0x212d:'c',0x2130:'e',0x2131:'f',\n0x2133:'m',0x213e:'\\u03b3',0x213f:'\\u03c0',0x2145:'d',\n0x3371:'hpa',0x3373:'au',0x3375:'ov',0x3380:'pa',\n0x3381:'na',0x3382:'\\u03bca',0x3383:'ma',0x3384:'ka',\n0x3385:'kb',0x3386:'mb',0x3387:'gb',0x338a:'pf',\n0x338b:'nf',0x338c:'\\u03bcf',0x3390:'hz',0x3391:'khz',\n0x3392:'mhz',0x3393:'ghz',0x3394:'thz',0x33a9:'pa',\n0x33aa:'kpa',0x33ab:'mpa',0x33ac:'gpa',0x33b4:'pv',\n0x33b5:'nv',0x33b6:'\\u03bcv',0x33b7:'mv',0x33b8:'kv',\n0x33b9:'mv',0x33ba:'pw',0x33bb:'nw',0x33bc:'\\u03bcw',\n0x33bd:'mw',0x33be:'kw',0x33bf:'mw',0x33c0:'k\\u03c9',\n0x33c1:'m\\u03c9',0x33c3:'bq',0x33c6:'c\\u2215kg',0x33c7:'co.',\n0x33c8:'db',0x33c9:'gy',0x33cb:'hp',0x33cd:'kk',\n0x33ce:'km',0x33d7:'ph',0x33d9:'ppm',0x33da:'pr',\n0x33dc:'sv',0x33dd:'wb',0xfb00:'ff',0xfb01:'fi',\n0xfb02:'fl',0xfb03:'ffi',0xfb04:'ffl',0xfb05:'st',\n0xfb06:'st',0xfb13:'\\u0574\\u0576',0xfb14:'\\u0574\\u0565',0xfb15:'\\u0574\\u056b',\n0xfb16:'\\u057e\\u0576',0xfb17:'\\u0574\\u056d',0x1d400:'a',0x1d401:'b',\n0x1d402:'c',0x1d403:'d',0x1d404:'e',0x1d405:'f',\n0x1d406:'g',0x1d407:'h',0x1d408:'i',0x1d409:'j',\n0x1d40a:'k',0x1d40b:'l',0x1d40c:'m',0x1d40d:'n',\n0x1d40e:'o',0x1d40f:'p',0x1d410:'q',0x1d411:'r',\n0x1d412:'s',0x1d413:'t',0x1d414:'u',0x1d415:'v',\n0x1d416:'w',0x1d417:'x',0x1d418:'y',0x1d419:'z',\n0x1d434:'a',0x1d435:'b',0x1d436:'c',0x1d437:'d',\n0x1d438:'e',0x1d439:'f',0x1d43a:'g',0x1d43b:'h',\n0x1d43c:'i',0x1d43d:'j',0x1d43e:'k',0x1d43f:'l',\n0x1d440:'m',0x1d441:'n',0x1d442:'o',0x1d443:'p',\n0x1d444:'q',0x1d445:'r',0x1d446:'s',0x1d447:'t',\n0x1d448:'u',0x1d449:'v',0x1d44a:'w',0x1d44b:'x',\n0x1d44c:'y',0x1d44d:'z',0x1d468:'a',0x1d469:'b',\n0x1d46a:'c',0x1d46b:'d',0x1d46c:'e',0x1d46d:'f',\n0x1d46e:'g',0x1d46f:'h',0x1d470:'i',0x1d471:'j',\n0x1d472:'k',0x1d473:'l',0x1d474:'m',0x1d475:'n',\n0x1d476:'o',0x1d477:'p',0x1d478:'q',0x1d479:'r',\n0x1d47a:'s',0x1d47b:'t',0x1d47c:'u',0x1d47d:'v',\n0x1d47e:'w',0x1d47f:'x',0x1d480:'y',0x1d481:'z',\n0x1d49c:'a',0x1d49e:'c',0x1d49f:'d',0x1d4a2:'g',\n0x1d4a5:'j',0x1d4a6:'k',0x1d4a9:'n',0x1d4aa:'o',\n0x1d4ab:'p',0x1d4ac:'q',0x1d4ae:'s',0x1d4af:'t',\n0x1d4b0:'u',0x1d4b1:'v',0x1d4b2:'w',0x1d4b3:'x',\n0x1d4b4:'y',0x1d4b5:'z',0x1d4d0:'a',0x1d4d1:'b',\n0x1d4d2:'c',0x1d4d3:'d',0x1d4d4:'e',0x1d4d5:'f',\n0x1d4d6:'g',0x1d4d7:'h',0x1d4d8:'i',0x1d4d9:'j',\n0x1d4da:'k',0x1d4db:'l',0x1d4dc:'m',0x1d4dd:'n',\n0x1d4de:'o',0x1d4df:'p',0x1d4e0:'q',0x1d4e1:'r',\n0x1d4e2:'s',0x1d4e3:'t',0x1d4e4:'u',0x1d4e5:'v',\n0x1d4e6:'w',0x1d4e7:'x',0x1d4e8:'y',0x1d4e9:'z',\n0x1d504:'a',0x1d505:'b',0x1d507:'d',0x1d508:'e',\n0x1d509:'f',0x1d50a:'g',0x1d50d:'j',0x1d50e:'k',\n0x1d50f:'l',0x1d510:'m',0x1d511:'n',0x1d512:'o',\n0x1d513:'p',0x1d514:'q',0x1d516:'s',0x1d517:'t',\n0x1d518:'u',0x1d519:'v',0x1d51a:'w',0x1d51b:'x',\n0x1d51c:'y',0x1d538:'a',0x1d539:'b',0x1d53b:'d',\n0x1d53c:'e',0x1d53d:'f',0x1d53e:'g',0x1d540:'i',\n0x1d541:'j',0x1d542:'k',0x1d543:'l',0x1d544:'m',\n0x1d546:'o',0x1d54a:'s',0x1d54b:'t',0x1d54c:'u',\n0x1d54d:'v',0x1d54e:'w',0x1d54f:'x',0x1d550:'y',\n0x1d56c:'a',0x1d56d:'b',0x1d56e:'c',0x1d56f:'d',\n0x1d570:'e',0x1d571:'f',0x1d572:'g',0x1d573:'h',\n0x1d574:'i',0x1d575:'j',0x1d576:'k',0x1d577:'l',\n0x1d578:'m',0x1d579:'n',0x1d57a:'o',0x1d57b:'p',\n0x1d57c:'q',0x1d57d:'r',0x1d57e:'s',0x1d57f:'t',\n0x1d580:'u',0x1d581:'v',0x1d582:'w',0x1d583:'x',\n0x1d584:'y',0x1d585:'z',0x1d5a0:'a',0x1d5a1:'b',\n0x1d5a2:'c',0x1d5a3:'d',0x1d5a4:'e',0x1d5a5:'f',\n0x1d5a6:'g',0x1d5a7:'h',0x1d5a8:'i',0x1d5a9:'j',\n0x1d5aa:'k',0x1d5ab:'l',0x1d5ac:'m',0x1d5ad:'n',\n0x1d5ae:'o',0x1d5af:'p',0x1d5b0:'q',0x1d5b1:'r',\n0x1d5b2:'s',0x1d5b3:'t',0x1d5b4:'u',0x1d5b5:'v',\n0x1d5b6:'w',0x1d5b7:'x',0x1d5b8:'y',0x1d5b9:'z',\n0x1d5d4:'a',0x1d5d5:'b',0x1d5d6:'c',0x1d5d7:'d',\n0x1d5d8:'e',0x1d5d9:'f',0x1d5da:'g',0x1d5db:'h',\n0x1d5dc:'i',0x1d5dd:'j',0x1d5de:'k',0x1d5df:'l',\n0x1d5e0:'m',0x1d5e1:'n',0x1d5e2:'o',0x1d5e3:'p',\n0x1d5e4:'q',0x1d5e5:'r',0x1d5e6:'s',0x1d5e7:'t',\n0x1d5e8:'u',0x1d5e9:'v',0x1d5ea:'w',0x1d5eb:'x',\n0x1d5ec:'y',0x1d5ed:'z',0x1d608:'a',0x1d609:'b',\n0x1d60a:'c',0x1d60b:'d',0x1d60c:'e',0x1d60d:'f',\n0x1d60e:'g',0x1d60f:'h',0x1d610:'i',0x1d611:'j',\n0x1d612:'k',0x1d613:'l',0x1d614:'m',0x1d615:'n',\n0x1d616:'o',0x1d617:'p',0x1d618:'q',0x1d619:'r',\n0x1d61a:'s',0x1d61b:'t',0x1d61c:'u',0x1d61d:'v',\n0x1d61e:'w',0x1d61f:'x',0x1d620:'y',0x1d621:'z',\n0x1d63c:'a',0x1d63d:'b',0x1d63e:'c',0x1d63f:'d',\n0x1d640:'e',0x1d641:'f',0x1d642:'g',0x1d643:'h',\n0x1d644:'i',0x1d645:'j',0x1d646:'k',0x1d647:'l',\n0x1d648:'m',0x1d649:'n',0x1d64a:'o',0x1d64b:'p',\n0x1d64c:'q',0x1d64d:'r',0x1d64e:'s',0x1d64f:'t',\n0x1d650:'u',0x1d651:'v',0x1d652:'w',0x1d653:'x',\n0x1d654:'y',0x1d655:'z',0x1d670:'a',0x1d671:'b',\n0x1d672:'c',0x1d673:'d',0x1d674:'e',0x1d675:'f',\n0x1d676:'g',0x1d677:'h',0x1d678:'i',0x1d679:'j',\n0x1d67a:'k',0x1d67b:'l',0x1d67c:'m',0x1d67d:'n',\n0x1d67e:'o',0x1d67f:'p',0x1d680:'q',0x1d681:'r',\n0x1d682:'s',0x1d683:'t',0x1d684:'u',0x1d685:'v',\n0x1d686:'w',0x1d687:'x',0x1d688:'y',0x1d689:'z',\n0x1d6a8:'\\u03b1',0x1d6a9:'\\u03b2',0x1d6aa:'\\u03b3',0x1d6ab:'\\u03b4',\n0x1d6ac:'\\u03b5',0x1d6ad:'\\u03b6',0x1d6ae:'\\u03b7',0x1d6af:'\\u03b8',\n0x1d6b0:'\\u03b9',0x1d6b1:'\\u03ba',0x1d6b2:'\\u03bb',0x1d6b3:'\\u03bc',\n0x1d6b4:'\\u03bd',0x1d6b5:'\\u03be',0x1d6b6:'\\u03bf',0x1d6b7:'\\u03c0',\n0x1d6b8:'\\u03c1',0x1d6b9:'\\u03b8',0x1d6ba:'\\u03c3',0x1d6bb:'\\u03c4',\n0x1d6bc:'\\u03c5',0x1d6bd:'\\u03c6',0x1d6be:'\\u03c7',0x1d6bf:'\\u03c8',\n0x1d6c0:'\\u03c9',0x1d6d3:'\\u03c3',0x1d6e2:'\\u03b1',0x1d6e3:'\\u03b2',\n0x1d6e4:'\\u03b3',0x1d6e5:'\\u03b4',0x1d6e6:'\\u03b5',0x1d6e7:'\\u03b6',\n0x1d6e8:'\\u03b7',0x1d6e9:'\\u03b8',0x1d6ea:'\\u03b9',0x1d6eb:'\\u03ba',\n0x1d6ec:'\\u03bb',0x1d6ed:'\\u03bc',0x1d6ee:'\\u03bd',0x1d6ef:'\\u03be',\n0x1d6f0:'\\u03bf',0x1d6f1:'\\u03c0',0x1d6f2:'\\u03c1',0x1d6f3:'\\u03b8',\n0x1d6f4:'\\u03c3',0x1d6f5:'\\u03c4',0x1d6f6:'\\u03c5',0x1d6f7:'\\u03c6',\n0x1d6f8:'\\u03c7',0x1d6f9:'\\u03c8',0x1d6fa:'\\u03c9',0x1d70d:'\\u03c3',\n0x1d71c:'\\u03b1',0x1d71d:'\\u03b2',0x1d71e:'\\u03b3',0x1d71f:'\\u03b4',\n0x1d720:'\\u03b5',0x1d721:'\\u03b6',0x1d722:'\\u03b7',0x1d723:'\\u03b8',\n0x1d724:'\\u03b9',0x1d725:'\\u03ba',0x1d726:'\\u03bb',0x1d727:'\\u03bc',\n0x1d728:'\\u03bd',0x1d729:'\\u03be',0x1d72a:'\\u03bf',0x1d72b:'\\u03c0',\n0x1d72c:'\\u03c1',0x1d72d:'\\u03b8',0x1d72e:'\\u03c3',0x1d72f:'\\u03c4',\n0x1d730:'\\u03c5',0x1d731:'\\u03c6',0x1d732:'\\u03c7',0x1d733:'\\u03c8',\n0x1d734:'\\u03c9',0x1d747:'\\u03c3',0x1d756:'\\u03b1',0x1d757:'\\u03b2',\n0x1d758:'\\u03b3',0x1d759:'\\u03b4',0x1d75a:'\\u03b5',0x1d75b:'\\u03b6',\n0x1d75c:'\\u03b7',0x1d75d:'\\u03b8',0x1d75e:'\\u03b9',0x1d75f:'\\u03ba',\n0x1d760:'\\u03bb',0x1d761:'\\u03bc',0x1d762:'\\u03bd',0x1d763:'\\u03be',\n0x1d764:'\\u03bf',0x1d765:'\\u03c0',0x1d766:'\\u03c1',0x1d767:'\\u03b8',\n0x1d768:'\\u03c3',0x1d769:'\\u03c4',0x1d76a:'\\u03c5',0x1d76b:'\\u03c6',\n0x1d76c:'\\u03c7',0x1d76d:'\\u03c8',0x1d76e:'\\u03c9',0x1d781:'\\u03c3',\n0x1d790:'\\u03b1',0x1d791:'\\u03b2',0x1d792:'\\u03b3',0x1d793:'\\u03b4',\n0x1d794:'\\u03b5',0x1d795:'\\u03b6',0x1d796:'\\u03b7',0x1d797:'\\u03b8',\n0x1d798:'\\u03b9',0x1d799:'\\u03ba',0x1d79a:'\\u03bb',0x1d79b:'\\u03bc',\n0x1d79c:'\\u03bd',0x1d79d:'\\u03be',0x1d79e:'\\u03bf',0x1d79f:'\\u03c0',\n0x1d7a0:'\\u03c1',0x1d7a1:'\\u03b8',0x1d7a2:'\\u03c3',0x1d7a3:'\\u03c4',\n0x1d7a4:'\\u03c5',0x1d7a5:'\\u03c6',0x1d7a6:'\\u03c7',0x1d7a7:'\\u03c8',\n0x1d7a8:'\\u03c9',0x1d7bb:'\\u03c3',}\n\ndef map_table_b3(code):\n r=b3_exceptions.get(ord(code))\n if r is not None:return r\n return code.lower()\n \n \ndef map_table_b2(a):\n al=map_table_b3(a)\n b=unicodedata.normalize(\"NFKC\",al)\n bl=\"\".join([map_table_b3(ch)for ch in b])\n c=unicodedata.normalize(\"NFKC\",bl)\n if b !=c:\n return c\n else:\n return al\n \n \ndef in_table_c11(code):\n return code ==\" \"\n \n \ndef in_table_c12(code):\n return unicodedata.category(code)==\"Zs\"and code !=\" \"\n \ndef in_table_c11_c12(code):\n return unicodedata.category(code)==\"Zs\"\n \n \ndef in_table_c21(code):\n return ord(code)<128 and unicodedata.category(code)==\"Cc\"\n \nc22_specials=set([1757,1807,6158,8204,8205,8232,8233,65279]+list(range(8288,8292))+list(range(8298,8304))+list(range(65529,65533))+list(range(119155,119163)))\ndef in_table_c22(code):\n c=ord(code)\n if c <128:return False\n if unicodedata.category(code)==\"Cc\":return True\n return c in c22_specials\n \ndef in_table_c21_c22(code):\n return unicodedata.category(code)==\"Cc\"or\\\n ord(code)in c22_specials\n \n \ndef in_table_c3(code):\n return unicodedata.category(code)==\"Co\"\n \n \ndef in_table_c4(code):\n c=ord(code)\n if c <0xFDD0:return False\n if c <0xFDF0:return True\n return(ord(code)&0xFFFF)in(0xFFFE,0xFFFF)\n \n \ndef in_table_c5(code):\n return unicodedata.category(code)==\"Cs\"\n \n \nc6_set=set(range(65529,65534))\ndef in_table_c6(code):\n return ord(code)in c6_set\n \n \nc7_set=set(range(12272,12284))\ndef in_table_c7(code):\n return ord(code)in c7_set\n \n \nc8_set=set([832,833,8206,8207]+list(range(8234,8239))+list(range(8298,8304)))\ndef in_table_c8(code):\n return ord(code)in c8_set\n \n \nc9_set=set([917505]+list(range(917536,917632)))\ndef in_table_c9(code):\n return ord(code)in c9_set\n \n \ndef in_table_d1(code):\n return unicodedata.bidirectional(code)in(\"R\",\"AL\")\n \n \ndef in_table_d2(code):\n return unicodedata.bidirectional(code)==\"L\"\n", ["unicodedata"]], "struct": [".py", "__all__=[\n\n'calcsize','pack','pack_into','unpack','unpack_from',\n'iter_unpack',\n\n\n'Struct',\n\n\n'error'\n]\n\nfrom _struct import *\nfrom _struct import _clearcache\nfrom _struct import __doc__\n", ["_struct"]], "subprocess": [".py", "\n\n\n\n\n\n\n\nr\"\"\"Subprocesses with accessible I/O streams\n\nThis module allows you to spawn processes, connect to their\ninput/output/error pipes, and obtain their return codes.\n\nFor a complete description of this module see the Python documentation.\n\nMain API\n========\nrun(...): Runs a command, waits for it to complete, then returns a\n CompletedProcess instance.\nPopen(...): A class for flexibly executing a command in a new process\n\nConstants\n---------\nDEVNULL: Special value that indicates that os.devnull should be used\nPIPE: Special value that indicates a pipe should be created\nSTDOUT: Special value that indicates that stderr should go to stdout\n\n\nOlder API\n=========\ncall(...): Runs a command, waits for it to complete, then returns\n the return code.\ncheck_call(...): Same as call() but raises CalledProcessError()\n if return code is not 0\ncheck_output(...): Same as check_call() but returns the contents of\n stdout instead of a return code\ngetoutput(...): Runs a command in the shell, waits for it to complete,\n then returns the output\ngetstatusoutput(...): Runs a command in the shell, waits for it to complete,\n then returns a (exitcode, output) tuple\n\"\"\"\n\nimport builtins\nimport errno\nimport io\nimport locale\nimport os\nimport time\nimport signal\nimport sys\nimport threading\nimport warnings\nimport contextlib\nfrom time import monotonic as _time\nimport types\n\ntry:\n import fcntl\nexcept ImportError:\n fcntl=None\n \n \n__all__=[\"Popen\",\"PIPE\",\"STDOUT\",\"call\",\"check_call\",\"getstatusoutput\",\n\"getoutput\",\"check_output\",\"run\",\"CalledProcessError\",\"DEVNULL\",\n\"SubprocessError\",\"TimeoutExpired\",\"CompletedProcess\"]\n\n\n\n\ntry:\n import msvcrt\nexcept ModuleNotFoundError:\n _mswindows=False\nelse:\n _mswindows=True\n \n \n_can_fork_exec=sys.platform not in{\"emscripten\",\"wasi\",\"ios\",\"tvos\",\"watchos\"}\n\nif _mswindows:\n import _winapi\n from _winapi import(CREATE_NEW_CONSOLE,CREATE_NEW_PROCESS_GROUP,\n STD_INPUT_HANDLE,STD_OUTPUT_HANDLE,\n STD_ERROR_HANDLE,SW_HIDE,\n STARTF_USESTDHANDLES,STARTF_USESHOWWINDOW,\n STARTF_FORCEONFEEDBACK,STARTF_FORCEOFFFEEDBACK,\n ABOVE_NORMAL_PRIORITY_CLASS,BELOW_NORMAL_PRIORITY_CLASS,\n HIGH_PRIORITY_CLASS,IDLE_PRIORITY_CLASS,\n NORMAL_PRIORITY_CLASS,REALTIME_PRIORITY_CLASS,\n CREATE_NO_WINDOW,DETACHED_PROCESS,\n CREATE_DEFAULT_ERROR_MODE,CREATE_BREAKAWAY_FROM_JOB)\n \n __all__.extend([\"CREATE_NEW_CONSOLE\",\"CREATE_NEW_PROCESS_GROUP\",\n \"STD_INPUT_HANDLE\",\"STD_OUTPUT_HANDLE\",\n \"STD_ERROR_HANDLE\",\"SW_HIDE\",\n \"STARTF_USESTDHANDLES\",\"STARTF_USESHOWWINDOW\",\n \"STARTF_FORCEONFEEDBACK\",\"STARTF_FORCEOFFFEEDBACK\",\n \"STARTUPINFO\",\n \"ABOVE_NORMAL_PRIORITY_CLASS\",\"BELOW_NORMAL_PRIORITY_CLASS\",\n \"HIGH_PRIORITY_CLASS\",\"IDLE_PRIORITY_CLASS\",\n \"NORMAL_PRIORITY_CLASS\",\"REALTIME_PRIORITY_CLASS\",\n \"CREATE_NO_WINDOW\",\"DETACHED_PROCESS\",\n \"CREATE_DEFAULT_ERROR_MODE\",\"CREATE_BREAKAWAY_FROM_JOB\"])\nelse:\n if _can_fork_exec:\n from _posixsubprocess import fork_exec as _fork_exec\n \n class _del_safe:\n waitpid=os.waitpid\n waitstatus_to_exitcode=os.waitstatus_to_exitcode\n WIFSTOPPED=os.WIFSTOPPED\n WSTOPSIG=os.WSTOPSIG\n WNOHANG=os.WNOHANG\n ECHILD=errno.ECHILD\n else:\n class _del_safe:\n waitpid=None\n waitstatus_to_exitcode=None\n WIFSTOPPED=None\n WSTOPSIG=None\n WNOHANG=None\n ECHILD=errno.ECHILD\n \n import select\n import selectors\n \n \n \nclass SubprocessError(Exception):pass\n\n\nclass CalledProcessError(SubprocessError):\n ''\n\n\n\n\n \n def __init__(self,returncode,cmd,output=None,stderr=None):\n self.returncode=returncode\n self.cmd=cmd\n self.output=output\n self.stderr=stderr\n \n def __str__(self):\n if self.returncode and self.returncode <0:\n try:\n return \"Command '%s' died with %r.\"%(\n self.cmd,signal.Signals(-self.returncode))\n except ValueError:\n return \"Command '%s' died with unknown signal %d.\"%(\n self.cmd,-self.returncode)\n else:\n return \"Command '%s' returned non-zero exit status %d.\"%(\n self.cmd,self.returncode)\n \n @property\n def stdout(self):\n ''\n return self.output\n \n @stdout.setter\n def stdout(self,value):\n \n \n self.output=value\n \n \nclass TimeoutExpired(SubprocessError):\n ''\n\n\n\n\n \n def __init__(self,cmd,timeout,output=None,stderr=None):\n self.cmd=cmd\n self.timeout=timeout\n self.output=output\n self.stderr=stderr\n \n def __str__(self):\n return(\"Command '%s' timed out after %s seconds\"%\n (self.cmd,self.timeout))\n \n @property\n def stdout(self):\n return self.output\n \n @stdout.setter\n def stdout(self,value):\n \n \n self.output=value\n \n \nif _mswindows:\n class STARTUPINFO:\n def __init__(self,*,dwFlags=0,hStdInput=None,hStdOutput=None,\n hStdError=None,wShowWindow=0,lpAttributeList=None):\n self.dwFlags=dwFlags\n self.hStdInput=hStdInput\n self.hStdOutput=hStdOutput\n self.hStdError=hStdError\n self.wShowWindow=wShowWindow\n self.lpAttributeList=lpAttributeList or{\"handle_list\":[]}\n \n def copy(self):\n attr_list=self.lpAttributeList.copy()\n if 'handle_list'in attr_list:\n attr_list['handle_list']=list(attr_list['handle_list'])\n \n return STARTUPINFO(dwFlags=self.dwFlags,\n hStdInput=self.hStdInput,\n hStdOutput=self.hStdOutput,\n hStdError=self.hStdError,\n wShowWindow=self.wShowWindow,\n lpAttributeList=attr_list)\n \n \n class Handle(int):\n closed=False\n \n def Close(self,CloseHandle=_winapi.CloseHandle):\n if not self.closed:\n self.closed=True\n CloseHandle(self)\n \n def Detach(self):\n if not self.closed:\n self.closed=True\n return int(self)\n raise ValueError(\"already closed\")\n \n def __repr__(self):\n return \"%s(%d)\"%(self.__class__.__name__,int(self))\n \n __del__=Close\nelse:\n\n\n\n _PIPE_BUF=getattr(select,'PIPE_BUF',512)\n \n \n \n \n if hasattr(selectors,'PollSelector'):\n _PopenSelector=selectors.PollSelector\n else:\n _PopenSelector=selectors.SelectSelector\n \n \nif _mswindows:\n\n\n\n\n\n\n\n\n _active=None\n \n def _cleanup():\n pass\nelse:\n\n\n\n\n _active=[]\n \n def _cleanup():\n if _active is None:\n return\n for inst in _active[:]:\n res=inst._internal_poll(_deadstate=sys.maxsize)\n if res is not None:\n try:\n _active.remove(inst)\n except ValueError:\n \n \n pass\n \nPIPE=-1\nSTDOUT=-2\nDEVNULL=-3\n\n\n\n\n\n\ndef _optim_args_from_interpreter_flags():\n ''\n \n args=[]\n value=sys.flags.optimize\n if value >0:\n args.append('-'+'O'*value)\n return args\n \n \ndef _args_from_interpreter_flags():\n ''\n \n flag_opt_map={\n 'debug':'d',\n \n \n 'dont_write_bytecode':'B',\n 'no_site':'S',\n 'verbose':'v',\n 'bytes_warning':'b',\n 'quiet':'q',\n \n }\n args=_optim_args_from_interpreter_flags()\n for flag,opt in flag_opt_map.items():\n v=getattr(sys.flags,flag)\n if v >0:\n args.append('-'+opt *v)\n \n if sys.flags.isolated:\n args.append('-I')\n else:\n if sys.flags.ignore_environment:\n args.append('-E')\n if sys.flags.no_user_site:\n args.append('-s')\n if sys.flags.safe_path:\n args.append('-P')\n \n \n warnopts=sys.warnoptions[:]\n xoptions=getattr(sys,'_xoptions',{})\n bytes_warning=sys.flags.bytes_warning\n dev_mode=sys.flags.dev_mode\n \n if bytes_warning >1:\n warnopts.remove(\"error::BytesWarning\")\n elif bytes_warning:\n warnopts.remove(\"default::BytesWarning\")\n if dev_mode:\n warnopts.remove('default')\n for opt in warnopts:\n args.append('-W'+opt)\n \n \n if dev_mode:\n args.extend(('-X','dev'))\n for opt in('faulthandler','tracemalloc','importtime',\n 'frozen_modules','showrefcount','utf8','gil'):\n if opt in xoptions:\n value=xoptions[opt]\n if value is True:\n arg=opt\n else:\n arg='%s=%s'%(opt,value)\n args.extend(('-X',arg))\n \n return args\n \n \ndef _text_encoding():\n\n\n if sys.flags.warn_default_encoding:\n f=sys._getframe()\n filename=f.f_code.co_filename\n stacklevel=2\n while f :=f.f_back:\n if f.f_code.co_filename !=filename:\n break\n stacklevel +=1\n warnings.warn(\"'encoding' argument not specified.\",\n EncodingWarning,stacklevel)\n \n if sys.flags.utf8_mode:\n return \"utf-8\"\n else:\n return locale.getencoding()\n \n \ndef call(*popenargs,timeout=None,**kwargs):\n ''\n\n\n\n\n\n \n with Popen(*popenargs,**kwargs)as p:\n try:\n return p.wait(timeout=timeout)\n except:\n p.kill()\n \n raise\n \n \ndef check_call(*popenargs,**kwargs):\n ''\n\n\n\n\n\n\n\n \n retcode=call(*popenargs,**kwargs)\n if retcode:\n cmd=kwargs.get(\"args\")\n if cmd is None:\n cmd=popenargs[0]\n raise CalledProcessError(retcode,cmd)\n return 0\n \n \ndef check_output(*popenargs,timeout=None,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n for kw in('stdout','check'):\n if kw in kwargs:\n raise ValueError(f'{kw} argument not allowed, it will be overridden.')\n \n if 'input'in kwargs and kwargs['input']is None:\n \n \n if kwargs.get('universal_newlines')or kwargs.get('text')or kwargs.get('encoding')\\\n or kwargs.get('errors'):\n empty=''\n else:\n empty=b''\n kwargs['input']=empty\n \n return run(*popenargs,stdout=PIPE,timeout=timeout,check=True,\n **kwargs).stdout\n \n \nclass CompletedProcess(object):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,args,returncode,stdout=None,stderr=None):\n self.args=args\n self.returncode=returncode\n self.stdout=stdout\n self.stderr=stderr\n \n def __repr__(self):\n args=['args={!r}'.format(self.args),\n 'returncode={!r}'.format(self.returncode)]\n if self.stdout is not None:\n args.append('stdout={!r}'.format(self.stdout))\n if self.stderr is not None:\n args.append('stderr={!r}'.format(self.stderr))\n return \"{}({})\".format(type(self).__name__,', '.join(args))\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \n def check_returncode(self):\n ''\n if self.returncode:\n raise CalledProcessError(self.returncode,self.args,self.stdout,\n self.stderr)\n \n \ndef run(*popenargs,\ninput=None,capture_output=False,timeout=None,check=False,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if input is not None:\n if kwargs.get('stdin')is not None:\n raise ValueError('stdin and input arguments may not both be used.')\n kwargs['stdin']=PIPE\n \n if capture_output:\n if kwargs.get('stdout')is not None or kwargs.get('stderr')is not None:\n raise ValueError('stdout and stderr arguments may not be used '\n 'with capture_output.')\n kwargs['stdout']=PIPE\n kwargs['stderr']=PIPE\n \n with Popen(*popenargs,**kwargs)as process:\n try:\n stdout,stderr=process.communicate(input,timeout=timeout)\n except TimeoutExpired as exc:\n process.kill()\n if _mswindows:\n \n \n \n \n \n exc.stdout,exc.stderr=process.communicate()\n else:\n \n \n process.wait()\n raise\n except:\n process.kill()\n \n raise\n retcode=process.poll()\n if check and retcode:\n raise CalledProcessError(retcode,process.args,\n output=stdout,stderr=stderr)\n return CompletedProcess(process.args,retcode,stdout,stderr)\n \n \ndef list2cmdline(seq):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n result=[]\n needquote=False\n for arg in map(os.fsdecode,seq):\n bs_buf=[]\n \n \n if result:\n result.append(' ')\n \n needquote=(\" \"in arg)or(\"\\t\"in arg)or not arg\n if needquote:\n result.append('\"')\n \n for c in arg:\n if c =='\\\\':\n \n bs_buf.append(c)\n elif c =='\"':\n \n result.append('\\\\'*len(bs_buf)*2)\n bs_buf=[]\n result.append('\\\\\"')\n else:\n \n if bs_buf:\n result.extend(bs_buf)\n bs_buf=[]\n result.append(c)\n \n \n if bs_buf:\n result.extend(bs_buf)\n \n if needquote:\n result.extend(bs_buf)\n result.append('\"')\n \n return ''.join(result)\n \n \n \n \n \ndef getstatusoutput(cmd,*,encoding=None,errors=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n data=check_output(cmd,shell=True,text=True,stderr=STDOUT,\n encoding=encoding,errors=errors)\n exitcode=0\n except CalledProcessError as ex:\n data=ex.output\n exitcode=ex.returncode\n if data[-1:]=='\\n':\n data=data[:-1]\n return exitcode,data\n \ndef getoutput(cmd,*,encoding=None,errors=None):\n ''\n\n\n\n\n\n\n\n \n return getstatusoutput(cmd,encoding=encoding,errors=errors)[1]\n \n \n \ndef _use_posix_spawn():\n ''\n\n\n\n\n\n\n\n\n\n\n \n if _mswindows or not hasattr(os,'posix_spawn'):\n \n return False\n \n if sys.platform in('darwin','sunos5'):\n \n \n return True\n \n \n try:\n ver=os.confstr('CS_GNU_LIBC_VERSION')\n \n parts=ver.split(maxsplit=1)\n if len(parts)!=2:\n \n raise ValueError\n libc=parts[0]\n version=tuple(map(int,parts[1].split('.')))\n \n if sys.platform =='linux'and libc =='glibc'and version >=(2,24):\n \n \n return True\n \n \n \n except(AttributeError,ValueError,OSError):\n \n pass\n \n \n return False\n \n \n \n \n_USE_POSIX_SPAWN=_use_posix_spawn()\n_USE_VFORK=True\n_HAVE_POSIX_SPAWN_CLOSEFROM=hasattr(os,'POSIX_SPAWN_CLOSEFROM')\n\n\nclass Popen:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n _child_created=False\n \n def __init__(self,args,bufsize=-1,executable=None,\n stdin=None,stdout=None,stderr=None,\n preexec_fn=None,close_fds=True,\n shell=False,cwd=None,env=None,universal_newlines=None,\n startupinfo=None,creationflags=0,\n restore_signals=True,start_new_session=False,\n pass_fds=(),*,user=None,group=None,extra_groups=None,\n encoding=None,errors=None,text=None,umask=-1,pipesize=-1,\n process_group=None):\n ''\n if not _can_fork_exec:\n raise OSError(\n errno.ENOTSUP,f\"{sys.platform} does not support processes.\"\n )\n \n _cleanup()\n \n \n \n \n \n self._waitpid_lock=threading.Lock()\n \n self._input=None\n self._communication_started=False\n if bufsize is None:\n bufsize=-1\n if not isinstance(bufsize,int):\n raise TypeError(\"bufsize must be an integer\")\n \n if stdout is STDOUT:\n raise ValueError(\"STDOUT can only be used for stderr\")\n \n if pipesize is None:\n pipesize=-1\n if not isinstance(pipesize,int):\n raise TypeError(\"pipesize must be an integer\")\n \n if _mswindows:\n if preexec_fn is not None:\n raise ValueError(\"preexec_fn is not supported on Windows \"\n \"platforms\")\n else:\n \n if pass_fds and not close_fds:\n warnings.warn(\"pass_fds overriding close_fds.\",RuntimeWarning)\n close_fds=True\n if startupinfo is not None:\n raise ValueError(\"startupinfo is only supported on Windows \"\n \"platforms\")\n if creationflags !=0:\n raise ValueError(\"creationflags is only supported on Windows \"\n \"platforms\")\n \n self.args=args\n self.stdin=None\n self.stdout=None\n self.stderr=None\n self.pid=None\n self.returncode=None\n self.encoding=encoding\n self.errors=errors\n self.pipesize=pipesize\n \n \n if(text is not None and universal_newlines is not None\n and bool(universal_newlines)!=bool(text)):\n raise SubprocessError('Cannot disambiguate when both text '\n 'and universal_newlines are supplied but '\n 'different. Pass one or the other.')\n \n self.text_mode=encoding or errors or text or universal_newlines\n if self.text_mode and encoding is None:\n self.encoding=encoding=_text_encoding()\n \n \n \n \n self._sigint_wait_secs=0.25\n \n self._closed_child_pipe_fds=False\n \n if self.text_mode:\n if bufsize ==1:\n line_buffering=True\n \n \n bufsize=-1\n else:\n line_buffering=False\n \n if process_group is None:\n process_group=-1\n \n gid=None\n if group is not None:\n if not hasattr(os,'setregid'):\n raise ValueError(\"The 'group' parameter is not supported on the \"\n \"current platform\")\n \n elif isinstance(group,str):\n try:\n import grp\n except ImportError:\n raise ValueError(\"The group parameter cannot be a string \"\n \"on systems without the grp module\")\n \n gid=grp.getgrnam(group).gr_gid\n elif isinstance(group,int):\n gid=group\n else:\n raise TypeError(\"Group must be a string or an integer, not {}\"\n .format(type(group)))\n \n if gid <0:\n raise ValueError(f\"Group ID cannot be negative, got {gid}\")\n \n gids=None\n if extra_groups is not None:\n if not hasattr(os,'setgroups'):\n raise ValueError(\"The 'extra_groups' parameter is not \"\n \"supported on the current platform\")\n \n elif isinstance(extra_groups,str):\n raise ValueError(\"Groups must be a list, not a string\")\n \n gids=[]\n for extra_group in extra_groups:\n if isinstance(extra_group,str):\n try:\n import grp\n except ImportError:\n raise ValueError(\"Items in extra_groups cannot be \"\n \"strings on systems without the \"\n \"grp module\")\n \n gids.append(grp.getgrnam(extra_group).gr_gid)\n elif isinstance(extra_group,int):\n gids.append(extra_group)\n else:\n raise TypeError(\"Items in extra_groups must be a string \"\n \"or integer, not {}\"\n .format(type(extra_group)))\n \n \n \n for gid_check in gids:\n if gid_check <0:\n raise ValueError(f\"Group ID cannot be negative, got {gid_check}\")\n \n uid=None\n if user is not None:\n if not hasattr(os,'setreuid'):\n raise ValueError(\"The 'user' parameter is not supported on \"\n \"the current platform\")\n \n elif isinstance(user,str):\n try:\n import pwd\n except ImportError:\n raise ValueError(\"The user parameter cannot be a string \"\n \"on systems without the pwd module\")\n uid=pwd.getpwnam(user).pw_uid\n elif isinstance(user,int):\n uid=user\n else:\n raise TypeError(\"User must be a string or an integer\")\n \n if uid <0:\n raise ValueError(f\"User ID cannot be negative, got {uid}\")\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n (p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)=self._get_handles(stdin,stdout,stderr)\n \n \n \n \n \n \n \n if _mswindows:\n if p2cwrite !=-1:\n p2cwrite=msvcrt.open_osfhandle(p2cwrite.Detach(),0)\n if c2pread !=-1:\n c2pread=msvcrt.open_osfhandle(c2pread.Detach(),0)\n if errread !=-1:\n errread=msvcrt.open_osfhandle(errread.Detach(),0)\n \n try:\n if p2cwrite !=-1:\n self.stdin=io.open(p2cwrite,'wb',bufsize)\n if self.text_mode:\n self.stdin=io.TextIOWrapper(self.stdin,write_through=True,\n line_buffering=line_buffering,\n encoding=encoding,errors=errors)\n if c2pread !=-1:\n self.stdout=io.open(c2pread,'rb',bufsize)\n if self.text_mode:\n self.stdout=io.TextIOWrapper(self.stdout,\n encoding=encoding,errors=errors)\n if errread !=-1:\n self.stderr=io.open(errread,'rb',bufsize)\n if self.text_mode:\n self.stderr=io.TextIOWrapper(self.stderr,\n encoding=encoding,errors=errors)\n \n self._execute_child(args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n restore_signals,\n gid,gids,uid,umask,\n start_new_session,process_group)\n except:\n \n for f in filter(None,(self.stdin,self.stdout,self.stderr)):\n try:\n f.close()\n except OSError:\n pass\n \n if not self._closed_child_pipe_fds:\n to_close=[]\n if stdin ==PIPE:\n to_close.append(p2cread)\n if stdout ==PIPE:\n to_close.append(c2pwrite)\n if stderr ==PIPE:\n to_close.append(errwrite)\n if hasattr(self,'_devnull'):\n to_close.append(self._devnull)\n for fd in to_close:\n try:\n if _mswindows and isinstance(fd,Handle):\n fd.Close()\n else:\n os.close(fd)\n except OSError:\n pass\n \n raise\n \n def __repr__(self):\n obj_repr=(\n f\"<{self.__class__.__name__}: \"\n f\"returncode: {self.returncode} args: {self.args !r}>\"\n )\n if len(obj_repr)>80:\n obj_repr=obj_repr[:76]+\"...>\"\n return obj_repr\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n @property\n def universal_newlines(self):\n \n \n return self.text_mode\n \n @universal_newlines.setter\n def universal_newlines(self,universal_newlines):\n self.text_mode=bool(universal_newlines)\n \n def _translate_newlines(self,data,encoding,errors):\n data=data.decode(encoding,errors)\n return data.replace(\"\\r\\n\",\"\\n\").replace(\"\\r\",\"\\n\")\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,value,traceback):\n if self.stdout:\n self.stdout.close()\n if self.stderr:\n self.stderr.close()\n try:\n if self.stdin:\n self.stdin.close()\n finally:\n if exc_type ==KeyboardInterrupt:\n \n \n \n \n \n \n \n if self._sigint_wait_secs >0:\n try:\n self._wait(timeout=self._sigint_wait_secs)\n except TimeoutExpired:\n pass\n self._sigint_wait_secs=0\n return\n \n \n self.wait()\n \n def __del__(self,_maxsize=sys.maxsize,_warn=warnings.warn):\n if not self._child_created:\n \n return\n if self.returncode is None:\n \n \n _warn(\"subprocess %s is still running\"%self.pid,\n ResourceWarning,source=self)\n \n self._internal_poll(_deadstate=_maxsize)\n if self.returncode is None and _active is not None:\n \n _active.append(self)\n \n def _get_devnull(self):\n if not hasattr(self,'_devnull'):\n self._devnull=os.open(os.devnull,os.O_RDWR)\n return self._devnull\n \n def _stdin_write(self,input):\n if input:\n try:\n self.stdin.write(input)\n except BrokenPipeError:\n pass\n except OSError as exc:\n if exc.errno ==errno.EINVAL:\n \n \n \n pass\n else:\n raise\n \n try:\n self.stdin.close()\n except BrokenPipeError:\n pass\n except OSError as exc:\n if exc.errno ==errno.EINVAL:\n pass\n else:\n raise\n \n def communicate(self,input=None,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if self._communication_started and input:\n raise ValueError(\"Cannot send input after starting communication\")\n \n \n \n \n if(timeout is None and not self._communication_started and\n [self.stdin,self.stdout,self.stderr].count(None)>=2):\n stdout=None\n stderr=None\n if self.stdin:\n self._stdin_write(input)\n elif self.stdout:\n stdout=self.stdout.read()\n self.stdout.close()\n elif self.stderr:\n stderr=self.stderr.read()\n self.stderr.close()\n self.wait()\n else:\n if timeout is not None:\n endtime=_time()+timeout\n else:\n endtime=None\n \n try:\n stdout,stderr=self._communicate(input,endtime,timeout)\n except KeyboardInterrupt:\n \n \n if timeout is not None:\n sigint_timeout=min(self._sigint_wait_secs,\n self._remaining_time(endtime))\n else:\n sigint_timeout=self._sigint_wait_secs\n self._sigint_wait_secs=0\n try:\n self._wait(timeout=sigint_timeout)\n except TimeoutExpired:\n pass\n raise\n \n finally:\n self._communication_started=True\n \n sts=self.wait(timeout=self._remaining_time(endtime))\n \n return(stdout,stderr)\n \n \n def poll(self):\n ''\n \n return self._internal_poll()\n \n \n def _remaining_time(self,endtime):\n ''\n if endtime is None:\n return None\n else:\n return endtime -_time()\n \n \n def _check_timeout(self,endtime,orig_timeout,stdout_seq,stderr_seq,\n skip_check_and_raise=False):\n ''\n if endtime is None:\n return\n if skip_check_and_raise or _time()>endtime:\n raise TimeoutExpired(\n self.args,orig_timeout,\n output=b''.join(stdout_seq)if stdout_seq else None,\n stderr=b''.join(stderr_seq)if stderr_seq else None)\n \n \n def wait(self,timeout=None):\n ''\n if timeout is not None:\n endtime=_time()+timeout\n try:\n return self._wait(timeout=timeout)\n except KeyboardInterrupt:\n \n \n \n \n if timeout is not None:\n sigint_timeout=min(self._sigint_wait_secs,\n self._remaining_time(endtime))\n else:\n sigint_timeout=self._sigint_wait_secs\n self._sigint_wait_secs=0\n try:\n self._wait(timeout=sigint_timeout)\n except TimeoutExpired:\n pass\n raise\n \n def _close_pipe_fds(self,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite):\n \n devnull_fd=getattr(self,'_devnull',None)\n \n with contextlib.ExitStack()as stack:\n if _mswindows:\n if p2cread !=-1:\n stack.callback(p2cread.Close)\n if c2pwrite !=-1:\n stack.callback(c2pwrite.Close)\n if errwrite !=-1:\n stack.callback(errwrite.Close)\n else:\n if p2cread !=-1 and p2cwrite !=-1 and p2cread !=devnull_fd:\n stack.callback(os.close,p2cread)\n if c2pwrite !=-1 and c2pread !=-1 and c2pwrite !=devnull_fd:\n stack.callback(os.close,c2pwrite)\n if errwrite !=-1 and errread !=-1 and errwrite !=devnull_fd:\n stack.callback(os.close,errwrite)\n \n if devnull_fd is not None:\n stack.callback(os.close,devnull_fd)\n \n \n self._closed_child_pipe_fds=True\n \n @contextlib.contextmanager\n def _on_error_fd_closer(self):\n ''\n to_close=[]\n try:\n yield to_close\n except:\n if hasattr(self,'_devnull'):\n to_close.append(self._devnull)\n del self._devnull\n for fd in to_close:\n try:\n if _mswindows and isinstance(fd,Handle):\n fd.Close()\n else:\n os.close(fd)\n except OSError:\n pass\n raise\n \n if _mswindows:\n \n \n \n def _get_handles(self,stdin,stdout,stderr):\n ''\n\n \n if stdin is None and stdout is None and stderr is None:\n return(-1,-1,-1,-1,-1,-1)\n \n p2cread,p2cwrite=-1,-1\n c2pread,c2pwrite=-1,-1\n errread,errwrite=-1,-1\n \n with self._on_error_fd_closer()as err_close_fds:\n if stdin is None:\n p2cread=_winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)\n if p2cread is None:\n p2cread,_=_winapi.CreatePipe(None,0)\n p2cread=Handle(p2cread)\n err_close_fds.append(p2cread)\n _winapi.CloseHandle(_)\n elif stdin ==PIPE:\n p2cread,p2cwrite=_winapi.CreatePipe(None,0)\n p2cread,p2cwrite=Handle(p2cread),Handle(p2cwrite)\n err_close_fds.extend((p2cread,p2cwrite))\n elif stdin ==DEVNULL:\n p2cread=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stdin,int):\n p2cread=msvcrt.get_osfhandle(stdin)\n else:\n \n p2cread=msvcrt.get_osfhandle(stdin.fileno())\n p2cread=self._make_inheritable(p2cread)\n \n if stdout is None:\n c2pwrite=_winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)\n if c2pwrite is None:\n _,c2pwrite=_winapi.CreatePipe(None,0)\n c2pwrite=Handle(c2pwrite)\n err_close_fds.append(c2pwrite)\n _winapi.CloseHandle(_)\n elif stdout ==PIPE:\n c2pread,c2pwrite=_winapi.CreatePipe(None,0)\n c2pread,c2pwrite=Handle(c2pread),Handle(c2pwrite)\n err_close_fds.extend((c2pread,c2pwrite))\n elif stdout ==DEVNULL:\n c2pwrite=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stdout,int):\n c2pwrite=msvcrt.get_osfhandle(stdout)\n else:\n \n c2pwrite=msvcrt.get_osfhandle(stdout.fileno())\n c2pwrite=self._make_inheritable(c2pwrite)\n \n if stderr is None:\n errwrite=_winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)\n if errwrite is None:\n _,errwrite=_winapi.CreatePipe(None,0)\n errwrite=Handle(errwrite)\n err_close_fds.append(errwrite)\n _winapi.CloseHandle(_)\n elif stderr ==PIPE:\n errread,errwrite=_winapi.CreatePipe(None,0)\n errread,errwrite=Handle(errread),Handle(errwrite)\n err_close_fds.extend((errread,errwrite))\n elif stderr ==STDOUT:\n errwrite=c2pwrite\n elif stderr ==DEVNULL:\n errwrite=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stderr,int):\n errwrite=msvcrt.get_osfhandle(stderr)\n else:\n \n errwrite=msvcrt.get_osfhandle(stderr.fileno())\n errwrite=self._make_inheritable(errwrite)\n \n return(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n def _make_inheritable(self,handle):\n ''\n h=_winapi.DuplicateHandle(\n _winapi.GetCurrentProcess(),handle,\n _winapi.GetCurrentProcess(),0,1,\n _winapi.DUPLICATE_SAME_ACCESS)\n return Handle(h)\n \n \n def _filter_handle_list(self,handle_list):\n ''\n\n \n \n \n \n return list({handle for handle in handle_list\n if handle&0x3 !=0x3\n or _winapi.GetFileType(handle)!=\n _winapi.FILE_TYPE_CHAR})\n \n \n def _execute_child(self,args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n unused_restore_signals,\n unused_gid,unused_gids,unused_uid,\n unused_umask,\n unused_start_new_session,unused_process_group):\n ''\n \n assert not pass_fds,\"pass_fds not supported on Windows.\"\n \n if isinstance(args,str):\n pass\n elif isinstance(args,bytes):\n if shell:\n raise TypeError('bytes args is not allowed on Windows')\n args=list2cmdline([args])\n elif isinstance(args,os.PathLike):\n if shell:\n raise TypeError('path-like args is not allowed when '\n 'shell is true')\n args=list2cmdline([args])\n else:\n args=list2cmdline(args)\n \n if executable is not None:\n executable=os.fsdecode(executable)\n \n \n if startupinfo is None:\n startupinfo=STARTUPINFO()\n else:\n \n \n startupinfo=startupinfo.copy()\n \n use_std_handles=-1 not in(p2cread,c2pwrite,errwrite)\n if use_std_handles:\n startupinfo.dwFlags |=_winapi.STARTF_USESTDHANDLES\n startupinfo.hStdInput=p2cread\n startupinfo.hStdOutput=c2pwrite\n startupinfo.hStdError=errwrite\n \n attribute_list=startupinfo.lpAttributeList\n have_handle_list=bool(attribute_list and\n \"handle_list\"in attribute_list and\n attribute_list[\"handle_list\"])\n \n \n if have_handle_list or(use_std_handles and close_fds):\n if attribute_list is None:\n attribute_list=startupinfo.lpAttributeList={}\n handle_list=attribute_list[\"handle_list\"]=\\\n list(attribute_list.get(\"handle_list\",[]))\n \n if use_std_handles:\n handle_list +=[int(p2cread),int(c2pwrite),int(errwrite)]\n \n handle_list[:]=self._filter_handle_list(handle_list)\n \n if handle_list:\n if not close_fds:\n warnings.warn(\"startupinfo.lpAttributeList['handle_list'] \"\n \"overriding close_fds\",RuntimeWarning)\n \n \n \n \n close_fds=False\n \n if shell:\n startupinfo.dwFlags |=_winapi.STARTF_USESHOWWINDOW\n startupinfo.wShowWindow=_winapi.SW_HIDE\n if not executable:\n \n \n \n \n \n comspec=os.environ.get('ComSpec')\n if not comspec:\n system_root=os.environ.get('SystemRoot','')\n comspec=os.path.join(system_root,'System32','cmd.exe')\n if not os.path.isabs(comspec):\n raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set')\n if os.path.isabs(comspec):\n executable=comspec\n else:\n comspec=executable\n \n args='{} /c \"{}\"'.format(comspec,args)\n \n if cwd is not None:\n cwd=os.fsdecode(cwd)\n \n sys.audit(\"subprocess.Popen\",executable,args,cwd,env)\n \n \n try:\n hp,ht,pid,tid=_winapi.CreateProcess(executable,args,\n \n None,None,\n int(not close_fds),\n creationflags,\n env,\n cwd,\n startupinfo)\n finally:\n \n \n \n \n \n \n self._close_pipe_fds(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n self._child_created=True\n self._handle=Handle(hp)\n self.pid=pid\n _winapi.CloseHandle(ht)\n \n def _internal_poll(self,_deadstate=None,\n _WaitForSingleObject=_winapi.WaitForSingleObject,\n _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,\n _GetExitCodeProcess=_winapi.GetExitCodeProcess):\n ''\n\n\n\n\n\n \n if self.returncode is None:\n if _WaitForSingleObject(self._handle,0)==_WAIT_OBJECT_0:\n self.returncode=_GetExitCodeProcess(self._handle)\n return self.returncode\n \n \n def _wait(self,timeout):\n ''\n if timeout is None:\n timeout_millis=_winapi.INFINITE\n elif timeout <=0:\n timeout_millis=0\n else:\n timeout_millis=int(timeout *1000)\n if self.returncode is None:\n \n result=_winapi.WaitForSingleObject(self._handle,\n timeout_millis)\n if result ==_winapi.WAIT_TIMEOUT:\n raise TimeoutExpired(self.args,timeout)\n self.returncode=_winapi.GetExitCodeProcess(self._handle)\n return self.returncode\n \n \n def _readerthread(self,fh,buffer):\n buffer.append(fh.read())\n fh.close()\n \n \n def _communicate(self,input,endtime,orig_timeout):\n \n \n if self.stdout and not hasattr(self,\"_stdout_buff\"):\n self._stdout_buff=[]\n self.stdout_thread=\\\n threading.Thread(target=self._readerthread,\n args=(self.stdout,self._stdout_buff))\n self.stdout_thread.daemon=True\n self.stdout_thread.start()\n if self.stderr and not hasattr(self,\"_stderr_buff\"):\n self._stderr_buff=[]\n self.stderr_thread=\\\n threading.Thread(target=self._readerthread,\n args=(self.stderr,self._stderr_buff))\n self.stderr_thread.daemon=True\n self.stderr_thread.start()\n \n if self.stdin:\n self._stdin_write(input)\n \n \n \n \n if self.stdout is not None:\n self.stdout_thread.join(self._remaining_time(endtime))\n if self.stdout_thread.is_alive():\n raise TimeoutExpired(self.args,orig_timeout)\n if self.stderr is not None:\n self.stderr_thread.join(self._remaining_time(endtime))\n if self.stderr_thread.is_alive():\n raise TimeoutExpired(self.args,orig_timeout)\n \n \n \n stdout=None\n stderr=None\n if self.stdout:\n stdout=self._stdout_buff\n self.stdout.close()\n if self.stderr:\n stderr=self._stderr_buff\n self.stderr.close()\n \n \n stdout=stdout[0]if stdout else None\n stderr=stderr[0]if stderr else None\n \n return(stdout,stderr)\n \n def send_signal(self,sig):\n ''\n \n if self.returncode is not None:\n return\n if sig ==signal.SIGTERM:\n self.terminate()\n elif sig ==signal.CTRL_C_EVENT:\n os.kill(self.pid,signal.CTRL_C_EVENT)\n elif sig ==signal.CTRL_BREAK_EVENT:\n os.kill(self.pid,signal.CTRL_BREAK_EVENT)\n else:\n raise ValueError(\"Unsupported signal: {}\".format(sig))\n \n def terminate(self):\n ''\n \n if self.returncode is not None:\n return\n try:\n _winapi.TerminateProcess(self._handle,1)\n except PermissionError:\n \n \n rc=_winapi.GetExitCodeProcess(self._handle)\n if rc ==_winapi.STILL_ACTIVE:\n raise\n self.returncode=rc\n \n kill=terminate\n \n else:\n \n \n \n def _get_handles(self,stdin,stdout,stderr):\n ''\n\n \n p2cread,p2cwrite=-1,-1\n c2pread,c2pwrite=-1,-1\n errread,errwrite=-1,-1\n \n with self._on_error_fd_closer()as err_close_fds:\n if stdin is None:\n pass\n elif stdin ==PIPE:\n p2cread,p2cwrite=os.pipe()\n err_close_fds.extend((p2cread,p2cwrite))\n if self.pipesize >0 and hasattr(fcntl,\"F_SETPIPE_SZ\"):\n fcntl.fcntl(p2cwrite,fcntl.F_SETPIPE_SZ,self.pipesize)\n elif stdin ==DEVNULL:\n p2cread=self._get_devnull()\n elif isinstance(stdin,int):\n p2cread=stdin\n else:\n \n p2cread=stdin.fileno()\n \n if stdout is None:\n pass\n elif stdout ==PIPE:\n c2pread,c2pwrite=os.pipe()\n err_close_fds.extend((c2pread,c2pwrite))\n if self.pipesize >0 and hasattr(fcntl,\"F_SETPIPE_SZ\"):\n fcntl.fcntl(c2pwrite,fcntl.F_SETPIPE_SZ,self.pipesize)\n elif stdout ==DEVNULL:\n c2pwrite=self._get_devnull()\n elif isinstance(stdout,int):\n c2pwrite=stdout\n else:\n \n c2pwrite=stdout.fileno()\n \n if stderr is None:\n pass\n elif stderr ==PIPE:\n errread,errwrite=os.pipe()\n err_close_fds.extend((errread,errwrite))\n if self.pipesize >0 and hasattr(fcntl,\"F_SETPIPE_SZ\"):\n fcntl.fcntl(errwrite,fcntl.F_SETPIPE_SZ,self.pipesize)\n elif stderr ==STDOUT:\n if c2pwrite !=-1:\n errwrite=c2pwrite\n else:\n errwrite=sys.__stdout__.fileno()\n elif stderr ==DEVNULL:\n errwrite=self._get_devnull()\n elif isinstance(stderr,int):\n errwrite=stderr\n else:\n \n errwrite=stderr.fileno()\n \n return(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n def _posix_spawn(self,args,executable,env,restore_signals,close_fds,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite):\n ''\n kwargs={}\n if restore_signals:\n \n sigset=[]\n for signame in('SIGPIPE','SIGXFZ','SIGXFSZ'):\n signum=getattr(signal,signame,None)\n if signum is not None:\n sigset.append(signum)\n kwargs['setsigdef']=sigset\n \n file_actions=[]\n for fd in(p2cwrite,c2pread,errread):\n if fd !=-1:\n file_actions.append((os.POSIX_SPAWN_CLOSE,fd))\n for fd,fd2 in(\n (p2cread,0),\n (c2pwrite,1),\n (errwrite,2),\n ):\n if fd !=-1:\n file_actions.append((os.POSIX_SPAWN_DUP2,fd,fd2))\n \n if close_fds:\n file_actions.append((os.POSIX_SPAWN_CLOSEFROM,3))\n \n if file_actions:\n kwargs['file_actions']=file_actions\n \n self.pid=os.posix_spawn(executable,args,env,**kwargs)\n self._child_created=True\n \n self._close_pipe_fds(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n def _execute_child(self,args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n restore_signals,\n gid,gids,uid,umask,\n start_new_session,process_group):\n ''\n \n if isinstance(args,(str,bytes)):\n args=[args]\n elif isinstance(args,os.PathLike):\n if shell:\n raise TypeError('path-like args is not allowed when '\n 'shell is true')\n args=[args]\n else:\n args=list(args)\n \n if shell:\n \n unix_shell=('/system/bin/sh'if\n hasattr(sys,'getandroidapilevel')else '/bin/sh')\n args=[unix_shell,\"-c\"]+args\n if executable:\n args[0]=executable\n \n if executable is None:\n executable=args[0]\n \n sys.audit(\"subprocess.Popen\",executable,args,cwd,env)\n \n if(_USE_POSIX_SPAWN\n and os.path.dirname(executable)\n and preexec_fn is None\n and(not close_fds or _HAVE_POSIX_SPAWN_CLOSEFROM)\n and not pass_fds\n and cwd is None\n and(p2cread ==-1 or p2cread >2)\n and(c2pwrite ==-1 or c2pwrite >2)\n and(errwrite ==-1 or errwrite >2)\n and not start_new_session\n and process_group ==-1\n and gid is None\n and gids is None\n and uid is None\n and umask <0):\n self._posix_spawn(args,executable,env,restore_signals,close_fds,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n return\n \n orig_executable=executable\n \n \n \n \n errpipe_read,errpipe_write=os.pipe()\n \n low_fds_to_close=[]\n while errpipe_write <3:\n low_fds_to_close.append(errpipe_write)\n errpipe_write=os.dup(errpipe_write)\n for low_fd in low_fds_to_close:\n os.close(low_fd)\n try:\n try:\n \n \n \n \n \n if env is not None:\n env_list=[]\n for k,v in env.items():\n k=os.fsencode(k)\n if b'='in k:\n raise ValueError(\"illegal environment variable name\")\n env_list.append(k+b'='+os.fsencode(v))\n else:\n env_list=None\n executable=os.fsencode(executable)\n if os.path.dirname(executable):\n executable_list=(executable,)\n else:\n \n executable_list=tuple(\n os.path.join(os.fsencode(dir),executable)\n for dir in os.get_exec_path(env))\n fds_to_keep=set(pass_fds)\n fds_to_keep.add(errpipe_write)\n self.pid=_fork_exec(\n args,executable_list,\n close_fds,tuple(sorted(map(int,fds_to_keep))),\n cwd,env_list,\n p2cread,p2cwrite,c2pread,c2pwrite,\n errread,errwrite,\n errpipe_read,errpipe_write,\n restore_signals,start_new_session,\n process_group,gid,gids,uid,umask,\n preexec_fn,_USE_VFORK)\n self._child_created=True\n finally:\n \n os.close(errpipe_write)\n \n self._close_pipe_fds(p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n \n errpipe_data=bytearray()\n while True:\n part=os.read(errpipe_read,50000)\n errpipe_data +=part\n if not part or len(errpipe_data)>50000:\n break\n finally:\n \n os.close(errpipe_read)\n \n if errpipe_data:\n try:\n pid,sts=os.waitpid(self.pid,0)\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n else:\n self.returncode=sys.maxsize\n except ChildProcessError:\n pass\n \n try:\n exception_name,hex_errno,err_msg=(\n errpipe_data.split(b':',2))\n \n \n \n err_msg=err_msg.decode()\n except ValueError:\n exception_name=b'SubprocessError'\n hex_errno=b'0'\n err_msg='Bad exception data from child: {!r}'.format(\n bytes(errpipe_data))\n child_exception_type=getattr(\n builtins,exception_name.decode('ascii'),\n SubprocessError)\n if issubclass(child_exception_type,OSError)and hex_errno:\n errno_num=int(hex_errno,16)\n if err_msg ==\"noexec:chdir\":\n err_msg=\"\"\n \n err_filename=cwd\n elif err_msg ==\"noexec\":\n err_msg=\"\"\n err_filename=None\n else:\n err_filename=orig_executable\n if errno_num !=0:\n err_msg=os.strerror(errno_num)\n if err_filename is not None:\n raise child_exception_type(errno_num,err_msg,err_filename)\n else:\n raise child_exception_type(errno_num,err_msg)\n raise child_exception_type(err_msg)\n \n \n def _handle_exitstatus(self,sts,_del_safe=_del_safe):\n ''\n \n \n if _del_safe.WIFSTOPPED(sts):\n self.returncode=-_del_safe.WSTOPSIG(sts)\n else:\n self.returncode=_del_safe.waitstatus_to_exitcode(sts)\n \n def _internal_poll(self,_deadstate=None,_del_safe=_del_safe):\n ''\n\n\n\n\n\n \n if self.returncode is None:\n if not self._waitpid_lock.acquire(False):\n \n \n return None\n try:\n if self.returncode is not None:\n return self.returncode\n pid,sts=_del_safe.waitpid(self.pid,_del_safe.WNOHANG)\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n except OSError as e:\n if _deadstate is not None:\n self.returncode=_deadstate\n elif e.errno ==_del_safe.ECHILD:\n \n \n \n \n \n self.returncode=0\n finally:\n self._waitpid_lock.release()\n return self.returncode\n \n \n def _try_wait(self,wait_flags):\n ''\n try:\n (pid,sts)=os.waitpid(self.pid,wait_flags)\n except ChildProcessError:\n \n \n \n pid=self.pid\n sts=0\n return(pid,sts)\n \n \n def _wait(self,timeout):\n ''\n if self.returncode is not None:\n return self.returncode\n \n if timeout is not None:\n endtime=_time()+timeout\n \n \n delay=0.0005\n while True:\n if self._waitpid_lock.acquire(False):\n try:\n if self.returncode is not None:\n break\n (pid,sts)=self._try_wait(os.WNOHANG)\n assert pid ==self.pid or pid ==0\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n break\n finally:\n self._waitpid_lock.release()\n remaining=self._remaining_time(endtime)\n if remaining <=0:\n raise TimeoutExpired(self.args,timeout)\n delay=min(delay *2,remaining,.05)\n time.sleep(delay)\n else:\n while self.returncode is None:\n with self._waitpid_lock:\n if self.returncode is not None:\n break\n (pid,sts)=self._try_wait(0)\n \n \n \n if pid ==self.pid:\n self._handle_exitstatus(sts)\n return self.returncode\n \n \n def _communicate(self,input,endtime,orig_timeout):\n if self.stdin and not self._communication_started:\n \n \n try:\n self.stdin.flush()\n except BrokenPipeError:\n pass\n if not input:\n try:\n self.stdin.close()\n except BrokenPipeError:\n pass\n \n stdout=None\n stderr=None\n \n \n if not self._communication_started:\n self._fileobj2output={}\n if self.stdout:\n self._fileobj2output[self.stdout]=[]\n if self.stderr:\n self._fileobj2output[self.stderr]=[]\n \n if self.stdout:\n stdout=self._fileobj2output[self.stdout]\n if self.stderr:\n stderr=self._fileobj2output[self.stderr]\n \n self._save_input(input)\n \n if self._input:\n input_view=memoryview(self._input)\n \n with _PopenSelector()as selector:\n if self.stdin and input:\n selector.register(self.stdin,selectors.EVENT_WRITE)\n if self.stdout and not self.stdout.closed:\n selector.register(self.stdout,selectors.EVENT_READ)\n if self.stderr and not self.stderr.closed:\n selector.register(self.stderr,selectors.EVENT_READ)\n \n while selector.get_map():\n timeout=self._remaining_time(endtime)\n if timeout is not None and timeout <0:\n self._check_timeout(endtime,orig_timeout,\n stdout,stderr,\n skip_check_and_raise=True)\n raise RuntimeError(\n '_check_timeout(..., skip_check_and_raise=True) '\n 'failed to raise TimeoutExpired.')\n \n ready=selector.select(timeout)\n self._check_timeout(endtime,orig_timeout,stdout,stderr)\n \n \n \n \n for key,events in ready:\n if key.fileobj is self.stdin:\n chunk=input_view[self._input_offset:\n self._input_offset+_PIPE_BUF]\n try:\n self._input_offset +=os.write(key.fd,chunk)\n except BrokenPipeError:\n selector.unregister(key.fileobj)\n key.fileobj.close()\n else:\n if self._input_offset >=len(self._input):\n selector.unregister(key.fileobj)\n key.fileobj.close()\n elif key.fileobj in(self.stdout,self.stderr):\n data=os.read(key.fd,32768)\n if not data:\n selector.unregister(key.fileobj)\n key.fileobj.close()\n self._fileobj2output[key.fileobj].append(data)\n \n self.wait(timeout=self._remaining_time(endtime))\n \n \n if stdout is not None:\n stdout=b''.join(stdout)\n if stderr is not None:\n stderr=b''.join(stderr)\n \n \n \n if self.text_mode:\n if stdout is not None:\n stdout=self._translate_newlines(stdout,\n self.stdout.encoding,\n self.stdout.errors)\n if stderr is not None:\n stderr=self._translate_newlines(stderr,\n self.stderr.encoding,\n self.stderr.errors)\n \n return(stdout,stderr)\n \n \n def _save_input(self,input):\n \n \n \n if self.stdin and self._input is None:\n self._input_offset=0\n self._input=input\n if input is not None and self.text_mode:\n self._input=self._input.encode(self.stdin.encoding,\n self.stdin.errors)\n \n \n def send_signal(self,sig):\n ''\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n self.poll()\n if self.returncode is not None:\n \n return\n \n \n \n \n try:\n os.kill(self.pid,sig)\n except ProcessLookupError:\n \n pass\n \n def terminate(self):\n ''\n \n self.send_signal(signal.SIGTERM)\n \n def kill(self):\n ''\n \n self.send_signal(signal.SIGKILL)\n", ["_posixsubprocess", "_winapi", "builtins", "contextlib", "errno", "fcntl", "grp", "io", "locale", "msvcrt", "os", "pwd", "select", "selectors", "signal", "sys", "threading", "time", "types", "warnings"]], "symtable": [".py", "''\n\nimport _symtable\nfrom _symtable import(USE,DEF_GLOBAL,DEF_NONLOCAL,DEF_LOCAL,DEF_PARAM,\nDEF_IMPORT,DEF_BOUND,DEF_ANNOT,SCOPE_OFF,SCOPE_MASK,FREE,\nLOCAL,GLOBAL_IMPLICIT,GLOBAL_EXPLICIT,CELL)\n\nimport weakref\nfrom enum import StrEnum\n\n__all__=[\"symtable\",\"SymbolTableType\",\"SymbolTable\",\"Class\",\"Function\",\"Symbol\"]\n\ndef symtable(code,filename,compile_type):\n ''\n\n\n\n \n top=_symtable.symtable(code,filename,compile_type)\n return _newSymbolTable(top,filename)\n \nclass SymbolTableFactory:\n def __init__(self):\n self.__memo=weakref.WeakValueDictionary()\n \n def new(self,table,filename):\n if table.type ==_symtable.TYPE_FUNCTION:\n return Function(table,filename)\n if table.type ==_symtable.TYPE_CLASS:\n return Class(table,filename)\n return SymbolTable(table,filename)\n \n def __call__(self,table,filename):\n key=table,filename\n obj=self.__memo.get(key,None)\n if obj is None:\n obj=self.__memo[key]=self.new(table,filename)\n return obj\n \n_newSymbolTable=SymbolTableFactory()\n\n\nclass SymbolTableType(StrEnum):\n MODULE=\"module\"\n FUNCTION=\"function\"\n CLASS=\"class\"\n ANNOTATION=\"annotation\"\n TYPE_ALIAS=\"type alias\"\n TYPE_PARAMETERS=\"type parameters\"\n TYPE_VARIABLE=\"type variable\"\n \n \nclass SymbolTable:\n\n def __init__(self,raw_table,filename):\n self._table=raw_table\n self._filename=filename\n self._symbols={}\n \n def __repr__(self):\n if self.__class__ ==SymbolTable:\n kind=\"\"\n else:\n kind=\"%s \"%self.__class__.__name__\n \n if self._table.name ==\"top\":\n return \"<{0}SymbolTable for module {1}>\".format(kind,self._filename)\n else:\n return \"<{0}SymbolTable for {1} in {2}>\".format(kind,\n self._table.name,\n self._filename)\n \n def get_type(self):\n ''\n\n\n\n \n if self._table.type ==_symtable.TYPE_MODULE:\n return SymbolTableType.MODULE\n if self._table.type ==_symtable.TYPE_FUNCTION:\n return SymbolTableType.FUNCTION\n if self._table.type ==_symtable.TYPE_CLASS:\n return SymbolTableType.CLASS\n if self._table.type ==_symtable.TYPE_ANNOTATION:\n return SymbolTableType.ANNOTATION\n if self._table.type ==_symtable.TYPE_TYPE_ALIAS:\n return SymbolTableType.TYPE_ALIAS\n if self._table.type ==_symtable.TYPE_TYPE_PARAMETERS:\n return SymbolTableType.TYPE_PARAMETERS\n if self._table.type ==_symtable.TYPE_TYPE_VARIABLE:\n return SymbolTableType.TYPE_VARIABLE\n assert False,f\"unexpected type: {self._table.type}\"\n \n def get_id(self):\n ''\n \n return self._table.id\n \n def get_name(self):\n ''\n\n\n\n\n \n return self._table.name\n \n def get_lineno(self):\n ''\n\n \n return self._table.lineno\n \n def is_optimized(self):\n ''\n\n \n return bool(self._table.type ==_symtable.TYPE_FUNCTION)\n \n def is_nested(self):\n ''\n \n return bool(self._table.nested)\n \n def has_children(self):\n ''\n \n return bool(self._table.children)\n \n def get_identifiers(self):\n ''\n \n return self._table.symbols.keys()\n \n def lookup(self,name):\n ''\n\n\n \n sym=self._symbols.get(name)\n if sym is None:\n flags=self._table.symbols[name]\n namespaces=self.__check_children(name)\n module_scope=(self._table.name ==\"top\")\n sym=self._symbols[name]=Symbol(name,flags,namespaces,\n module_scope=module_scope)\n return sym\n \n def get_symbols(self):\n ''\n\n \n return[self.lookup(ident)for ident in self.get_identifiers()]\n \n def __check_children(self,name):\n return[_newSymbolTable(st,self._filename)\n for st in self._table.children\n if st.name ==name]\n \n def get_children(self):\n ''\n \n return[_newSymbolTable(st,self._filename)\n for st in self._table.children]\n \n \nclass Function(SymbolTable):\n\n\n __params=None\n __locals=None\n __frees=None\n __globals=None\n __nonlocals=None\n \n def __idents_matching(self,test_func):\n return tuple(ident for ident in self.get_identifiers()\n if test_func(self._table.symbols[ident]))\n \n def get_parameters(self):\n ''\n \n if self.__params is None:\n self.__params=self.__idents_matching(lambda x:x&DEF_PARAM)\n return self.__params\n \n def get_locals(self):\n ''\n \n if self.__locals is None:\n locs=(LOCAL,CELL)\n test=lambda x:((x >>SCOPE_OFF)&SCOPE_MASK)in locs\n self.__locals=self.__idents_matching(test)\n return self.__locals\n \n def get_globals(self):\n ''\n \n if self.__globals is None:\n glob=(GLOBAL_IMPLICIT,GLOBAL_EXPLICIT)\n test=lambda x:((x >>SCOPE_OFF)&SCOPE_MASK)in glob\n self.__globals=self.__idents_matching(test)\n return self.__globals\n \n def get_nonlocals(self):\n ''\n \n if self.__nonlocals is None:\n self.__nonlocals=self.__idents_matching(lambda x:x&DEF_NONLOCAL)\n return self.__nonlocals\n \n def get_frees(self):\n ''\n \n if self.__frees is None:\n is_free=lambda x:((x >>SCOPE_OFF)&SCOPE_MASK)==FREE\n self.__frees=self.__idents_matching(is_free)\n return self.__frees\n \n \nclass Class(SymbolTable):\n\n __methods=None\n \n def get_methods(self):\n ''\n \n if self.__methods is None:\n d={}\n \n def is_local_symbol(ident):\n flags=self._table.symbols.get(ident,0)\n return((flags >>SCOPE_OFF)&SCOPE_MASK)==LOCAL\n \n for st in self._table.children:\n \n if is_local_symbol(st.name):\n match st.type:\n case _symtable.TYPE_FUNCTION:\n \n \n \n if st.name =='genexpr'and '.0'in st.varnames:\n continue\n d[st.name]=1\n case _symtable.TYPE_TYPE_PARAMETERS:\n \n \n scope_name=st.name\n for c in st.children:\n if c.name ==scope_name and c.type ==_symtable.TYPE_FUNCTION:\n \n \n \n \n \n \n assert scope_name !='genexpr'or '.0'not in c.varnames\n d[scope_name]=1\n break\n self.__methods=tuple(d)\n return self.__methods\n \n \nclass Symbol:\n\n def __init__(self,name,flags,namespaces=None,*,module_scope=False):\n self.__name=name\n self.__flags=flags\n self.__scope=(flags >>SCOPE_OFF)&SCOPE_MASK\n self.__namespaces=namespaces or()\n self.__module_scope=module_scope\n \n def __repr__(self):\n flags_str='|'.join(self._flags_str())\n return f''\n \n def _scope_str(self):\n return _scopes_value_to_name.get(self.__scope)or str(self.__scope)\n \n def _flags_str(self):\n for flagname,flagvalue in _flags:\n if self.__flags&flagvalue ==flagvalue:\n yield flagname\n \n def get_name(self):\n ''\n \n return self.__name\n \n def is_referenced(self):\n ''\n\n \n return bool(self.__flags&_symtable.USE)\n \n def is_parameter(self):\n ''\n \n return bool(self.__flags&DEF_PARAM)\n \n def is_global(self):\n ''\n \n return bool(self.__scope in(GLOBAL_IMPLICIT,GLOBAL_EXPLICIT)\n or(self.__module_scope and self.__flags&DEF_BOUND))\n \n def is_nonlocal(self):\n ''\n return bool(self.__flags&DEF_NONLOCAL)\n \n def is_declared_global(self):\n ''\n \n return bool(self.__scope ==GLOBAL_EXPLICIT)\n \n def is_local(self):\n ''\n \n return bool(self.__scope in(LOCAL,CELL)\n or(self.__module_scope and self.__flags&DEF_BOUND))\n \n def is_annotated(self):\n ''\n \n return bool(self.__flags&DEF_ANNOT)\n \n def is_free(self):\n ''\n\n \n return bool(self.__scope ==FREE)\n \n def is_imported(self):\n ''\n\n \n return bool(self.__flags&DEF_IMPORT)\n \n def is_assigned(self):\n ''\n return bool(self.__flags&DEF_LOCAL)\n \n def is_namespace(self):\n ''\n\n\n\n\n\n\n\n\n \n return bool(self.__namespaces)\n \n def get_namespaces(self):\n ''\n return self.__namespaces\n \n def get_namespace(self):\n ''\n\n\n\n \n if len(self.__namespaces)==0:\n raise ValueError(\"name is not bound to any namespaces\")\n elif len(self.__namespaces)>1:\n raise ValueError(\"name is bound to multiple namespaces\")\n else:\n return self.__namespaces[0]\n \n \n_flags=[('USE',USE)]\n_flags.extend(kv for kv in globals().items()if kv[0].startswith('DEF_'))\n_scopes_names=('FREE','LOCAL','GLOBAL_IMPLICIT','GLOBAL_EXPLICIT','CELL')\n_scopes_value_to_name={globals()[n]:n for n in _scopes_names}\n\n\ndef main(args):\n import sys\n def print_symbols(table,level=0):\n indent=' '*level\n nested=\"nested \"if table.is_nested()else \"\"\n if table.get_type()=='module':\n what=f'from file {table._filename !r}'\n else:\n what=f'{table.get_name()!r}'\n print(f'{indent}symbol table for {nested}{table.get_type()} {what}:')\n for ident in table.get_identifiers():\n symbol=table.lookup(ident)\n flags=', '.join(symbol._flags_str()).lower()\n print(f' {indent}{symbol._scope_str().lower()} symbol {symbol.get_name()!r}: {flags}')\n print()\n \n for table2 in table.get_children():\n print_symbols(table2,level+1)\n \n for filename in args or['-']:\n if filename =='-':\n src=sys.stdin.read()\n filename=''\n else:\n with open(filename,'rb')as f:\n src=f.read()\n mod=symtable(src,filename,'exec')\n print_symbols(mod)\n \n \nif __name__ ==\"__main__\":\n import sys\n main(sys.argv[1:])\n", ["_symtable", "enum", "sys", "weakref"]], "sys": [".py", "\nfrom _sys import *\nimport _sys\n\n_getframe=_sys._getframe\n\nclass _dataclass(tuple):\n\n def __init__(self,**kwargs):\n self.keys=list(kwargs)\n self.__dict__.update(kwargs)\n \n def __getitem__(self,key):\n if isinstance(key,int)and 0 <=key <=len(self.keys):\n return self.__dict__[self.keys[key]]\n elif isinstance(key,slice):\n return[self.__dict__[k]for k in self.keys[key]]\n raise KeyError(key)\n \n def __iter__(self):\n return(self.__dict__[key]for key in self.keys)\n \n def __len__(self):\n return len(self.keys)\n \n def __repr__(self):\n s=', '.join(f'{k}={self.__dict__[k]!r}'for k in self.keys)\n return f'sys.{self.__class__.__name__}({s})'\n \n \ndef make_dataclass(name,bases=None):\n bases=[_dataclass]if bases is None else[*bases,_dataclass]\n cls=type(name,bases,{})\n return cls\n \n \n__breakpointhook__=breakpointhook\n\nabiflags=0\n\ndef audit(event,*args):\n ''\n pass\n \nbrython_debug_mode=__BRYTHON__.get_option('debug')\n\nbase_exec_prefix=__BRYTHON__.brython_path\n\nbase_prefix=__BRYTHON__.brython_path\n\nbuiltin_module_names=__BRYTHON__.builtin_module_names\n\nbyteorder='little'\n\ncopyright=\"\"\"Copyright (c) 2001-2023 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.\"\"\"\n\ndont_write_bytecode=True\n\nexec_prefix=__BRYTHON__.brython_path\n\nargv=orig_argv=[__BRYTHON__.script_path]+list(__BRYTHON__.get_option('args'))\n\ndef displayhook(value):\n if value is not None:\n stdout.write(repr(value))\n \n__displayhook__=displayhook\n\ndef exit(i=None):\n raise SystemExit('')\n \nflags=make_dataclass('flags')(\ndebug=0,\ninspect=0,\ninteractive=0,\noptimize=0,\ndont_write_bytecode=0,\nno_user_site=0,\nno_site=0,\nignore_environment=0,\nverbose=0,\nbytes_warning=0,\nquiet=0,\nhash_randomization=1,\nisolated=0,\ndev_mode=False,\nutf8_mode=0,\nwarn_default_encoding=0\n)\n\ndef getfilesystemencoding(*args,**kw):\n ''\n\n \n return 'utf-8'\n \ndef getfilesystemencodeerrors():\n return \"utf-8\"\n \ndef intern(string):\n return string\n \nint_info=make_dataclass('int_info')(\nbits_per_digit=30,\nsizeof_digit=4,\ndefault_max_str_digits=__BRYTHON__.int_max_str_digits,\nstr_digits_check_threshold=__BRYTHON__.str_digits_check_threshold)\n\ndef get_int_max_str_digits():\n return __BRYTHON__.int_max_str_digits\n \ndef set_int_max_str_digits(value):\n try:\n value=int(value)\n except:\n raise ValueError(f\"'{value.__class__.__name__}' object \"\n \"cannot be interpreted as an integer\")\n if value !=0 and value =other\n \n return NotImplemented\n \n def __gt__(self,other):\n if isinstance(other,tuple):\n return(self.major,self.minor,self.micro)>other\n \n return NotImplemented\n \n def __le__(self,other):\n if isinstance(other,tuple):\n return(self.major,self.minor,self.micro)<=other\n \n return NotImplemented\n \n def __lt__(self,other):\n if isinstance(other,tuple):\n return(self.major,self.minor,self.micro)0:\n for name in tuple(variables):\n value=notdone[name]\n m1=re.search(_findvar1_rx,value)\n m2=re.search(_findvar2_rx,value)\n if m1 and m2:\n m=m1 if m1.start()=\"5\":\n osname=\"solaris\"\n release=f\"{int(release[0])-3}.{release[2:]}\"\n \n \n \n bitness={2147483647:\"32bit\",9223372036854775807:\"64bit\"}\n machine +=f\".{bitness[sys.maxsize]}\"\n \n elif osname[:3]==\"aix\":\n from _aix_support import aix_platform\n return aix_platform()\n elif osname[:6]==\"cygwin\":\n osname=\"cygwin\"\n import re\n rel_re=re.compile(r'[\\d.]+')\n m=rel_re.match(release)\n if m:\n release=m.group()\n elif osname[:6]==\"darwin\":\n import _osx_support\n osname,release,machine=_osx_support.get_platform_osx(\n get_config_vars(),\n osname,release,machine)\n \n return f\"{osname}-{release}-{machine}\"\n \n \ndef get_python_version():\n return _PY_VERSION_SHORT\n \n \ndef expand_makefile_vars(s,vars):\n ''\n\n\n\n\n\n \n import re\n \n \n \n \n \n \n \n while True:\n m=re.search(_findvar1_rx,s)or re.search(_findvar2_rx,s)\n if m:\n (beg,end)=m.span()\n s=s[0:beg]+vars.get(m.group(1))+s[end:]\n else:\n break\n return s\n \n \ndef _print_dict(title,data):\n for index,(key,value)in enumerate(sorted(data.items())):\n if index ==0:\n print(f'{title}: ')\n print(f'\\t{key} = \"{value}\"')\n \n \ndef _main():\n ''\n if '--generate-posix-vars'in sys.argv:\n _generate_posix_vars()\n return\n print(f'Platform: \"{get_platform()}\"')\n print(f'Python version: \"{get_python_version()}\"')\n print(f'Current installation scheme: \"{get_default_scheme()}\"')\n print()\n _print_dict('Paths',get_paths())\n print()\n _print_dict('Variables',get_config_vars())\n \n \nif __name__ =='__main__':\n _main()\n", ["_aix_support", "_imp", "_osx_support", "os", "os.path", "pprint", "re", "sys", "threading", "types", "warnings"]], "tabnanny": [".py", "#! /usr/bin/env python3\n\n\"\"\"The Tab Nanny despises ambiguous indentation. She knows no mercy.\n\ntabnanny -- Detection of ambiguous indentation\n\nFor the time being this module is intended to be called as a script.\nHowever it is possible to import it into an IDE and use the function\ncheck() described below.\n\nWarning: The API provided by this module is likely to change in future\nreleases; such changes may not be backward compatible.\n\"\"\"\n\n\n\n\n\n\n\n__version__=\"6\"\n\nimport os\nimport sys\nimport tokenize\n\n__all__=[\"check\",\"NannyNag\",\"process_tokens\"]\n\nverbose=0\nfilename_only=0\n\ndef errprint(*args):\n sep=\"\"\n for arg in args:\n sys.stderr.write(sep+str(arg))\n sep=\" \"\n sys.stderr.write(\"\\n\")\n sys.exit(1)\n \ndef main():\n import getopt\n \n global verbose,filename_only\n try:\n opts,args=getopt.getopt(sys.argv[1:],\"qv\")\n except getopt.error as msg:\n errprint(msg)\n for o,a in opts:\n if o =='-q':\n filename_only=filename_only+1\n if o =='-v':\n verbose=verbose+1\n if not args:\n errprint(\"Usage:\",sys.argv[0],\"[-v] file_or_directory ...\")\n for arg in args:\n check(arg)\n \nclass NannyNag(Exception):\n ''\n\n\n \n def __init__(self,lineno,msg,line):\n self.lineno,self.msg,self.line=lineno,msg,line\n def get_lineno(self):\n return self.lineno\n def get_msg(self):\n return self.msg\n def get_line(self):\n return self.line\n \ndef check(file):\n ''\n\n\n\n\n\n\n \n \n if os.path.isdir(file)and not os.path.islink(file):\n if verbose:\n print(\"%r: listing directory\"%(file,))\n names=os.listdir(file)\n for name in names:\n fullname=os.path.join(file,name)\n if(os.path.isdir(fullname)and\n not os.path.islink(fullname)or\n os.path.normcase(name[-3:])==\".py\"):\n check(fullname)\n return\n \n try:\n f=tokenize.open(file)\n except OSError as msg:\n errprint(\"%r: I/O Error: %s\"%(file,msg))\n return\n \n if verbose >1:\n print(\"checking %r ...\"%file)\n \n try:\n process_tokens(tokenize.generate_tokens(f.readline))\n \n except tokenize.TokenError as msg:\n errprint(\"%r: Token Error: %s\"%(file,msg))\n return\n \n except SyntaxError as msg:\n errprint(\"%r: Token Error: %s\"%(file,msg))\n return\n \n except IndentationError as msg:\n errprint(\"%r: Indentation Error: %s\"%(file,msg))\n return\n \n except NannyNag as nag:\n badline=nag.get_lineno()\n line=nag.get_line()\n if verbose:\n print(\"%r: *** Line %d: trouble in tab city! ***\"%(file,badline))\n print(\"offending line: %r\"%(line,))\n print(nag.get_msg())\n else:\n if ' 'in file:file='\"'+file+'\"'\n if filename_only:print(file)\n else:print(file,badline,repr(line))\n return\n \n finally:\n f.close()\n \n if verbose:\n print(\"%r: Clean bill of health.\"%(file,))\n \nclass Whitespace:\n\n S,T=' \\t'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def __init__(self,ws):\n self.raw=ws\n S,T=Whitespace.S,Whitespace.T\n count=[]\n b=n=nt=0\n for ch in self.raw:\n if ch ==S:\n n=n+1\n b=b+1\n elif ch ==T:\n n=n+1\n nt=nt+1\n if b >=len(count):\n count=count+[0]*(b -len(count)+1)\n count[b]=count[b]+1\n b=0\n else:\n break\n self.n=n\n self.nt=nt\n self.norm=tuple(count),b\n self.is_simple=len(count)<=1\n \n \n \n def longest_run_of_spaces(self):\n count,trailing=self.norm\n return max(len(count)-1,trailing)\n \n def indent_level(self,tabsize):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n count,trailing=self.norm\n il=0\n for i in range(tabsize,len(count)):\n il=il+i //tabsize *count[i]\n return trailing+tabsize *(il+self.nt)\n \n \n \n def equal(self,other):\n return self.norm ==other.norm\n \n \n \n \n \n def not_equal_witness(self,other):\n n=max(self.longest_run_of_spaces(),\n other.longest_run_of_spaces())+1\n a=[]\n for ts in range(1,n+1):\n if self.indent_level(ts)!=other.indent_level(ts):\n a.append((ts,\n self.indent_level(ts),\n other.indent_level(ts)))\n return a\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def less(self,other):\n if self.n >=other.n:\n return False\n if self.is_simple and other.is_simple:\n return self.nt <=other.nt\n n=max(self.longest_run_of_spaces(),\n other.longest_run_of_spaces())+1\n \n for ts in range(2,n+1):\n if self.indent_level(ts)>=other.indent_level(ts):\n return False\n return True\n \n \n \n \n \n def not_less_witness(self,other):\n n=max(self.longest_run_of_spaces(),\n other.longest_run_of_spaces())+1\n a=[]\n for ts in range(1,n+1):\n if self.indent_level(ts)>=other.indent_level(ts):\n a.append((ts,\n self.indent_level(ts),\n other.indent_level(ts)))\n return a\n \ndef format_witnesses(w):\n firsts=(str(tup[0])for tup in w)\n prefix=\"at tab size\"\n if len(w)>1:\n prefix=prefix+\"s\"\n return prefix+\" \"+', '.join(firsts)\n \ndef process_tokens(tokens):\n try:\n _process_tokens(tokens)\n except TabError as e:\n raise NannyNag(e.lineno,e.msg,e.text)\n \ndef _process_tokens(tokens):\n INDENT=tokenize.INDENT\n DEDENT=tokenize.DEDENT\n NEWLINE=tokenize.NEWLINE\n JUNK=tokenize.COMMENT,tokenize.NL\n indents=[Whitespace(\"\")]\n check_equal=0\n \n for(type,token,start,end,line)in tokens:\n if type ==NEWLINE:\n \n \n \n \n \n check_equal=1\n \n elif type ==INDENT:\n check_equal=0\n thisguy=Whitespace(token)\n if not indents[-1].less(thisguy):\n witness=indents[-1].not_less_witness(thisguy)\n msg=\"indent not greater e.g. \"+format_witnesses(witness)\n raise NannyNag(start[0],msg,line)\n indents.append(thisguy)\n \n elif type ==DEDENT:\n \n \n \n \n \n \n \n \n \n check_equal=1\n \n del indents[-1]\n \n elif check_equal and type not in JUNK:\n \n \n \n \n \n \n check_equal=0\n thisguy=Whitespace(line)\n if not indents[-1].equal(thisguy):\n witness=indents[-1].not_equal_witness(thisguy)\n msg=\"indent not equal e.g. \"+format_witnesses(witness)\n raise NannyNag(start[0],msg,line)\n \n \nif __name__ =='__main__':\n main()\n", ["getopt", "os", "sys", "tokenize"]], "tarfile": [".py", "#!/usr/bin/env python3\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n''\n\n\nversion=\"0.9.0\"\n__author__=\"Lars Gust\\u00e4bel (lars@gustaebel.de)\"\n__credits__=\"Gustavo Niemeyer, Niels Gust\\u00e4bel, Richard Townsend.\"\n\n\n\n\nfrom builtins import open as bltn_open\nimport sys\nimport os\nimport io\nimport shutil\nimport stat\nimport time\nimport struct\nimport copy\nimport re\n\ntry:\n import pwd\nexcept ImportError:\n pwd=None\ntry:\n import grp\nexcept ImportError:\n grp=None\n \n \n \n \nsymlink_exception=(AttributeError,NotImplementedError,OSError)\n\n\n__all__=[\"TarFile\",\"TarInfo\",\"is_tarfile\",\"TarError\",\"ReadError\",\n\"CompressionError\",\"StreamError\",\"ExtractError\",\"HeaderError\",\n\"ENCODING\",\"USTAR_FORMAT\",\"GNU_FORMAT\",\"PAX_FORMAT\",\n\"DEFAULT_FORMAT\",\"open\",\"fully_trusted_filter\",\"data_filter\",\n\"tar_filter\",\"FilterError\",\"AbsoluteLinkError\",\n\"OutsideDestinationError\",\"SpecialFileError\",\"AbsolutePathError\",\n\"LinkOutsideDestinationError\"]\n\n\n\n\n\nNUL=b\"\\0\"\nBLOCKSIZE=512\nRECORDSIZE=BLOCKSIZE *20\nGNU_MAGIC=b\"ustar \\0\"\nPOSIX_MAGIC=b\"ustar\\x0000\"\n\nLENGTH_NAME=100\nLENGTH_LINK=100\nLENGTH_PREFIX=155\n\nREGTYPE=b\"0\"\nAREGTYPE=b\"\\0\"\nLNKTYPE=b\"1\"\nSYMTYPE=b\"2\"\nCHRTYPE=b\"3\"\nBLKTYPE=b\"4\"\nDIRTYPE=b\"5\"\nFIFOTYPE=b\"6\"\nCONTTYPE=b\"7\"\n\nGNUTYPE_LONGNAME=b\"L\"\nGNUTYPE_LONGLINK=b\"K\"\nGNUTYPE_SPARSE=b\"S\"\n\nXHDTYPE=b\"x\"\nXGLTYPE=b\"g\"\nSOLARIS_XHDTYPE=b\"X\"\n\nUSTAR_FORMAT=0\nGNU_FORMAT=1\nPAX_FORMAT=2\nDEFAULT_FORMAT=PAX_FORMAT\n\n\n\n\n\nSUPPORTED_TYPES=(REGTYPE,AREGTYPE,LNKTYPE,\nSYMTYPE,DIRTYPE,FIFOTYPE,\nCONTTYPE,CHRTYPE,BLKTYPE,\nGNUTYPE_LONGNAME,GNUTYPE_LONGLINK,\nGNUTYPE_SPARSE)\n\n\nREGULAR_TYPES=(REGTYPE,AREGTYPE,\nCONTTYPE,GNUTYPE_SPARSE)\n\n\nGNU_TYPES=(GNUTYPE_LONGNAME,GNUTYPE_LONGLINK,\nGNUTYPE_SPARSE)\n\n\nPAX_FIELDS=(\"path\",\"linkpath\",\"size\",\"mtime\",\n\"uid\",\"gid\",\"uname\",\"gname\")\n\n\nPAX_NAME_FIELDS={\"path\",\"linkpath\",\"uname\",\"gname\"}\n\n\n\nPAX_NUMBER_FIELDS={\n\"atime\":float,\n\"ctime\":float,\n\"mtime\":float,\n\"uid\":int,\n\"gid\":int,\n\"size\":int\n}\n\n\n\n\nif os.name ==\"nt\":\n ENCODING=\"utf-8\"\nelse:\n ENCODING=sys.getfilesystemencoding()\n \n \n \n \n \ndef stn(s,length,encoding,errors):\n ''\n \n if s is None:\n raise ValueError(\"metadata cannot contain None\")\n s=s.encode(encoding,errors)\n return s[:length]+(length -len(s))*NUL\n \ndef nts(s,encoding,errors):\n ''\n \n p=s.find(b\"\\0\")\n if p !=-1:\n s=s[:p]\n return s.decode(encoding,errors)\n \ndef nti(s):\n ''\n \n \n \n if s[0]in(0o200,0o377):\n n=0\n for i in range(len(s)-1):\n n <<=8\n n +=s[i+1]\n if s[0]==0o377:\n n=-(256 **(len(s)-1)-n)\n else:\n try:\n s=nts(s,\"ascii\",\"strict\")\n n=int(s.strip()or \"0\",8)\n except ValueError:\n raise InvalidHeaderError(\"invalid header\")\n return n\n \ndef itn(n,digits=8,format=DEFAULT_FORMAT):\n ''\n \n \n \n \n \n \n \n \n \n original_n=n\n n=int(n)\n if 0 <=n <8 **(digits -1):\n s=bytes(\"%0*o\"%(digits -1,n),\"ascii\")+NUL\n elif format ==GNU_FORMAT and -256 **(digits -1)<=n <256 **(digits -1):\n if n >=0:\n s=bytearray([0o200])\n else:\n s=bytearray([0o377])\n n=256 **digits+n\n \n for i in range(digits -1):\n s.insert(1,n&0o377)\n n >>=8\n else:\n raise ValueError(\"overflow in number field\")\n \n return s\n \ndef calc_chksums(buf):\n ''\n\n\n\n\n\n\n \n unsigned_chksum=256+sum(struct.unpack_from(\"148B8x356B\",buf))\n signed_chksum=256+sum(struct.unpack_from(\"148b8x356b\",buf))\n return unsigned_chksum,signed_chksum\n \ndef copyfileobj(src,dst,length=None,exception=OSError,bufsize=None):\n ''\n\n \n bufsize=bufsize or 16 *1024\n if length ==0:\n return\n if length is None:\n shutil.copyfileobj(src,dst,bufsize)\n return\n \n blocks,remainder=divmod(length,bufsize)\n for b in range(blocks):\n buf=src.read(bufsize)\n if len(buf)self.bufsize:\n self.fileobj.write(self.buf[:self.bufsize])\n self.buf=self.buf[self.bufsize:]\n \n def close(self):\n ''\n\n \n if self.closed:\n return\n \n self.closed=True\n try:\n if self.mode ==\"w\"and self.comptype !=\"tar\":\n self.buf +=self.cmp.flush()\n \n if self.mode ==\"w\"and self.buf:\n self.fileobj.write(self.buf)\n self.buf=b\"\"\n if self.comptype ==\"gz\":\n self.fileobj.write(struct.pack(\"=0:\n blocks,remainder=divmod(pos -self.pos,self.bufsize)\n for i in range(blocks):\n self.read(self.bufsize)\n self.read(remainder)\n else:\n raise StreamError(\"seeking backwards is not allowed\")\n return self.pos\n \n def read(self,size):\n ''\n assert size is not None\n buf=self._read(size)\n self.pos +=len(buf)\n return buf\n \n def _read(self,size):\n ''\n \n if self.comptype ==\"tar\":\n return self.__read(size)\n \n c=len(self.dbuf)\n t=[self.dbuf]\n while c lastpos:\n self.map.append((False,lastpos,offset,None))\n self.map.append((True,offset,offset+size,realpos))\n realpos +=size\n lastpos=offset+size\n if lastpos 0:\n while True:\n data,start,stop,offset=self.map[self.map_index]\n if start <=self.position \"%(self.__class__.__name__,self.name,id(self))\n \n def replace(self,*,\n name=_KEEP,mtime=_KEEP,mode=_KEEP,linkname=_KEEP,\n uid=_KEEP,gid=_KEEP,uname=_KEEP,gname=_KEEP,\n deep=True,_KEEP=_KEEP):\n ''\n \n if deep:\n result=copy.deepcopy(self)\n else:\n result=copy.copy(self)\n if name is not _KEEP:\n result.name=name\n if mtime is not _KEEP:\n result.mtime=mtime\n if mode is not _KEEP:\n result.mode=mode\n if linkname is not _KEEP:\n result.linkname=linkname\n if uid is not _KEEP:\n result.uid=uid\n if gid is not _KEEP:\n result.gid=gid\n if uname is not _KEEP:\n result.uname=uname\n if gname is not _KEEP:\n result.gname=gname\n return result\n \n def get_info(self):\n ''\n \n if self.mode is None:\n mode=None\n else:\n mode=self.mode&0o7777\n info={\n \"name\":self.name,\n \"mode\":mode,\n \"uid\":self.uid,\n \"gid\":self.gid,\n \"size\":self.size,\n \"mtime\":self.mtime,\n \"chksum\":self.chksum,\n \"type\":self.type,\n \"linkname\":self.linkname,\n \"uname\":self.uname,\n \"gname\":self.gname,\n \"devmajor\":self.devmajor,\n \"devminor\":self.devminor\n }\n \n if info[\"type\"]==DIRTYPE and not info[\"name\"].endswith(\"/\"):\n info[\"name\"]+=\"/\"\n \n return info\n \n def tobuf(self,format=DEFAULT_FORMAT,encoding=ENCODING,errors=\"surrogateescape\"):\n ''\n \n info=self.get_info()\n for name,value in info.items():\n if value is None:\n raise ValueError(\"%s may not be None\"%name)\n \n if format ==USTAR_FORMAT:\n return self.create_ustar_header(info,encoding,errors)\n elif format ==GNU_FORMAT:\n return self.create_gnu_header(info,encoding,errors)\n elif format ==PAX_FORMAT:\n return self.create_pax_header(info,encoding)\n else:\n raise ValueError(\"invalid format\")\n \n def create_ustar_header(self,info,encoding,errors):\n ''\n \n info[\"magic\"]=POSIX_MAGIC\n \n if len(info[\"linkname\"].encode(encoding,errors))>LENGTH_LINK:\n raise ValueError(\"linkname is too long\")\n \n if len(info[\"name\"].encode(encoding,errors))>LENGTH_NAME:\n info[\"prefix\"],info[\"name\"]=self._posix_split_name(info[\"name\"],encoding,errors)\n \n return self._create_header(info,USTAR_FORMAT,encoding,errors)\n \n def create_gnu_header(self,info,encoding,errors):\n ''\n \n info[\"magic\"]=GNU_MAGIC\n \n buf=b\"\"\n if len(info[\"linkname\"].encode(encoding,errors))>LENGTH_LINK:\n buf +=self._create_gnu_long_header(info[\"linkname\"],GNUTYPE_LONGLINK,encoding,errors)\n \n if len(info[\"name\"].encode(encoding,errors))>LENGTH_NAME:\n buf +=self._create_gnu_long_header(info[\"name\"],GNUTYPE_LONGNAME,encoding,errors)\n \n return buf+self._create_header(info,GNU_FORMAT,encoding,errors)\n \n def create_pax_header(self,info,encoding):\n ''\n\n\n \n info[\"magic\"]=POSIX_MAGIC\n pax_headers=self.pax_headers.copy()\n \n \n \n for name,hname,length in(\n (\"name\",\"path\",LENGTH_NAME),(\"linkname\",\"linkpath\",LENGTH_LINK),\n (\"uname\",\"uname\",32),(\"gname\",\"gname\",32)):\n \n if hname in pax_headers:\n \n continue\n \n \n try:\n info[name].encode(\"ascii\",\"strict\")\n except UnicodeEncodeError:\n pax_headers[hname]=info[name]\n continue\n \n if len(info[name])>length:\n pax_headers[hname]=info[name]\n \n \n \n for name,digits in((\"uid\",8),(\"gid\",8),(\"size\",12),(\"mtime\",12)):\n needs_pax=False\n \n val=info[name]\n val_is_float=isinstance(val,float)\n val_int=round(val)if val_is_float else val\n if not 0 <=val_int <8 **(digits -1):\n \n info[name]=0\n needs_pax=True\n elif val_is_float:\n \n \n info[name]=val_int\n needs_pax=True\n \n \n if needs_pax and name not in pax_headers:\n pax_headers[name]=str(val)\n \n \n if pax_headers:\n buf=self._create_pax_generic_header(pax_headers,XHDTYPE,encoding)\n else:\n buf=b\"\"\n \n return buf+self._create_header(info,USTAR_FORMAT,\"ascii\",\"replace\")\n \n @classmethod\n def create_pax_global_header(cls,pax_headers):\n ''\n \n return cls._create_pax_generic_header(pax_headers,XGLTYPE,\"utf-8\")\n \n def _posix_split_name(self,name,encoding,errors):\n ''\n\n \n components=name.split(\"/\")\n for i in range(1,len(components)):\n prefix=\"/\".join(components[:i])\n name=\"/\".join(components[i:])\n if len(prefix.encode(encoding,errors))<=LENGTH_PREFIX and\\\n len(name.encode(encoding,errors))<=LENGTH_NAME:\n break\n else:\n raise ValueError(\"name is too long\")\n \n return prefix,name\n \n @staticmethod\n def _create_header(info,format,encoding,errors):\n ''\n\n \n has_device_fields=info.get(\"type\")in(CHRTYPE,BLKTYPE)\n if has_device_fields:\n devmajor=itn(info.get(\"devmajor\",0),8,format)\n devminor=itn(info.get(\"devminor\",0),8,format)\n else:\n devmajor=stn(\"\",8,encoding,errors)\n devminor=stn(\"\",8,encoding,errors)\n \n \n \n filetype=info.get(\"type\",REGTYPE)\n if filetype is None:\n raise ValueError(\"TarInfo.type must not be None\")\n \n parts=[\n stn(info.get(\"name\",\"\"),100,encoding,errors),\n itn(info.get(\"mode\",0)&0o7777,8,format),\n itn(info.get(\"uid\",0),8,format),\n itn(info.get(\"gid\",0),8,format),\n itn(info.get(\"size\",0),12,format),\n itn(info.get(\"mtime\",0),12,format),\n b\" \",\n filetype,\n stn(info.get(\"linkname\",\"\"),100,encoding,errors),\n info.get(\"magic\",POSIX_MAGIC),\n stn(info.get(\"uname\",\"\"),32,encoding,errors),\n stn(info.get(\"gname\",\"\"),32,encoding,errors),\n devmajor,\n devminor,\n stn(info.get(\"prefix\",\"\"),155,encoding,errors)\n ]\n \n buf=struct.pack(\"%ds\"%BLOCKSIZE,b\"\".join(parts))\n chksum=calc_chksums(buf[-BLOCKSIZE:])[0]\n buf=buf[:-364]+bytes(\"%06o\\0\"%chksum,\"ascii\")+buf[-357:]\n return buf\n \n @staticmethod\n def _create_payload(payload):\n ''\n\n \n blocks,remainder=divmod(len(payload),BLOCKSIZE)\n if remainder >0:\n payload +=(BLOCKSIZE -remainder)*NUL\n return payload\n \n @classmethod\n def _create_gnu_long_header(cls,name,type,encoding,errors):\n ''\n\n \n name=name.encode(encoding,errors)+NUL\n \n info={}\n info[\"name\"]=\"././@LongLink\"\n info[\"type\"]=type\n info[\"size\"]=len(name)\n info[\"magic\"]=GNU_MAGIC\n \n \n return cls._create_header(info,USTAR_FORMAT,encoding,errors)+\\\n cls._create_payload(name)\n \n @classmethod\n def _create_pax_generic_header(cls,pax_headers,type,encoding):\n ''\n\n\n \n \n \n binary=False\n for keyword,value in pax_headers.items():\n try:\n value.encode(\"utf-8\",\"strict\")\n except UnicodeEncodeError:\n binary=True\n break\n \n records=b\"\"\n if binary:\n \n records +=b\"21 hdrcharset=BINARY\\n\"\n \n for keyword,value in pax_headers.items():\n keyword=keyword.encode(\"utf-8\")\n if binary:\n \n \n value=value.encode(encoding,\"surrogateescape\")\n else:\n value=value.encode(\"utf-8\")\n \n l=len(keyword)+len(value)+3\n n=p=0\n while True:\n n=l+len(str(p))\n if n ==p:\n break\n p=n\n records +=bytes(str(p),\"ascii\")+b\" \"+keyword+b\"=\"+value+b\"\\n\"\n \n \n \n info={}\n info[\"name\"]=\"././@PaxHeader\"\n info[\"type\"]=type\n info[\"size\"]=len(records)\n info[\"magic\"]=POSIX_MAGIC\n \n \n return cls._create_header(info,USTAR_FORMAT,\"ascii\",\"replace\")+\\\n cls._create_payload(records)\n \n @classmethod\n def frombuf(cls,buf,encoding,errors):\n ''\n \n if len(buf)==0:\n raise EmptyHeaderError(\"empty header\")\n if len(buf)!=BLOCKSIZE:\n raise TruncatedHeaderError(\"truncated header\")\n if buf.count(NUL)==BLOCKSIZE:\n raise EOFHeaderError(\"end of file header\")\n \n chksum=nti(buf[148:156])\n if chksum not in calc_chksums(buf):\n raise InvalidHeaderError(\"bad checksum\")\n \n obj=cls()\n obj.name=nts(buf[0:100],encoding,errors)\n obj.mode=nti(buf[100:108])\n obj.uid=nti(buf[108:116])\n obj.gid=nti(buf[116:124])\n obj.size=nti(buf[124:136])\n obj.mtime=nti(buf[136:148])\n obj.chksum=chksum\n obj.type=buf[156:157]\n obj.linkname=nts(buf[157:257],encoding,errors)\n obj.uname=nts(buf[265:297],encoding,errors)\n obj.gname=nts(buf[297:329],encoding,errors)\n obj.devmajor=nti(buf[329:337])\n obj.devminor=nti(buf[337:345])\n prefix=nts(buf[345:500],encoding,errors)\n \n \n \n if obj.type ==AREGTYPE and obj.name.endswith(\"/\"):\n obj.type=DIRTYPE\n \n \n \n \n if obj.type ==GNUTYPE_SPARSE:\n pos=386\n structs=[]\n for i in range(4):\n try:\n offset=nti(buf[pos:pos+12])\n numbytes=nti(buf[pos+12:pos+24])\n except ValueError:\n break\n structs.append((offset,numbytes))\n pos +=24\n isextended=bool(buf[482])\n origsize=nti(buf[483:495])\n obj._sparse_structs=(structs,isextended,origsize)\n \n \n if obj.isdir():\n obj.name=obj.name.rstrip(\"/\")\n \n \n if prefix and obj.type not in GNU_TYPES:\n obj.name=prefix+\"/\"+obj.name\n return obj\n \n @classmethod\n def fromtarfile(cls,tarfile):\n ''\n\n \n buf=tarfile.fileobj.read(BLOCKSIZE)\n obj=cls.frombuf(buf,tarfile.encoding,tarfile.errors)\n obj.offset=tarfile.fileobj.tell()-BLOCKSIZE\n return obj._proc_member(tarfile)\n \n \n \n \n \n \n \n \n \n \n \n \n def _proc_member(self,tarfile):\n ''\n\n \n if self.type in(GNUTYPE_LONGNAME,GNUTYPE_LONGLINK):\n return self._proc_gnulong(tarfile)\n elif self.type ==GNUTYPE_SPARSE:\n return self._proc_sparse(tarfile)\n elif self.type in(XHDTYPE,XGLTYPE,SOLARIS_XHDTYPE):\n return self._proc_pax(tarfile)\n else:\n return self._proc_builtin(tarfile)\n \n def _proc_builtin(self,tarfile):\n ''\n\n \n self.offset_data=tarfile.fileobj.tell()\n offset=self.offset_data\n if self.isreg()or self.type not in SUPPORTED_TYPES:\n \n offset +=self._block(self.size)\n tarfile.offset=offset\n \n \n \n self._apply_pax_info(tarfile.pax_headers,tarfile.encoding,tarfile.errors)\n \n \n \n if self.isdir():\n self.name=self.name.rstrip(\"/\")\n \n return self\n \n def _proc_gnulong(self,tarfile):\n ''\n\n \n buf=tarfile.fileobj.read(self._block(self.size))\n \n \n try:\n next=self.fromtarfile(tarfile)\n except HeaderError as e:\n raise SubsequentHeaderError(str(e))from None\n \n \n \n next.offset=self.offset\n if self.type ==GNUTYPE_LONGNAME:\n next.name=nts(buf,tarfile.encoding,tarfile.errors)\n elif self.type ==GNUTYPE_LONGLINK:\n next.linkname=nts(buf,tarfile.encoding,tarfile.errors)\n \n \n \n if next.isdir():\n next.name=next.name.removesuffix(\"/\")\n \n return next\n \n def _proc_sparse(self,tarfile):\n ''\n \n \n structs,isextended,origsize=self._sparse_structs\n del self._sparse_structs\n \n \n while isextended:\n buf=tarfile.fileobj.read(BLOCKSIZE)\n pos=0\n for i in range(21):\n try:\n offset=nti(buf[pos:pos+12])\n numbytes=nti(buf[pos+12:pos+24])\n except ValueError:\n break\n if offset and numbytes:\n structs.append((offset,numbytes))\n pos +=24\n isextended=bool(buf[504])\n self.sparse=structs\n \n self.offset_data=tarfile.fileobj.tell()\n tarfile.offset=self.offset_data+self._block(self.size)\n self.size=origsize\n return self\n \n def _proc_pax(self,tarfile):\n ''\n\n \n \n buf=tarfile.fileobj.read(self._block(self.size))\n \n \n \n \n if self.type ==XGLTYPE:\n pax_headers=tarfile.pax_headers\n else:\n pax_headers=tarfile.pax_headers.copy()\n \n \n \n \n \n \n match=re.search(br\"\\d+ hdrcharset=([^\\n]+)\\n\",buf)\n if match is not None:\n pax_headers[\"hdrcharset\"]=match.group(1).decode(\"utf-8\")\n \n \n \n \n hdrcharset=pax_headers.get(\"hdrcharset\")\n if hdrcharset ==\"BINARY\":\n encoding=tarfile.encoding\n else:\n encoding=\"utf-8\"\n \n \n \n \n \n regex=re.compile(br\"(\\d+) ([^=]+)=\")\n pos=0\n while match :=regex.match(buf,pos):\n length,keyword=match.groups()\n length=int(length)\n if length ==0:\n raise InvalidHeaderError(\"invalid header\")\n value=buf[match.end(2)+1:match.start(1)+length -1]\n \n \n \n \n \n \n \n \n keyword=self._decode_pax_field(keyword,\"utf-8\",\"utf-8\",\n tarfile.errors)\n if keyword in PAX_NAME_FIELDS:\n value=self._decode_pax_field(value,encoding,tarfile.encoding,\n tarfile.errors)\n else:\n value=self._decode_pax_field(value,\"utf-8\",\"utf-8\",\n tarfile.errors)\n \n pax_headers[keyword]=value\n pos +=length\n \n \n try:\n next=self.fromtarfile(tarfile)\n except HeaderError as e:\n raise SubsequentHeaderError(str(e))from None\n \n \n if \"GNU.sparse.map\"in pax_headers:\n \n self._proc_gnusparse_01(next,pax_headers)\n \n elif \"GNU.sparse.size\"in pax_headers:\n \n self._proc_gnusparse_00(next,pax_headers,buf)\n \n elif pax_headers.get(\"GNU.sparse.major\")==\"1\"and pax_headers.get(\"GNU.sparse.minor\")==\"0\":\n \n self._proc_gnusparse_10(next,pax_headers,tarfile)\n \n if self.type in(XHDTYPE,SOLARIS_XHDTYPE):\n \n next._apply_pax_info(pax_headers,tarfile.encoding,tarfile.errors)\n next.offset=self.offset\n \n if \"size\"in pax_headers:\n \n \n \n offset=next.offset_data\n if next.isreg()or next.type not in SUPPORTED_TYPES:\n offset +=next._block(next.size)\n tarfile.offset=offset\n \n return next\n \n def _proc_gnusparse_00(self,next,pax_headers,buf):\n ''\n \n offsets=[]\n for match in re.finditer(br\"\\d+ GNU.sparse.offset=(\\d+)\\n\",buf):\n offsets.append(int(match.group(1)))\n numbytes=[]\n for match in re.finditer(br\"\\d+ GNU.sparse.numbytes=(\\d+)\\n\",buf):\n numbytes.append(int(match.group(1)))\n next.sparse=list(zip(offsets,numbytes))\n \n def _proc_gnusparse_01(self,next,pax_headers):\n ''\n \n sparse=[int(x)for x in pax_headers[\"GNU.sparse.map\"].split(\",\")]\n next.sparse=list(zip(sparse[::2],sparse[1::2]))\n \n def _proc_gnusparse_10(self,next,pax_headers,tarfile):\n ''\n \n fields=None\n sparse=[]\n buf=tarfile.fileobj.read(BLOCKSIZE)\n fields,buf=buf.split(b\"\\n\",1)\n fields=int(fields)\n while len(sparse)0:\n self.fileobj.write(NUL *(RECORDSIZE -remainder))\n finally:\n if not self._extfileobj:\n self.fileobj.close()\n \n def getmember(self,name):\n ''\n\n\n\n \n tarinfo=self._getmember(name.rstrip('/'))\n if tarinfo is None:\n raise KeyError(\"filename %r not found\"%name)\n return tarinfo\n \n def getmembers(self):\n ''\n\n \n self._check()\n if not self._loaded:\n self._load()\n \n return self.members\n \n def getnames(self):\n ''\n\n \n return[tarinfo.name for tarinfo in self.getmembers()]\n \n def gettarinfo(self,name=None,arcname=None,fileobj=None):\n ''\n\n\n\n\n\n\n \n self._check(\"awx\")\n \n \n \n if fileobj is not None:\n name=fileobj.name\n \n \n \n \n if arcname is None:\n arcname=name\n drv,arcname=os.path.splitdrive(arcname)\n arcname=arcname.replace(os.sep,\"/\")\n arcname=arcname.lstrip(\"/\")\n \n \n \n tarinfo=self.tarinfo()\n tarinfo._tarfile=self\n \n \n if fileobj is None:\n if not self.dereference:\n statres=os.lstat(name)\n else:\n statres=os.stat(name)\n else:\n statres=os.fstat(fileobj.fileno())\n linkname=\"\"\n \n stmd=statres.st_mode\n if stat.S_ISREG(stmd):\n inode=(statres.st_ino,statres.st_dev)\n if not self.dereference and statres.st_nlink >1 and\\\n inode in self.inodes and arcname !=self.inodes[inode]:\n \n \n type=LNKTYPE\n linkname=self.inodes[inode]\n else:\n \n \n type=REGTYPE\n if inode[0]:\n self.inodes[inode]=arcname\n elif stat.S_ISDIR(stmd):\n type=DIRTYPE\n elif stat.S_ISFIFO(stmd):\n type=FIFOTYPE\n elif stat.S_ISLNK(stmd):\n type=SYMTYPE\n linkname=os.readlink(name)\n elif stat.S_ISCHR(stmd):\n type=CHRTYPE\n elif stat.S_ISBLK(stmd):\n type=BLKTYPE\n else:\n return None\n \n \n \n tarinfo.name=arcname\n tarinfo.mode=stmd\n tarinfo.uid=statres.st_uid\n tarinfo.gid=statres.st_gid\n if type ==REGTYPE:\n tarinfo.size=statres.st_size\n else:\n tarinfo.size=0\n tarinfo.mtime=statres.st_mtime\n tarinfo.type=type\n tarinfo.linkname=linkname\n if pwd:\n try:\n tarinfo.uname=pwd.getpwuid(tarinfo.uid)[0]\n except KeyError:\n pass\n if grp:\n try:\n tarinfo.gname=grp.getgrgid(tarinfo.gid)[0]\n except KeyError:\n pass\n \n if type in(CHRTYPE,BLKTYPE):\n if hasattr(os,\"major\")and hasattr(os,\"minor\"):\n tarinfo.devmajor=os.major(statres.st_rdev)\n tarinfo.devminor=os.minor(statres.st_rdev)\n return tarinfo\n \n def list(self,verbose=True,*,members=None):\n ''\n\n\n\n \n \n type2mode={REGTYPE:stat.S_IFREG,SYMTYPE:stat.S_IFLNK,\n FIFOTYPE:stat.S_IFIFO,CHRTYPE:stat.S_IFCHR,\n DIRTYPE:stat.S_IFDIR,BLKTYPE:stat.S_IFBLK}\n self._check()\n \n if members is None:\n members=self\n for tarinfo in members:\n if verbose:\n if tarinfo.mode is None:\n _safe_print(\"??????????\")\n else:\n modetype=type2mode.get(tarinfo.type,0)\n _safe_print(stat.filemode(modetype |tarinfo.mode))\n _safe_print(\"%s/%s\"%(tarinfo.uname or tarinfo.uid,\n tarinfo.gname or tarinfo.gid))\n if tarinfo.ischr()or tarinfo.isblk():\n _safe_print(\"%10s\"%\n (\"%d,%d\"%(tarinfo.devmajor,tarinfo.devminor)))\n else:\n _safe_print(\"%10d\"%tarinfo.size)\n if tarinfo.mtime is None:\n _safe_print(\"????-??-?? ??:??:??\")\n else:\n _safe_print(\"%d-%02d-%02d %02d:%02d:%02d\"\\\n %time.localtime(tarinfo.mtime)[:6])\n \n _safe_print(tarinfo.name+(\"/\"if tarinfo.isdir()else \"\"))\n \n if verbose:\n if tarinfo.issym():\n _safe_print(\"-> \"+tarinfo.linkname)\n if tarinfo.islnk():\n _safe_print(\"link to \"+tarinfo.linkname)\n print()\n \n def add(self,name,arcname=None,recursive=True,*,filter=None):\n ''\n\n\n\n\n\n\n\n \n self._check(\"awx\")\n \n if arcname is None:\n arcname=name\n \n \n if self.name is not None and os.path.abspath(name)==self.name:\n self._dbg(2,\"tarfile: Skipped %r\"%name)\n return\n \n self._dbg(1,name)\n \n \n tarinfo=self.gettarinfo(name,arcname)\n \n if tarinfo is None:\n self._dbg(1,\"tarfile: Unsupported type %r\"%name)\n return\n \n \n if filter is not None:\n tarinfo=filter(tarinfo)\n if tarinfo is None:\n self._dbg(2,\"tarfile: Excluded %r\"%name)\n return\n \n \n if tarinfo.isreg():\n with bltn_open(name,\"rb\")as f:\n self.addfile(tarinfo,f)\n \n elif tarinfo.isdir():\n self.addfile(tarinfo)\n if recursive:\n for f in sorted(os.listdir(name)):\n self.add(os.path.join(name,f),os.path.join(arcname,f),\n recursive,filter=filter)\n \n else:\n self.addfile(tarinfo)\n \n def addfile(self,tarinfo,fileobj=None):\n ''\n\n\n\n \n self._check(\"awx\")\n \n if fileobj is None and tarinfo.isreg()and tarinfo.size !=0:\n raise ValueError(\"fileobj not provided for non zero-size regular file\")\n \n tarinfo=copy.copy(tarinfo)\n \n buf=tarinfo.tobuf(self.format,self.encoding,self.errors)\n self.fileobj.write(buf)\n self.offset +=len(buf)\n bufsize=self.copybufsize\n \n if fileobj is not None:\n copyfileobj(fileobj,self.fileobj,tarinfo.size,bufsize=bufsize)\n blocks,remainder=divmod(tarinfo.size,BLOCKSIZE)\n if remainder >0:\n self.fileobj.write(NUL *(BLOCKSIZE -remainder))\n blocks +=1\n self.offset +=blocks *BLOCKSIZE\n \n self.members.append(tarinfo)\n \n def _get_filter_function(self,filter):\n if filter is None:\n filter=self.extraction_filter\n if filter is None:\n import warnings\n warnings.warn(\n 'Python 3.14 will, by default, filter extracted tar '\n +'archives and reject files or modify their metadata. '\n +'Use the filter argument to control this behavior.',\n DeprecationWarning,stacklevel=3)\n return fully_trusted_filter\n if isinstance(filter,str):\n raise TypeError(\n 'String names are not supported for '\n +'TarFile.extraction_filter. Use a function such as '\n +'tarfile.data_filter directly.')\n return filter\n if callable(filter):\n return filter\n try:\n return _NAMED_FILTERS[filter]\n except KeyError:\n raise ValueError(f\"filter {filter !r} not found\")from None\n \n def extractall(self,path=\".\",members=None,*,numeric_owner=False,\n filter=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n directories=[]\n \n filter_function=self._get_filter_function(filter)\n if members is None:\n members=self\n \n for member in members:\n tarinfo=self._get_extract_tarinfo(member,filter_function,path)\n if tarinfo is None:\n continue\n if tarinfo.isdir():\n \n \n \n directories.append(tarinfo)\n self._extract_one(tarinfo,path,set_attrs=not tarinfo.isdir(),\n numeric_owner=numeric_owner)\n \n \n directories.sort(key=lambda a:a.name,reverse=True)\n \n \n for tarinfo in directories:\n dirpath=os.path.join(path,tarinfo.name)\n try:\n self.chown(tarinfo,dirpath,numeric_owner=numeric_owner)\n self.utime(tarinfo,dirpath)\n self.chmod(tarinfo,dirpath)\n except ExtractError as e:\n self._handle_nonfatal_error(e)\n \n def extract(self,member,path=\"\",set_attrs=True,*,numeric_owner=False,\n filter=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n filter_function=self._get_filter_function(filter)\n tarinfo=self._get_extract_tarinfo(member,filter_function,path)\n if tarinfo is not None:\n self._extract_one(tarinfo,path,set_attrs,numeric_owner)\n \n def _get_extract_tarinfo(self,member,filter_function,path):\n ''\n if isinstance(member,str):\n tarinfo=self.getmember(member)\n else:\n tarinfo=member\n \n unfiltered=tarinfo\n try:\n tarinfo=filter_function(tarinfo,path)\n except(OSError,FilterError)as e:\n self._handle_fatal_error(e)\n except ExtractError as e:\n self._handle_nonfatal_error(e)\n if tarinfo is None:\n self._dbg(2,\"tarfile: Excluded %r\"%unfiltered.name)\n return None\n \n if tarinfo.islnk():\n tarinfo=copy.copy(tarinfo)\n tarinfo._link_target=os.path.join(path,tarinfo.linkname)\n return tarinfo\n \n def _extract_one(self,tarinfo,path,set_attrs,numeric_owner):\n ''\n self._check(\"r\")\n \n try:\n self._extract_member(tarinfo,os.path.join(path,tarinfo.name),\n set_attrs=set_attrs,\n numeric_owner=numeric_owner)\n except OSError as e:\n self._handle_fatal_error(e)\n except ExtractError as e:\n self._handle_nonfatal_error(e)\n \n def _handle_nonfatal_error(self,e):\n ''\n if self.errorlevel >1:\n raise\n else:\n self._dbg(1,\"tarfile: %s\"%e)\n \n def _handle_fatal_error(self,e):\n ''\n if self.errorlevel >0:\n raise\n elif isinstance(e,OSError):\n if e.filename is None:\n self._dbg(1,\"tarfile: %s\"%e.strerror)\n else:\n self._dbg(1,\"tarfile: %s %r\"%(e.strerror,e.filename))\n else:\n self._dbg(1,\"tarfile: %s %s\"%(type(e).__name__,e))\n \n def extractfile(self,member):\n ''\n\n\n\n\n \n self._check(\"r\")\n \n if isinstance(member,str):\n tarinfo=self.getmember(member)\n else:\n tarinfo=member\n \n if tarinfo.isreg()or tarinfo.type not in SUPPORTED_TYPES:\n \n return self.fileobject(self,tarinfo)\n \n elif tarinfo.islnk()or tarinfo.issym():\n if isinstance(self.fileobj,_Stream):\n \n \n \n raise StreamError(\"cannot extract (sym)link as file object\")\n else:\n \n return self.extractfile(self._find_link_target(tarinfo))\n else:\n \n \n return None\n \n def _extract_member(self,tarinfo,targetpath,set_attrs=True,\n numeric_owner=False):\n ''\n\n \n \n \n \n targetpath=targetpath.rstrip(\"/\")\n targetpath=targetpath.replace(\"/\",os.sep)\n \n \n upperdirs=os.path.dirname(targetpath)\n if upperdirs and not os.path.exists(upperdirs):\n \n \n os.makedirs(upperdirs,exist_ok=True)\n \n if tarinfo.islnk()or tarinfo.issym():\n self._dbg(1,\"%s -> %s\"%(tarinfo.name,tarinfo.linkname))\n else:\n self._dbg(1,tarinfo.name)\n \n if tarinfo.isreg():\n self.makefile(tarinfo,targetpath)\n elif tarinfo.isdir():\n self.makedir(tarinfo,targetpath)\n elif tarinfo.isfifo():\n self.makefifo(tarinfo,targetpath)\n elif tarinfo.ischr()or tarinfo.isblk():\n self.makedev(tarinfo,targetpath)\n elif tarinfo.islnk()or tarinfo.issym():\n self.makelink(tarinfo,targetpath)\n elif tarinfo.type not in SUPPORTED_TYPES:\n self.makeunknown(tarinfo,targetpath)\n else:\n self.makefile(tarinfo,targetpath)\n \n if set_attrs:\n self.chown(tarinfo,targetpath,numeric_owner)\n if not tarinfo.issym():\n self.chmod(tarinfo,targetpath)\n self.utime(tarinfo,targetpath)\n \n \n \n \n \n \n def makedir(self,tarinfo,targetpath):\n ''\n \n try:\n if tarinfo.mode is None:\n \n os.mkdir(targetpath)\n else:\n \n \n os.mkdir(targetpath,0o700)\n except FileExistsError:\n if not os.path.isdir(targetpath):\n raise\n \n def makefile(self,tarinfo,targetpath):\n ''\n \n source=self.fileobj\n source.seek(tarinfo.offset_data)\n bufsize=self.copybufsize\n with bltn_open(targetpath,\"wb\")as target:\n if tarinfo.sparse is not None:\n for offset,size in tarinfo.sparse:\n target.seek(offset)\n copyfileobj(source,target,size,ReadError,bufsize)\n target.seek(tarinfo.size)\n target.truncate()\n else:\n copyfileobj(source,target,tarinfo.size,ReadError,bufsize)\n \n def makeunknown(self,tarinfo,targetpath):\n ''\n\n \n self.makefile(tarinfo,targetpath)\n self._dbg(1,\"tarfile: Unknown file type %r, \"\\\n \"extracted as regular file.\"%tarinfo.type)\n \n def makefifo(self,tarinfo,targetpath):\n ''\n \n if hasattr(os,\"mkfifo\"):\n os.mkfifo(targetpath)\n else:\n raise ExtractError(\"fifo not supported by system\")\n \n def makedev(self,tarinfo,targetpath):\n ''\n \n if not hasattr(os,\"mknod\")or not hasattr(os,\"makedev\"):\n raise ExtractError(\"special devices not supported by system\")\n \n mode=tarinfo.mode\n if mode is None:\n \n mode=0o600\n if tarinfo.isblk():\n mode |=stat.S_IFBLK\n else:\n mode |=stat.S_IFCHR\n \n os.mknod(targetpath,mode,\n os.makedev(tarinfo.devmajor,tarinfo.devminor))\n \n def makelink(self,tarinfo,targetpath):\n ''\n\n\n \n try:\n \n if tarinfo.issym():\n if os.path.lexists(targetpath):\n \n os.unlink(targetpath)\n os.symlink(tarinfo.linkname,targetpath)\n else:\n if os.path.exists(tarinfo._link_target):\n os.link(tarinfo._link_target,targetpath)\n else:\n self._extract_member(self._find_link_target(tarinfo),\n targetpath)\n except symlink_exception:\n try:\n self._extract_member(self._find_link_target(tarinfo),\n targetpath)\n except KeyError:\n raise ExtractError(\"unable to resolve link inside archive\")from None\n \n def chown(self,tarinfo,targetpath,numeric_owner):\n ''\n\n\n\n \n if hasattr(os,\"geteuid\")and os.geteuid()==0:\n \n g=tarinfo.gid\n u=tarinfo.uid\n if not numeric_owner:\n try:\n if grp and tarinfo.gname:\n g=grp.getgrnam(tarinfo.gname)[2]\n except KeyError:\n pass\n try:\n if pwd and tarinfo.uname:\n u=pwd.getpwnam(tarinfo.uname)[2]\n except KeyError:\n pass\n if g is None:\n g=-1\n if u is None:\n u=-1\n try:\n if tarinfo.issym()and hasattr(os,\"lchown\"):\n os.lchown(targetpath,u,g)\n else:\n os.chown(targetpath,u,g)\n except(OSError,OverflowError)as e:\n \n raise ExtractError(\"could not change owner\")from e\n \n def chmod(self,tarinfo,targetpath):\n ''\n \n if tarinfo.mode is None:\n return\n try:\n os.chmod(targetpath,tarinfo.mode)\n except OSError as e:\n raise ExtractError(\"could not change mode\")from e\n \n def utime(self,tarinfo,targetpath):\n ''\n \n mtime=tarinfo.mtime\n if mtime is None:\n return\n if not hasattr(os,'utime'):\n return\n try:\n os.utime(targetpath,(mtime,mtime))\n except OSError as e:\n raise ExtractError(\"could not change modification time\")from e\n \n \n def next(self):\n ''\n\n\n \n self._check(\"ra\")\n if self.firstmember is not None:\n m=self.firstmember\n self.firstmember=None\n return m\n \n \n if self.offset !=self.fileobj.tell():\n if self.offset ==0:\n return None\n self.fileobj.seek(self.offset -1)\n if not self.fileobj.read(1):\n raise ReadError(\"unexpected end of data\")\n \n \n tarinfo=None\n while True:\n try:\n tarinfo=self.tarinfo.fromtarfile(self)\n except EOFHeaderError as e:\n if self.ignore_zeros:\n self._dbg(2,\"0x%X: %s\"%(self.offset,e))\n self.offset +=BLOCKSIZE\n continue\n except InvalidHeaderError as e:\n if self.ignore_zeros:\n self._dbg(2,\"0x%X: %s\"%(self.offset,e))\n self.offset +=BLOCKSIZE\n continue\n elif self.offset ==0:\n raise ReadError(str(e))from None\n except EmptyHeaderError:\n if self.offset ==0:\n raise ReadError(\"empty file\")from None\n except TruncatedHeaderError as e:\n if self.offset ==0:\n raise ReadError(str(e))from None\n except SubsequentHeaderError as e:\n raise ReadError(str(e))from None\n except Exception as e:\n try:\n import zlib\n if isinstance(e,zlib.error):\n raise ReadError(f'zlib error: {e}')from None\n else:\n raise e\n except ImportError:\n raise e\n break\n \n if tarinfo is not None:\n \n if not self.stream:\n self.members.append(tarinfo)\n else:\n self._loaded=True\n \n return tarinfo\n \n \n \n \n def _getmember(self,name,tarinfo=None,normalize=False):\n ''\n\n \n \n members=self.getmembers()\n \n \n skipping=False\n if tarinfo is not None:\n try:\n index=members.index(tarinfo)\n except ValueError:\n \n \n skipping=True\n else:\n \n members=members[:index]\n \n if normalize:\n name=os.path.normpath(name)\n \n for member in reversed(members):\n if skipping:\n if tarinfo.offset ==member.offset:\n skipping=False\n continue\n if normalize:\n member_name=os.path.normpath(member.name)\n else:\n member_name=member.name\n \n if name ==member_name:\n return member\n \n if skipping:\n \n raise ValueError(tarinfo)\n \n def _load(self):\n ''\n\n \n if not self.stream:\n while self.next()is not None:\n pass\n self._loaded=True\n \n def _check(self,mode=None):\n ''\n\n \n if self.closed:\n raise OSError(\"%s is closed\"%self.__class__.__name__)\n if mode is not None and self.mode not in mode:\n raise OSError(\"bad operation for mode %r\"%self.mode)\n \n def _find_link_target(self,tarinfo):\n ''\n\n \n if tarinfo.issym():\n \n linkname=\"/\".join(filter(None,(os.path.dirname(tarinfo.name),tarinfo.linkname)))\n limit=None\n else:\n \n \n linkname=tarinfo.linkname\n limit=tarinfo\n \n member=self._getmember(linkname,tarinfo=limit,normalize=True)\n if member is None:\n raise KeyError(\"linkname %r not found\"%linkname)\n return member\n \n def __iter__(self):\n ''\n \n if self._loaded:\n yield from self.members\n return\n \n \n \n index=0\n \n \n \n if self.firstmember is not None:\n tarinfo=self.next()\n index +=1\n yield tarinfo\n \n while True:\n if index ',''),\n help='Extract tarfile into target dir')\n group.add_argument('-c','--create',nargs='+',\n metavar=('',''),\n help='Create tarfile from sources')\n group.add_argument('-t','--test',metavar='',\n help='Test if a tarfile is valid')\n \n args=parser.parse_args()\n \n if args.filter and args.extract is None:\n parser.exit(1,'--filter is only valid for extraction\\n')\n \n if args.test is not None:\n src=args.test\n if is_tarfile(src):\n with open(src,'r')as tar:\n tar.getmembers()\n print(tar.getmembers(),file=sys.stderr)\n if args.verbose:\n print('{!r} is a tar archive.'.format(src))\n else:\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.list is not None:\n src=args.list\n if is_tarfile(src):\n with TarFile.open(src,'r:*')as tf:\n tf.list(verbose=args.verbose)\n else:\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.extract is not None:\n if len(args.extract)==1:\n src=args.extract[0]\n curdir=os.curdir\n elif len(args.extract)==2:\n src,curdir=args.extract\n else:\n parser.exit(1,parser.format_help())\n \n if is_tarfile(src):\n with TarFile.open(src,'r:*')as tf:\n tf.extractall(path=curdir,filter=args.filter)\n if args.verbose:\n if curdir =='.':\n msg='{!r} file is extracted.'.format(src)\n else:\n msg=('{!r} file is extracted '\n 'into {!r} directory.').format(src,curdir)\n print(msg)\n else:\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.create is not None:\n tar_name=args.create.pop(0)\n _,ext=os.path.splitext(tar_name)\n compressions={\n \n '.gz':'gz',\n '.tgz':'gz',\n \n '.xz':'xz',\n '.txz':'xz',\n \n '.bz2':'bz2',\n '.tbz':'bz2',\n '.tbz2':'bz2',\n '.tb2':'bz2',\n }\n tar_mode='w:'+compressions[ext]if ext in compressions else 'w'\n tar_files=args.create\n \n with TarFile.open(tar_name,tar_mode)as tf:\n for file_name in tar_files:\n tf.add(file_name)\n \n if args.verbose:\n print('{!r} file created.'.format(tar_name))\n \nif __name__ =='__main__':\n main()\n", ["argparse", "builtins", "bz2", "copy", "grp", "gzip", "io", "lzma", "os", "pwd", "re", "shutil", "stat", "struct", "sys", "time", "warnings", "zlib"]], "tb": [".py", "import sys\nfrom browser import console\n\nclass Trace:\n\n def __init__(self):\n self.lines=[]\n \n def write(self,*data):\n self.lines.append(\" \".join([str(x)for x in data]))\n \n def format(self):\n return '\\n'.join(self.lines)+'\\n'\n \ndef format_exc():\n trace=Trace()\n exc_class,exc,tb=sys.exc_info()\n exc_msg=str(exc)\n \n def handle_repeats(filename,lineno,count_repeats):\n if count_repeats >0:\n trace_lines=trace.lines[:]\n for _ in range(2):\n if not filename.startswith('<'):\n trace.write(trace_lines[-2])\n trace.write(trace_lines[-1])\n else:\n trace.write(trace_lines[-1])\n count_repeats -=1\n if count_repeats ==0:\n break\n if count_repeats >1:\n trace.write(f'[Previous line repeated {count_repeats} '+\n f'more time{\"s\"if count_repeats >1 else \"\"}]')\n \n def show_line():\n trace.write(f' File \"{filename}\", line {lineno}, in {name}')\n if not filename.startswith(\"<\"):\n src=open(filename,encoding='utf-8').read()\n lines=src.split('\\n')\n line=lines[tb.tb_lineno -1]\n trace.write(f\" {line.strip()}\")\n \n show=True\n started=False\n save_filename=None\n save_lineno=None\n save_scope=None\n same_line=False\n count_repeats=0\n \n while tb is not None:\n if show:\n trace.write(\"Traceback (most recent call last):\")\n show=False\n frame=tb.tb_frame\n code=frame.f_code\n lineno=frame.f_lineno\n name=code.co_name\n filename=code.co_filename\n if filename ==save_filename and lineno ==save_lineno\\\n and name ==save_name:\n count_repeats +=1\n tb=tb.tb_next\n continue\n handle_repeats(save_filename,save_lineno,count_repeats)\n save_filename=filename\n save_lineno=lineno\n save_name=name\n count_repeats=0\n show_line()\n tb=tb.tb_next\n \n handle_repeats(filename,lineno,count_repeats)\n \n if isinstance(exc,SyntaxError):\n trace.write(syntax_error(exc.args))\n else:\n message=exc_msg\n if isinstance(exc,AttributeError):\n suggestion=__BRYTHON__.offer_suggestions_for_attribute_error(exc)\n if suggestion is not None:\n message +=f\". Did you mean: '{suggestion}'?\"\n elif isinstance(exc,NameError):\n suggestion=__BRYTHON__.offer_suggestions_for_name_error(exc)\n if suggestion is not None:\n message +=f\". Did you mean: '{suggestion}'?\"\n elif exc.name in __BRYTHON__.stdlib_module_names:\n message +=f\". Did you forget to import '{exc.name}'?\"\n trace.write(f\"{exc_class.__name__}: {message}\")\n \n return trace.format()\n \ndef print_exc(file=None):\n if file is None:\n file=sys.stderr\n file.write(format_exc())\n \ndef syntax_error(args):\n trace=Trace()\n info,[filename,lineno,offset,line,*extra]=args\n trace.write(f' File \"{filename}\", line {lineno}')\n indent=len(line)-len(line.lstrip())\n trace.write(\" \"+line.strip())\n nb_marks=1\n if extra:\n end_lineno,end_offset=extra\n if end_lineno >lineno:\n nb_marks=len(line)-offset\n else:\n nb_marks=end_offset -offset\n nb_marks=max(nb_marks,1)\n trace.write(\" \"+(offset -1)*\" \"+\"^\"*nb_marks)\n trace.write(\"SyntaxError:\",info)\n return trace.format()\n", ["browser", "sys"]], "tempfile": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\n\"NamedTemporaryFile\",\"TemporaryFile\",\n\"SpooledTemporaryFile\",\"TemporaryDirectory\",\n\"mkstemp\",\"mkdtemp\",\n\"mktemp\",\n\"TMP_MAX\",\"gettempprefix\",\n\"tempdir\",\"gettempdir\",\n\"gettempprefixb\",\"gettempdirb\",\n]\n\n\n\n\nimport functools as _functools\nimport warnings as _warnings\nimport io as _io\nimport os as _os\nimport shutil as _shutil\nimport errno as _errno\nfrom random import Random as _Random\nimport sys as _sys\nimport types as _types\nimport weakref as _weakref\nimport _thread\n_allocate_lock=_thread.allocate_lock\n\n_text_openflags=_os.O_RDWR |_os.O_CREAT |_os.O_EXCL\nif hasattr(_os,'O_NOFOLLOW'):\n _text_openflags |=_os.O_NOFOLLOW\n \n_bin_openflags=_text_openflags\nif hasattr(_os,'O_BINARY'):\n _bin_openflags |=_os.O_BINARY\n \nif hasattr(_os,'TMP_MAX'):\n TMP_MAX=_os.TMP_MAX\nelse:\n TMP_MAX=10000\n \n \n \n \n \ntemplate=\"tmp\"\n\n\n\n_once_lock=_allocate_lock()\n\n\ndef _exists(fn):\n try:\n _os.lstat(fn)\n except OSError:\n return False\n else:\n return True\n \n \ndef _infer_return_type(*args):\n ''\n return_type=None\n for arg in args:\n if arg is None:\n continue\n \n if isinstance(arg,_os.PathLike):\n arg=_os.fspath(arg)\n \n if isinstance(arg,bytes):\n if return_type is str:\n raise TypeError(\"Can't mix bytes and non-bytes in \"\n \"path components.\")\n return_type=bytes\n else:\n if return_type is bytes:\n raise TypeError(\"Can't mix bytes and non-bytes in \"\n \"path components.\")\n return_type=str\n if return_type is None:\n if tempdir is None or isinstance(tempdir,str):\n return str\n else:\n \n return bytes\n return return_type\n \n \ndef _sanitize_params(prefix,suffix,dir):\n ''\n output_type=_infer_return_type(prefix,suffix,dir)\n if suffix is None:\n suffix=output_type()\n if prefix is None:\n if output_type is str:\n prefix=template\n else:\n prefix=_os.fsencode(template)\n if dir is None:\n if output_type is str:\n dir=gettempdir()\n else:\n dir=gettempdirb()\n return prefix,suffix,dir,output_type\n \n \nclass _RandomNameSequence:\n ''\n\n\n\n\n \n \n characters=\"abcdefghijklmnopqrstuvwxyz0123456789_\"\n \n @property\n def rng(self):\n cur_pid=_os.getpid()\n if cur_pid !=getattr(self,'_rng_pid',None):\n self._rng=_Random()\n self._rng_pid=cur_pid\n return self._rng\n \n def __iter__(self):\n return self\n \n def __next__(self):\n return ''.join(self.rng.choices(self.characters,k=8))\n \ndef _candidate_tempdir_list():\n ''\n \n \n dirlist=[]\n \n \n for envname in 'TMPDIR','TEMP','TMP':\n dirname=_os.getenv(envname)\n if dirname:dirlist.append(dirname)\n \n \n if _os.name =='nt':\n dirlist.extend([_os.path.expanduser(r'~\\AppData\\Local\\Temp'),\n _os.path.expandvars(r'%SYSTEMROOT%\\Temp'),\n r'c:\\temp',r'c:\\tmp',r'\\temp',r'\\tmp'])\n else:\n dirlist.extend(['/tmp','/var/tmp','/usr/tmp'])\n \n \n try:\n dirlist.append(_os.getcwd())\n except(AttributeError,OSError):\n dirlist.append(_os.curdir)\n \n return dirlist\n \ndef _get_default_tempdir():\n ''\n\n\n\n\n\n \n \n namer=_RandomNameSequence()\n dirlist=_candidate_tempdir_list()\n \n for dir in dirlist:\n if dir !=_os.curdir:\n dir=_os.path.abspath(dir)\n \n for seq in range(100):\n name=next(namer)\n filename=_os.path.join(dir,name)\n try:\n fd=_os.open(filename,_bin_openflags,0o600)\n try:\n try:\n _os.write(fd,b'blat')\n finally:\n _os.close(fd)\n finally:\n _os.unlink(filename)\n return dir\n except FileExistsError:\n pass\n except PermissionError:\n \n \n if(_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n break\n except OSError:\n break\n raise FileNotFoundError(_errno.ENOENT,\n \"No usable temporary directory found in %s\"%\n dirlist)\n \n_name_sequence=None\n\ndef _get_candidate_names():\n ''\n \n global _name_sequence\n if _name_sequence is None:\n _once_lock.acquire()\n try:\n if _name_sequence is None:\n _name_sequence=_RandomNameSequence()\n finally:\n _once_lock.release()\n return _name_sequence\n \n \ndef _mkstemp_inner(dir,pre,suf,flags,output_type):\n ''\n \n dir=_os.path.abspath(dir)\n names=_get_candidate_names()\n if output_type is bytes:\n names=map(_os.fsencode,names)\n \n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,pre+name+suf)\n _sys.audit(\"tempfile.mkstemp\",file)\n try:\n fd=_os.open(file,flags,0o600)\n except FileExistsError:\n continue\n except PermissionError:\n \n \n if(_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n else:\n raise\n return fd,file\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary file name found\")\n \ndef _dont_follow_symlinks(func,path,*args):\n\n if func in _os.supports_follow_symlinks:\n func(path,*args,follow_symlinks=False)\n elif not _os.path.islink(path):\n func(path,*args)\n \ndef _resetperms(path):\n try:\n chflags=_os.chflags\n except AttributeError:\n pass\n else:\n _dont_follow_symlinks(chflags,path,0)\n _dont_follow_symlinks(_os.chmod,path,0o700)\n \n \n \n \ndef gettempprefix():\n ''\n return _os.fsdecode(template)\n \ndef gettempprefixb():\n ''\n return _os.fsencode(template)\n \ntempdir=None\n\ndef _gettempdir():\n ''\n global tempdir\n if tempdir is None:\n _once_lock.acquire()\n try:\n if tempdir is None:\n tempdir=_get_default_tempdir()\n finally:\n _once_lock.release()\n return tempdir\n \ndef gettempdir():\n ''\n return _os.fsdecode(_gettempdir())\n \ndef gettempdirb():\n ''\n return _os.fsencode(_gettempdir())\n \ndef mkstemp(suffix=None,prefix=None,dir=None,text=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n if text:\n flags=_text_openflags\n else:\n flags=_bin_openflags\n \n return _mkstemp_inner(dir,prefix,suffix,flags,output_type)\n \n \ndef mkdtemp(suffix=None,prefix=None,dir=None):\n ''\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n names=_get_candidate_names()\n if output_type is bytes:\n names=map(_os.fsencode,names)\n \n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,prefix+name+suffix)\n _sys.audit(\"tempfile.mkdtemp\",file)\n try:\n _os.mkdir(file,0o700)\n except FileExistsError:\n continue\n except PermissionError:\n \n \n if(_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n else:\n raise\n return _os.path.abspath(file)\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary directory name found\")\n \ndef mktemp(suffix=\"\",prefix=template,dir=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n if dir is None:\n dir=gettempdir()\n \n names=_get_candidate_names()\n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,prefix+name+suffix)\n if not _exists(file):\n return file\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary filename found\")\n \n \nclass _TemporaryFileCloser:\n ''\n\n \n \n cleanup_called=False\n close_called=False\n \n def __init__(self,file,name,delete=True,delete_on_close=True):\n self.file=file\n self.name=name\n self.delete=delete\n self.delete_on_close=delete_on_close\n \n def cleanup(self,windows=(_os.name =='nt'),unlink=_os.unlink):\n if not self.cleanup_called:\n self.cleanup_called=True\n try:\n if not self.close_called:\n self.close_called=True\n self.file.close()\n finally:\n \n \n if self.delete and not(windows and self.delete_on_close):\n try:\n unlink(self.name)\n except FileNotFoundError:\n pass\n \n def close(self):\n if not self.close_called:\n self.close_called=True\n try:\n self.file.close()\n finally:\n if self.delete and self.delete_on_close:\n self.cleanup()\n \n def __del__(self):\n self.cleanup()\n \n \nclass _TemporaryFileWrapper:\n ''\n\n\n\n\n \n \n def __init__(self,file,name,delete=True,delete_on_close=True):\n self.file=file\n self.name=name\n self._closer=_TemporaryFileCloser(file,name,delete,\n delete_on_close)\n \n def __getattr__(self,name):\n \n \n \n file=self.__dict__['file']\n a=getattr(file,name)\n if hasattr(a,'__call__'):\n func=a\n @_functools.wraps(func)\n def func_wrapper(*args,**kwargs):\n return func(*args,**kwargs)\n \n \n func_wrapper._closer=self._closer\n a=func_wrapper\n if not isinstance(a,int):\n setattr(self,name,a)\n return a\n \n \n \n def __enter__(self):\n self.file.__enter__()\n return self\n \n \n \n def __exit__(self,exc,value,tb):\n result=self.file.__exit__(exc,value,tb)\n self._closer.cleanup()\n return result\n \n def close(self):\n ''\n\n \n self._closer.close()\n \n \n def __iter__(self):\n \n \n \n \n \n for line in self.file:\n yield line\n \ndef NamedTemporaryFile(mode='w+b',buffering=-1,encoding=None,\nnewline=None,suffix=None,prefix=None,\ndir=None,delete=True,*,errors=None,\ndelete_on_close=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n flags=_bin_openflags\n \n \n \n if _os.name =='nt'and delete and delete_on_close:\n flags |=_os.O_TEMPORARY\n \n if \"b\"not in mode:\n encoding=_io.text_encoding(encoding)\n \n name=None\n def opener(*args):\n nonlocal name\n fd,name=_mkstemp_inner(dir,prefix,suffix,flags,output_type)\n return fd\n try:\n file=_io.open(dir,mode,buffering=buffering,\n newline=newline,encoding=encoding,errors=errors,\n opener=opener)\n try:\n raw=getattr(file,'buffer',file)\n raw=getattr(raw,'raw',raw)\n raw.name=name\n return _TemporaryFileWrapper(file,name,delete,delete_on_close)\n except:\n file.close()\n raise\n except:\n if name is not None and not(\n _os.name =='nt'and delete and delete_on_close):\n _os.unlink(name)\n raise\n \nif _os.name !='posix'or _sys.platform =='cygwin':\n\n\n TemporaryFile=NamedTemporaryFile\n \nelse:\n\n\n\n _O_TMPFILE_WORKS=hasattr(_os,'O_TMPFILE')\n \n def TemporaryFile(mode='w+b',buffering=-1,encoding=None,\n newline=None,suffix=None,prefix=None,\n dir=None,*,errors=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n global _O_TMPFILE_WORKS\n \n if \"b\"not in mode:\n encoding=_io.text_encoding(encoding)\n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n flags=_bin_openflags\n if _O_TMPFILE_WORKS:\n fd=None\n def opener(*args):\n nonlocal fd\n flags2=(flags |_os.O_TMPFILE)&~_os.O_CREAT\n fd=_os.open(dir,flags2,0o600)\n return fd\n try:\n file=_io.open(dir,mode,buffering=buffering,\n newline=newline,encoding=encoding,\n errors=errors,opener=opener)\n raw=getattr(file,'buffer',file)\n raw=getattr(raw,'raw',raw)\n raw.name=fd\n return file\n except IsADirectoryError:\n \n \n \n \n \n _O_TMPFILE_WORKS=False\n except OSError:\n \n \n \n \n \n \n \n pass\n \n \n fd=None\n def opener(*args):\n nonlocal fd\n fd,name=_mkstemp_inner(dir,prefix,suffix,flags,output_type)\n try:\n _os.unlink(name)\n except BaseException as e:\n _os.close(fd)\n raise\n return fd\n file=_io.open(dir,mode,buffering=buffering,\n newline=newline,encoding=encoding,errors=errors,\n opener=opener)\n raw=getattr(file,'buffer',file)\n raw=getattr(raw,'raw',raw)\n raw.name=fd\n return file\n \nclass SpooledTemporaryFile(_io.IOBase):\n ''\n\n\n \n _rolled=False\n \n def __init__(self,max_size=0,mode='w+b',buffering=-1,\n encoding=None,newline=None,\n suffix=None,prefix=None,dir=None,*,errors=None):\n if 'b'in mode:\n self._file=_io.BytesIO()\n else:\n encoding=_io.text_encoding(encoding)\n self._file=_io.TextIOWrapper(_io.BytesIO(),\n encoding=encoding,errors=errors,\n newline=newline)\n self._max_size=max_size\n self._rolled=False\n self._TemporaryFileArgs={'mode':mode,'buffering':buffering,\n 'suffix':suffix,'prefix':prefix,\n 'encoding':encoding,'newline':newline,\n 'dir':dir,'errors':errors}\n \n __class_getitem__=classmethod(_types.GenericAlias)\n \n def _check(self,file):\n if self._rolled:return\n max_size=self._max_size\n if max_size and file.tell()>max_size:\n self.rollover()\n \n def rollover(self):\n if self._rolled:return\n file=self._file\n newfile=self._file=TemporaryFile(**self._TemporaryFileArgs)\n del self._TemporaryFileArgs\n \n pos=file.tell()\n if hasattr(newfile,'buffer'):\n newfile.buffer.write(file.detach().getvalue())\n else:\n newfile.write(file.getvalue())\n newfile.seek(pos,0)\n \n self._rolled=True\n \n \n \n \n \n \n \n def __enter__(self):\n if self._file.closed:\n raise ValueError(\"Cannot enter context with closed file\")\n return self\n \n def __exit__(self,exc,value,tb):\n self._file.close()\n \n \n def __iter__(self):\n return self._file.__iter__()\n \n def __del__(self):\n if not self.closed:\n _warnings.warn(\n \"Unclosed file {!r}\".format(self),\n ResourceWarning,\n stacklevel=2,\n source=self\n )\n self.close()\n \n def close(self):\n self._file.close()\n \n @property\n def closed(self):\n return self._file.closed\n \n @property\n def encoding(self):\n return self._file.encoding\n \n @property\n def errors(self):\n return self._file.errors\n \n def fileno(self):\n self.rollover()\n return self._file.fileno()\n \n def flush(self):\n self._file.flush()\n \n def isatty(self):\n return self._file.isatty()\n \n @property\n def mode(self):\n try:\n return self._file.mode\n except AttributeError:\n return self._TemporaryFileArgs['mode']\n \n @property\n def name(self):\n try:\n return self._file.name\n except AttributeError:\n return None\n \n @property\n def newlines(self):\n return self._file.newlines\n \n def readable(self):\n return self._file.readable()\n \n def read(self,*args):\n return self._file.read(*args)\n \n def read1(self,*args):\n return self._file.read1(*args)\n \n def readinto(self,b):\n return self._file.readinto(b)\n \n def readinto1(self,b):\n return self._file.readinto1(b)\n \n def readline(self,*args):\n return self._file.readline(*args)\n \n def readlines(self,*args):\n return self._file.readlines(*args)\n \n def seekable(self):\n return self._file.seekable()\n \n def seek(self,*args):\n return self._file.seek(*args)\n \n def tell(self):\n return self._file.tell()\n \n def truncate(self,size=None):\n if size is None:\n return self._file.truncate()\n else:\n if size >self._max_size:\n self.rollover()\n return self._file.truncate(size)\n \n def writable(self):\n return self._file.writable()\n \n def write(self,s):\n file=self._file\n rv=file.write(s)\n self._check(file)\n return rv\n \n def writelines(self,iterable):\n file=self._file\n rv=file.writelines(iterable)\n self._check(file)\n return rv\n \n def detach(self):\n return self._file.detach()\n \n \nclass TemporaryDirectory:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,suffix=None,prefix=None,dir=None,\n ignore_cleanup_errors=False,*,delete=True):\n self.name=mkdtemp(suffix,prefix,dir)\n self._ignore_cleanup_errors=ignore_cleanup_errors\n self._delete=delete\n self._finalizer=_weakref.finalize(\n self,self._cleanup,self.name,\n warn_message=\"Implicitly cleaning up {!r}\".format(self),\n ignore_errors=self._ignore_cleanup_errors,delete=self._delete)\n \n @classmethod\n def _rmtree(cls,name,ignore_errors=False,repeated=False):\n def onexc(func,path,exc):\n if isinstance(exc,PermissionError):\n if repeated and path ==name:\n if ignore_errors:\n return\n raise\n \n try:\n if path !=name:\n _resetperms(_os.path.dirname(path))\n _resetperms(path)\n \n try:\n _os.unlink(path)\n except IsADirectoryError:\n cls._rmtree(path,ignore_errors=ignore_errors)\n except PermissionError:\n \n \n \n \n \n \n \n if not _os.path.isdir(path)or _os.path.isjunction(path):\n if ignore_errors:\n return\n raise\n cls._rmtree(path,ignore_errors=ignore_errors,\n repeated=(path ==name))\n except FileNotFoundError:\n pass\n elif isinstance(exc,FileNotFoundError):\n pass\n else:\n if not ignore_errors:\n raise\n \n _shutil.rmtree(name,onexc=onexc)\n \n @classmethod\n def _cleanup(cls,name,warn_message,ignore_errors=False,delete=True):\n if delete:\n cls._rmtree(name,ignore_errors=ignore_errors)\n _warnings.warn(warn_message,ResourceWarning)\n \n def __repr__(self):\n return \"<{} {!r}>\".format(self.__class__.__name__,self.name)\n \n def __enter__(self):\n return self.name\n \n def __exit__(self,exc,value,tb):\n if self._delete:\n self.cleanup()\n \n def cleanup(self):\n if self._finalizer.detach()or _os.path.exists(self.name):\n self._rmtree(self.name,ignore_errors=self._ignore_cleanup_errors)\n \n __class_getitem__=classmethod(_types.GenericAlias)\n", ["_thread", "errno", "functools", "io", "os", "random", "shutil", "sys", "types", "warnings", "weakref"]], "textwrap": [".py", "''\n\n\n\n\n\n\nimport re\n\n__all__=['TextWrapper','wrap','fill','dedent','indent','shorten']\n\n\n\n\n_whitespace='\\t\\n\\x0b\\x0c\\r '\n\nclass TextWrapper:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n unicode_whitespace_trans=dict.fromkeys(map(ord,_whitespace),ord(' '))\n \n \n \n \n \n \n \n word_punct=r'[\\w!\"\\'&.,?]'\n letter=r'[^\\d\\W]'\n whitespace=r'[%s]'%re.escape(_whitespace)\n nowhitespace='[^'+whitespace[1:]\n wordsep_re=re.compile(r'''\n ( # any whitespace\n %(ws)s+\n | # em-dash between words\n (?<=%(wp)s) -{2,} (?=\\w)\n | # word, possibly hyphenated\n %(nws)s+? (?:\n # hyphenated word\n -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))\n (?= %(lt)s -? %(lt)s)\n | # end of word\n (?=%(ws)s|\\Z)\n | # em-dash\n (?<=%(wp)s) (?=-{2,}\\w)\n )\n )'''%{'wp':word_punct,'lt':letter,\n 'ws':whitespace,'nws':nowhitespace},\n re.VERBOSE)\n del word_punct,letter,nowhitespace\n \n \n \n \n \n wordsep_simple_re=re.compile(r'(%s+)'%whitespace)\n del whitespace\n \n \n \n sentence_end_re=re.compile(r'[a-z]'\n r'[\\.\\!\\?]'\n r'[\\\"\\']?'\n r'\\Z')\n \n def __init__(self,\n width=70,\n initial_indent=\"\",\n subsequent_indent=\"\",\n expand_tabs=True,\n replace_whitespace=True,\n fix_sentence_endings=False,\n break_long_words=True,\n drop_whitespace=True,\n break_on_hyphens=True,\n tabsize=8,\n *,\n max_lines=None,\n placeholder=' [...]'):\n self.width=width\n self.initial_indent=initial_indent\n self.subsequent_indent=subsequent_indent\n self.expand_tabs=expand_tabs\n self.replace_whitespace=replace_whitespace\n self.fix_sentence_endings=fix_sentence_endings\n self.break_long_words=break_long_words\n self.drop_whitespace=drop_whitespace\n self.break_on_hyphens=break_on_hyphens\n self.tabsize=tabsize\n self.max_lines=max_lines\n self.placeholder=placeholder\n \n \n \n \n \n def _munge_whitespace(self,text):\n ''\n\n\n\n\n \n if self.expand_tabs:\n text=text.expandtabs(self.tabsize)\n if self.replace_whitespace:\n text=text.translate(self.unicode_whitespace_trans)\n return text\n \n \n def _split(self,text):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self.break_on_hyphens is True:\n chunks=self.wordsep_re.split(text)\n else:\n chunks=self.wordsep_simple_re.split(text)\n chunks=[c for c in chunks if c]\n return chunks\n \n def _fix_sentence_endings(self,chunks):\n ''\n\n\n\n\n\n\n \n i=0\n patsearch=self.sentence_end_re.search\n while i space_left:\n \n \n hyphen=chunk.rfind('-',0,space_left)\n if hyphen >0 and any(c !='-'for c in chunk[:hyphen]):\n end=hyphen+1\n cur_line.append(chunk[:end])\n reversed_chunks[-1]=chunk[end:]\n \n \n \n \n elif not cur_line:\n cur_line.append(reversed_chunks.pop())\n \n \n \n \n \n \n \n def _wrap_chunks(self,chunks):\n ''\n\n\n\n\n\n\n\n\n\n\n \n lines=[]\n if self.width <=0:\n raise ValueError(\"invalid width %r (must be > 0)\"%self.width)\n if self.max_lines is not None:\n if self.max_lines >1:\n indent=self.subsequent_indent\n else:\n indent=self.initial_indent\n if len(indent)+len(self.placeholder.lstrip())>self.width:\n raise ValueError(\"placeholder too large for max width\")\n \n \n \n chunks.reverse()\n \n while chunks:\n \n \n \n cur_line=[]\n cur_len=0\n \n \n if lines:\n indent=self.subsequent_indent\n else:\n indent=self.initial_indent\n \n \n width=self.width -len(indent)\n \n \n \n if self.drop_whitespace and chunks[-1].strip()==''and lines:\n del chunks[-1]\n \n while chunks:\n l=len(chunks[-1])\n \n \n if cur_len+l <=width:\n cur_line.append(chunks.pop())\n cur_len +=l\n \n \n else:\n break\n \n \n \n if chunks and len(chunks[-1])>width:\n self._handle_long_word(chunks,cur_line,cur_len,width)\n cur_len=sum(map(len,cur_line))\n \n \n if self.drop_whitespace and cur_line and cur_line[-1].strip()=='':\n cur_len -=len(cur_line[-1])\n del cur_line[-1]\n \n if cur_line:\n if(self.max_lines is None or\n len(lines)+1 \"%(\n \"locked\"if self._block.locked()else \"unlocked\",\n self.__class__.__module__,\n self.__class__.__qualname__,\n owner,\n self._count,\n hex(id(self))\n )\n \n def _at_fork_reinit(self):\n self._block._at_fork_reinit()\n self._owner=None\n self._count=0\n \n def acquire(self,blocking=True,timeout=-1):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n me=get_ident()\n if self._owner ==me:\n self._count +=1\n return 1\n rc=self._block.acquire(blocking,timeout)\n if rc:\n self._owner=me\n self._count=1\n return rc\n \n __enter__=acquire\n \n def release(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self._owner !=get_ident():\n raise RuntimeError(\"cannot release un-acquired lock\")\n self._count=count=self._count -1\n if not count:\n self._owner=None\n self._block.release()\n \n def __exit__(self,t,v,tb):\n self.release()\n \n \n \n def _acquire_restore(self,state):\n self._block.acquire()\n self._count,self._owner=state\n \n def _release_save(self):\n if self._count ==0:\n raise RuntimeError(\"cannot release un-acquired lock\")\n count=self._count\n self._count=0\n owner=self._owner\n self._owner=None\n self._block.release()\n return(count,owner)\n \n def _is_owned(self):\n return self._owner ==get_ident()\n \n \n \n def _recursion_count(self):\n if self._owner !=get_ident():\n return 0\n return self._count\n \n_PyRLock=_RLock\n\n\nclass Condition:\n ''\n\n\n\n\n\n\n\n\n \n \n def __init__(self,lock=None):\n if lock is None:\n lock=RLock()\n self._lock=lock\n \n self.acquire=lock.acquire\n self.release=lock.release\n \n \n \n if hasattr(lock,'_release_save'):\n self._release_save=lock._release_save\n if hasattr(lock,'_acquire_restore'):\n self._acquire_restore=lock._acquire_restore\n if hasattr(lock,'_is_owned'):\n self._is_owned=lock._is_owned\n self._waiters=_deque()\n \n def _at_fork_reinit(self):\n self._lock._at_fork_reinit()\n self._waiters.clear()\n \n def __enter__(self):\n return self._lock.__enter__()\n \n def __exit__(self,*args):\n return self._lock.__exit__(*args)\n \n def __repr__(self):\n return \"\"%(self._lock,len(self._waiters))\n \n def _release_save(self):\n self._lock.release()\n \n def _acquire_restore(self,x):\n self._lock.acquire()\n \n def _is_owned(self):\n \n \n if self._lock.acquire(False):\n self._lock.release()\n return False\n else:\n return True\n \n def wait(self,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not self._is_owned():\n raise RuntimeError(\"cannot wait on un-acquired lock\")\n waiter=_allocate_lock()\n waiter.acquire()\n self._waiters.append(waiter)\n saved_state=self._release_save()\n gotit=False\n try:\n if timeout is None:\n waiter.acquire()\n gotit=True\n else:\n if timeout >0:\n gotit=waiter.acquire(True,timeout)\n else:\n gotit=waiter.acquire(False)\n return gotit\n finally:\n self._acquire_restore(saved_state)\n if not gotit:\n try:\n self._waiters.remove(waiter)\n except ValueError:\n pass\n \n def wait_for(self,predicate,timeout=None):\n ''\n\n\n\n\n\n \n endtime=None\n waittime=timeout\n result=predicate()\n while not result:\n if waittime is not None:\n if endtime is None:\n endtime=_time()+waittime\n else:\n waittime=endtime -_time()\n if waittime <=0:\n break\n self.wait(waittime)\n result=predicate()\n return result\n \n def notify(self,n=1):\n ''\n\n\n\n\n\n\n\n \n if not self._is_owned():\n raise RuntimeError(\"cannot notify on un-acquired lock\")\n waiters=self._waiters\n while waiters and n >0:\n waiter=waiters[0]\n try:\n waiter.release()\n except RuntimeError:\n \n \n \n \n pass\n else:\n n -=1\n try:\n waiters.remove(waiter)\n except ValueError:\n pass\n \n def notify_all(self):\n ''\n\n\n\n\n \n self.notify(len(self._waiters))\n \n def notifyAll(self):\n ''\n\n\n\n \n import warnings\n warnings.warn('notifyAll() is deprecated, use notify_all() instead',\n DeprecationWarning,stacklevel=2)\n self.notify_all()\n \n \nclass Semaphore:\n ''\n\n\n\n\n\n\n \n \n \n \n def __init__(self,value=1):\n if value <0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n self._cond=Condition(Lock())\n self._value=value\n \n def __repr__(self):\n cls=self.__class__\n return(f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}:\"\n f\" value={self._value}>\")\n \n def acquire(self,blocking=True,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not blocking and timeout is not None:\n raise ValueError(\"can't specify timeout for non-blocking acquire\")\n rc=False\n endtime=None\n with self._cond:\n while self._value ==0:\n if not blocking:\n break\n if timeout is not None:\n if endtime is None:\n endtime=_time()+timeout\n else:\n timeout=endtime -_time()\n if timeout <=0:\n break\n self._cond.wait(timeout)\n else:\n self._value -=1\n rc=True\n return rc\n \n __enter__=acquire\n \n def release(self,n=1):\n ''\n\n\n\n\n \n if n <1:\n raise ValueError('n must be one or more')\n with self._cond:\n self._value +=n\n self._cond.notify(n)\n \n def __exit__(self,t,v,tb):\n self.release()\n \n \nclass BoundedSemaphore(Semaphore):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,value=1):\n super().__init__(value)\n self._initial_value=value\n \n def __repr__(self):\n cls=self.__class__\n return(f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}:\"\n f\" value={self._value}/{self._initial_value}>\")\n \n def release(self,n=1):\n ''\n\n\n\n\n\n\n\n \n if n <1:\n raise ValueError('n must be one or more')\n with self._cond:\n if self._value+n >self._initial_value:\n raise ValueError(\"Semaphore released too many times\")\n self._value +=n\n self._cond.notify(n)\n \n \nclass Event:\n ''\n\n\n\n\n\n \n \n \n \n def __init__(self):\n self._cond=Condition(Lock())\n self._flag=False\n \n def __repr__(self):\n cls=self.__class__\n status='set'if self._flag else 'unset'\n return f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}: {status}>\"\n \n def _at_fork_reinit(self):\n \n self._cond._at_fork_reinit()\n \n def is_set(self):\n ''\n return self._flag\n \n def isSet(self):\n ''\n\n\n\n \n import warnings\n warnings.warn('isSet() is deprecated, use is_set() instead',\n DeprecationWarning,stacklevel=2)\n return self.is_set()\n \n def set(self):\n ''\n\n\n\n\n \n with self._cond:\n self._flag=True\n self._cond.notify_all()\n \n def clear(self):\n ''\n\n\n\n\n \n with self._cond:\n self._flag=False\n \n def wait(self,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n with self._cond:\n signaled=self._flag\n if not signaled:\n signaled=self._cond.wait(timeout)\n return signaled\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass Barrier:\n ''\n\n\n\n\n\n \n \n def __init__(self,parties,action=None,timeout=None):\n ''\n\n\n\n\n\n\n \n self._cond=Condition(Lock())\n self._action=action\n self._timeout=timeout\n self._parties=parties\n self._state=0\n self._count=0\n \n def __repr__(self):\n cls=self.__class__\n if self.broken:\n return f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}: broken>\"\n return(f\"<{cls.__module__}.{cls.__qualname__} at {id(self):#x}:\"\n f\" waiters={self.n_waiting}/{self.parties}>\")\n \n def wait(self,timeout=None):\n ''\n\n\n\n\n\n\n \n if timeout is None:\n timeout=self._timeout\n with self._cond:\n self._enter()\n index=self._count\n self._count +=1\n try:\n if index+1 ==self._parties:\n \n self._release()\n else:\n \n self._wait(timeout)\n return index\n finally:\n self._count -=1\n \n self._exit()\n \n \n \n def _enter(self):\n while self._state in(-1,1):\n \n self._cond.wait()\n \n if self._state <0:\n raise BrokenBarrierError\n assert self._state ==0\n \n \n \n def _release(self):\n try:\n if self._action:\n self._action()\n \n self._state=1\n self._cond.notify_all()\n except:\n \n self._break()\n raise\n \n \n \n def _wait(self,timeout):\n if not self._cond.wait_for(lambda:self._state !=0,timeout):\n \n self._break()\n raise BrokenBarrierError\n if self._state <0:\n raise BrokenBarrierError\n assert self._state ==1\n \n \n \n def _exit(self):\n if self._count ==0:\n if self._state in(-1,1):\n \n self._state=0\n self._cond.notify_all()\n \n def reset(self):\n ''\n\n\n\n\n \n with self._cond:\n if self._count >0:\n if self._state ==0:\n \n self._state=-1\n elif self._state ==-2:\n \n \n self._state=-1\n else:\n self._state=0\n self._cond.notify_all()\n \n def abort(self):\n ''\n\n\n\n\n \n with self._cond:\n self._break()\n \n def _break(self):\n \n \n self._state=-2\n self._cond.notify_all()\n \n @property\n def parties(self):\n ''\n return self._parties\n \n @property\n def n_waiting(self):\n ''\n \n \n if self._state ==0:\n return self._count\n return 0\n \n @property\n def broken(self):\n ''\n return self._state ==-2\n \n \nclass BrokenBarrierError(RuntimeError):\n pass\n \n \n \n_counter=_count(1).__next__\ndef _newname(name_template):\n return name_template %_counter()\n \n \n \n \n \n_active_limbo_lock=RLock()\n_active={}\n_limbo={}\n_dangling=WeakSet()\n\n\n\n\nclass Thread:\n ''\n\n\n\n\n\n \n \n _initialized=False\n \n def __init__(self,group=None,target=None,name=None,\n args=(),kwargs=None,*,daemon=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n assert group is None,\"group argument must be None for now\"\n if kwargs is None:\n kwargs={}\n if name:\n name=str(name)\n else:\n name=_newname(\"Thread-%d\")\n if target is not None:\n try:\n target_name=target.__name__\n name +=f\" ({target_name})\"\n except AttributeError:\n pass\n \n self._target=target\n self._name=name\n self._args=args\n self._kwargs=kwargs\n if daemon is not None:\n if daemon and not _daemon_threads_allowed():\n raise RuntimeError('daemon threads are disabled in this (sub)interpreter')\n self._daemonic=daemon\n else:\n self._daemonic=current_thread().daemon\n self._ident=None\n if _HAVE_THREAD_NATIVE_ID:\n self._native_id=None\n self._handle=_ThreadHandle()\n self._started=Event()\n self._initialized=True\n \n self._stderr=_sys.stderr\n self._invoke_excepthook=_make_invoke_excepthook()\n \n _dangling.add(self)\n \n def _after_fork(self,new_ident=None):\n \n self._started._at_fork_reinit()\n if new_ident is not None:\n \n self._ident=new_ident\n assert self._handle.ident ==new_ident\n else:\n \n \n pass\n \n def __repr__(self):\n assert self._initialized,\"Thread.__init__() was not called\"\n status=\"initial\"\n if self._started.is_set():\n status=\"started\"\n if self._handle.is_done():\n status=\"stopped\"\n if self._daemonic:\n status +=\" daemon\"\n if self._ident is not None:\n status +=\" %s\"%self._ident\n return \"<%s(%s, %s)>\"%(self.__class__.__name__,self._name,status)\n \n def start(self):\n ''\n\n\n\n\n\n\n\n \n if not self._initialized:\n raise RuntimeError(\"thread.__init__() not called\")\n \n if self._started.is_set():\n raise RuntimeError(\"threads can only be started once\")\n \n with _active_limbo_lock:\n _limbo[self]=self\n try:\n \n _start_joinable_thread(self._bootstrap,handle=self._handle,\n daemon=self.daemon)\n except Exception:\n with _active_limbo_lock:\n del _limbo[self]\n raise\n self._started.wait()\n \n def run(self):\n ''\n\n\n\n\n\n\n \n try:\n if self._target is not None:\n self._target(*self._args,**self._kwargs)\n finally:\n \n \n del self._target,self._args,self._kwargs\n \n def _bootstrap(self):\n \n \n \n \n \n \n \n \n \n \n \n \n try:\n self._bootstrap_inner()\n except:\n if self._daemonic and _sys is None:\n return\n raise\n \n def _set_ident(self):\n self._ident=get_ident()\n \n if _HAVE_THREAD_NATIVE_ID:\n def _set_native_id(self):\n self._native_id=get_native_id()\n \n def _bootstrap_inner(self):\n try:\n self._set_ident()\n if _HAVE_THREAD_NATIVE_ID:\n self._set_native_id()\n self._started.set()\n with _active_limbo_lock:\n _active[self._ident]=self\n del _limbo[self]\n \n if _trace_hook:\n _sys.settrace(_trace_hook)\n if _profile_hook:\n _sys.setprofile(_profile_hook)\n \n try:\n self.run()\n except:\n self._invoke_excepthook(self)\n finally:\n self._delete()\n \n def _delete(self):\n ''\n with _active_limbo_lock:\n del _active[get_ident()]\n \n \n \n \n \n def join(self,timeout=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not self._initialized:\n raise RuntimeError(\"Thread.__init__() not called\")\n if not self._started.is_set():\n raise RuntimeError(\"cannot join thread before it is started\")\n if self is current_thread():\n raise RuntimeError(\"cannot join current thread\")\n \n \n \n if timeout is not None:\n timeout=max(timeout,0)\n \n self._handle.join(timeout)\n \n @property\n def name(self):\n ''\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._name\n \n @name.setter\n def name(self,name):\n assert self._initialized,\"Thread.__init__() not called\"\n self._name=str(name)\n \n @property\n def ident(self):\n ''\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._ident\n \n if _HAVE_THREAD_NATIVE_ID:\n @property\n def native_id(self):\n ''\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._native_id\n \n def is_alive(self):\n ''\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._started.is_set()and not self._handle.is_done()\n \n @property\n def daemon(self):\n ''\n\n\n\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._daemonic\n \n @daemon.setter\n def daemon(self,daemonic):\n if not self._initialized:\n raise RuntimeError(\"Thread.__init__() not called\")\n if daemonic and not _daemon_threads_allowed():\n raise RuntimeError('daemon threads are disabled in this interpreter')\n if self._started.is_set():\n raise RuntimeError(\"cannot set daemon status of active thread\")\n self._daemonic=daemonic\n \n def isDaemon(self):\n ''\n\n\n\n \n import warnings\n warnings.warn('isDaemon() is deprecated, get the daemon attribute instead',\n DeprecationWarning,stacklevel=2)\n return self.daemon\n \n def setDaemon(self,daemonic):\n ''\n\n\n\n \n import warnings\n warnings.warn('setDaemon() is deprecated, set the daemon attribute instead',\n DeprecationWarning,stacklevel=2)\n self.daemon=daemonic\n \n def getName(self):\n ''\n\n\n\n \n import warnings\n warnings.warn('getName() is deprecated, get the name attribute instead',\n DeprecationWarning,stacklevel=2)\n return self.name\n \n def setName(self,name):\n ''\n\n\n\n \n import warnings\n warnings.warn('setName() is deprecated, set the name attribute instead',\n DeprecationWarning,stacklevel=2)\n self.name=name\n \n \ntry:\n from _thread import(_excepthook as excepthook,\n _ExceptHookArgs as ExceptHookArgs)\nexcept ImportError:\n\n from traceback import print_exception as _print_exception\n from collections import namedtuple\n \n _ExceptHookArgs=namedtuple(\n 'ExceptHookArgs',\n 'exc_type exc_value exc_traceback thread')\n \n def ExceptHookArgs(args):\n return _ExceptHookArgs(*args)\n \n def excepthook(args,/):\n ''\n\n \n if args.exc_type ==SystemExit:\n \n return\n \n if _sys is not None and _sys.stderr is not None:\n stderr=_sys.stderr\n elif args.thread is not None:\n stderr=args.thread._stderr\n if stderr is None:\n \n \n return\n else:\n \n return\n \n if args.thread is not None:\n name=args.thread.name\n else:\n name=get_ident()\n print(f\"Exception in thread {name}:\",\n file=stderr,flush=True)\n _print_exception(args.exc_type,args.exc_value,args.exc_traceback,\n file=stderr)\n stderr.flush()\n \n \n \n__excepthook__=excepthook\n\n\ndef _make_invoke_excepthook():\n\n\n\n\n old_excepthook=excepthook\n old_sys_excepthook=_sys.excepthook\n if old_excepthook is None:\n raise RuntimeError(\"threading.excepthook is None\")\n if old_sys_excepthook is None:\n raise RuntimeError(\"sys.excepthook is None\")\n \n sys_exc_info=_sys.exc_info\n local_print=print\n local_sys=_sys\n \n def invoke_excepthook(thread):\n global excepthook\n try:\n hook=excepthook\n if hook is None:\n hook=old_excepthook\n \n args=ExceptHookArgs([*sys_exc_info(),thread])\n \n hook(args)\n except Exception as exc:\n exc.__suppress_context__=True\n del exc\n \n if local_sys is not None and local_sys.stderr is not None:\n stderr=local_sys.stderr\n else:\n stderr=thread._stderr\n \n local_print(\"Exception in threading.excepthook:\",\n file=stderr,flush=True)\n \n if local_sys is not None and local_sys.excepthook is not None:\n sys_excepthook=local_sys.excepthook\n else:\n sys_excepthook=old_sys_excepthook\n \n sys_excepthook(*sys_exc_info())\n finally:\n \n args=None\n \n return invoke_excepthook\n \n \n \n \nclass Timer(Thread):\n ''\n\n\n\n\n\n \n \n def __init__(self,interval,function,args=None,kwargs=None):\n Thread.__init__(self)\n self.interval=interval\n self.function=function\n self.args=args if args is not None else[]\n self.kwargs=kwargs if kwargs is not None else{}\n self.finished=Event()\n \n def cancel(self):\n ''\n self.finished.set()\n \n def run(self):\n self.finished.wait(self.interval)\n if not self.finished.is_set():\n self.function(*self.args,**self.kwargs)\n self.finished.set()\n \n \n \n \nclass _MainThread(Thread):\n\n def __init__(self):\n Thread.__init__(self,name=\"MainThread\",daemon=False)\n self._started.set()\n self._ident=_get_main_thread_ident()\n self._handle=_make_thread_handle(self._ident)\n if _HAVE_THREAD_NATIVE_ID:\n self._set_native_id()\n with _active_limbo_lock:\n _active[self._ident]=self\n \n \n \n \n_thread_local_info=local()\n\n\nclass _DeleteDummyThreadOnDel:\n ''\n\n \n \n def __init__(self,dummy_thread):\n self._dummy_thread=dummy_thread\n self._tident=dummy_thread.ident\n \n \n \n \n \n \n _thread_local_info._track_dummy_thread_ref=self\n \n def __del__(self):\n with _active_limbo_lock:\n if _active.get(self._tident)is self._dummy_thread:\n _active.pop(self._tident,None)\n \n \n \n \n \n \n \n \n \nclass _DummyThread(Thread):\n\n def __init__(self):\n Thread.__init__(self,name=_newname(\"Dummy-%d\"),\n daemon=_daemon_threads_allowed())\n self._started.set()\n self._set_ident()\n self._handle=_make_thread_handle(self._ident)\n if _HAVE_THREAD_NATIVE_ID:\n self._set_native_id()\n with _active_limbo_lock:\n _active[self._ident]=self\n _DeleteDummyThreadOnDel(self)\n \n def is_alive(self):\n if not self._handle.is_done()and self._started.is_set():\n return True\n raise RuntimeError(\"thread is not alive\")\n \n def join(self,timeout=None):\n raise RuntimeError(\"cannot join a dummy thread\")\n \n def _after_fork(self,new_ident=None):\n if new_ident is not None:\n self.__class__=_MainThread\n self._name='MainThread'\n self._daemonic=False\n Thread._after_fork(self,new_ident=new_ident)\n \n \n \n \ndef current_thread():\n ''\n\n\n\n\n \n try:\n return _active[get_ident()]\n except KeyError:\n return _DummyThread()\n \ndef currentThread():\n ''\n\n\n\n \n import warnings\n warnings.warn('currentThread() is deprecated, use current_thread() instead',\n DeprecationWarning,stacklevel=2)\n return current_thread()\n \ndef active_count():\n ''\n\n\n\n\n \n \n \n with _active_limbo_lock:\n return len(_active)+len(_limbo)\n \ndef activeCount():\n ''\n\n\n\n \n import warnings\n warnings.warn('activeCount() is deprecated, use active_count() instead',\n DeprecationWarning,stacklevel=2)\n return active_count()\n \ndef _enumerate():\n\n return list(_active.values())+list(_limbo.values())\n \ndef enumerate():\n ''\n\n\n\n\n\n \n with _active_limbo_lock:\n return list(_active.values())+list(_limbo.values())\n \n \n_threading_atexits=[]\n_SHUTTING_DOWN=False\n\ndef _register_atexit(func,*arg,**kwargs):\n ''\n\n\n\n\n\n\n\n \n if _SHUTTING_DOWN:\n raise RuntimeError(\"can't register atexit after shutdown\")\n \n _threading_atexits.append(lambda:func(*arg,**kwargs))\n \n \nfrom _thread import stack_size\n\n\n\n\n\n_main_thread=_MainThread()\n\ndef _shutdown():\n ''\n\n \n \n \n \n \n if _main_thread._handle.is_done()and _is_main_interpreter():\n \n return\n \n global _SHUTTING_DOWN\n _SHUTTING_DOWN=True\n \n \n \n for atexit_call in reversed(_threading_atexits):\n atexit_call()\n \n if _is_main_interpreter():\n _main_thread._handle._set_done()\n \n \n _thread_shutdown()\n \n \ndef main_thread():\n ''\n\n\n\n \n \n return _main_thread\n \n \ndef _after_fork():\n ''\n\n \n \n \n global _active_limbo_lock,_main_thread\n _active_limbo_lock=RLock()\n \n \n new_active={}\n \n try:\n current=_active[get_ident()]\n except KeyError:\n \n \n \n current=_MainThread()\n \n _main_thread=current\n \n with _active_limbo_lock:\n \n \n threads=set(_enumerate())\n threads.update(_dangling)\n for thread in threads:\n \n \n if thread is current:\n \n ident=get_ident()\n thread._after_fork(new_ident=ident)\n new_active[ident]=thread\n else:\n \n thread._after_fork()\n \n _limbo.clear()\n _active.clear()\n _active.update(new_active)\n assert len(_active)==1\n \n \nif hasattr(_os,\"register_at_fork\"):\n _os.register_at_fork(after_in_child=_after_fork)\n", ["_collections", "_thread", "_threading_local", "_weakrefset", "collections", "itertools", "os", "sys", "time", "traceback", "warnings"]], "time": [".py", "from browser import self as window\nimport _locale\nimport javascript\n\n\ndate=javascript.Date.new\nnow=javascript.Date.now\n\n\n\n\n\n\n\n_STRUCT_TM_ITEMS=9\n\n\n\n\n\ndef _get_day_of_year(arg):\n ''\n\n\n\n\n\n\n\n\n\n \n ml=[31,28,31,30,31,30,31,31,30,31,30,31]\n if arg[0]%4 ==0:\n ml[1]+=1\n i=1\n yday=0\n while i mm >13:\n raise ValueError(\"month out of range\")\n \n dd=t[2]\n if dd ==0:dd=1\n if -1 >dd >32:\n raise ValueError(\"day of month out of range\")\n \n hh=t[3]\n if -1 >hh >24:\n raise ValueError(\"hour out of range\")\n \n minu=t[4]\n if -1 >minu >60:\n raise ValueError(\"minute out of range\")\n \n ss=t[5]\n if -1 >ss >62:\n raise ValueError(\"seconds out of range\")\n \n wd=t[6]%7\n if wd <-2:\n raise ValueError(\"day of week out of range\")\n \n dy=t[7]\n if dy ==0:dy=1\n if -1 >dy >367:\n raise ValueError(\"day of year out of range\")\n \n return t[0],mm,dd,hh,minu,ss,wd,dy,t[-1]\n \n \ndef _is_dst(secs=None):\n ''\n d=date()\n if secs is not None:\n d=date(secs *1000)\n \n \n \n jan=date(d.getFullYear(),0,1)\n jul=date(d.getFullYear(),6,1)\n dst=int(d.getTimezoneOffset()=0 else 6\n tmp=struct_time([d.getUTCFullYear(),\n d.getUTCMonth()+1,d.getUTCDate(),\n d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),\n wday,0,0])\n tmp.args[7]=_get_day_of_year(tmp.args)\n return tmp\n \ndef localtime(secs=None):\n d=date()\n if secs is not None:\n d=date(secs *1000)\n dst=_is_dst(secs)\n wday=d.getDay()-1 if d.getDay()-1 >=0 else 6\n tmp=struct_time([d.getFullYear(),\n d.getMonth()+1,d.getDate(),\n d.getHours(),d.getMinutes(),d.getSeconds(),\n wday,0,dst])\n tmp.args[7]=_get_day_of_year(tmp.args)\n return tmp\n \ndef mktime(t):\n if isinstance(t,struct_time):\n d1=date(t.tm_year,t.tm_mon -1,t.tm_mday,\n t.tm_hour,t.tm_min,t.tm_sec,0).getTime()\n elif isinstance(t,tuple):\n d1=date(t[0],t[1]-1,t[2],t[3],t[4],t[5],0).getTime()\n else:\n raise ValueError(\"Tuple or struct_time argument required\")\n d2=date(0).getTime()\n return(d1 -d2)/1000.\n \ndef monotonic():\n return now()/1000.\n \ndef perf_counter():\n return window.performance.now()/1000.\n \ndef process_time():\n return now()/1000.\n \ndef time():\n return float(date().getTime()/1000)\n \ndef sleep(secs):\n ''\n\n \n \n float(secs)\n raise NotImplementedError(\"Blocking functions like time.sleep() are not \"\n \"supported in the browser. Use functions in module browser.timer \"\n \"instead.\")\n \ndef strftime(_format,t=None):\n def ns(t,nb):\n \n res=str(t)\n while len(res) float\n repeat(string, string) -> list\n default_timer() -> float\n\n\"\"\"\n\nimport gc\nimport itertools\nimport sys\nimport time\n\n__all__=[\"Timer\",\"timeit\",\"repeat\",\"default_timer\"]\n\ndummy_src_name=\"\"\ndefault_number=1000000\ndefault_repeat=5\ndefault_timer=time.perf_counter\n\n_globals=globals\n\n\n\n\ntemplate=\"\"\"\ndef inner(_it, _timer{init}):\n {setup}\n _t0 = _timer()\n for _i in _it:\n {stmt}\n pass\n _t1 = _timer()\n return _t1 - _t0\n\"\"\"\n\n\ndef reindent(src,indent):\n ''\n return src.replace(\"\\n\",\"\\n\"+\" \"*indent)\n \n \nclass Timer:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,stmt=\"pass\",setup=\"pass\",timer=default_timer,\n globals=None):\n ''\n self.timer=timer\n local_ns={}\n global_ns=_globals()if globals is None else globals\n init=''\n if isinstance(setup,str):\n \n compile(setup,dummy_src_name,\"exec\")\n stmtprefix=setup+'\\n'\n setup=reindent(setup,4)\n elif callable(setup):\n local_ns['_setup']=setup\n init +=', _setup=_setup'\n stmtprefix=''\n setup='_setup()'\n else:\n raise ValueError(\"setup is neither a string nor callable\")\n if isinstance(stmt,str):\n \n compile(stmtprefix+stmt,dummy_src_name,\"exec\")\n stmt=reindent(stmt,8)\n elif callable(stmt):\n local_ns['_stmt']=stmt\n init +=', _stmt=_stmt'\n stmt='_stmt()'\n else:\n raise ValueError(\"stmt is neither a string nor callable\")\n src=template.format(stmt=stmt,setup=setup,init=init)\n self.src=src\n code=compile(src,dummy_src_name,\"exec\")\n exec(code,global_ns,local_ns)\n self.inner=local_ns[\"inner\"]\n \n def print_exc(self,file=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n import linecache,traceback\n if self.src is not None:\n linecache.cache[dummy_src_name]=(len(self.src),\n None,\n self.src.split(\"\\n\"),\n dummy_src_name)\n \n \n traceback.print_exc(file=file)\n \n def timeit(self,number=default_number):\n ''\n\n\n\n\n\n\n\n \n it=itertools.repeat(None,number)\n gcold=gc.isenabled()\n gc.disable()\n try:\n timing=self.inner(it,self.timer)\n finally:\n if gcold:\n gc.enable()\n return timing\n \n def repeat(self,repeat=default_repeat,number=default_number):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n r=[]\n for i in range(repeat):\n t=self.timeit(number)\n r.append(t)\n return r\n \n def autorange(self,callback=None):\n ''\n\n\n\n\n\n\n\n \n i=1\n while True:\n for j in 1,2,5:\n number=i *j\n time_taken=self.timeit(number)\n if callback:\n callback(number,time_taken)\n if time_taken >=0.2:\n return(number,time_taken)\n i *=10\n \n \ndef timeit(stmt=\"pass\",setup=\"pass\",timer=default_timer,\nnumber=default_number,globals=None):\n ''\n return Timer(stmt,setup,timer,globals).timeit(number)\n \n \ndef repeat(stmt=\"pass\",setup=\"pass\",timer=default_timer,\nrepeat=default_repeat,number=default_number,globals=None):\n ''\n return Timer(stmt,setup,timer,globals).repeat(repeat,number)\n \n \ndef main(args=None,*,_wrap_timer=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if args is None:\n args=sys.argv[1:]\n import getopt\n try:\n opts,args=getopt.getopt(args,\"n:u:s:r:pvh\",\n [\"number=\",\"setup=\",\"repeat=\",\n \"process\",\"verbose\",\"unit=\",\"help\"])\n except getopt.error as err:\n print(err)\n print(\"use -h/--help for command line help\")\n return 2\n \n timer=default_timer\n stmt=\"\\n\".join(args)or \"pass\"\n number=0\n setup=[]\n repeat=default_repeat\n verbose=0\n time_unit=None\n units={\"nsec\":1e-9,\"usec\":1e-6,\"msec\":1e-3,\"sec\":1.0}\n precision=3\n for o,a in opts:\n if o in(\"-n\",\"--number\"):\n number=int(a)\n if o in(\"-s\",\"--setup\"):\n setup.append(a)\n if o in(\"-u\",\"--unit\"):\n if a in units:\n time_unit=a\n else:\n print(\"Unrecognized unit. Please select nsec, usec, msec, or sec.\",\n file=sys.stderr)\n return 2\n if o in(\"-r\",\"--repeat\"):\n repeat=int(a)\n if repeat <=0:\n repeat=1\n if o in(\"-p\",\"--process\"):\n timer=time.process_time\n if o in(\"-v\",\"--verbose\"):\n if verbose:\n precision +=1\n verbose +=1\n if o in(\"-h\",\"--help\"):\n print(__doc__,end=' ')\n return 0\n setup=\"\\n\".join(setup)or \"pass\"\n \n \n \n \n import os\n sys.path.insert(0,os.curdir)\n if _wrap_timer is not None:\n timer=_wrap_timer(timer)\n \n t=Timer(stmt,setup,timer)\n if number ==0:\n \n callback=None\n if verbose:\n def callback(number,time_taken):\n msg=\"{num} loop{s} -> {secs:.{prec}g} secs\"\n plural=(number !=1)\n print(msg.format(num=number,s='s'if plural else '',\n secs=time_taken,prec=precision))\n try:\n number,_=t.autorange(callback)\n except:\n t.print_exc()\n return 1\n \n if verbose:\n print()\n \n try:\n raw_timings=t.repeat(repeat,number)\n except:\n t.print_exc()\n return 1\n \n def format_time(dt):\n unit=time_unit\n \n if unit is not None:\n scale=units[unit]\n else:\n scales=[(scale,unit)for unit,scale in units.items()]\n scales.sort(reverse=True)\n for scale,unit in scales:\n if dt >=scale:\n break\n \n return \"%.*g %s\"%(precision,dt /scale,unit)\n \n if verbose:\n print(\"raw times: %s\"%\", \".join(map(format_time,raw_timings)))\n print()\n timings=[dt /number for dt in raw_timings]\n \n best=min(timings)\n print(\"%d loop%s, best of %d: %s per loop\"\n %(number,'s'if number !=1 else '',\n repeat,format_time(best)))\n \n best=min(timings)\n worst=max(timings)\n if worst >=best *4:\n import warnings\n warnings.warn_explicit(\"The test results are likely unreliable. \"\n \"The worst time (%s) was more than four times \"\n \"slower than the best time (%s).\"\n %(format_time(worst),format_time(best)),\n UserWarning,'',0)\n return None\n \n \nif __name__ ==\"__main__\":\n sys.exit(main())\n", ["gc", "getopt", "itertools", "linecache", "os", "sys", "time", "traceback", "warnings"]], "token": [".py", "''\n\n\n__all__=['tok_name','ISTERMINAL','ISNONTERMINAL','ISEOF']\n\nENDMARKER=0\nNAME=1\nNUMBER=2\nSTRING=3\nNEWLINE=4\nINDENT=5\nDEDENT=6\nLPAR=7\nRPAR=8\nLSQB=9\nRSQB=10\nCOLON=11\nCOMMA=12\nSEMI=13\nPLUS=14\nMINUS=15\nSTAR=16\nSLASH=17\nVBAR=18\nAMPER=19\nLESS=20\nGREATER=21\nEQUAL=22\nDOT=23\nPERCENT=24\nLBRACE=25\nRBRACE=26\nEQEQUAL=27\nNOTEQUAL=28\nLESSEQUAL=29\nGREATEREQUAL=30\nTILDE=31\nCIRCUMFLEX=32\nLEFTSHIFT=33\nRIGHTSHIFT=34\nDOUBLESTAR=35\nPLUSEQUAL=36\nMINEQUAL=37\nSTAREQUAL=38\nSLASHEQUAL=39\nPERCENTEQUAL=40\nAMPEREQUAL=41\nVBAREQUAL=42\nCIRCUMFLEXEQUAL=43\nLEFTSHIFTEQUAL=44\nRIGHTSHIFTEQUAL=45\nDOUBLESTAREQUAL=46\nDOUBLESLASH=47\nDOUBLESLASHEQUAL=48\nAT=49\nATEQUAL=50\nRARROW=51\nELLIPSIS=52\nCOLONEQUAL=53\nEXCLAMATION=54\nOP=55\nTYPE_IGNORE=56\nTYPE_COMMENT=57\nSOFT_KEYWORD=58\nFSTRING_START=59\nFSTRING_MIDDLE=60\nFSTRING_END=61\nCOMMENT=62\nNL=63\n\nERRORTOKEN=64\nENCODING=65\nN_TOKENS=66\n\nNT_OFFSET=256\n\ntok_name={value:name\nfor name,value in globals().items()\nif isinstance(value,int)and not name.startswith('_')}\n__all__.extend(tok_name.values())\n\nEXACT_TOKEN_TYPES={\n'!':EXCLAMATION,\n'!=':NOTEQUAL,\n'%':PERCENT,\n'%=':PERCENTEQUAL,\n'&':AMPER,\n'&=':AMPEREQUAL,\n'(':LPAR,\n')':RPAR,\n'*':STAR,\n'**':DOUBLESTAR,\n'**=':DOUBLESTAREQUAL,\n'*=':STAREQUAL,\n'+':PLUS,\n'+=':PLUSEQUAL,\n',':COMMA,\n'-':MINUS,\n'-=':MINEQUAL,\n'->':RARROW,\n'.':DOT,\n'...':ELLIPSIS,\n'/':SLASH,\n'//':DOUBLESLASH,\n'//=':DOUBLESLASHEQUAL,\n'/=':SLASHEQUAL,\n':':COLON,\n':=':COLONEQUAL,\n';':SEMI,\n'<':LESS,\n'<<':LEFTSHIFT,\n'<<=':LEFTSHIFTEQUAL,\n'<=':LESSEQUAL,\n'=':EQUAL,\n'==':EQEQUAL,\n'>':GREATER,\n'>=':GREATEREQUAL,\n'>>':RIGHTSHIFT,\n'>>=':RIGHTSHIFTEQUAL,\n'@':AT,\n'@=':ATEQUAL,\n'[':LSQB,\n']':RSQB,\n'^':CIRCUMFLEX,\n'^=':CIRCUMFLEXEQUAL,\n'{':LBRACE,\n'|':VBAR,\n'|=':VBAREQUAL,\n'}':RBRACE,\n'~':TILDE,\n}\n\ndef ISTERMINAL(x):\n return x =NT_OFFSET\n \ndef ISEOF(x):\n return x ==ENDMARKER\n", []], "tokenize": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__='Ka-Ping Yee '\n__credits__=('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '\n'Skip Montanaro, Raymond Hettinger, Trent Nelson, '\n'Michael Foord')\nfrom builtins import open as _builtin_open\nfrom codecs import lookup,BOM_UTF8\nimport collections\nimport functools\nfrom io import TextIOWrapper\nimport itertools as _itertools\nimport re\nimport sys\nfrom token import *\nfrom token import EXACT_TOKEN_TYPES\nimport _tokenize\n\ncookie_re=re.compile(r'^[ \\t\\f]*#.*?coding[:=][ \\t]*([-\\w.]+)',re.ASCII)\nblank_re=re.compile(br'^[ \\t\\f]*(?:[#\\r\\n]|$)',re.ASCII)\n\nimport token\n__all__=token.__all__+[\"tokenize\",\"generate_tokens\",\"detect_encoding\",\n\"untokenize\",\"TokenInfo\",\"open\",\"TokenError\"]\ndel token\n\nclass TokenInfo(collections.namedtuple('TokenInfo','type string start end line')):\n def __repr__(self):\n annotated_type='%d (%s)'%(self.type,tok_name[self.type])\n return('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)'%\n self._replace(type=annotated_type))\n \n @property\n def exact_type(self):\n if self.type ==OP and self.string in EXACT_TOKEN_TYPES:\n return EXACT_TOKEN_TYPES[self.string]\n else:\n return self.type\n \ndef group(*choices):return '('+'|'.join(choices)+')'\ndef any(*choices):return group(*choices)+'*'\ndef maybe(*choices):return group(*choices)+'?'\n\n\n\nWhitespace=r'[ \\f\\t]*'\nComment=r'#[^\\r\\n]*'\nIgnore=Whitespace+any(r'\\\\\\r?\\n'+Whitespace)+maybe(Comment)\nName=r'\\w+'\n\nHexnumber=r'0[xX](?:_?[0-9a-fA-F])+'\nBinnumber=r'0[bB](?:_?[01])+'\nOctnumber=r'0[oO](?:_?[0-7])+'\nDecnumber=r'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)'\nIntnumber=group(Hexnumber,Binnumber,Octnumber,Decnumber)\nExponent=r'[eE][-+]?[0-9](?:_?[0-9])*'\nPointfloat=group(r'[0-9](?:_?[0-9])*\\.(?:[0-9](?:_?[0-9])*)?',\nr'\\.[0-9](?:_?[0-9])*')+maybe(Exponent)\nExpfloat=r'[0-9](?:_?[0-9])*'+Exponent\nFloatnumber=group(Pointfloat,Expfloat)\nImagnumber=group(r'[0-9](?:_?[0-9])*[jJ]',Floatnumber+r'[jJ]')\nNumber=group(Imagnumber,Floatnumber,Intnumber)\n\n\ndef _all_string_prefixes():\n\n\n\n _valid_string_prefixes=['b','r','u','f','br','fr']\n \n result={''}\n for prefix in _valid_string_prefixes:\n for t in _itertools.permutations(prefix):\n \n \n for u in _itertools.product(*[(c,c.upper())for c in t]):\n result.add(''.join(u))\n return result\n \n@functools.lru_cache\ndef _compile(expr):\n return re.compile(expr,re.UNICODE)\n \n \n \nStringPrefix=group(*_all_string_prefixes())\n\n\nSingle=r\"[^'\\\\]*(?:\\\\.[^'\\\\]*)*'\"\n\nDouble=r'[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"'\n\nSingle3=r\"[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''\"\n\nDouble3=r'[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\"'\nTriple=group(StringPrefix+\"'''\",StringPrefix+'\"\"\"')\n\nString=group(StringPrefix+r\"'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'\",\nStringPrefix+r'\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*\"')\n\n\n\n\nSpecial=group(*map(re.escape,sorted(EXACT_TOKEN_TYPES,reverse=True)))\nFunny=group(r'\\r?\\n',Special)\n\nPlainToken=group(Number,Funny,String,Name)\nToken=Ignore+PlainToken\n\n\nContStr=group(StringPrefix+r\"'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*\"+\ngroup(\"'\",r'\\\\\\r?\\n'),\nStringPrefix+r'\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*'+\ngroup('\"',r'\\\\\\r?\\n'))\nPseudoExtras=group(r'\\\\\\r?\\n|\\Z',Comment,Triple)\nPseudoToken=Whitespace+group(PseudoExtras,Number,Funny,ContStr,Name)\n\n\n\n\nendpats={}\nfor _prefix in _all_string_prefixes():\n endpats[_prefix+\"'\"]=Single\n endpats[_prefix+'\"']=Double\n endpats[_prefix+\"'''\"]=Single3\n endpats[_prefix+'\"\"\"']=Double3\ndel _prefix\n\n\n\nsingle_quoted=set()\ntriple_quoted=set()\nfor t in _all_string_prefixes():\n for u in(t+'\"',t+\"'\"):\n single_quoted.add(u)\n for u in(t+'\"\"\"',t+\"'''\"):\n triple_quoted.add(u)\ndel t,u\n\ntabsize=8\n\nclass TokenError(Exception):pass\n\n\nclass Untokenizer:\n\n def __init__(self):\n self.tokens=[]\n self.prev_row=1\n self.prev_col=0\n self.prev_type=None\n self.encoding=None\n \n def add_whitespace(self,start):\n row,col=start\n if row =len(indent):\n self.tokens.append(indent)\n self.prev_col=len(indent)\n startline=False\n elif tok_type ==FSTRING_MIDDLE:\n if '{'in token or '}'in token:\n token=self.escape_brackets(token)\n last_line=token.splitlines()[-1]\n end_line,end_col=end\n extra_chars=last_line.count(\"{{\")+last_line.count(\"}}\")\n end=(end_line,end_col+extra_chars)\n elif tok_type in(STRING,FSTRING_START)and self.prev_type in(STRING,FSTRING_END):\n self.tokens.append(\" \")\n \n self.add_whitespace(start)\n self.tokens.append(token)\n self.prev_row,self.prev_col=end\n if tok_type in(NEWLINE,NL):\n self.prev_row +=1\n self.prev_col=0\n self.prev_type=tok_type\n return \"\".join(self.tokens)\n \n def compat(self,token,iterable):\n indents=[]\n toks_append=self.tokens.append\n startline=token[0]in(NEWLINE,NL)\n prevstring=False\n in_fstring=0\n \n for tok in _itertools.chain([token],iterable):\n toknum,tokval=tok[:2]\n if toknum ==ENCODING:\n self.encoding=tokval\n continue\n \n if toknum in(NAME,NUMBER):\n tokval +=' '\n \n \n if toknum ==STRING:\n if prevstring:\n tokval=' '+tokval\n prevstring=True\n else:\n prevstring=False\n \n if toknum ==FSTRING_START:\n in_fstring +=1\n elif toknum ==FSTRING_END:\n in_fstring -=1\n if toknum ==INDENT:\n indents.append(tokval)\n continue\n elif toknum ==DEDENT:\n indents.pop()\n continue\n elif toknum in(NEWLINE,NL):\n startline=True\n elif startline and indents:\n toks_append(indents[-1])\n startline=False\n elif toknum ==FSTRING_MIDDLE:\n tokval=self.escape_brackets(tokval)\n \n \n if tokval in{\"{\",\"}\"}and self.tokens and self.tokens[-1]==tokval and in_fstring:\n tokval=' '+tokval\n \n \n if toknum in(STRING,FSTRING_START)and self.prev_type in(STRING,FSTRING_END):\n self.tokens.append(\" \")\n \n toks_append(tokval)\n self.prev_type=toknum\n \n \ndef untokenize(iterable):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n ut=Untokenizer()\n out=ut.untokenize(iterable)\n if ut.encoding is not None:\n out=out.encode(ut.encoding)\n return out\n \n \ndef _get_normal_name(orig_enc):\n ''\n \n enc=orig_enc[:12].lower().replace(\"_\",\"-\")\n if enc ==\"utf-8\"or enc.startswith(\"utf-8-\"):\n return \"utf-8\"\n if enc in(\"latin-1\",\"iso-8859-1\",\"iso-latin-1\")or\\\n enc.startswith((\"latin-1-\",\"iso-8859-1-\",\"iso-latin-1-\")):\n return \"iso-8859-1\"\n return orig_enc\n \ndef detect_encoding(readline):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n filename=readline.__self__.name\n except AttributeError:\n filename=None\n bom_found=False\n encoding=None\n default='utf-8'\n def read_or_stop():\n try:\n return readline()\n except StopIteration:\n return b''\n \n def find_cookie(line):\n try:\n \n \n \n line_string=line.decode('utf-8')\n except UnicodeDecodeError:\n msg=\"invalid or missing encoding declaration\"\n if filename is not None:\n msg='{} for {!r}'.format(msg,filename)\n raise SyntaxError(msg)\n \n match=cookie_re.match(line_string)\n if not match:\n return None\n encoding=_get_normal_name(match.group(1))\n try:\n codec=lookup(encoding)\n except LookupError:\n \n if filename is None:\n msg=\"unknown encoding: \"+encoding\n else:\n msg=\"unknown encoding for {!r}: {}\".format(filename,\n encoding)\n raise SyntaxError(msg)\n \n if bom_found:\n if encoding !='utf-8':\n \n if filename is None:\n msg='encoding problem: utf-8'\n else:\n msg='encoding problem for {!r}: utf-8'.format(filename)\n raise SyntaxError(msg)\n encoding +='-sig'\n return encoding\n \n first=read_or_stop()\n if first.startswith(BOM_UTF8):\n bom_found=True\n first=first[3:]\n default='utf-8-sig'\n if not first:\n return default,[]\n \n encoding=find_cookie(first)\n if encoding:\n return encoding,[first]\n if not blank_re.match(first):\n return default,[first]\n \n second=read_or_stop()\n if not second:\n return default,[first]\n \n encoding=find_cookie(second)\n if encoding:\n return encoding,[first,second]\n \n return default,[first,second]\n \n \ndef open(filename):\n ''\n\n \n buffer=_builtin_open(filename,'rb')\n try:\n encoding,lines=detect_encoding(buffer.readline)\n buffer.seek(0)\n text=TextIOWrapper(buffer,encoding,line_buffering=True)\n text.mode='r'\n return text\n except:\n buffer.close()\n raise\n \ndef tokenize(readline):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n encoding,consumed=detect_encoding(readline)\n rl_gen=_itertools.chain(consumed,iter(readline,b\"\"))\n if encoding is not None:\n if encoding ==\"utf-8-sig\":\n \n encoding=\"utf-8\"\n yield TokenInfo(ENCODING,encoding,(0,0),(0,0),'')\n yield from _generate_tokens_from_c_tokenizer(rl_gen.__next__,encoding,extra_tokens=True)\n \ndef generate_tokens(readline):\n ''\n\n\n\n \n return _generate_tokens_from_c_tokenizer(readline,extra_tokens=True)\n \ndef main():\n import argparse\n \n \n def perror(message):\n sys.stderr.write(message)\n sys.stderr.write('\\n')\n \n def error(message,filename=None,location=None):\n if location:\n args=(filename,)+location+(message,)\n perror(\"%s:%d:%d: error: %s\"%args)\n elif filename:\n perror(\"%s: error: %s\"%(filename,message))\n else:\n perror(\"error: %s\"%message)\n sys.exit(1)\n \n \n parser=argparse.ArgumentParser(prog='python -m tokenize')\n parser.add_argument(dest='filename',nargs='?',\n metavar='filename.py',\n help='the file to tokenize; defaults to stdin')\n parser.add_argument('-e','--exact',dest='exact',action='store_true',\n help='display token names using the exact type')\n args=parser.parse_args()\n \n try:\n \n if args.filename:\n filename=args.filename\n with _builtin_open(filename,'rb')as f:\n tokens=list(tokenize(f.readline))\n else:\n filename=\"\"\n tokens=_generate_tokens_from_c_tokenizer(\n sys.stdin.readline,extra_tokens=True)\n \n \n \n for token in tokens:\n token_type=token.type\n if args.exact:\n token_type=token.exact_type\n token_range=\"%d,%d-%d,%d:\"%(token.start+token.end)\n print(\"%-20s%-15s%-15r\"%\n (token_range,tok_name[token_type],token.string))\n except IndentationError as err:\n line,column=err.args[1][1:3]\n error(err.args[0],filename,(line,column))\n except TokenError as err:\n line,column=err.args[1]\n error(err.args[0],filename,(line,column))\n except SyntaxError as err:\n error(err,filename)\n except OSError as err:\n error(err)\n except KeyboardInterrupt:\n print(\"interrupted\\n\")\n except Exception as err:\n perror(\"unexpected error: %s\"%err)\n raise\n \ndef _transform_msg(msg):\n ''\n\n\n\n \n if \"unterminated triple-quoted string literal\"in msg:\n return \"EOF in multi-line string\"\n return msg\n \ndef _generate_tokens_from_c_tokenizer(source,encoding=None,extra_tokens=False):\n ''\n if encoding is None:\n it=_tokenize.TokenizerIter(source,extra_tokens=extra_tokens)\n else:\n it=_tokenize.TokenizerIter(source,encoding=encoding,extra_tokens=extra_tokens)\n try:\n for info in it:\n yield TokenInfo._make(info)\n except SyntaxError as e:\n if type(e)!=SyntaxError:\n raise e from None\n msg=_transform_msg(e.msg)\n raise TokenError(msg,(e.lineno,e.offset))from None\n \n \nif __name__ ==\"__main__\":\n main()\n", ["_tokenize", "argparse", "builtins", "codecs", "collections", "functools", "io", "itertools", "re", "sys", "token"]], "traceback": [".py", "''\n\nimport collections.abc\nimport itertools\nimport linecache\nimport sys\nimport textwrap\nimport warnings\nfrom contextlib import suppress\nimport _colorize\nfrom _colorize import ANSIColors\n\n__all__=['extract_stack','extract_tb','format_exception',\n'format_exception_only','format_list','format_stack',\n'format_tb','print_exc','format_exc','print_exception',\n'print_last','print_stack','print_tb','clear_frames',\n'FrameSummary','StackSummary','TracebackException',\n'walk_stack','walk_tb']\n\n\n\n\n\n\ndef print_list(extracted_list,file=None):\n ''\n \n if file is None:\n file=sys.stderr\n for item in StackSummary.from_list(extracted_list).format():\n print(item,file=file,end=\"\")\n \ndef format_list(extracted_list):\n ''\n\n\n\n\n\n\n\n\n\n \n return StackSummary.from_list(extracted_list).format()\n \n \n \n \n \ndef print_tb(tb,limit=None,file=None):\n ''\n\n\n\n\n\n \n print_list(extract_tb(tb,limit=limit),file=file)\n \ndef format_tb(tb,limit=None):\n ''\n return extract_tb(tb,limit=limit).format()\n \ndef extract_tb(tb,limit=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n return StackSummary._extract_from_extended_frame_gen(\n _walk_tb_with_full_positions(tb),limit=limit)\n \n \n \n \n \n_cause_message=(\n\"\\nThe above exception was the direct cause \"\n\"of the following exception:\\n\\n\")\n\n_context_message=(\n\"\\nDuring handling of the above exception, \"\n\"another exception occurred:\\n\\n\")\n\n\nclass _Sentinel:\n def __repr__(self):\n return \"\"\n \n_sentinel=_Sentinel()\n\ndef _parse_value_tb(exc,value,tb):\n if(value is _sentinel)!=(tb is _sentinel):\n raise ValueError(\"Both or neither of value and tb must be given\")\n if value is tb is _sentinel:\n if exc is not None:\n if isinstance(exc,BaseException):\n return exc,exc.__traceback__\n \n raise TypeError(f'Exception expected for value, '\n f'{type(exc).__name__} found')\n else:\n return None,None\n return value,tb\n \n \ndef print_exception(exc,/,value=_sentinel,tb=_sentinel,limit=None,\\\nfile=None,chain=True,**kwargs):\n ''\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n value,tb=_parse_value_tb(exc,value,tb)\n te=TracebackException(type(value),value,tb,limit=limit,compact=True)\n te.print(file=file,chain=chain,colorize=colorize)\n \n \nBUILTIN_EXCEPTION_LIMIT=object()\n\n\ndef _print_exception_bltin(exc,/):\n file=sys.stderr if sys.stderr is not None else sys.__stderr__\n colorize=_colorize.can_colorize()\n return print_exception(exc,limit=BUILTIN_EXCEPTION_LIMIT,file=file,colorize=colorize)\n \n \ndef format_exception(exc,/,value=_sentinel,tb=_sentinel,limit=None,\\\nchain=True,**kwargs):\n ''\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n value,tb=_parse_value_tb(exc,value,tb)\n te=TracebackException(type(value),value,tb,limit=limit,compact=True)\n return list(te.format(chain=chain,colorize=colorize))\n \n \ndef format_exception_only(exc,/,value=_sentinel,*,show_group=False,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n if value is _sentinel:\n value=exc\n te=TracebackException(type(value),value,None,compact=True)\n return list(te.format_exception_only(show_group=show_group,colorize=colorize))\n \n \n \n \ndef _format_final_exc_line(etype,value,*,insert_final_newline=True,colorize=False):\n valuestr=_safe_string(value,'exception')\n end_char=\"\\n\"if insert_final_newline else \"\"\n if colorize:\n if value is None or not valuestr:\n line=f\"{ANSIColors.BOLD_MAGENTA}{etype}{ANSIColors.RESET}{end_char}\"\n else:\n line=f\"{ANSIColors.BOLD_MAGENTA}{etype}{ANSIColors.RESET}: {ANSIColors.MAGENTA}{valuestr}{ANSIColors.RESET}{end_char}\"\n else:\n if value is None or not valuestr:\n line=f\"{etype}{end_char}\"\n else:\n line=f\"{etype}: {valuestr}{end_char}\"\n return line\n \n \ndef _safe_string(value,what,func=str):\n try:\n return func(value)\n except:\n return f'<{what} {func.__name__}() failed>'\n \n \n \ndef print_exc(limit=None,file=None,chain=True):\n ''\n print_exception(sys.exception(),limit=limit,file=file,chain=chain)\n \ndef format_exc(limit=None,chain=True):\n ''\n return \"\".join(format_exception(sys.exception(),limit=limit,chain=chain))\n \ndef print_last(limit=None,file=None,chain=True):\n ''\n if not hasattr(sys,\"last_exc\")and not hasattr(sys,\"last_type\"):\n raise ValueError(\"no last exception\")\n \n if hasattr(sys,\"last_exc\"):\n print_exception(sys.last_exc,limit,file,chain)\n else:\n print_exception(sys.last_type,sys.last_value,sys.last_traceback,\n limit,file,chain)\n \n \n \n \n \n \ndef print_stack(f=None,limit=None,file=None):\n ''\n\n\n\n\n \n if f is None:\n f=sys._getframe().f_back\n print_list(extract_stack(f,limit=limit),file=file)\n \n \ndef format_stack(f=None,limit=None):\n ''\n if f is None:\n f=sys._getframe().f_back\n return format_list(extract_stack(f,limit=limit))\n \n \ndef extract_stack(f=None,limit=None):\n ''\n\n\n\n\n\n\n \n if f is None:\n f=sys._getframe().f_back\n stack=StackSummary.extract(walk_stack(f),limit=limit)\n stack.reverse()\n return stack\n \n \ndef clear_frames(tb):\n ''\n while tb is not None:\n try:\n tb.tb_frame.clear()\n except RuntimeError:\n \n pass\n tb=tb.tb_next\n \n \nclass FrameSummary:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('filename','lineno','end_lineno','colno','end_colno',\n 'name','_lines','_lines_dedented','locals')\n \n def __init__(self,filename,lineno,name,*,lookup_line=True,\n locals=None,line=None,\n end_lineno=None,colno=None,end_colno=None):\n ''\n\n\n\n\n\n\n\n \n self.filename=filename\n self.lineno=lineno\n self.end_lineno=lineno if end_lineno is None else end_lineno\n self.colno=colno\n self.end_colno=end_colno\n self.name=name\n self._lines=line\n self._lines_dedented=None\n if lookup_line:\n self.line\n self.locals={k:_safe_string(v,'local',func=repr)\n for k,v in locals.items()}if locals else None\n \n def __eq__(self,other):\n if isinstance(other,FrameSummary):\n return(self.filename ==other.filename and\n self.lineno ==other.lineno and\n self.name ==other.name and\n self.locals ==other.locals)\n if isinstance(other,tuple):\n return(self.filename,self.lineno,self.name,self.line)==other\n return NotImplemented\n \n def __getitem__(self,pos):\n return(self.filename,self.lineno,self.name,self.line)[pos]\n \n def __iter__(self):\n return iter([self.filename,self.lineno,self.name,self.line])\n \n def __repr__(self):\n return \"\".format(\n filename=self.filename,lineno=self.lineno,name=self.name)\n \n def __len__(self):\n return 4\n \n def _set_lines(self):\n if(\n self._lines is None\n and self.lineno is not None\n and self.end_lineno is not None\n ):\n lines=[]\n for lineno in range(self.lineno,self.end_lineno+1):\n \n lines.append(linecache.getline(self.filename,lineno).rstrip())\n self._lines=\"\\n\".join(lines)+\"\\n\"\n \n @property\n def _original_lines(self):\n \n self._set_lines()\n return self._lines\n \n @property\n def _dedented_lines(self):\n \n self._set_lines()\n if self._lines_dedented is None and self._lines is not None:\n self._lines_dedented=textwrap.dedent(self._lines)\n return self._lines_dedented\n \n @property\n def line(self):\n self._set_lines()\n if self._lines is None:\n return None\n \n return self._lines.partition(\"\\n\")[0].strip()\n \n \ndef walk_stack(f):\n ''\n\n\n\n \n if f is None:\n f=sys._getframe().f_back.f_back.f_back.f_back\n while f is not None:\n yield f,f.f_lineno\n f=f.f_back\n \n \ndef walk_tb(tb):\n ''\n\n\n\n \n while tb is not None:\n yield tb.tb_frame,tb.tb_lineno\n tb=tb.tb_next\n \n \ndef _walk_tb_with_full_positions(tb):\n\n\n while tb is not None:\n positions=_get_code_position(tb.tb_frame.f_code,tb.tb_lasti)\n \n \n if positions[0]is None:\n yield tb.tb_frame,(tb.tb_lineno,)+positions[1:]\n else:\n yield tb.tb_frame,positions\n tb=tb.tb_next\n \n \ndef _get_code_position(code,instruction_index):\n if instruction_index <0:\n return(None,None,None,None)\n positions_gen=code.co_positions()\n return next(itertools.islice(positions_gen,instruction_index //2,None))\n \n \n_RECURSIVE_CUTOFF=3\n\n\nclass StackSummary(list):\n ''\n \n @classmethod\n def extract(klass,frame_gen,*,limit=None,lookup_lines=True,\n capture_locals=False):\n ''\n\n\n\n\n\n\n\n\n\n \n def extended_frame_gen():\n for f,lineno in frame_gen:\n yield f,(lineno,None,None,None)\n \n return klass._extract_from_extended_frame_gen(\n extended_frame_gen(),limit=limit,lookup_lines=lookup_lines,\n capture_locals=capture_locals)\n \n @classmethod\n def _extract_from_extended_frame_gen(klass,frame_gen,*,limit=None,\n lookup_lines=True,capture_locals=False):\n \n \n \n \n builtin_limit=limit is BUILTIN_EXCEPTION_LIMIT\n if limit is None or builtin_limit:\n limit=getattr(sys,'tracebacklimit',None)\n if limit is not None and limit <0:\n limit=0\n if limit is not None:\n if builtin_limit:\n frame_gen=tuple(frame_gen)\n frame_gen=frame_gen[len(frame_gen)-limit:]\n elif limit >=0:\n frame_gen=itertools.islice(frame_gen,limit)\n else:\n frame_gen=collections.deque(frame_gen,maxlen=-limit)\n \n result=klass()\n fnames=set()\n for f,(lineno,end_lineno,colno,end_colno)in frame_gen:\n co=f.f_code\n filename=co.co_filename\n name=co.co_name\n fnames.add(filename)\n linecache.lazycache(filename,f.f_globals)\n \n if capture_locals:\n f_locals=f.f_locals\n else:\n f_locals=None\n result.append(FrameSummary(\n filename,lineno,name,lookup_line=False,locals=f_locals,\n end_lineno=end_lineno,colno=colno,end_colno=end_colno))\n for filename in fnames:\n linecache.checkcache(filename)\n \n \n if lookup_lines:\n for f in result:\n f.line\n return result\n \n @classmethod\n def from_list(klass,a_list):\n ''\n\n\n \n \n \n \n \n result=StackSummary()\n for frame in a_list:\n if isinstance(frame,FrameSummary):\n result.append(frame)\n else:\n filename,lineno,name,line=frame\n result.append(FrameSummary(filename,lineno,name,line=line))\n return result\n \n def format_frame_summary(self,frame_summary,**kwargs):\n ''\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n row=[]\n filename=frame_summary.filename\n if frame_summary.filename.startswith(\"-\"):\n filename=\"\"\n if colorize:\n row.append(' File {}\"{}\"{}, line {}{}{}, in {}{}{}\\n'.format(\n ANSIColors.MAGENTA,\n filename,\n ANSIColors.RESET,\n ANSIColors.MAGENTA,\n frame_summary.lineno,\n ANSIColors.RESET,\n ANSIColors.MAGENTA,\n frame_summary.name,\n ANSIColors.RESET,\n )\n )\n else:\n row.append(' File \"{}\", line {}, in {}\\n'.format(\n filename,frame_summary.lineno,frame_summary.name))\n if frame_summary._dedented_lines and frame_summary._dedented_lines.strip():\n if(\n frame_summary.colno is None or\n frame_summary.end_colno is None\n ):\n \n row.append(textwrap.indent(frame_summary.line,' ')+\"\\n\")\n else:\n \n all_lines_original=frame_summary._original_lines.splitlines()\n first_line=all_lines_original[0]\n \n last_line=all_lines_original[frame_summary.end_lineno -frame_summary.lineno]\n \n \n start_offset=_byte_offset_to_character_offset(first_line,frame_summary.colno)\n end_offset=_byte_offset_to_character_offset(last_line,frame_summary.end_colno)\n \n all_lines=frame_summary._dedented_lines.splitlines()[\n :frame_summary.end_lineno -frame_summary.lineno+1\n ]\n \n \n dedent_characters=len(first_line)-len(all_lines[0])\n start_offset=max(0,start_offset -dedent_characters)\n end_offset=max(0,end_offset -dedent_characters)\n \n \n \n \n dp_start_offset=_display_width(all_lines[0],offset=start_offset)\n dp_end_offset=_display_width(all_lines[-1],offset=end_offset)\n \n \n segment=\"\\n\".join(all_lines)\n segment=segment[start_offset:len(segment)-(len(all_lines[-1])-end_offset)]\n \n \n anchors=None\n show_carets=False\n with suppress(Exception):\n anchors=_extract_caret_anchors_from_line_segment(segment)\n show_carets=self._should_show_carets(start_offset,end_offset,all_lines,anchors)\n \n result=[]\n \n \n significant_lines={0,len(all_lines)-1}\n \n anchors_left_end_offset=0\n anchors_right_start_offset=0\n primary_char=\"^\"\n secondary_char=\"^\"\n if anchors:\n anchors_left_end_offset=anchors.left_end_offset\n anchors_right_start_offset=anchors.right_start_offset\n \n \n if anchors.left_end_lineno ==0:\n anchors_left_end_offset +=start_offset\n if anchors.right_start_lineno ==0:\n anchors_right_start_offset +=start_offset\n \n \n anchors_left_end_offset=_display_width(\n all_lines[anchors.left_end_lineno],offset=anchors_left_end_offset\n )\n anchors_right_start_offset=_display_width(\n all_lines[anchors.right_start_lineno],offset=anchors_right_start_offset\n )\n \n primary_char=anchors.primary_char\n secondary_char=anchors.secondary_char\n significant_lines.update(\n range(anchors.left_end_lineno -1,anchors.left_end_lineno+2)\n )\n significant_lines.update(\n range(anchors.right_start_lineno -1,anchors.right_start_lineno+2)\n )\n \n \n significant_lines.discard(-1)\n significant_lines.discard(len(all_lines))\n \n def output_line(lineno):\n ''\n result.append(all_lines[lineno]+\"\\n\")\n if not show_carets:\n return\n num_spaces=len(all_lines[lineno])-len(all_lines[lineno].lstrip())\n carets=[]\n num_carets=dp_end_offset if lineno ==len(all_lines)-1 else _display_width(all_lines[lineno])\n \n for col in range(num_carets):\n if col anchors.left_end_lineno or\n (lineno ==anchors.left_end_lineno and col >=anchors_left_end_offset)\n )and(\n lineno 2:\n \n result.append(f\"...<{linediff -1} lines>...\\n\")\n output_line(lineno)\n \n row.append(\n textwrap.indent(textwrap.dedent(\"\".join(result)),' ',lambda line:True)\n )\n if frame_summary.locals:\n for name,value in sorted(frame_summary.locals.items()):\n row.append(' {name} = {value}\\n'.format(name=name,value=value))\n \n return ''.join(row)\n \n def _should_show_carets(self,start_offset,end_offset,all_lines,anchors):\n with suppress(SyntaxError,ImportError):\n import ast\n tree=ast.parse('\\n'.join(all_lines))\n statement=tree.body[0]\n value=None\n def _spawns_full_line(value):\n return(\n value.lineno ==1\n and value.end_lineno ==len(all_lines)\n and value.col_offset ==start_offset\n and value.end_col_offset ==end_offset\n )\n match statement:\n case ast.Return(value=ast.Call()):\n if isinstance(statement.value.func,ast.Name):\n value=statement.value\n case ast.Assign(value=ast.Call()):\n if(\n len(statement.targets)==1 and\n isinstance(statement.targets[0],ast.Name)\n ):\n value=statement.value\n if value is not None and _spawns_full_line(value):\n return False\n if anchors:\n return True\n if all_lines[0][:start_offset].lstrip()or all_lines[-1][end_offset:].rstrip():\n return True\n return False\n \n def format(self,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n result=[]\n last_file=None\n last_line=None\n last_name=None\n count=0\n for frame_summary in self:\n formatted_frame=self.format_frame_summary(frame_summary,colorize=colorize)\n if formatted_frame is None:\n continue\n if(last_file is None or last_file !=frame_summary.filename or\n last_line is None or last_line !=frame_summary.lineno or\n last_name is None or last_name !=frame_summary.name):\n if count >_RECURSIVE_CUTOFF:\n count -=_RECURSIVE_CUTOFF\n result.append(\n f' [Previous line repeated {count} more '\n f'time{\"s\"if count >1 else \"\"}]\\n'\n )\n last_file=frame_summary.filename\n last_line=frame_summary.lineno\n last_name=frame_summary.name\n count=0\n count +=1\n if count >_RECURSIVE_CUTOFF:\n continue\n result.append(formatted_frame)\n \n if count >_RECURSIVE_CUTOFF:\n count -=_RECURSIVE_CUTOFF\n result.append(\n f' [Previous line repeated {count} more '\n f'time{\"s\"if count >1 else \"\"}]\\n'\n )\n return result\n \n \ndef _byte_offset_to_character_offset(str,offset):\n as_utf8=str.encode('utf-8')\n return len(as_utf8[:offset].decode(\"utf-8\",errors=\"replace\"))\n \n \n_Anchors=collections.namedtuple(\n\"_Anchors\",\n[\n\"left_end_lineno\",\n\"left_end_offset\",\n\"right_start_lineno\",\n\"right_start_offset\",\n\"primary_char\",\n\"secondary_char\",\n],\ndefaults=[\"~\",\"^\"]\n)\n\ndef _extract_caret_anchors_from_line_segment(segment):\n ''\n\n\n\n\n \n import ast\n \n try:\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n tree=ast.parse(f\"(\\n{segment}\\n)\")\n except SyntaxError:\n return None\n \n if len(tree.body)!=1:\n return None\n \n lines=segment.splitlines()\n \n def normalize(lineno,offset):\n ''\n return _byte_offset_to_character_offset(lines[lineno],offset)\n \n def next_valid_char(lineno,col):\n ''\n\n \n while lineno =len(lines[lineno]):\n col=0\n lineno +=1\n assert lineno lineno or\n right_col \"\n stype=smod+'.'+stype\n return stype\n \n def _load_lines(self):\n ''\n for frame in self.stack:\n frame.line\n \n def __eq__(self,other):\n if isinstance(other,TracebackException):\n return self.__dict__ ==other.__dict__\n return NotImplemented\n \n def __str__(self):\n return self._str\n \n def format_exception_only(self,*,show_group=False,_depth=0,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n \n indent=3 *_depth *' '\n if not self._have_exc_type:\n yield indent+_format_final_exc_line(None,self._str,colorize=colorize)\n return\n \n stype=self.exc_type_str\n if not self._is_syntax_error:\n if _depth >0:\n \n formatted=_format_final_exc_line(\n stype,self._str,insert_final_newline=False,colorize=colorize\n ).split('\\n')\n yield from[\n indent+l+'\\n'\n for l in formatted\n ]\n else:\n yield _format_final_exc_line(stype,self._str,colorize=colorize)\n else:\n yield from[indent+l for l in self._format_syntax_error(stype,colorize=colorize)]\n \n if(\n isinstance(self.__notes__,collections.abc.Sequence)\n and not isinstance(self.__notes__,(str,bytes))\n ):\n for note in self.__notes__:\n note=_safe_string(note,'note')\n yield from[indent+l+'\\n'for l in note.split('\\n')]\n elif self.__notes__ is not None:\n yield indent+\"{}\\n\".format(_safe_string(self.__notes__,'__notes__',func=repr))\n \n if self.exceptions and show_group:\n for ex in self.exceptions:\n yield from ex.format_exception_only(show_group=show_group,_depth=_depth+1,colorize=colorize)\n \n def _format_syntax_error(self,stype,**kwargs):\n ''\n \n colorize=kwargs.get(\"colorize\",False)\n filename_suffix=''\n if self.lineno is not None:\n if colorize:\n yield ' File {}\"{}\"{}, line {}{}{}\\n'.format(\n ANSIColors.MAGENTA,\n self.filename or \"\",\n ANSIColors.RESET,\n ANSIColors.MAGENTA,\n self.lineno,\n ANSIColors.RESET,\n )\n else:\n yield ' File \"{}\", line {}\\n'.format(\n self.filename or \"\",self.lineno)\n elif self.filename is not None:\n filename_suffix=' ({})'.format(self.filename)\n \n text=self.text\n if text is not None:\n \n \n \n rtext=text.rstrip('\\n')\n ltext=rtext.lstrip(' \\n\\f')\n spaces=len(rtext)-len(ltext)\n if self.offset is None:\n yield ' {}\\n'.format(ltext)\n else:\n offset=self.offset\n end_offset=self.end_offset if self.end_offset not in{None,0}else offset\n if self.text and offset >len(self.text):\n offset=len(self.text)+1\n if self.text and end_offset >len(self.text):\n end_offset=len(self.text)+1\n if offset >=end_offset or end_offset <0:\n end_offset=offset+1\n \n \n colno=offset -1 -spaces\n end_colno=end_offset -1 -spaces\n caretspace=' '\n if colno >=0:\n \n caretspace=((c if c.isspace()else ' ')for c in ltext[:colno])\n start_color=end_color=\"\"\n if colorize:\n \n ltext=(\n ltext[:colno]+\n ANSIColors.BOLD_RED+ltext[colno:end_colno]+ANSIColors.RESET+\n ltext[end_colno:]\n )\n start_color=ANSIColors.BOLD_RED\n end_color=ANSIColors.RESET\n yield ' {}\\n'.format(ltext)\n yield ' {}{}{}{}\\n'.format(\n \"\".join(caretspace),\n start_color,\n ('^'*(end_colno -colno)),\n end_color,\n )\n else:\n yield ' {}\\n'.format(ltext)\n msg=self.msg or \"\"\n if colorize:\n yield \"{}{}{}: {}{}{}{}\\n\".format(\n ANSIColors.BOLD_MAGENTA,\n stype,\n ANSIColors.RESET,\n ANSIColors.MAGENTA,\n msg,\n ANSIColors.RESET,\n filename_suffix)\n else:\n yield \"{}: {}{}\\n\".format(stype,msg,filename_suffix)\n \n def format(self,*,chain=True,_ctx=None,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n colorize=kwargs.get(\"colorize\",False)\n if _ctx is None:\n _ctx=_ExceptionPrintContext()\n \n output=[]\n exc=self\n if chain:\n while exc:\n if exc.__cause__ is not None:\n chained_msg=_cause_message\n chained_exc=exc.__cause__\n elif(exc.__context__ is not None and\n not exc.__suppress_context__):\n chained_msg=_context_message\n chained_exc=exc.__context__\n else:\n chained_msg=None\n chained_exc=None\n \n output.append((chained_msg,exc))\n exc=chained_exc\n else:\n output.append((None,exc))\n \n for msg,exc in reversed(output):\n if msg is not None:\n yield from _ctx.emit(msg)\n if exc.exceptions is None:\n if exc.stack:\n yield from _ctx.emit('Traceback (most recent call last):\\n')\n yield from _ctx.emit(exc.stack.format(colorize=colorize))\n yield from _ctx.emit(exc.format_exception_only(colorize=colorize))\n elif _ctx.exception_group_depth >self.max_group_depth:\n \n yield from _ctx.emit(\n f\"... (max_group_depth is {self.max_group_depth})\\n\")\n else:\n \n is_toplevel=(_ctx.exception_group_depth ==0)\n if is_toplevel:\n _ctx.exception_group_depth +=1\n \n if exc.stack:\n yield from _ctx.emit(\n 'Exception Group Traceback (most recent call last):\\n',\n margin_char='+'if is_toplevel else None)\n yield from _ctx.emit(exc.stack.format(colorize=colorize))\n \n yield from _ctx.emit(exc.format_exception_only(colorize=colorize))\n num_excs=len(exc.exceptions)\n if num_excs <=self.max_group_width:\n n=num_excs\n else:\n n=self.max_group_width+1\n _ctx.need_close=False\n for i in range(n):\n last_exc=(i ==n -1)\n if last_exc:\n \n _ctx.need_close=True\n \n if self.max_group_width is not None:\n truncated=(i >=self.max_group_width)\n else:\n truncated=False\n title=f'{i+1}'if not truncated else '...'\n yield(_ctx.indent()+\n ('+-'if i ==0 else ' ')+\n f'+---------------- {title} ----------------\\n')\n _ctx.exception_group_depth +=1\n if not truncated:\n yield from exc.exceptions[i].format(chain=chain,_ctx=_ctx)\n else:\n remaining=num_excs -self.max_group_width\n plural='s'if remaining >1 else ''\n yield from _ctx.emit(\n f\"and {remaining} more exception{plural}\\n\")\n \n if last_exc and _ctx.need_close:\n yield(_ctx.indent()+\n \"+------------------------------------\\n\")\n _ctx.need_close=False\n _ctx.exception_group_depth -=1\n \n if is_toplevel:\n assert _ctx.exception_group_depth ==1\n _ctx.exception_group_depth=0\n \n \n def print(self,*,file=None,chain=True,**kwargs):\n ''\n colorize=kwargs.get(\"colorize\",False)\n if file is None:\n file=sys.stderr\n for line in self.format(chain=chain,colorize=colorize):\n print(line,file=file,end=\"\")\n \n \n_MAX_CANDIDATE_ITEMS=750\n_MAX_STRING_SIZE=40\n_MOVE_COST=2\n_CASE_COST=1\n\n\ndef _substitution_cost(ch_a,ch_b):\n if ch_a ==ch_b:\n return 0\n if ch_a.lower()==ch_b.lower():\n return _CASE_COST\n return _MOVE_COST\n \n \ndef _compute_suggestion_error(exc_value,tb,wrong_name):\n if wrong_name is None or not isinstance(wrong_name,str):\n return None\n if isinstance(exc_value,AttributeError):\n obj=exc_value.obj\n try:\n d=dir(obj)\n hide_underscored=(wrong_name[:1]!='_')\n if hide_underscored and tb is not None:\n while tb.tb_next is not None:\n tb=tb.tb_next\n frame=tb.tb_frame\n if 'self'in frame.f_locals and frame.f_locals['self']is obj:\n hide_underscored=False\n if hide_underscored:\n d=[x for x in d if x[:1]!='_']\n except Exception:\n return None\n elif isinstance(exc_value,ImportError):\n try:\n mod=__import__(exc_value.name)\n d=dir(mod)\n if wrong_name[:1]!='_':\n d=[x for x in d if x[:1]!='_']\n except Exception:\n return None\n else:\n assert isinstance(exc_value,NameError)\n \n if tb is None:\n return None\n while tb.tb_next is not None:\n tb=tb.tb_next\n frame=tb.tb_frame\n d=(\n list(frame.f_locals)\n +list(frame.f_globals)\n +list(frame.f_builtins)\n )\n \n \n \n if 'self'in frame.f_locals:\n self=frame.f_locals['self']\n if hasattr(self,wrong_name):\n return f\"self.{wrong_name}\"\n \n try:\n import _suggestions\n except ImportError:\n pass\n else:\n return _suggestions._generate_suggestions(d,wrong_name)\n \n \n \n if len(d)>_MAX_CANDIDATE_ITEMS:\n return None\n wrong_name_len=len(wrong_name)\n if wrong_name_len >_MAX_STRING_SIZE:\n return None\n best_distance=wrong_name_len\n suggestion=None\n for possible_name in d:\n if possible_name ==wrong_name:\n \n continue\n \n max_distance=(len(possible_name)+wrong_name_len+3)*_MOVE_COST //6\n \n max_distance=min(max_distance,best_distance -1)\n current_distance=_levenshtein_distance(wrong_name,possible_name,max_distance)\n if current_distance >max_distance:\n continue\n if not suggestion or current_distance _MAX_STRING_SIZE or len(b)>_MAX_STRING_SIZE:\n return max_cost+1\n \n \n if len(b)max_cost:\n return max_cost+1\n \n \n \n \n row=list(range(_MOVE_COST,_MOVE_COST *(len(a)+1),_MOVE_COST))\n \n result=0\n for bindex in range(len(b)):\n bchar=b[bindex]\n distance=result=bindex *_MOVE_COST\n minimum=sys.maxsize\n for index in range(len(a)):\n \n substitute=distance+_substitution_cost(bchar,a[index])\n \n distance=row[index]\n \n \n insert_delete=min(result,distance)+_MOVE_COST\n result=min(insert_delete,substitute)\n \n \n row[index]=result\n if result max_cost:\n \n return max_cost+1\n return result\n", ["_colorize", "_suggestions", "ast", "collections.abc", "contextlib", "itertools", "linecache", "sys", "textwrap", "unicodedata", "warnings"]], "turtle": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport math\nimport sys\n\nfrom math import cos,sin\n\nfrom browser import console,document,html,timer\nimport _svg as svg\n\n\n\n\n\n\n_CFG={\n\n\n\"canvwidth\":500,\n\"canvheight\":500,\n\n\n\"mode\":\"standard\",\n\n\n\n\"shape\":\"classic\",\n\"pencolor\":\"black\",\n\"fillcolor\":\"black\",\n\n\"visible\":True,\n\n\n\n\n\n\n\n\"turtle_canvas_wrapper\":None,\n\"turtle_canvas_id\":\"turtle-canvas\",\n\"min_duration\":\"1ms\"\n}\n\n_cfg_copy=_CFG.copy()\n\n\ndef set_defaults(**params):\n ''\n _CFG.update(**params)\n Screen().reset()\n \n \nclass FormattedTuple(tuple):\n ''\n def __new__(cls,x,y):\n return tuple.__new__(cls,(x,y))\n def __repr__(self):\n return \"(%.2f, %.2f)\"%self\n \ndef create_circle(r):\n ''\n circle=svg.circle(x=0,y=0,r=r,stroke=\"black\",fill=\"black\")\n circle.setAttribute(\"stroke-width\",1)\n return circle\n \n \ndef create_polygon(points):\n ''\n points=[\"%s,%s \"%(x,y)for x,y in points]\n polygon=svg.polygon(points=points,stroke=\"black\",fill=\"black\")\n polygon.setAttribute(\"stroke-width\",1)\n return polygon\n \n \ndef create_rectangle(width=2,height=2,rx=None,ry=None):\n ''\n \n rectangle=svg.rect(x=-width /2,y=-height /2,width=width,\n height=height,stroke=\"black\",fill=\"black\")\n rectangle.setAttribute(\"stroke-width\",1)\n if rx is not None:\n rectangle.setAttribute(\"rx\",rx)\n if ry is not None:\n rectangle.setAttribute(\"ry\",ry)\n return rectangle\n \n \ndef create_square(size=2,r=None):\n ''\n \n return create_rectangle(width=size,height=size,rx=r,ry=r)\n \n \nclass TurtleGraphicsError(Exception):\n ''\n \n pass\n \n \nclass Singleton(type):\n _instances={}\n def __call__(cls,*args,**kwargs):\n if cls not in cls._instances:\n cls._instances[cls]=super(Singleton,cls).__call__(*args,**kwargs)\n return cls._instances[cls]\n \n \nclass Screen(metaclass=Singleton):\n\n def __init__(self):\n self.shapes={\n 'arrow':(create_polygon,((-10,0),(10,0),(0,10))),\n 'turtle':(create_polygon,((0,16),(-2,14),(-1,10),(-4,7),\n (-7,9),(-9,8),(-6,5),(-7,1),(-5,-3),(-8,-6),\n (-6,-8),(-4,-5),(0,-7),(4,-5),(6,-8),(8,-6),\n (5,-3),(7,1),(6,5),(9,8),(7,9),(4,7),(1,10),\n (2,14))),\n 'classic':(create_polygon,((0,0),(-5,-9),(0,-7),(5,-9))),\n 'triangle':(create_polygon,((10,-5.77),(0,11.55),(-10,-5.77))),\n 'square':(create_square,20),\n 'circle':(create_circle,10)\n }\n self.reset()\n self._set_geometry()\n \n def bgcolor(self,color=None):\n ''\n\n \n if color is None:\n return self.background_color\n self.background_color=color\n width=_CFG['canvwidth']\n height=_CFG['canvheight']\n if self.mode()in['logo','standard']:\n x=-width //2\n y=-height //2\n else:\n x=0\n y=-height\n \n self.frame_index +=1\n rect=svg.rect(x=x,y=y,width=width,height=height,fill=color,\n style={'display':'none'})\n an=svg.animate(Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"display\",attributeType=\"CSS\",\n From=\"block\",to=\"block\",\n dur=_CFG[\"min_duration\"],fill='freeze')\n an.setAttribute('begin',\"animation_frame%s.end\"%(self.frame_index -1))\n rect <=an\n \n self.background_canvas <=rect\n \n def _convert_coordinates(self,x,y):\n ''\n\n\n\n\n\n \n return x *self.yscale,self.y_points_down *y *self.yscale\n \n \n def create_svg_turtle(self,_turtle,name):\n if name in self.shapes:\n fn=self.shapes[name][0]\n arg=self.shapes[name][1]\n else:\n print(\"Unknown turtle '%s'; the default turtle will be used\")\n fn=self.shapes[_CVG[\"shape\"]][0]\n arg=self.shapes[_CVG[\"shape\"]][1]\n shape=fn(arg)\n if self._mode =='standard'or self._mode =='world':\n rotation=-90\n else:\n rotation=0\n return shape,rotation\n \n def _dot(self,pos,size,color):\n ''\n if color is None:\n color='black'\n if size is None or size <1:\n size=1\n self.frame_index +=1\n \n \n radius=size /2\n \n x,y=self._convert_coordinates(pos[0],pos[1])\n \n circle=svg.circle(cx=x,cy=y,r=radius,fill=color,\n style={'display':'none'})\n an=svg.animate(Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"display\",attributeType=\"CSS\",\n From=\"block\",to=\"block\",\n dur=_CFG[\"min_duration\"],fill='freeze')\n an.setAttribute('begin',\"animation_frame%s.end\"%(self.frame_index -1))\n circle <=an\n self.canvas <=circle\n \n def _drawline(self,_turtle,coordlist=None,\n color=None,width=1,speed=None):\n ''\n\n\n\n\n \n \n outline=color[0]\n fill=color[1]\n \n x0,y0=coordlist[0]\n x1,y1=coordlist[1]\n \n x0,y0=self._convert_coordinates(x0,y0)\n x1,y1=self._convert_coordinates(x1,y1)\n \n \n if speed ==0:\n duration=_CFG[\"min_duration\"]\n else:\n dist=_turtle._distance\n if speed is None or speed ==1:\n duration=0.02 *dist\n else:\n duration=0.02 *dist /speed **1.2\n if duration <0.001:\n duration=_CFG[\"min_duration\"]\n else:\n duration=\"%6.3fs\"%duration\n \n drawing=_turtle._drawing\n \n _line=svg.line(x1=x0,y1=y0,x2=x0,y2=y0,\n style={'stroke':outline,'stroke-width':width})\n if not drawing:\n _line.setAttribute('opacity',0)\n \n \n begin=\"animation_frame%s.end\"%self.frame_index\n self.frame_index +=1\n _an1=svg.animate(Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"x2\",attributeType=\"XML\",\n From=x0,to=x1,dur=duration,fill='freeze',\n begin=begin)\n _line <=_an1\n \n \n if drawing:\n _an2=svg.animate(attributeName=\"y2\",attributeType=\"XML\",\n begin=begin,\n From=y0,to=y1,dur=duration,fill='freeze')\n _line <=_an2\n \n if width >2:\n _line_cap=svg.set(attributeName=\"stroke-linecap\",\n begin=begin,\n attributeType=\"xml\",to=\"round\",dur=duration,fill='freeze')\n _line <=_line_cap\n \n self.canvas <=_line\n return begin,duration,(x0,y0),(x1,y1)\n \n def _drawpoly(self,coordlist,outline=None,fill=None,width=None):\n ''\n\n\n\n\n \n self.frame_index +=1\n shape=[\"%s,%s\"%self._convert_coordinates(x,y)for x,y in coordlist]\n \n style={'display':'none'}\n if fill is not None:\n style['fill']=fill\n if outline is not None:\n style['stroke']=outline\n if width is not None:\n style['stroke-width']=width\n else:\n style['stroke-width']=1\n \n polygon=svg.polygon(points=\" \".join(shape),style=style)\n \n an=svg.animate(Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"display\",attributeType=\"CSS\",\n From=\"block\",to=\"block\",\n dur=_CFG[\"min_duration\"],fill='freeze')\n \n an.setAttribute('begin',\"animation_frame%s.end\"%(self.frame_index -1))\n polygon <=an\n self.canvas <=polygon\n \n \n def _new_frame(self):\n ''\n \n previous_end=\"animation_frame%s.end\"%self.frame_index\n self.frame_index +=1\n new_frame_id=\"animation_frame%s\"%self.frame_index\n return previous_end,new_frame_id\n \n def mode(self,_mode=None):\n if _mode is None:\n return self._mode\n _CFG['mode']=_mode\n self.reset()\n \n \n def reset(self):\n self._turtles=[]\n self.frame_index=0\n self.background_color=\"white\"\n self._set_geometry()\n \n def _set_geometry(self):\n self.width=_CFG[\"canvwidth\"]\n self.height=_CFG[\"canvheight\"]\n self.x_offset=self.y_offset=0\n self.xscale=self.yscale=1\n \n self.y_points_down=-1\n self._mode=_CFG[\"mode\"].lower()\n if self._mode in['logo','standard']:\n self.translate_canvas=(self.width //2,self.height //2)\n elif self._mode =='world':\n self.translate_canvas=(0,self.height)\n self._setup_canvas()\n \n def _setup_canvas(self):\n self.svg_scene=svg.svg(Id=_CFG[\"turtle_canvas_id\"],width=self.width,\n height=self.height)\n translate=\"translate(%d %d)\"%self.translate_canvas\n \n \n self.svg_scene <=svg.animate(\n Id=\"animation_frame%s\"%self.frame_index,\n attributeName=\"width\",attributeType=\"CSS\",\n From=self.width,to=self.width,begin=\"0s\",\n dur=_CFG[\"min_duration\"],fill='freeze')\n \n \n \n \n self.background_canvas=svg.g(transform=translate)\n self.canvas=svg.g(transform=translate)\n self.writing_canvas=svg.g(transform=translate)\n self.turtle_canvas=svg.g(transform=translate)\n \n self.svg_scene <=self.background_canvas\n self.svg_scene <=self.canvas\n self.svg_scene <=self.writing_canvas\n self.svg_scene <=self.turtle_canvas\n \n \n def setworldcoordinates(self,llx,lly,urx,ury):\n ''\n\n\n\n\n\n\n\n\n\n\n \n self._mode=\"world\"\n \n if urx 2:\n self.screen._drawpoly(self._fillpath,outline=self._pencolor,\n fill=self._fillcolor,)\n else:\n print(\"No path to fill.\")\n self._fillpath=None\n \n def dot(self,size=None,color=None):\n ''\n \n if size is None:\n size=max(self._pensize+4,2 *self._pensize)\n if color is None:\n color=self._pencolor\n item=self.screen._dot((self._x,self._y),size,color=color)\n \n def _write(self,txt,align,font,color=None):\n ''\n \n if color is None:\n color=self._pencolor\n self.screen._write((self._x,self._y),txt,align,font,color)\n \n \n def write(self,arg,align=\"left\",font=(\"Arial\",8,\"normal\"),color=None):\n ''\n\n\n\n\n\n\n \n self._write(str(arg),align.lower(),font,color=color)\n \n def begin_poly(self):\n ''\n \n self._poly=[(self._x,self._y)]\n self._creatingPoly=True\n \n def end_poly(self):\n ''\n \n self._creatingPoly=False\n \n def get_poly(self):\n ''\n \n \n if self._poly is not None:\n return tuple(self._poly)\n \n def getscreen(self):\n ''\n \n return self.screen\n \n def getturtle(self):\n ''\n\n\n \n return self\n getpen=getturtle\n \n def _make_copy(self,name=None):\n ''\n\n \n \n if name is None:\n name=self.name\n \n \n \n \n \n _turtle,rotation=self.screen.create_svg_turtle(self,name=name)\n _turtle.setAttribute(\"opacity\",0)\n _turtle.setAttribute(\"fill\",self._fillcolor)\n _turtle.setAttribute(\"stroke\",self._pencolor)\n \n \n \n previous_end,new_frame_id=self.screen._new_frame()\n x,y=self.screen._convert_coordinates(self._x,self._y)\n _turtle <=svg.animateMotion(begin=previous_end,dur=_CFG[\"min_duration\"],\n fill=\"remove\")\n \n _turtle <=svg.animateMotion(Id=new_frame_id,\n From=\"%s,%s\"%(x,y),to=\"%s,%s\"%(x,y),\n dur=_CFG[\"min_duration\"],begin=previous_end,\n fill=\"freeze\")\n _turtle <=svg.animateTransform(attributeName=\"transform\",\n type=\"rotate\",\n From=\"%s,%s,%s\"%(self._old_heading,0,0),\n to=\"%s,%s,%s\"%(self._old_heading,0,0),\n begin=previous_end,\n dur=_CFG[\"min_duration\"],fill=\"freeze\")\n _turtle <=svg.animate(begin=previous_end,\n dur=_CFG[\"min_duration\"],fill=\"freeze\",\n attributeName=\"opacity\",attributeType=\"XML\",\n From=0,to=1)\n return _turtle\n \n def stamp(self):\n ''\n \n _turtle=self._make_copy(name=self.name)\n self.screen.canvas <=_turtle\n \n \n def clone(self):\n ''\n \n n=Turtle(self.name)\n \n attrs=vars(self)\n new_dict={}\n for attr in attrs:\n if isinstance(getattr(self,attr),(int,str,float)):\n new_dict[attr]=getattr(self,attr)\n n.__dict__.update(**new_dict)\n \n if not n._shown:\n n._shown=True\n n.hideturtle()\n n.left(0)\n n.fd(0)\n n.color(n.color())\n return n\n \n \nPen=Turtle\n\n\ndef done():\n Screen().show_scene()\nshow_scene=done\n\n\ndef replay_scene():\n ''\n if(_CFG[\"turtle_canvas_id\"]in document and\n document[_CFG[\"turtle_canvas_id\"]]is not None):\n element=document[_CFG[\"turtle_canvas_id\"]]\n element.parentNode.removeChild(element)\n show_scene()\n \n \ndef restart():\n ''\n _CFG.update(_cfg_copy)\n Screen().reset()\n Turtle._pen=None\n \n if(_CFG[\"turtle_canvas_id\"]in document and\n document[_CFG[\"turtle_canvas_id\"]]is not None):\n element=document[_CFG[\"turtle_canvas_id\"]]\n element.parentNode.removeChild(element)\n \n \n \n_tg_screen_functions=['addshape','bgcolor','bgpic','bye',\n'clearscreen','colormode','delay','exitonclick','getcanvas',\n'getshapes','listen','mainloop','mode','numinput',\n'onkey','onkeypress','onkeyrelease','onscreenclick','ontimer',\n'register_shape','resetscreen','screensize','setup',\n'setworldcoordinates','textinput','title','tracer','turtles','update',\n'window_height','window_width']\n\n_tg_turtle_functions=['back','backward','begin_fill','begin_poly','bk',\n'circle','clear','clearstamp','clearstamps','clone','color',\n'degrees','distance','dot','down','end_fill','end_poly','fd',\n'fillcolor','filling','forward','get_poly','getpen','getscreen','get_shapepoly',\n'getturtle','goto','heading','hideturtle','home','ht','isdown',\n'isvisible','left','lt','onclick','ondrag','onrelease','pd',\n'pen','pencolor','pendown','pensize','penup','pos','position',\n'pu','radians','right','reset','resizemode','rt',\n'seth','setheading','setpos','setposition','settiltangle',\n'setundobuffer','setx','sety','shape','shapesize','shapetransform','shearfactor','showturtle',\n'speed','st','stamp','tilt','tiltangle','towards',\n'turtlesize','undo','undobufferentries','up','width',\n'write','xcor','ycor']\n\n\n__all__=(_tg_screen_functions+_tg_turtle_functions+\n['done','restart','replay_scene','Turtle','Screen'])\n\n\n\n\n\n__func_body=\"\"\"\\\ndef {name}(*args, **kw):\n if {obj} is None:\n {obj} = {init}\n return {obj}.{name}(*args, **kw)\n\"\"\"\n\ndef _make_global_funcs(functions,cls,obj,init):\n for methodname in functions:\n try:\n method=getattr(cls,methodname)\n except AttributeError:\n print(\"methodname missing:\",methodname)\n continue\n defstr=__func_body.format(obj=obj,init=init,name=methodname)\n exec(defstr,globals())\n \n_make_global_funcs(_tg_turtle_functions,Turtle,'Turtle._pen','Turtle()')\n\n_make_global_funcs(_tg_screen_functions,Screen,'Turtle.screen','Screen()')\n", ["_svg", "browser", "browser.timer", "math", "sys"]], "types": [".py", "''\n\n\n\nimport sys\n\n\n\n\n\n\ndef _f():pass\nFunctionType=type(_f)\nLambdaType=type(lambda:None)\nCodeType=type(_f.__code__)\nMappingProxyType=type(type.__dict__)\nSimpleNamespace=type(sys.implementation)\n\ndef _cell_factory():\n a=1\n def f():\n nonlocal a\n return f.__closure__[0]\nCellType=type(_cell_factory())\n\ndef _g():\n yield 1\nGeneratorType=type(_g())\n\nasync def _c():pass\n_c=_c()\nCoroutineType=type(_c)\n_c.close()\n\nasync def _ag():\n yield\n_ag=_ag()\nAsyncGeneratorType=type(_ag)\n\nclass _C:\n def _m(self):pass\nMethodType=type(_C()._m)\n\nBuiltinFunctionType=type(len)\nBuiltinMethodType=type([].append)\n\nWrapperDescriptorType=type(object.__init__)\nMethodWrapperType=type(object().__str__)\nMethodDescriptorType=type(str.join)\nClassMethodDescriptorType=type(dict.__dict__['fromkeys'])\n\nModuleType=type(sys)\n\ntry:\n raise TypeError\nexcept TypeError as exc:\n TracebackType=type(exc.__traceback__)\n FrameType=type(exc.__traceback__.tb_frame)\n \nGetSetDescriptorType=type(FunctionType.__code__)\nMemberDescriptorType=type(FunctionType.__globals__)\n\ndel sys,_f,_g,_C,_c,_ag,_cell_factory\n\n\n\ndef new_class(name,bases=(),kwds=None,exec_body=None):\n ''\n resolved_bases=resolve_bases(bases)\n meta,ns,kwds=prepare_class(name,resolved_bases,kwds)\n if exec_body is not None:\n exec_body(ns)\n if resolved_bases is not bases:\n ns['__orig_bases__']=bases\n return meta(name,resolved_bases,ns,**kwds)\n \ndef resolve_bases(bases):\n ''\n new_bases=list(bases)\n updated=False\n shift=0\n for i,base in enumerate(bases):\n if isinstance(base,type):\n continue\n if not hasattr(base,\"__mro_entries__\"):\n continue\n new_base=base.__mro_entries__(bases)\n updated=True\n if not isinstance(new_base,tuple):\n raise TypeError(\"__mro_entries__ must return a tuple\")\n else:\n new_bases[i+shift:i+shift+1]=new_base\n shift +=len(new_base)-1\n if not updated:\n return bases\n return tuple(new_bases)\n \ndef prepare_class(name,bases=(),kwds=None):\n ''\n\n\n\n\n\n\n\n\n \n if kwds is None:\n kwds={}\n else:\n kwds=dict(kwds)\n if 'metaclass'in kwds:\n meta=kwds.pop('metaclass')\n else:\n if bases:\n meta=type(bases[0])\n else:\n meta=type\n if isinstance(meta,type):\n \n \n meta=_calculate_meta(meta,bases)\n if hasattr(meta,'__prepare__'):\n ns=meta.__prepare__(name,bases,**kwds)\n else:\n ns={}\n return meta,ns,kwds\n \ndef _calculate_meta(meta,bases):\n ''\n winner=meta\n for base in bases:\n base_meta=type(base)\n if issubclass(winner,base_meta):\n continue\n if issubclass(base_meta,winner):\n winner=base_meta\n continue\n \n raise TypeError(\"metaclass conflict: \"\n \"the metaclass of a derived class \"\n \"must be a (non-strict) subclass \"\n \"of the metaclasses of all its bases\")\n return winner\n \n \ndef get_original_bases(cls,/):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n return cls.__dict__.get(\"__orig_bases__\",cls.__bases__)\n except AttributeError:\n raise TypeError(\n f\"Expected an instance of type, not {type(cls).__name__ !r}\"\n )from None\n \n \nclass DynamicClassAttribute:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,fget=None,fset=None,fdel=None,doc=None):\n self.fget=fget\n self.fset=fset\n self.fdel=fdel\n \n self.__doc__=doc or fget.__doc__\n self.overwrite_doc=doc is None\n \n self.__isabstractmethod__=bool(getattr(fget,'__isabstractmethod__',False))\n \n def __get__(self,instance,ownerclass=None):\n if instance is None:\n if self.__isabstractmethod__:\n return self\n raise AttributeError()\n elif self.fget is None:\n raise AttributeError(\"unreadable attribute\")\n return self.fget(instance)\n \n def __set__(self,instance,value):\n if self.fset is None:\n raise AttributeError(\"can't set attribute\")\n self.fset(instance,value)\n \n def __delete__(self,instance):\n if self.fdel is None:\n raise AttributeError(\"can't delete attribute\")\n self.fdel(instance)\n \n def getter(self,fget):\n fdoc=fget.__doc__ if self.overwrite_doc else None\n result=type(self)(fget,self.fset,self.fdel,fdoc or self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n def setter(self,fset):\n result=type(self)(self.fget,fset,self.fdel,self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n def deleter(self,fdel):\n result=type(self)(self.fget,self.fset,fdel,self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n \nclass _GeneratorWrapper:\n\n def __init__(self,gen):\n self.__wrapped=gen\n self.__isgen=gen.__class__ is GeneratorType\n self.__name__=getattr(gen,'__name__',None)\n self.__qualname__=getattr(gen,'__qualname__',None)\n def send(self,val):\n return self.__wrapped.send(val)\n def throw(self,tp,*rest):\n return self.__wrapped.throw(tp,*rest)\n def close(self):\n return self.__wrapped.close()\n @property\n def gi_code(self):\n return self.__wrapped.gi_code\n @property\n def gi_frame(self):\n return self.__wrapped.gi_frame\n @property\n def gi_running(self):\n return self.__wrapped.gi_running\n @property\n def gi_yieldfrom(self):\n return self.__wrapped.gi_yieldfrom\n cr_code=gi_code\n cr_frame=gi_frame\n cr_running=gi_running\n cr_await=gi_yieldfrom\n def __next__(self):\n return next(self.__wrapped)\n def __iter__(self):\n if self.__isgen:\n return self.__wrapped\n return self\n __await__=__iter__\n \ndef coroutine(func):\n ''\n \n if not callable(func):\n raise TypeError('types.coroutine() expects a callable')\n \n if(func.__class__ is FunctionType and\n getattr(func,'__code__',None).__class__ is CodeType):\n \n co_flags=func.__code__.co_flags\n \n \n \n if co_flags&0x180:\n return func\n \n \n \n if co_flags&0x20:\n \n co=func.__code__\n \n func.__code__=co.replace(co_flags=co.co_flags |0x100)\n return func\n \n \n \n \n \n \n import functools\n import _collections_abc\n @functools.wraps(func)\n def wrapped(*args,**kwargs):\n coro=func(*args,**kwargs)\n if(coro.__class__ is CoroutineType or\n coro.__class__ is GeneratorType and coro.gi_code.co_flags&0x100):\n \n return coro\n if(isinstance(coro,_collections_abc.Generator)and\n not isinstance(coro,_collections_abc.Coroutine)):\n \n \n \n return _GeneratorWrapper(coro)\n \n \n return coro\n \n return wrapped\n \nGenericAlias=type(list[int])\nUnionType=type(int |str)\n\nEllipsisType=type(Ellipsis)\nNoneType=type(None)\nNotImplementedType=type(NotImplemented)\n\ndef __getattr__(name):\n if name =='CapsuleType':\n import _socket\n return type(_socket.CAPI)\n raise AttributeError(f\"module {__name__ !r} has no attribute {name !r}\")\n \n__all__=[n for n in globals()if n[:1]!='_']\n__all__ +=['CapsuleType']\n", ["_collections_abc", "_socket", "functools", "sys"]], "typing": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom abc import abstractmethod,ABCMeta\nimport collections\nfrom collections import defaultdict\nimport collections.abc\nimport copyreg\nimport functools\nimport operator\nimport sys\nimport types\nfrom types import WrapperDescriptorType,MethodWrapperType,MethodDescriptorType,GenericAlias\n\nfrom _typing import(\n_idfunc,\nTypeVar,\nParamSpec,\nTypeVarTuple,\nParamSpecArgs,\nParamSpecKwargs,\nTypeAliasType,\nGeneric,\nNoDefault,\n)\n\n\n__all__=[\n\n'Annotated',\n'Any',\n'Callable',\n'ClassVar',\n'Concatenate',\n'Final',\n'ForwardRef',\n'Generic',\n'Literal',\n'Optional',\n'ParamSpec',\n'Protocol',\n'Tuple',\n'Type',\n'TypeVar',\n'TypeVarTuple',\n'Union',\n\n\n'AbstractSet',\n'ByteString',\n'Container',\n'ContextManager',\n'Hashable',\n'ItemsView',\n'Iterable',\n'Iterator',\n'KeysView',\n'Mapping',\n'MappingView',\n'MutableMapping',\n'MutableSequence',\n'MutableSet',\n'Sequence',\n'Sized',\n'ValuesView',\n'Awaitable',\n'AsyncIterator',\n'AsyncIterable',\n'Coroutine',\n'Collection',\n'AsyncGenerator',\n'AsyncContextManager',\n\n\n'Reversible',\n'SupportsAbs',\n'SupportsBytes',\n'SupportsComplex',\n'SupportsFloat',\n'SupportsIndex',\n'SupportsInt',\n'SupportsRound',\n\n\n'ChainMap',\n'Counter',\n'Deque',\n'Dict',\n'DefaultDict',\n'List',\n'OrderedDict',\n'Set',\n'FrozenSet',\n'NamedTuple',\n'TypedDict',\n'Generator',\n\n\n'BinaryIO',\n'IO',\n'Match',\n'Pattern',\n'TextIO',\n\n\n'AnyStr',\n'assert_type',\n'assert_never',\n'cast',\n'clear_overloads',\n'dataclass_transform',\n'final',\n'get_args',\n'get_origin',\n'get_overloads',\n'get_protocol_members',\n'get_type_hints',\n'is_protocol',\n'is_typeddict',\n'LiteralString',\n'Never',\n'NewType',\n'no_type_check',\n'no_type_check_decorator',\n'NoDefault',\n'NoReturn',\n'NotRequired',\n'overload',\n'override',\n'ParamSpecArgs',\n'ParamSpecKwargs',\n'ReadOnly',\n'Required',\n'reveal_type',\n'runtime_checkable',\n'Self',\n'Text',\n'TYPE_CHECKING',\n'TypeAlias',\n'TypeGuard',\n'TypeIs',\n'TypeAliasType',\n'Unpack',\n]\n\n\ndef _type_convert(arg,module=None,*,allow_special_forms=False):\n ''\n if arg is None:\n return type(None)\n if isinstance(arg,str):\n return ForwardRef(arg,module=module,is_class=allow_special_forms)\n return arg\n \n \ndef _type_check(arg,msg,is_argument=True,module=None,*,allow_special_forms=False):\n ''\n\n\n\n\n\n\n\n\n\n \n invalid_generic_forms=(Generic,Protocol)\n if not allow_special_forms:\n invalid_generic_forms +=(ClassVar,)\n if is_argument:\n invalid_generic_forms +=(Final,)\n \n arg=_type_convert(arg,module=module,allow_special_forms=allow_special_forms)\n if(isinstance(arg,_GenericAlias)and\n arg.__origin__ in invalid_generic_forms):\n raise TypeError(f\"{arg} is not valid as type argument\")\n if arg in(Any,LiteralString,NoReturn,Never,Self,TypeAlias):\n return arg\n if allow_special_forms and arg in(ClassVar,Final):\n return arg\n if isinstance(arg,_SpecialForm)or arg in(Generic,Protocol):\n raise TypeError(f\"Plain {arg} is not valid as type argument\")\n if type(arg)is tuple:\n raise TypeError(f\"{msg} Got {arg !r:.100}.\")\n return arg\n \n \ndef _is_param_expr(arg):\n return arg is ...or isinstance(arg,\n (tuple,list,ParamSpec,_ConcatenateGenericAlias))\n \n \ndef _should_unflatten_callable_args(typ,args):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return(\n typ.__origin__ is collections.abc.Callable\n and not(len(args)==2 and _is_param_expr(args[0]))\n )\n \n \ndef _type_repr(obj):\n ''\n\n\n\n\n\n \n \n \n \n if isinstance(obj,type):\n if obj.__module__ =='builtins':\n return obj.__qualname__\n return f'{obj.__module__}.{obj.__qualname__}'\n if obj is ...:\n return '...'\n if isinstance(obj,types.FunctionType):\n return obj.__name__\n if isinstance(obj,tuple):\n \n return '['+', '.join(_type_repr(t)for t in obj)+']'\n return repr(obj)\n \n \ndef _collect_type_parameters(args,*,enforce_default_ordering:bool=True):\n ''\n\n\n\n\n\n\n\n\n \n \n default_encountered=False\n \n type_var_tuple_encountered=False\n parameters=[]\n for t in args:\n if isinstance(t,type):\n \n pass\n elif isinstance(t,tuple):\n \n \n for x in t:\n for collected in _collect_type_parameters([x]):\n if collected not in parameters:\n parameters.append(collected)\n elif hasattr(t,'__typing_subst__'):\n if t not in parameters:\n if enforce_default_ordering:\n if type_var_tuple_encountered and t.has_default():\n raise TypeError('Type parameter with a default'\n ' follows TypeVarTuple')\n \n if t.has_default():\n default_encountered=True\n elif default_encountered:\n raise TypeError(f'Type parameter {t !r} without a default'\n ' follows type parameter with a default')\n \n parameters.append(t)\n else:\n if _is_unpacked_typevartuple(t):\n type_var_tuple_encountered=True\n for x in getattr(t,'__parameters__',()):\n if x not in parameters:\n parameters.append(x)\n return tuple(parameters)\n \n \ndef _check_generic_specialization(cls,arguments):\n ''\n\n\n \n expected_len=len(cls.__parameters__)\n if not expected_len:\n raise TypeError(f\"{cls} is not a generic class\")\n actual_len=len(arguments)\n if actual_len !=expected_len:\n \n if actual_len expected_len else 'few'} arguments\"\n f\" for {cls}; actual {actual_len}, expected {expect_val}\")\n \n \ndef _unpack_args(*args):\n newargs=[]\n for arg in args:\n subargs=getattr(arg,'__typing_unpacked_tuple_args__',None)\n if subargs is not None and not(subargs and subargs[-1]is ...):\n newargs.extend(subargs)\n else:\n newargs.append(arg)\n return newargs\n \ndef _deduplicate(params,*,unhashable_fallback=False):\n\n try:\n return dict.fromkeys(params)\n except TypeError:\n if not unhashable_fallback:\n raise\n \n return _deduplicate_unhashable(params)\n \ndef _deduplicate_unhashable(unhashable_params):\n new_unhashable=[]\n for t in unhashable_params:\n if t not in new_unhashable:\n new_unhashable.append(t)\n return new_unhashable\n \ndef _compare_args_orderless(first_args,second_args):\n first_unhashable=_deduplicate_unhashable(first_args)\n second_unhashable=_deduplicate_unhashable(second_args)\n t=list(second_unhashable)\n try:\n for elem in first_unhashable:\n t.remove(elem)\n except ValueError:\n return False\n return not t\n \ndef _remove_dups_flatten(parameters):\n ''\n\n\n \n \n params=[]\n for p in parameters:\n if isinstance(p,(_UnionGenericAlias,types.UnionType)):\n params.extend(p.__args__)\n else:\n params.append(p)\n \n return tuple(_deduplicate(params,unhashable_fallback=True))\n \n \ndef _flatten_literal_params(parameters):\n ''\n params=[]\n for p in parameters:\n if isinstance(p,_LiteralGenericAlias):\n params.extend(p.__args__)\n else:\n params.append(p)\n return tuple(params)\n \n \n_cleanups=[]\n_caches={}\n\n\ndef _tp_cache(func=None,/,*,typed=False):\n ''\n\n\n \n def decorator(func):\n \n \n \n \n \n cache=functools.lru_cache(typed=typed)(func)\n _caches[func]=cache\n _cleanups.append(cache.cache_clear)\n del cache\n \n @functools.wraps(func)\n def inner(*args,**kwds):\n try:\n return _caches[func](*args,**kwds)\n except TypeError:\n pass\n return func(*args,**kwds)\n return inner\n \n if func is not None:\n return decorator(func)\n \n return decorator\n \n \ndef _deprecation_warning_for_no_type_params_passed(funcname:str)->None:\n import warnings\n \n depr_message=(\n f\"Failing to pass a value to the 'type_params' parameter \"\n f\"of {funcname !r} is deprecated, as it leads to incorrect behaviour \"\n f\"when calling {funcname} on a stringified annotation \"\n f\"that references a PEP 695 type parameter. \"\n f\"It will be disallowed in Python 3.15.\"\n )\n warnings.warn(depr_message,category=DeprecationWarning,stacklevel=3)\n \n \nclass _Sentinel:\n __slots__=()\n def __repr__(self):\n return ''\n \n \n_sentinel=_Sentinel()\n\n\ndef _eval_type(t,globalns,localns,type_params=_sentinel,*,recursive_guard=frozenset()):\n ''\n\n\n\n\n \n if type_params is _sentinel:\n _deprecation_warning_for_no_type_params_passed(\"typing._eval_type\")\n type_params=()\n if isinstance(t,ForwardRef):\n return t._evaluate(globalns,localns,type_params,recursive_guard=recursive_guard)\n if isinstance(t,(_GenericAlias,GenericAlias,types.UnionType)):\n if isinstance(t,GenericAlias):\n args=tuple(\n ForwardRef(arg)if isinstance(arg,str)else arg\n for arg in t.__args__\n )\n is_unpacked=t.__unpacked__\n if _should_unflatten_callable_args(t,args):\n t=t.__origin__[(args[:-1],args[-1])]\n else:\n t=t.__origin__[args]\n if is_unpacked:\n t=Unpack[t]\n \n ev_args=tuple(\n _eval_type(\n a,globalns,localns,type_params,recursive_guard=recursive_guard\n )\n for a in t.__args__\n )\n if ev_args ==t.__args__:\n return t\n if isinstance(t,GenericAlias):\n return GenericAlias(t.__origin__,ev_args)\n if isinstance(t,types.UnionType):\n return functools.reduce(operator.or_,ev_args)\n else:\n return t.copy_with(ev_args)\n return t\n \n \nclass _Final:\n ''\n \n __slots__=('__weakref__',)\n \n def __init_subclass__(cls,/,*args,**kwds):\n if '_root'not in kwds:\n raise TypeError(\"Cannot subclass special typing classes\")\n \n \nclass _NotIterable:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n __iter__=None\n \n \n \n \nclass _SpecialForm(_Final,_NotIterable,_root=True):\n __slots__=('_name','__doc__','_getitem')\n \n def __init__(self,getitem):\n self._getitem=getitem\n self._name=getitem.__name__\n self.__doc__=getitem.__doc__\n \n def __getattr__(self,item):\n if item in{'__name__','__qualname__'}:\n return self._name\n \n raise AttributeError(item)\n \n def __mro_entries__(self,bases):\n raise TypeError(f\"Cannot subclass {self !r}\")\n \n def __repr__(self):\n return 'typing.'+self._name\n \n def __reduce__(self):\n return self._name\n \n def __call__(self,*args,**kwds):\n raise TypeError(f\"Cannot instantiate {self !r}\")\n \n def __or__(self,other):\n return Union[self,other]\n \n def __ror__(self,other):\n return Union[other,self]\n \n def __instancecheck__(self,obj):\n raise TypeError(f\"{self} cannot be used with isinstance()\")\n \n def __subclasscheck__(self,cls):\n raise TypeError(f\"{self} cannot be used with issubclass()\")\n \n @_tp_cache\n def __getitem__(self,parameters):\n return self._getitem(self,parameters)\n \n \nclass _TypedCacheSpecialForm(_SpecialForm,_root=True):\n def __getitem__(self,parameters):\n if not isinstance(parameters,tuple):\n parameters=(parameters,)\n return self._getitem(self,*parameters)\n \n \nclass _AnyMeta(type):\n def __instancecheck__(self,obj):\n if self is Any:\n raise TypeError(\"typing.Any cannot be used with isinstance()\")\n return super().__instancecheck__(obj)\n \n def __repr__(self):\n if self is Any:\n return \"typing.Any\"\n return super().__repr__()\n \n \nclass Any(metaclass=_AnyMeta):\n ''\n\n\n\n\n\n\n\n\n \n \n def __new__(cls,*args,**kwargs):\n if cls is Any:\n raise TypeError(\"Any cannot be instantiated\")\n return super().__new__(cls)\n \n \n@_SpecialForm\ndef NoReturn(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n \n \n@_SpecialForm\ndef Never(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n@_SpecialForm\ndef Self(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n@_SpecialForm\ndef LiteralString(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n@_SpecialForm\ndef ClassVar(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.',allow_special_forms=True)\n return _GenericAlias(self,(item,))\n \n@_SpecialForm\ndef Final(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.',allow_special_forms=True)\n return _GenericAlias(self,(item,))\n \n@_SpecialForm\ndef Union(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if parameters ==():\n raise TypeError(\"Cannot take a Union of no types.\")\n if not isinstance(parameters,tuple):\n parameters=(parameters,)\n msg=\"Union[arg, ...]: each arg must be a type.\"\n parameters=tuple(_type_check(p,msg)for p in parameters)\n parameters=_remove_dups_flatten(parameters)\n if len(parameters)==1:\n return parameters[0]\n if len(parameters)==2 and type(None)in parameters:\n return _UnionGenericAlias(self,parameters,name=\"Optional\")\n return _UnionGenericAlias(self,parameters)\n \ndef _make_union(left,right):\n ''\n\n\n\n\n \n return Union[left,right]\n \n@_SpecialForm\ndef Optional(self,parameters):\n ''\n arg=_type_check(parameters,f\"{self} requires a single type.\")\n return Union[arg,type(None)]\n \n@_TypedCacheSpecialForm\n@_tp_cache(typed=True)\ndef Literal(self,*parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n parameters=_flatten_literal_params(parameters)\n \n try:\n parameters=tuple(p for p,_ in _deduplicate(list(_value_and_type_iter(parameters))))\n except TypeError:\n pass\n \n return _LiteralGenericAlias(self,parameters)\n \n \n@_SpecialForm\ndef TypeAlias(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f\"{self} is not subscriptable\")\n \n \n@_SpecialForm\ndef Concatenate(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if parameters ==():\n raise TypeError(\"Cannot take a Concatenate of no types.\")\n if not isinstance(parameters,tuple):\n parameters=(parameters,)\n if not(parameters[-1]is ...or isinstance(parameters[-1],ParamSpec)):\n raise TypeError(\"The last parameter to Concatenate should be a \"\n \"ParamSpec variable or ellipsis.\")\n msg=\"Concatenate[arg, ...]: each arg must be a type.\"\n parameters=(*(_type_check(p,msg)for p in parameters[:-1]),parameters[-1])\n return _ConcatenateGenericAlias(self,parameters)\n \n \n@_SpecialForm\ndef TypeGuard(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.')\n return _GenericAlias(self,(item,))\n \n \n@_SpecialForm\ndef TypeIs(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.')\n return _GenericAlias(self,(item,))\n \n \nclass ForwardRef(_Final,_root=True):\n ''\n \n __slots__=('__forward_arg__','__forward_code__',\n '__forward_evaluated__','__forward_value__',\n '__forward_is_argument__','__forward_is_class__',\n '__forward_module__')\n \n def __init__(self,arg,is_argument=True,module=None,*,is_class=False):\n if not isinstance(arg,str):\n raise TypeError(f\"Forward reference must be a string -- got {arg !r}\")\n \n \n \n \n if arg.startswith('*'):\n arg_to_compile=f'({arg},)[0]'\n else:\n arg_to_compile=arg\n try:\n code=compile(arg_to_compile,'','eval')\n except SyntaxError:\n raise SyntaxError(f\"Forward reference must be an expression -- got {arg !r}\")\n \n self.__forward_arg__=arg\n self.__forward_code__=code\n self.__forward_evaluated__=False\n self.__forward_value__=None\n self.__forward_is_argument__=is_argument\n self.__forward_is_class__=is_class\n self.__forward_module__=module\n \n def _evaluate(self,globalns,localns,type_params=_sentinel,*,recursive_guard):\n if type_params is _sentinel:\n _deprecation_warning_for_no_type_params_passed(\"typing.ForwardRef._evaluate\")\n type_params=()\n if self.__forward_arg__ in recursive_guard:\n return self\n if not self.__forward_evaluated__ or localns is not globalns:\n if globalns is None and localns is None:\n globalns=localns={}\n elif globalns is None:\n globalns=localns\n elif localns is None:\n localns=globalns\n if self.__forward_module__ is not None:\n globalns=getattr(\n sys.modules.get(self.__forward_module__,None),'__dict__',globalns\n )\n \n \n \n \n \n \n \n \n if type_params:\n globalns,localns=dict(globalns),dict(localns)\n for param in type_params:\n param_name=param.__name__\n if not self.__forward_is_class__ or param_name not in globalns:\n globalns[param_name]=param\n localns.pop(param_name,None)\n \n type_=_type_check(\n eval(self.__forward_code__,globalns,localns),\n \"Forward references must evaluate to types.\",\n is_argument=self.__forward_is_argument__,\n allow_special_forms=self.__forward_is_class__,\n )\n self.__forward_value__=_eval_type(\n type_,\n globalns,\n localns,\n type_params,\n recursive_guard=(recursive_guard |{self.__forward_arg__}),\n )\n self.__forward_evaluated__=True\n return self.__forward_value__\n \n def __eq__(self,other):\n if not isinstance(other,ForwardRef):\n return NotImplemented\n if self.__forward_evaluated__ and other.__forward_evaluated__:\n return(self.__forward_arg__ ==other.__forward_arg__ and\n self.__forward_value__ ==other.__forward_value__)\n return(self.__forward_arg__ ==other.__forward_arg__ and\n self.__forward_module__ ==other.__forward_module__)\n \n def __hash__(self):\n return hash((self.__forward_arg__,self.__forward_module__))\n \n def __or__(self,other):\n return Union[self,other]\n \n def __ror__(self,other):\n return Union[other,self]\n \n def __repr__(self):\n if self.__forward_module__ is None:\n module_repr=''\n else:\n module_repr=f', module={self.__forward_module__ !r}'\n return f'ForwardRef({self.__forward_arg__ !r}{module_repr})'\n \n \ndef _is_unpacked_typevartuple(x:Any)->bool:\n return((not isinstance(x,type))and\n getattr(x,'__typing_is_unpacked_typevartuple__',False))\n \n \ndef _is_typevar_like(x:Any)->bool:\n return isinstance(x,(TypeVar,ParamSpec))or _is_unpacked_typevartuple(x)\n \n \ndef _typevar_subst(self,arg):\n msg=\"Parameters to generic types must be types.\"\n arg=_type_check(arg,msg,is_argument=True)\n if((isinstance(arg,_GenericAlias)and arg.__origin__ is Unpack)or\n (isinstance(arg,GenericAlias)and getattr(arg,'__unpacked__',False))):\n raise TypeError(f\"{arg} is not valid as type argument\")\n return arg\n \n \ndef _typevartuple_prepare_subst(self,alias,args):\n params=alias.__parameters__\n typevartuple_index=params.index(self)\n for param in params[typevartuple_index+1:]:\n if isinstance(param,TypeVarTuple):\n raise TypeError(f\"More than one TypeVarTuple parameter in {alias}\")\n \n alen=len(args)\n plen=len(params)\n left=typevartuple_index\n right=plen -typevartuple_index -1\n var_tuple_index=None\n fillarg=None\n for k,arg in enumerate(args):\n if not isinstance(arg,type):\n subargs=getattr(arg,'__typing_unpacked_tuple_args__',None)\n if subargs and len(subargs)==2 and subargs[-1]is ...:\n if var_tuple_index is not None:\n raise TypeError(\"More than one unpacked arbitrary-length tuple argument\")\n var_tuple_index=k\n fillarg=subargs[0]\n if var_tuple_index is not None:\n left=min(left,var_tuple_index)\n right=min(right,alen -var_tuple_index -1)\n elif left+right >alen:\n raise TypeError(f\"Too few arguments for {alias};\"\n f\" actual {alen}, expected at least {plen -1}\")\n if left ==alen -right and self.has_default():\n replacement=_unpack_args(self.__default__)\n else:\n replacement=args[left:alen -right]\n \n return(\n *args[:left],\n *([fillarg]*(typevartuple_index -left)),\n replacement,\n *([fillarg]*(plen -right -left -typevartuple_index -1)),\n *args[alen -right:],\n )\n \n \ndef _paramspec_subst(self,arg):\n if isinstance(arg,(list,tuple)):\n arg=tuple(_type_check(a,\"Expected a type.\")for a in arg)\n elif not _is_param_expr(arg):\n raise TypeError(f\"Expected a list of types, an ellipsis, \"\n f\"ParamSpec, or Concatenate. Got {arg}\")\n return arg\n \n \ndef _paramspec_prepare_subst(self,alias,args):\n params=alias.__parameters__\n i=params.index(self)\n if i ==len(args)and self.has_default():\n args=[*args,self.__default__]\n if i >=len(args):\n raise TypeError(f\"Too few arguments for {alias}\")\n \n if len(params)==1 and not _is_param_expr(args[0]):\n assert i ==0\n args=(args,)\n \n elif isinstance(args[i],list):\n args=(*args[:i],tuple(args[i]),*args[i+1:])\n return args\n \n \n@_tp_cache\ndef _generic_class_getitem(cls,args):\n ''\n\n\n\n\n\n\n\n \n if not isinstance(args,tuple):\n args=(args,)\n \n args=tuple(_type_convert(p)for p in args)\n is_generic_or_protocol=cls in(Generic,Protocol)\n \n if is_generic_or_protocol:\n \n if not args:\n raise TypeError(\n f\"Parameter list to {cls.__qualname__}[...] cannot be empty\"\n )\n if not all(_is_typevar_like(p)for p in args):\n raise TypeError(\n f\"Parameters to {cls.__name__}[...] must all be type variables \"\n f\"or parameter specification variables.\")\n if len(set(args))!=len(args):\n raise TypeError(\n f\"Parameters to {cls.__name__}[...] must all be unique\")\n else:\n \n for param in cls.__parameters__:\n prepare=getattr(param,'__typing_prepare_subst__',None)\n if prepare is not None:\n args=prepare(cls,args)\n _check_generic_specialization(cls,args)\n \n new_args=[]\n for param,new_arg in zip(cls.__parameters__,args):\n if isinstance(param,TypeVarTuple):\n new_args.extend(new_arg)\n else:\n new_args.append(new_arg)\n args=tuple(new_args)\n \n return _GenericAlias(cls,args)\n \n \ndef _generic_init_subclass(cls,*args,**kwargs):\n super(Generic,cls).__init_subclass__(*args,**kwargs)\n tvars=[]\n if '__orig_bases__'in cls.__dict__:\n error=Generic in cls.__orig_bases__\n else:\n error=(Generic in cls.__bases__ and\n cls.__name__ !='Protocol'and\n type(cls)!=_TypedDictMeta)\n if error:\n raise TypeError(\"Cannot inherit from plain Generic\")\n if '__orig_bases__'in cls.__dict__:\n tvars=_collect_type_parameters(cls.__orig_bases__)\n \n \n \n \n \n gvars=None\n for base in cls.__orig_bases__:\n if(isinstance(base,_GenericAlias)and\n base.__origin__ is Generic):\n if gvars is not None:\n raise TypeError(\n \"Cannot inherit from Generic[...] multiple times.\")\n gvars=base.__parameters__\n if gvars is not None:\n tvarset=set(tvars)\n gvarset=set(gvars)\n if not tvarset <=gvarset:\n s_vars=', '.join(str(t)for t in tvars if t not in gvarset)\n s_args=', '.join(str(g)for g in gvars)\n raise TypeError(f\"Some type variables ({s_vars}) are\"\n f\" not listed in Generic[{s_args}]\")\n tvars=gvars\n cls.__parameters__=tuple(tvars)\n \n \ndef _is_dunder(attr):\n return attr.startswith('__')and attr.endswith('__')\n \nclass _BaseGenericAlias(_Final,_root=True):\n ''\n\n\n\n\n\n\n \n \n def __init__(self,origin,*,inst=True,name=None):\n self._inst=inst\n self._name=name\n self.__origin__=origin\n self.__slots__=None\n \n def __call__(self,*args,**kwargs):\n if not self._inst:\n raise TypeError(f\"Type {self._name} cannot be instantiated; \"\n f\"use {self.__origin__.__name__}() instead\")\n result=self.__origin__(*args,**kwargs)\n try:\n result.__orig_class__=self\n \n \n except Exception:\n pass\n return result\n \n def __mro_entries__(self,bases):\n res=[]\n if self.__origin__ not in bases:\n res.append(self.__origin__)\n \n \n \n \n \n \n \n i=bases.index(self)\n for b in bases[i+1:]:\n if isinstance(b,_BaseGenericAlias):\n break\n if not isinstance(b,type):\n meth=getattr(b,\"__mro_entries__\",None)\n new_bases=meth(bases)if meth else None\n if(\n isinstance(new_bases,tuple)and\n any(\n isinstance(b2,type)and issubclass(b2,Generic)\n for b2 in new_bases\n )\n ):\n break\n elif issubclass(b,Generic):\n break\n else:\n res.append(Generic)\n return tuple(res)\n \n def __getattr__(self,attr):\n if attr in{'__name__','__qualname__'}:\n return self._name or self.__origin__.__name__\n \n \n \n if '__origin__'in self.__dict__ and not _is_dunder(attr):\n return getattr(self.__origin__,attr)\n raise AttributeError(attr)\n \n def __setattr__(self,attr,val):\n if _is_dunder(attr)or attr in{'_name','_inst','_nparams','_defaults'}:\n super().__setattr__(attr,val)\n else:\n setattr(self.__origin__,attr,val)\n \n def __instancecheck__(self,obj):\n return self.__subclasscheck__(type(obj))\n \n def __subclasscheck__(self,cls):\n raise TypeError(\"Subscripted generics cannot be used with\"\n \" class and instance checks\")\n \n def __dir__(self):\n return list(set(super().__dir__()\n +[attr for attr in dir(self.__origin__)if not _is_dunder(attr)]))\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass _GenericAlias(_BaseGenericAlias,_root=True):\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n def __init__(self,origin,args,*,inst=True,name=None):\n super().__init__(origin,inst=inst,name=name)\n if not isinstance(args,tuple):\n args=(args,)\n self.__args__=tuple(...if a is _TypingEllipsis else\n a for a in args)\n enforce_default_ordering=origin in(Generic,Protocol)\n self.__parameters__=_collect_type_parameters(\n args,\n enforce_default_ordering=enforce_default_ordering,\n )\n if not name:\n self.__module__=origin.__module__\n \n def __eq__(self,other):\n if not isinstance(other,_GenericAlias):\n return NotImplemented\n return(self.__origin__ ==other.__origin__\n and self.__args__ ==other.__args__)\n \n def __hash__(self):\n return hash((self.__origin__,self.__args__))\n \n def __or__(self,right):\n return Union[self,right]\n \n def __ror__(self,left):\n return Union[left,self]\n \n @_tp_cache\n def __getitem__(self,args):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if self.__origin__ in(Generic,Protocol):\n \n raise TypeError(f\"Cannot subscript already-subscripted {self}\")\n if not self.__parameters__:\n raise TypeError(f\"{self} is not a generic class\")\n \n \n if not isinstance(args,tuple):\n args=(args,)\n args=_unpack_args(*(_type_convert(p)for p in args))\n new_args=self._determine_new_args(args)\n r=self.copy_with(new_args)\n return r\n \n def _determine_new_args(self,args):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n params=self.__parameters__\n \n for param in params:\n prepare=getattr(param,'__typing_prepare_subst__',None)\n if prepare is not None:\n args=prepare(self,args)\n alen=len(args)\n plen=len(params)\n if alen !=plen:\n raise TypeError(f\"Too {'many'if alen >plen else 'few'} arguments for {self};\"\n f\" actual {alen}, expected {plen}\")\n new_arg_by_param=dict(zip(params,args))\n return tuple(self._make_substitution(self.__args__,new_arg_by_param))\n \n def _make_substitution(self,args,new_arg_by_param):\n ''\n new_args=[]\n for old_arg in args:\n if isinstance(old_arg,type):\n new_args.append(old_arg)\n continue\n \n substfunc=getattr(old_arg,'__typing_subst__',None)\n if substfunc:\n new_arg=substfunc(new_arg_by_param[old_arg])\n else:\n subparams=getattr(old_arg,'__parameters__',())\n if not subparams:\n new_arg=old_arg\n else:\n subargs=[]\n for x in subparams:\n if isinstance(x,TypeVarTuple):\n subargs.extend(new_arg_by_param[x])\n else:\n subargs.append(new_arg_by_param[x])\n new_arg=old_arg[tuple(subargs)]\n \n if self.__origin__ ==collections.abc.Callable and isinstance(new_arg,tuple):\n \n \n \n \n \n \n \n \n \n \n new_args.extend(new_arg)\n elif _is_unpacked_typevartuple(old_arg):\n \n \n \n \n \n \n \n \n \n new_args.extend(new_arg)\n elif isinstance(old_arg,tuple):\n \n \n \n \n \n \n \n new_args.append(\n tuple(self._make_substitution(old_arg,new_arg_by_param)),\n )\n else:\n new_args.append(new_arg)\n return new_args\n \n def copy_with(self,args):\n return self.__class__(self.__origin__,args,name=self._name,inst=self._inst)\n \n def __repr__(self):\n if self._name:\n name='typing.'+self._name\n else:\n name=_type_repr(self.__origin__)\n if self.__args__:\n args=\", \".join([_type_repr(a)for a in self.__args__])\n else:\n \n args=\"()\"\n return f'{name}[{args}]'\n \n def __reduce__(self):\n if self._name:\n origin=globals()[self._name]\n else:\n origin=self.__origin__\n args=tuple(self.__args__)\n if len(args)==1 and not isinstance(args[0],tuple):\n args,=args\n return operator.getitem,(origin,args)\n \n def __mro_entries__(self,bases):\n if isinstance(self.__origin__,_SpecialForm):\n raise TypeError(f\"Cannot subclass {self !r}\")\n \n if self._name:\n return super().__mro_entries__(bases)\n if self.__origin__ is Generic:\n if Protocol in bases:\n return()\n i=bases.index(self)\n for b in bases[i+1:]:\n if isinstance(b,_BaseGenericAlias)and b is not self:\n return()\n return(self.__origin__,)\n \n def __iter__(self):\n yield Unpack[self]\n \n \n \n \n \n \nclass _SpecialGenericAlias(_NotIterable,_BaseGenericAlias,_root=True):\n def __init__(self,origin,nparams,*,inst=True,name=None,defaults=()):\n if name is None:\n name=origin.__name__\n super().__init__(origin,inst=inst,name=name)\n self._nparams=nparams\n self._defaults=defaults\n if origin.__module__ =='builtins':\n self.__doc__=f'A generic version of {origin.__qualname__}.'\n else:\n self.__doc__=f'A generic version of {origin.__module__}.{origin.__qualname__}.'\n \n @_tp_cache\n def __getitem__(self,params):\n if not isinstance(params,tuple):\n params=(params,)\n msg=\"Parameters to generic types must be types.\"\n params=tuple(_type_check(p,msg)for p in params)\n if(self._defaults\n and len(params)=self._nparams\n ):\n params=(*params,*self._defaults[len(params)-self._nparams:])\n actual_len=len(params)\n \n if actual_len !=self._nparams:\n if self._defaults:\n expected=f\"at least {self._nparams -len(self._defaults)}\"\n else:\n expected=str(self._nparams)\n if not self._nparams:\n raise TypeError(f\"{self} is not a generic class\")\n raise TypeError(f\"Too {'many'if actual_len >self._nparams else 'few'} arguments for {self};\"\n f\" actual {actual_len}, expected {expected}\")\n return self.copy_with(params)\n \n def copy_with(self,params):\n return _GenericAlias(self.__origin__,params,\n name=self._name,inst=self._inst)\n \n def __repr__(self):\n return 'typing.'+self._name\n \n def __subclasscheck__(self,cls):\n if isinstance(cls,_SpecialGenericAlias):\n return issubclass(cls.__origin__,self.__origin__)\n if not isinstance(cls,_GenericAlias):\n return issubclass(cls,self.__origin__)\n return super().__subclasscheck__(cls)\n \n def __reduce__(self):\n return self._name\n \n def __or__(self,right):\n return Union[self,right]\n \n def __ror__(self,left):\n return Union[left,self]\n \n \nclass _DeprecatedGenericAlias(_SpecialGenericAlias,_root=True):\n def __init__(\n self,origin,nparams,*,removal_version,inst=True,name=None\n ):\n super().__init__(origin,nparams,inst=inst,name=name)\n self._removal_version=removal_version\n \n def __instancecheck__(self,inst):\n import warnings\n warnings._deprecated(\n f\"{self.__module__}.{self._name}\",remove=self._removal_version\n )\n return super().__instancecheck__(inst)\n \n \nclass _CallableGenericAlias(_NotIterable,_GenericAlias,_root=True):\n def __repr__(self):\n assert self._name =='Callable'\n args=self.__args__\n if len(args)==2 and _is_param_expr(args[0]):\n return super().__repr__()\n return(f'typing.Callable'\n f'[[{\", \".join([_type_repr(a)for a in args[:-1]])}], '\n f'{_type_repr(args[-1])}]')\n \n def __reduce__(self):\n args=self.__args__\n if not(len(args)==2 and _is_param_expr(args[0])):\n args=list(args[:-1]),args[-1]\n return operator.getitem,(Callable,args)\n \n \nclass _CallableType(_SpecialGenericAlias,_root=True):\n def copy_with(self,params):\n return _CallableGenericAlias(self.__origin__,params,\n name=self._name,inst=self._inst)\n \n def __getitem__(self,params):\n if not isinstance(params,tuple)or len(params)!=2:\n raise TypeError(\"Callable must be used as \"\n \"Callable[[arg, ...], result].\")\n args,result=params\n \n \n \n if isinstance(args,list):\n params=(tuple(args),result)\n else:\n params=(args,result)\n return self.__getitem_inner__(params)\n \n @_tp_cache\n def __getitem_inner__(self,params):\n args,result=params\n msg=\"Callable[args, result]: result must be a type.\"\n result=_type_check(result,msg)\n if args is Ellipsis:\n return self.copy_with((_TypingEllipsis,result))\n if not isinstance(args,tuple):\n args=(args,)\n args=tuple(_type_convert(arg)for arg in args)\n params=args+(result,)\n return self.copy_with(params)\n \n \nclass _TupleType(_SpecialGenericAlias,_root=True):\n @_tp_cache\n def __getitem__(self,params):\n if not isinstance(params,tuple):\n params=(params,)\n if len(params)>=2 and params[-1]is ...:\n msg=\"Tuple[t, ...]: t must be a type.\"\n params=tuple(_type_check(p,msg)for p in params[:-1])\n return self.copy_with((*params,_TypingEllipsis))\n msg=\"Tuple[t0, t1, ...]: each t must be a type.\"\n params=tuple(_type_check(p,msg)for p in params)\n return self.copy_with(params)\n \n \nclass _UnionGenericAlias(_NotIterable,_GenericAlias,_root=True):\n def copy_with(self,params):\n return Union[params]\n \n def __eq__(self,other):\n if not isinstance(other,(_UnionGenericAlias,types.UnionType)):\n return NotImplemented\n try:\n return set(self.__args__)==set(other.__args__)\n except TypeError:\n return _compare_args_orderless(self.__args__,other.__args__)\n \n def __hash__(self):\n return hash(frozenset(self.__args__))\n \n def __repr__(self):\n args=self.__args__\n if len(args)==2:\n if args[0]is type(None):\n return f'typing.Optional[{_type_repr(args[1])}]'\n elif args[1]is type(None):\n return f'typing.Optional[{_type_repr(args[0])}]'\n return super().__repr__()\n \n def __instancecheck__(self,obj):\n return self.__subclasscheck__(type(obj))\n \n def __subclasscheck__(self,cls):\n for arg in self.__args__:\n if issubclass(cls,arg):\n return True\n \n def __reduce__(self):\n func,(origin,args)=super().__reduce__()\n return func,(Union,args)\n \n \ndef _value_and_type_iter(parameters):\n return((p,type(p))for p in parameters)\n \n \nclass _LiteralGenericAlias(_GenericAlias,_root=True):\n def __eq__(self,other):\n if not isinstance(other,_LiteralGenericAlias):\n return NotImplemented\n \n return set(_value_and_type_iter(self.__args__))==set(_value_and_type_iter(other.__args__))\n \n def __hash__(self):\n return hash(frozenset(_value_and_type_iter(self.__args__)))\n \n \nclass _ConcatenateGenericAlias(_GenericAlias,_root=True):\n def copy_with(self,params):\n if isinstance(params[-1],(list,tuple)):\n return(*params[:-1],*params[-1])\n if isinstance(params[-1],_ConcatenateGenericAlias):\n params=(*params[:-1],*params[-1].__args__)\n return super().copy_with(params)\n \n \n@_SpecialForm\ndef Unpack(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self} accepts only single type.')\n return _UnpackGenericAlias(origin=self,args=(item,))\n \n \nclass _UnpackGenericAlias(_GenericAlias,_root=True):\n def __repr__(self):\n \n \n return f'typing.Unpack[{_type_repr(self.__args__[0])}]'\n \n def __getitem__(self,args):\n if self.__typing_is_unpacked_typevartuple__:\n return args\n return super().__getitem__(args)\n \n @property\n def __typing_unpacked_tuple_args__(self):\n assert self.__origin__ is Unpack\n assert len(self.__args__)==1\n arg,=self.__args__\n if isinstance(arg,(_GenericAlias,types.GenericAlias)):\n if arg.__origin__ is not tuple:\n raise TypeError(\"Unpack[...] must be used with a tuple type\")\n return arg.__args__\n return None\n \n @property\n def __typing_is_unpacked_typevartuple__(self):\n assert self.__origin__ is Unpack\n assert len(self.__args__)==1\n return isinstance(self.__args__[0],TypeVarTuple)\n \n \nclass _TypingEllipsis:\n ''\n \n \n_TYPING_INTERNALS=frozenset({\n'__parameters__','__orig_bases__','__orig_class__',\n'_is_protocol','_is_runtime_protocol','__protocol_attrs__',\n'__non_callable_proto_members__','__type_params__',\n})\n\n_SPECIAL_NAMES=frozenset({\n'__abstractmethods__','__annotations__','__dict__','__doc__',\n'__init__','__module__','__new__','__slots__',\n'__subclasshook__','__weakref__','__class_getitem__',\n'__match_args__','__static_attributes__','__firstlineno__',\n})\n\n\nEXCLUDED_ATTRIBUTES=_TYPING_INTERNALS |_SPECIAL_NAMES |{'_MutableMapping__marker'}\n\n\ndef _get_protocol_attrs(cls):\n ''\n\n\n\n \n attrs=set()\n for base in cls.__mro__[:-1]:\n if base.__name__ in{'Protocol','Generic'}:\n continue\n annotations=getattr(base,'__annotations__',{})\n for attr in(*base.__dict__,*annotations):\n if not attr.startswith('_abc_')and attr not in EXCLUDED_ATTRIBUTES:\n attrs.add(attr)\n return attrs\n \n \ndef _no_init_or_replace_init(self,*args,**kwargs):\n cls=type(self)\n \n if cls._is_protocol:\n raise TypeError('Protocols cannot be instantiated')\n \n \n \n if cls.__init__ is not _no_init_or_replace_init:\n return\n \n \n \n \n \n \n \n for base in cls.__mro__:\n init=base.__dict__.get('__init__',_no_init_or_replace_init)\n if init is not _no_init_or_replace_init:\n cls.__init__=init\n break\n else:\n \n cls.__init__=object.__init__\n \n cls.__init__(self,*args,**kwargs)\n \n \ndef _caller(depth=1,default='__main__'):\n try:\n return sys._getframemodulename(depth+1)or default\n except AttributeError:\n pass\n try:\n return sys._getframe(depth+1).f_globals.get('__name__',default)\n except(AttributeError,ValueError):\n pass\n return None\n \ndef _allow_reckless_class_checks(depth=2):\n ''\n\n\n\n \n return _caller(depth)in{'abc','functools',None}\n \n \n_PROTO_ALLOWLIST={\n'collections.abc':[\n'Callable','Awaitable','Iterable','Iterator','AsyncIterable',\n'Hashable','Sized','Container','Collection','Reversible','Buffer',\n],\n'contextlib':['AbstractContextManager','AbstractAsyncContextManager'],\n}\n\n\n@functools.cache\ndef _lazy_load_getattr_static():\n\n\n from inspect import getattr_static\n return getattr_static\n \n \n_cleanups.append(_lazy_load_getattr_static.cache_clear)\n\ndef _pickle_psargs(psargs):\n return ParamSpecArgs,(psargs.__origin__,)\n \ncopyreg.pickle(ParamSpecArgs,_pickle_psargs)\n\ndef _pickle_pskwargs(pskwargs):\n return ParamSpecKwargs,(pskwargs.__origin__,)\n \ncopyreg.pickle(ParamSpecKwargs,_pickle_pskwargs)\n\ndel _pickle_psargs,_pickle_pskwargs\n\n\n\n\n\n\n_abc_instancecheck=ABCMeta.__instancecheck__\n_abc_subclasscheck=ABCMeta.__subclasscheck__\n\n\ndef _type_check_issubclass_arg_1(arg):\n ''\n\n\n\n\n\n\n\n\n\n \n if not isinstance(arg,type):\n \n raise TypeError('issubclass() arg 1 must be a class')\n \n \nclass _ProtocolMeta(ABCMeta):\n\n\n def __new__(mcls,name,bases,namespace,/,**kwargs):\n if name ==\"Protocol\"and bases ==(Generic,):\n pass\n elif Protocol in bases:\n for base in bases:\n if not(\n base in{object,Generic}\n or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__,[])\n or(\n issubclass(base,Generic)\n and getattr(base,\"_is_protocol\",False)\n )\n ):\n raise TypeError(\n f\"Protocols can only inherit from other protocols, \"\n f\"got {base !r}\"\n )\n return super().__new__(mcls,name,bases,namespace,**kwargs)\n \n def __init__(cls,*args,**kwargs):\n super().__init__(*args,**kwargs)\n if getattr(cls,\"_is_protocol\",False):\n cls.__protocol_attrs__=_get_protocol_attrs(cls)\n \n def __subclasscheck__(cls,other):\n if cls is Protocol:\n return type.__subclasscheck__(cls,other)\n if(\n getattr(cls,'_is_protocol',False)\n and not _allow_reckless_class_checks()\n ):\n if not getattr(cls,'_is_runtime_protocol',False):\n _type_check_issubclass_arg_1(other)\n raise TypeError(\n \"Instance and class checks can only be used with \"\n \"@runtime_checkable protocols\"\n )\n if(\n \n cls.__non_callable_proto_members__\n and cls.__dict__.get(\"__subclasshook__\")is _proto_hook\n ):\n _type_check_issubclass_arg_1(other)\n non_method_attrs=sorted(cls.__non_callable_proto_members__)\n raise TypeError(\n \"Protocols with non-method members don't support issubclass().\"\n f\" Non-method members: {str(non_method_attrs)[1:-1]}.\"\n )\n return _abc_subclasscheck(cls,other)\n \n def __instancecheck__(cls,instance):\n \n \n if cls is Protocol:\n return type.__instancecheck__(cls,instance)\n if not getattr(cls,\"_is_protocol\",False):\n \n return _abc_instancecheck(cls,instance)\n \n if(\n not getattr(cls,'_is_runtime_protocol',False)and\n not _allow_reckless_class_checks()\n ):\n raise TypeError(\"Instance and class checks can only be used with\"\n \" @runtime_checkable protocols\")\n \n if _abc_instancecheck(cls,instance):\n return True\n \n getattr_static=_lazy_load_getattr_static()\n for attr in cls.__protocol_attrs__:\n try:\n val=getattr_static(instance,attr)\n except AttributeError:\n break\n \n if val is None and attr not in cls.__non_callable_proto_members__:\n break\n else:\n return True\n \n return False\n \n \n@classmethod\ndef _proto_hook(cls,other):\n if not cls.__dict__.get('_is_protocol',False):\n return NotImplemented\n \n for attr in cls.__protocol_attrs__:\n for base in other.__mro__:\n \n if attr in base.__dict__:\n if base.__dict__[attr]is None:\n return NotImplemented\n break\n \n \n annotations=getattr(base,'__annotations__',{})\n if(isinstance(annotations,collections.abc.Mapping)and\n attr in annotations and\n issubclass(other,Generic)and getattr(other,'_is_protocol',False)):\n break\n else:\n return NotImplemented\n return True\n \n \nclass Protocol(Generic,metaclass=_ProtocolMeta):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n _is_protocol=True\n _is_runtime_protocol=False\n \n def __init_subclass__(cls,*args,**kwargs):\n super().__init_subclass__(*args,**kwargs)\n \n \n if not cls.__dict__.get('_is_protocol',False):\n cls._is_protocol=any(b is Protocol for b in cls.__bases__)\n \n \n if '__subclasshook__'not in cls.__dict__:\n cls.__subclasshook__=_proto_hook\n \n \n if cls._is_protocol and cls.__init__ is Protocol.__init__:\n cls.__init__=_no_init_or_replace_init\n \n \nclass _AnnotatedAlias(_NotIterable,_GenericAlias,_root=True):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,origin,metadata):\n if isinstance(origin,_AnnotatedAlias):\n metadata=origin.__metadata__+metadata\n origin=origin.__origin__\n super().__init__(origin,origin,name='Annotated')\n self.__metadata__=metadata\n \n def copy_with(self,params):\n assert len(params)==1\n new_type=params[0]\n return _AnnotatedAlias(new_type,self.__metadata__)\n \n def __repr__(self):\n return \"typing.Annotated[{}, {}]\".format(\n _type_repr(self.__origin__),\n \", \".join(repr(a)for a in self.__metadata__)\n )\n \n def __reduce__(self):\n return operator.getitem,(\n Annotated,(self.__origin__,)+self.__metadata__\n )\n \n def __eq__(self,other):\n if not isinstance(other,_AnnotatedAlias):\n return NotImplemented\n return(self.__origin__ ==other.__origin__\n and self.__metadata__ ==other.__metadata__)\n \n def __hash__(self):\n return hash((self.__origin__,self.__metadata__))\n \n def __getattr__(self,attr):\n if attr in{'__name__','__qualname__'}:\n return 'Annotated'\n return super().__getattr__(attr)\n \n def __mro_entries__(self,bases):\n return(self.__origin__,)\n \n \n@_TypedCacheSpecialForm\n@_tp_cache(typed=True)\ndef Annotated(self,*params):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if len(params)<2:\n raise TypeError(\"Annotated[...] should be used \"\n \"with at least two arguments (a type and an \"\n \"annotation).\")\n if _is_unpacked_typevartuple(params[0]):\n raise TypeError(\"Annotated[...] should not be used with an \"\n \"unpacked TypeVarTuple\")\n msg=\"Annotated[t, ...]: t must be a type.\"\n origin=_type_check(params[0],msg,allow_special_forms=True)\n metadata=tuple(params[1:])\n return _AnnotatedAlias(origin,metadata)\n \n \ndef runtime_checkable(cls):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not issubclass(cls,Generic)or not getattr(cls,'_is_protocol',False):\n raise TypeError('@runtime_checkable can be only applied to protocol classes,'\n ' got %r'%cls)\n cls._is_runtime_protocol=True\n \n \n \n \n cls.__non_callable_proto_members__=set()\n for attr in cls.__protocol_attrs__:\n try:\n is_callable=callable(getattr(cls,attr,None))\n except Exception as e:\n raise TypeError(\n f\"Failed to determine whether protocol member {attr !r} \"\n \"is a method member\"\n )from e\n else:\n if not is_callable:\n cls.__non_callable_proto_members__.add(attr)\n return cls\n \n \ndef cast(typ,val):\n ''\n\n\n\n\n\n \n return val\n \n \ndef assert_type(val,typ,/):\n ''\n\n\n\n\n\n\n\n\n\n\n \n return val\n \n \n_allowed_types=(types.FunctionType,types.BuiltinFunctionType,\ntypes.MethodType,types.ModuleType,\nWrapperDescriptorType,MethodWrapperType,MethodDescriptorType)\n\n\ndef get_type_hints(obj,globalns=None,localns=None,include_extras=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if getattr(obj,'__no_type_check__',None):\n return{}\n \n if isinstance(obj,type):\n hints={}\n for base in reversed(obj.__mro__):\n if globalns is None:\n base_globals=getattr(sys.modules.get(base.__module__,None),'__dict__',{})\n else:\n base_globals=globalns\n ann=base.__dict__.get('__annotations__',{})\n if isinstance(ann,types.GetSetDescriptorType):\n ann={}\n base_locals=dict(vars(base))if localns is None else localns\n if localns is None and globalns is None:\n \n \n \n \n \n \n base_globals,base_locals=base_locals,base_globals\n for name,value in ann.items():\n if value is None:\n value=type(None)\n if isinstance(value,str):\n value=ForwardRef(value,is_argument=False,is_class=True)\n value=_eval_type(value,base_globals,base_locals,base.__type_params__)\n hints[name]=value\n return hints if include_extras else{k:_strip_annotations(t)for k,t in hints.items()}\n \n if globalns is None:\n if isinstance(obj,types.ModuleType):\n globalns=obj.__dict__\n else:\n nsobj=obj\n \n while hasattr(nsobj,'__wrapped__'):\n nsobj=nsobj.__wrapped__\n globalns=getattr(nsobj,'__globals__',{})\n if localns is None:\n localns=globalns\n elif localns is None:\n localns=globalns\n hints=getattr(obj,'__annotations__',None)\n if hints is None:\n \n if isinstance(obj,_allowed_types):\n return{}\n else:\n raise TypeError('{!r} is not a module, class, method, '\n 'or function.'.format(obj))\n hints=dict(hints)\n type_params=getattr(obj,\"__type_params__\",())\n for name,value in hints.items():\n if value is None:\n value=type(None)\n if isinstance(value,str):\n \n \n value=ForwardRef(\n value,\n is_argument=not isinstance(obj,types.ModuleType),\n is_class=False,\n )\n hints[name]=_eval_type(value,globalns,localns,type_params)\n return hints if include_extras else{k:_strip_annotations(t)for k,t in hints.items()}\n \n \ndef _strip_annotations(t):\n ''\n if isinstance(t,_AnnotatedAlias):\n return _strip_annotations(t.__origin__)\n if hasattr(t,\"__origin__\")and t.__origin__ in(Required,NotRequired,ReadOnly):\n return _strip_annotations(t.__args__[0])\n if isinstance(t,_GenericAlias):\n stripped_args=tuple(_strip_annotations(a)for a in t.__args__)\n if stripped_args ==t.__args__:\n return t\n return t.copy_with(stripped_args)\n if isinstance(t,GenericAlias):\n stripped_args=tuple(_strip_annotations(a)for a in t.__args__)\n if stripped_args ==t.__args__:\n return t\n return GenericAlias(t.__origin__,stripped_args)\n if isinstance(t,types.UnionType):\n stripped_args=tuple(_strip_annotations(a)for a in t.__args__)\n if stripped_args ==t.__args__:\n return t\n return functools.reduce(operator.or_,stripped_args)\n \n return t\n \n \ndef get_origin(tp):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(tp,_AnnotatedAlias):\n return Annotated\n if isinstance(tp,(_BaseGenericAlias,GenericAlias,\n ParamSpecArgs,ParamSpecKwargs)):\n return tp.__origin__\n if tp is Generic:\n return Generic\n if isinstance(tp,types.UnionType):\n return types.UnionType\n return None\n \n \ndef get_args(tp):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(tp,_AnnotatedAlias):\n return(tp.__origin__,)+tp.__metadata__\n if isinstance(tp,(_GenericAlias,GenericAlias)):\n res=tp.__args__\n if _should_unflatten_callable_args(tp,res):\n res=(list(res[:-1]),res[-1])\n return res\n if isinstance(tp,types.UnionType):\n return tp.__args__\n return()\n \n \ndef is_typeddict(tp):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n return isinstance(tp,_TypedDictMeta)\n \n \n_ASSERT_NEVER_REPR_MAX_LENGTH=100\n\n\ndef assert_never(arg:Never,/)->Never:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n value=repr(arg)\n if len(value)>_ASSERT_NEVER_REPR_MAX_LENGTH:\n value=value[:_ASSERT_NEVER_REPR_MAX_LENGTH]+'...'\n raise AssertionError(f\"Expected code to be unreachable, but got: {value}\")\n \n \ndef no_type_check(arg):\n ''\n\n\n\n\n\n\n \n if isinstance(arg,type):\n for key in dir(arg):\n obj=getattr(arg,key)\n if(\n not hasattr(obj,'__qualname__')\n or obj.__qualname__ !=f'{arg.__qualname__}.{obj.__name__}'\n or getattr(obj,'__module__',None)!=arg.__module__\n ):\n \n \n \n continue\n \n if isinstance(obj,types.FunctionType):\n obj.__no_type_check__=True\n if isinstance(obj,types.MethodType):\n obj.__func__.__no_type_check__=True\n \n if isinstance(obj,type):\n no_type_check(obj)\n try:\n arg.__no_type_check__=True\n except TypeError:\n pass\n return arg\n \n \ndef no_type_check_decorator(decorator):\n ''\n\n\n\n \n import warnings\n warnings._deprecated(\"typing.no_type_check_decorator\",remove=(3,15))\n @functools.wraps(decorator)\n def wrapped_decorator(*args,**kwds):\n func=decorator(*args,**kwds)\n func=no_type_check(func)\n return func\n \n return wrapped_decorator\n \n \ndef _overload_dummy(*args,**kwds):\n ''\n raise NotImplementedError(\n \"You should not call an overloaded function. \"\n \"A series of @overload-decorated functions \"\n \"outside a stub module should always be followed \"\n \"by an implementation that is not @overload-ed.\")\n \n \n \n_overload_registry=defaultdict(functools.partial(defaultdict,dict))\n\n\ndef overload(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n f=getattr(func,\"__func__\",func)\n try:\n _overload_registry[f.__module__][f.__qualname__][f.__code__.co_firstlineno]=func\n except AttributeError:\n \n pass\n return _overload_dummy\n \n \ndef get_overloads(func):\n ''\n \n f=getattr(func,\"__func__\",func)\n if f.__module__ not in _overload_registry:\n return[]\n mod_dict=_overload_registry[f.__module__]\n if f.__qualname__ not in mod_dict:\n return[]\n return list(mod_dict[f.__qualname__].values())\n \n \ndef clear_overloads():\n ''\n _overload_registry.clear()\n \n \ndef final(f):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n f.__final__=True\n except(AttributeError,TypeError):\n \n \n \n pass\n return f\n \n \n \n \n \nT=TypeVar('T')\nKT=TypeVar('KT')\nVT=TypeVar('VT')\nT_co=TypeVar('T_co',covariant=True)\nV_co=TypeVar('V_co',covariant=True)\nVT_co=TypeVar('VT_co',covariant=True)\nT_contra=TypeVar('T_contra',contravariant=True)\n\nCT_co=TypeVar('CT_co',covariant=True,bound=type)\n\n\n\n\nAnyStr=TypeVar('AnyStr',bytes,str)\n\n\n\n_alias=_SpecialGenericAlias\n\nHashable=_alias(collections.abc.Hashable,0)\nAwaitable=_alias(collections.abc.Awaitable,1)\nCoroutine=_alias(collections.abc.Coroutine,3)\nAsyncIterable=_alias(collections.abc.AsyncIterable,1)\nAsyncIterator=_alias(collections.abc.AsyncIterator,1)\nIterable=_alias(collections.abc.Iterable,1)\nIterator=_alias(collections.abc.Iterator,1)\nReversible=_alias(collections.abc.Reversible,1)\nSized=_alias(collections.abc.Sized,0)\nContainer=_alias(collections.abc.Container,1)\nCollection=_alias(collections.abc.Collection,1)\nCallable=_CallableType(collections.abc.Callable,2)\nCallable.__doc__=\\\n\"\"\"Deprecated alias to collections.abc.Callable.\n\n Callable[[int], str] signifies a function that takes a single\n parameter of type int and returns a str.\n\n The subscription syntax must always be used with exactly two\n values: the argument list and the return type.\n The argument list must be a list of types, a ParamSpec,\n Concatenate or ellipsis. The return type must be a single type.\n\n There is no syntax to indicate optional or keyword arguments;\n such function types are rarely used as callback types.\n \"\"\"\nAbstractSet=_alias(collections.abc.Set,1,name='AbstractSet')\nMutableSet=_alias(collections.abc.MutableSet,1)\n\nMapping=_alias(collections.abc.Mapping,2)\nMutableMapping=_alias(collections.abc.MutableMapping,2)\nSequence=_alias(collections.abc.Sequence,1)\nMutableSequence=_alias(collections.abc.MutableSequence,1)\nByteString=_DeprecatedGenericAlias(\ncollections.abc.ByteString,0,removal_version=(3,14)\n)\n\nTuple=_TupleType(tuple,-1,inst=False,name='Tuple')\nTuple.__doc__=\\\n\"\"\"Deprecated alias to builtins.tuple.\n\n Tuple[X, Y] is the cross-product type of X and Y.\n\n Example: Tuple[T1, T2] is a tuple of two elements corresponding\n to type variables T1 and T2. Tuple[int, float, str] is a tuple\n of an int, a float and a string.\n\n To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].\n \"\"\"\nList=_alias(list,1,inst=False,name='List')\nDeque=_alias(collections.deque,1,name='Deque')\nSet=_alias(set,1,inst=False,name='Set')\nFrozenSet=_alias(frozenset,1,inst=False,name='FrozenSet')\nMappingView=_alias(collections.abc.MappingView,1)\nKeysView=_alias(collections.abc.KeysView,1)\nItemsView=_alias(collections.abc.ItemsView,2)\nValuesView=_alias(collections.abc.ValuesView,1)\nDict=_alias(dict,2,inst=False,name='Dict')\nDefaultDict=_alias(collections.defaultdict,2,name='DefaultDict')\nOrderedDict=_alias(collections.OrderedDict,2)\nCounter=_alias(collections.Counter,1)\nChainMap=_alias(collections.ChainMap,2)\nGenerator=_alias(collections.abc.Generator,3,defaults=(types.NoneType,types.NoneType))\nAsyncGenerator=_alias(collections.abc.AsyncGenerator,2,defaults=(types.NoneType,))\nType=_alias(type,1,inst=False,name='Type')\nType.__doc__=\\\n\"\"\"Deprecated alias to builtins.type.\n\n builtins.type or typing.Type can be used to annotate class objects.\n For example, suppose we have the following classes::\n\n class User: ... # Abstract base for User classes\n class BasicUser(User): ...\n class ProUser(User): ...\n class TeamUser(User): ...\n\n And a function that takes a class argument that's a subclass of\n User and returns an instance of the corresponding class::\n\n def new_user[U](user_class: Type[U]) -> U:\n user = user_class()\n # (Here we could write the user object to a database)\n return user\n\n joe = new_user(BasicUser)\n\n At this point the type checker knows that joe has type BasicUser.\n \"\"\"\n\n\n@runtime_checkable\nclass SupportsInt(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __int__(self)->int:\n pass\n \n \n@runtime_checkable\nclass SupportsFloat(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __float__(self)->float:\n pass\n \n \n@runtime_checkable\nclass SupportsComplex(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __complex__(self)->complex:\n pass\n \n \n@runtime_checkable\nclass SupportsBytes(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __bytes__(self)->bytes:\n pass\n \n \n@runtime_checkable\nclass SupportsIndex(Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __index__(self)->int:\n pass\n \n \n@runtime_checkable\nclass SupportsAbs[T](Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __abs__(self)->T:\n pass\n \n \n@runtime_checkable\nclass SupportsRound[T](Protocol):\n ''\n \n __slots__=()\n \n @abstractmethod\n def __round__(self,ndigits:int=0)->T:\n pass\n \n \ndef _make_nmtuple(name,types,module,defaults=()):\n fields=[n for n,t in types]\n types={n:_type_check(t,f\"field {n} annotation must be a type\")\n for n,t in types}\n nm_tpl=collections.namedtuple(name,fields,\n defaults=defaults,module=module)\n nm_tpl.__annotations__=nm_tpl.__new__.__annotations__=types\n return nm_tpl\n \n \n \n_prohibited=frozenset({'__new__','__init__','__slots__','__getnewargs__',\n'_fields','_field_defaults',\n'_make','_replace','_asdict','_source'})\n\n_special=frozenset({'__module__','__name__','__annotations__'})\n\n\nclass NamedTupleMeta(type):\n def __new__(cls,typename,bases,ns):\n assert _NamedTuple in bases\n for base in bases:\n if base is not _NamedTuple and base is not Generic:\n raise TypeError(\n 'can only inherit from a NamedTuple type and Generic')\n bases=tuple(tuple if base is _NamedTuple else base for base in bases)\n types=ns.get('__annotations__',{})\n default_names=[]\n for field_name in types:\n if field_name in ns:\n default_names.append(field_name)\n elif default_names:\n raise TypeError(f\"Non-default namedtuple field {field_name} \"\n f\"cannot follow default field\"\n f\"{'s'if len(default_names)>1 else ''} \"\n f\"{', '.join(default_names)}\")\n nm_tpl=_make_nmtuple(typename,types.items(),\n defaults=[ns[n]for n in default_names],\n module=ns['__module__'])\n nm_tpl.__bases__=bases\n if Generic in bases:\n class_getitem=_generic_class_getitem\n nm_tpl.__class_getitem__=classmethod(class_getitem)\n \n for key,val in ns.items():\n if key in _prohibited:\n raise AttributeError(\"Cannot overwrite NamedTuple attribute \"+key)\n elif key not in _special:\n if key not in nm_tpl._fields:\n setattr(nm_tpl,key,val)\n try:\n set_name=type(val).__set_name__\n except AttributeError:\n pass\n else:\n try:\n set_name(val,nm_tpl,key)\n except BaseException as e:\n e.add_note(\n f\"Error calling __set_name__ on {type(val).__name__ !r} \"\n f\"instance {key !r} in {typename !r}\"\n )\n raise\n \n if Generic in bases:\n nm_tpl.__init_subclass__()\n return nm_tpl\n \n \ndef NamedTuple(typename,fields=_sentinel,/,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if fields is _sentinel:\n if kwargs:\n deprecated_thing=\"Creating NamedTuple classes using keyword arguments\"\n deprecation_msg=(\n \"{name} is deprecated and will be disallowed in Python {remove}. \"\n \"Use the class-based or functional syntax instead.\"\n )\n else:\n deprecated_thing=\"Failing to pass a value for the 'fields' parameter\"\n example=f\"`{typename} = NamedTuple({typename !r}, [])`\"\n deprecation_msg=(\n \"{name} is deprecated and will be disallowed in Python {remove}. \"\n \"To create a NamedTuple class with 0 fields \"\n \"using the functional syntax, \"\n \"pass an empty list, e.g. \"\n )+example+\".\"\n elif fields is None:\n if kwargs:\n raise TypeError(\n \"Cannot pass `None` as the 'fields' parameter \"\n \"and also specify fields using keyword arguments\"\n )\n else:\n deprecated_thing=\"Passing `None` as the 'fields' parameter\"\n example=f\"`{typename} = NamedTuple({typename !r}, [])`\"\n deprecation_msg=(\n \"{name} is deprecated and will be disallowed in Python {remove}. \"\n \"To create a NamedTuple class with 0 fields \"\n \"using the functional syntax, \"\n \"pass an empty list, e.g. \"\n )+example+\".\"\n elif kwargs:\n raise TypeError(\"Either list of fields or keywords\"\n \" can be provided to NamedTuple, not both\")\n if fields is _sentinel or fields is None:\n import warnings\n warnings._deprecated(deprecated_thing,message=deprecation_msg,remove=(3,15))\n fields=kwargs.items()\n nt=_make_nmtuple(typename,fields,module=_caller())\n nt.__orig_bases__=(NamedTuple,)\n return nt\n \n_NamedTuple=type.__new__(NamedTupleMeta,'NamedTuple',(),{})\n\ndef _namedtuple_mro_entries(bases):\n assert NamedTuple in bases\n return(_NamedTuple,)\n \nNamedTuple.__mro_entries__=_namedtuple_mro_entries\n\n\ndef _get_typeddict_qualifiers(annotation_type):\n while True:\n annotation_origin=get_origin(annotation_type)\n if annotation_origin is Annotated:\n annotation_args=get_args(annotation_type)\n if annotation_args:\n annotation_type=annotation_args[0]\n else:\n break\n elif annotation_origin is Required:\n yield Required\n (annotation_type,)=get_args(annotation_type)\n elif annotation_origin is NotRequired:\n yield NotRequired\n (annotation_type,)=get_args(annotation_type)\n elif annotation_origin is ReadOnly:\n yield ReadOnly\n (annotation_type,)=get_args(annotation_type)\n else:\n break\n \n \nclass _TypedDictMeta(type):\n def __new__(cls,name,bases,ns,total=True):\n ''\n\n\n\n\n\n \n for base in bases:\n if type(base)is not _TypedDictMeta and base is not Generic:\n raise TypeError('cannot inherit from both a TypedDict type '\n 'and a non-TypedDict base class')\n \n if any(issubclass(b,Generic)for b in bases):\n generic_base=(Generic,)\n else:\n generic_base=()\n \n tp_dict=type.__new__(_TypedDictMeta,name,(*generic_base,dict),ns)\n \n if not hasattr(tp_dict,'__orig_bases__'):\n tp_dict.__orig_bases__=bases\n \n annotations={}\n own_annotations=ns.get('__annotations__',{})\n msg=\"TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type\"\n own_annotations={\n n:_type_check(tp,msg,module=tp_dict.__module__)\n for n,tp in own_annotations.items()\n }\n required_keys=set()\n optional_keys=set()\n readonly_keys=set()\n mutable_keys=set()\n \n for base in bases:\n annotations.update(base.__dict__.get('__annotations__',{}))\n \n base_required=base.__dict__.get('__required_keys__',set())\n required_keys |=base_required\n optional_keys -=base_required\n \n base_optional=base.__dict__.get('__optional_keys__',set())\n required_keys -=base_optional\n optional_keys |=base_optional\n \n readonly_keys.update(base.__dict__.get('__readonly_keys__',()))\n mutable_keys.update(base.__dict__.get('__mutable_keys__',()))\n \n annotations.update(own_annotations)\n for annotation_key,annotation_type in own_annotations.items():\n qualifiers=set(_get_typeddict_qualifiers(annotation_type))\n if Required in qualifiers:\n is_required=True\n elif NotRequired in qualifiers:\n is_required=False\n else:\n is_required=total\n \n if is_required:\n required_keys.add(annotation_key)\n optional_keys.discard(annotation_key)\n else:\n optional_keys.add(annotation_key)\n required_keys.discard(annotation_key)\n \n if ReadOnly in qualifiers:\n if annotation_key in mutable_keys:\n raise TypeError(\n f\"Cannot override mutable key {annotation_key !r}\"\n \" with read-only key\"\n )\n readonly_keys.add(annotation_key)\n else:\n mutable_keys.add(annotation_key)\n readonly_keys.discard(annotation_key)\n \n assert required_keys.isdisjoint(optional_keys),(\n f\"Required keys overlap with optional keys in {name}:\"\n f\" {required_keys=}, {optional_keys=}\"\n )\n tp_dict.__annotations__=annotations\n tp_dict.__required_keys__=frozenset(required_keys)\n tp_dict.__optional_keys__=frozenset(optional_keys)\n tp_dict.__readonly_keys__=frozenset(readonly_keys)\n tp_dict.__mutable_keys__=frozenset(mutable_keys)\n tp_dict.__total__=total\n return tp_dict\n \n __call__=dict\n \n def __subclasscheck__(cls,other):\n \n raise TypeError('TypedDict does not support instance and class checks')\n \n __instancecheck__=__subclasscheck__\n \n \ndef TypedDict(typename,fields=_sentinel,/,*,total=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if fields is _sentinel or fields is None:\n import warnings\n \n if fields is _sentinel:\n deprecated_thing=\"Failing to pass a value for the 'fields' parameter\"\n else:\n deprecated_thing=\"Passing `None` as the 'fields' parameter\"\n \n example=f\"`{typename} = TypedDict({typename !r}, {{{{}}}})`\"\n deprecation_msg=(\n \"{name} is deprecated and will be disallowed in Python {remove}. \"\n \"To create a TypedDict class with 0 fields \"\n \"using the functional syntax, \"\n \"pass an empty dictionary, e.g. \"\n )+example+\".\"\n warnings._deprecated(deprecated_thing,message=deprecation_msg,remove=(3,15))\n fields={}\n \n ns={'__annotations__':dict(fields)}\n module=_caller()\n if module is not None:\n \n ns['__module__']=module\n \n td=_TypedDictMeta(typename,(),ns,total=total)\n td.__orig_bases__=(TypedDict,)\n return td\n \n_TypedDict=type.__new__(_TypedDictMeta,'TypedDict',(),{})\nTypedDict.__mro_entries__=lambda bases:(_TypedDict,)\n\n\n@_SpecialForm\ndef Required(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self._name} accepts only a single type.')\n return _GenericAlias(self,(item,))\n \n \n@_SpecialForm\ndef NotRequired(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self._name} accepts only a single type.')\n return _GenericAlias(self,(item,))\n \n \n@_SpecialForm\ndef ReadOnly(self,parameters):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n item=_type_check(parameters,f'{self._name} accepts only a single type.')\n return _GenericAlias(self,(item,))\n \n \nclass NewType:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __call__=_idfunc\n \n def __init__(self,name,tp):\n self.__qualname__=name\n if '.'in name:\n name=name.rpartition('.')[-1]\n self.__name__=name\n self.__supertype__=tp\n def_mod=_caller()\n if def_mod !='typing':\n self.__module__=def_mod\n \n def __mro_entries__(self,bases):\n \n \n superclass_name=self.__name__\n \n class Dummy:\n def __init_subclass__(cls):\n subclass_name=cls.__name__\n raise TypeError(\n f\"Cannot subclass an instance of NewType. Perhaps you were looking for: \"\n f\"`{subclass_name} = NewType({subclass_name !r}, {superclass_name})`\"\n )\n \n return(Dummy,)\n \n def __repr__(self):\n return f'{self.__module__}.{self.__qualname__}'\n \n def __reduce__(self):\n return self.__qualname__\n \n def __or__(self,other):\n return Union[self,other]\n \n def __ror__(self,other):\n return Union[other,self]\n \n \n \nText=str\n\n\n\nTYPE_CHECKING=False\n\n\nclass IO(Generic[AnyStr]):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n @property\n @abstractmethod\n def mode(self)->str:\n pass\n \n @property\n @abstractmethod\n def name(self)->str:\n pass\n \n @abstractmethod\n def close(self)->None:\n pass\n \n @property\n @abstractmethod\n def closed(self)->bool:\n pass\n \n @abstractmethod\n def fileno(self)->int:\n pass\n \n @abstractmethod\n def flush(self)->None:\n pass\n \n @abstractmethod\n def isatty(self)->bool:\n pass\n \n @abstractmethod\n def read(self,n:int=-1)->AnyStr:\n pass\n \n @abstractmethod\n def readable(self)->bool:\n pass\n \n @abstractmethod\n def readline(self,limit:int=-1)->AnyStr:\n pass\n \n @abstractmethod\n def readlines(self,hint:int=-1)->List[AnyStr]:\n pass\n \n @abstractmethod\n def seek(self,offset:int,whence:int=0)->int:\n pass\n \n @abstractmethod\n def seekable(self)->bool:\n pass\n \n @abstractmethod\n def tell(self)->int:\n pass\n \n @abstractmethod\n def truncate(self,size:int=None)->int:\n pass\n \n @abstractmethod\n def writable(self)->bool:\n pass\n \n @abstractmethod\n def write(self,s:AnyStr)->int:\n pass\n \n @abstractmethod\n def writelines(self,lines:List[AnyStr])->None:\n pass\n \n @abstractmethod\n def __enter__(self)->'IO[AnyStr]':\n pass\n \n @abstractmethod\n def __exit__(self,type,value,traceback)->None:\n pass\n \n \nclass BinaryIO(IO[bytes]):\n ''\n \n __slots__=()\n \n @abstractmethod\n def write(self,s:Union[bytes,bytearray])->int:\n pass\n \n @abstractmethod\n def __enter__(self)->'BinaryIO':\n pass\n \n \nclass TextIO(IO[str]):\n ''\n \n __slots__=()\n \n @property\n @abstractmethod\n def buffer(self)->BinaryIO:\n pass\n \n @property\n @abstractmethod\n def encoding(self)->str:\n pass\n \n @property\n @abstractmethod\n def errors(self)->Optional[str]:\n pass\n \n @property\n @abstractmethod\n def line_buffering(self)->bool:\n pass\n \n @property\n @abstractmethod\n def newlines(self)->Any:\n pass\n \n @abstractmethod\n def __enter__(self)->'TextIO':\n pass\n \n \ndef reveal_type[T](obj:T,/)->T:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n print(f\"Runtime type is {type(obj).__name__ !r}\",file=sys.stderr)\n return obj\n \n \nclass _IdentityCallable(Protocol):\n def __call__[T](self,arg:T,/)->T:\n ...\n \n \ndef dataclass_transform(\n*,\neq_default:bool=True,\norder_default:bool=False,\nkw_only_default:bool=False,\nfrozen_default:bool=False,\nfield_specifiers:tuple[type[Any]|Callable[...,Any],...]=(),\n**kwargs:Any,\n)->_IdentityCallable:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def decorator(cls_or_fn):\n cls_or_fn.__dataclass_transform__={\n \"eq_default\":eq_default,\n \"order_default\":order_default,\n \"kw_only_default\":kw_only_default,\n \"frozen_default\":frozen_default,\n \"field_specifiers\":field_specifiers,\n \"kwargs\":kwargs,\n }\n return cls_or_fn\n return decorator\n \n \ntype _Func=Callable[...,Any]\n\n\ndef override[F:_Func](method:F,/)->F:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try:\n method.__override__=True\n except(AttributeError,TypeError):\n \n \n \n pass\n return method\n \n \ndef is_protocol(tp:type,/)->bool:\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n return(\n isinstance(tp,type)\n and getattr(tp,'_is_protocol',False)\n and tp !=Protocol\n )\n \n \ndef get_protocol_members(tp:type,/)->frozenset[str]:\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if not is_protocol(tp):\n raise TypeError(f'{tp !r} is not a Protocol')\n return frozenset(tp.__protocol_attrs__)\n \n \ndef __getattr__(attr):\n ''\n\n\n\n \n if attr in{\"Pattern\",\"Match\"}:\n import re\n obj=_alias(getattr(re,attr),1)\n elif attr in{\"ContextManager\",\"AsyncContextManager\"}:\n import contextlib\n obj=_alias(getattr(contextlib,f\"Abstract{attr}\"),2,name=attr,defaults=(bool |None,))\n elif attr ==\"_collect_parameters\":\n import warnings\n \n depr_message=(\n \"The private _collect_parameters function is deprecated and will be\"\n \" removed in a future version of Python. Any use of private functions\"\n \" is discouraged and may break in the future.\"\n )\n warnings.warn(depr_message,category=DeprecationWarning,stacklevel=2)\n obj=_collect_type_parameters\n else:\n raise AttributeError(f\"module {__name__ !r} has no attribute {attr !r}\")\n globals()[attr]=obj\n return obj\n", ["_typing", "abc", "collections", "collections.abc", "contextlib", "copyreg", "functools", "inspect", "operator", "re", "sys", "types", "warnings"]], "uuid": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport os\nimport sys\n\nfrom enum import Enum,_simple_enum\n\n\n__author__='Ka-Ping Yee '\n\n\nif sys.platform in{'win32','darwin','emscripten','wasi'}:\n _AIX=_LINUX=False\nelif sys.platform =='linux':\n _LINUX=True\n _AIX=False\nelse:\n import platform\n _platform_system=platform.system()\n _AIX=_platform_system =='AIX'\n _LINUX=_platform_system in('Linux','Android')\n \n_MAC_DELIM=b':'\n_MAC_OMITS_LEADING_ZEROES=False\nif _AIX:\n _MAC_DELIM=b'.'\n _MAC_OMITS_LEADING_ZEROES=True\n \nRESERVED_NCS,RFC_4122,RESERVED_MICROSOFT,RESERVED_FUTURE=[\n'reserved for NCS compatibility','specified in RFC 4122',\n'reserved for Microsoft compatibility','reserved for future definition']\n\nint_=int\nbytes_=bytes\n\n\n@_simple_enum(Enum)\nclass SafeUUID:\n safe=0\n unsafe=-1\n unknown=None\n \n \nclass UUID:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('int','is_safe','__weakref__')\n \n def __init__(self,hex=None,bytes=None,bytes_le=None,fields=None,\n int=None,version=None,\n *,is_safe=SafeUUID.unknown):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if[hex,bytes,bytes_le,fields,int].count(None)!=4:\n raise TypeError('one of the hex, bytes, bytes_le, fields, '\n 'or int arguments must be given')\n if hex is not None:\n hex=hex.replace('urn:','').replace('uuid:','')\n hex=hex.strip('{}').replace('-','')\n if len(hex)!=32:\n raise ValueError('badly formed hexadecimal UUID string')\n int=int_(hex,16)\n if bytes_le is not None:\n if len(bytes_le)!=16:\n raise ValueError('bytes_le is not a 16-char string')\n bytes=(bytes_le[4 -1::-1]+bytes_le[6 -1:4 -1:-1]+\n bytes_le[8 -1:6 -1:-1]+bytes_le[8:])\n if bytes is not None:\n if len(bytes)!=16:\n raise ValueError('bytes is not a 16-char string')\n assert isinstance(bytes,bytes_),repr(bytes)\n int=int_.from_bytes(bytes)\n if fields is not None:\n if len(fields)!=6:\n raise ValueError('fields is not a 6-tuple')\n (time_low,time_mid,time_hi_version,\n clock_seq_hi_variant,clock_seq_low,node)=fields\n if not 0 <=time_low <1 <<32:\n raise ValueError('field 1 out of range (need a 32-bit value)')\n if not 0 <=time_mid <1 <<16:\n raise ValueError('field 2 out of range (need a 16-bit value)')\n if not 0 <=time_hi_version <1 <<16:\n raise ValueError('field 3 out of range (need a 16-bit value)')\n if not 0 <=clock_seq_hi_variant <1 <<8:\n raise ValueError('field 4 out of range (need an 8-bit value)')\n if not 0 <=clock_seq_low <1 <<8:\n raise ValueError('field 5 out of range (need an 8-bit value)')\n if not 0 <=node <1 <<48:\n raise ValueError('field 6 out of range (need a 48-bit value)')\n clock_seq=(clock_seq_hi_variant <<8)|clock_seq_low\n int=((time_low <<96)|(time_mid <<80)|\n (time_hi_version <<64)|(clock_seq <<48)|node)\n if int is not None:\n if not 0 <=int <1 <<128:\n raise ValueError('int is out of range (need a 128-bit value)')\n if version is not None:\n if not 1 <=version <=5:\n raise ValueError('illegal version number')\n \n int &=~(0xc000 <<48)\n int |=0x8000 <<48\n \n int &=~(0xf000 <<64)\n int |=version <<76\n object.__setattr__(self,'int',int)\n object.__setattr__(self,'is_safe',is_safe)\n \n def __getstate__(self):\n d={'int':self.int}\n if self.is_safe !=SafeUUID.unknown:\n \n \n d['is_safe']=self.is_safe.value\n return d\n \n def __setstate__(self,state):\n object.__setattr__(self,'int',state['int'])\n \n object.__setattr__(self,'is_safe',\n SafeUUID(state['is_safe'])\n if 'is_safe'in state else SafeUUID.unknown)\n \n def __eq__(self,other):\n if isinstance(other,UUID):\n return self.int ==other.int\n return NotImplemented\n \n \n \n \n def __lt__(self,other):\n if isinstance(other,UUID):\n return self.int other.int\n return NotImplemented\n \n def __le__(self,other):\n if isinstance(other,UUID):\n return self.int <=other.int\n return NotImplemented\n \n def __ge__(self,other):\n if isinstance(other,UUID):\n return self.int >=other.int\n return NotImplemented\n \n def __hash__(self):\n return hash(self.int)\n \n def __int__(self):\n return self.int\n \n def __repr__(self):\n return '%s(%r)'%(self.__class__.__name__,str(self))\n \n def __setattr__(self,name,value):\n raise TypeError('UUID objects are immutable')\n \n def __str__(self):\n hex='%032x'%self.int\n return '%s-%s-%s-%s-%s'%(\n hex[:8],hex[8:12],hex[12:16],hex[16:20],hex[20:])\n \n @property\n def bytes(self):\n return self.int.to_bytes(16)\n \n @property\n def bytes_le(self):\n bytes=self.bytes\n return(bytes[4 -1::-1]+bytes[6 -1:4 -1:-1]+bytes[8 -1:6 -1:-1]+\n bytes[8:])\n \n @property\n def fields(self):\n return(self.time_low,self.time_mid,self.time_hi_version,\n self.clock_seq_hi_variant,self.clock_seq_low,self.node)\n \n @property\n def time_low(self):\n return self.int >>96\n \n @property\n def time_mid(self):\n return(self.int >>80)&0xffff\n \n @property\n def time_hi_version(self):\n return(self.int >>64)&0xffff\n \n @property\n def clock_seq_hi_variant(self):\n return(self.int >>56)&0xff\n \n @property\n def clock_seq_low(self):\n return(self.int >>48)&0xff\n \n @property\n def time(self):\n return(((self.time_hi_version&0x0fff)<<48)|\n (self.time_mid <<32)|self.time_low)\n \n @property\n def clock_seq(self):\n return(((self.clock_seq_hi_variant&0x3f)<<8)|\n self.clock_seq_low)\n \n @property\n def node(self):\n return self.int&0xffffffffffff\n \n @property\n def hex(self):\n return '%032x'%self.int\n \n @property\n def urn(self):\n return 'urn:uuid:'+str(self)\n \n @property\n def variant(self):\n if not self.int&(0x8000 <<48):\n return RESERVED_NCS\n elif not self.int&(0x4000 <<48):\n return RFC_4122\n elif not self.int&(0x2000 <<48):\n return RESERVED_MICROSOFT\n else:\n return RESERVED_FUTURE\n \n @property\n def version(self):\n \n if self.variant ==RFC_4122:\n return int((self.int >>76)&0xf)\n \n \ndef _get_command_stdout(command,*args):\n import io,os,shutil,subprocess\n \n try:\n path_dirs=os.environ.get('PATH',os.defpath).split(os.pathsep)\n path_dirs.extend(['/sbin','/usr/sbin'])\n executable=shutil.which(command,path=os.pathsep.join(path_dirs))\n if executable is None:\n return None\n \n \n \n env=dict(os.environ)\n env['LC_ALL']='C'\n \n if args !=('',):\n command=(executable,*args)\n else:\n command=(executable,)\n proc=subprocess.Popen(command,\n stdout=subprocess.PIPE,\n stderr=subprocess.DEVNULL,\n env=env)\n if not proc:\n return None\n stdout,stderr=proc.communicate()\n return io.BytesIO(stdout)\n except(OSError,subprocess.SubprocessError):\n return None\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef _is_universal(mac):\n return not(mac&(1 <<41))\n \n \ndef _find_mac_near_keyword(command,args,keywords,get_word_index):\n ''\n\n\n\n\n\n\n \n stdout=_get_command_stdout(command,args)\n if stdout is None:\n return None\n \n first_local_mac=None\n for line in stdout:\n words=line.lower().rstrip().split()\n for i in range(len(words)):\n if words[i]in keywords:\n try:\n word=words[get_word_index(i)]\n mac=int(word.replace(_MAC_DELIM,b''),16)\n except(ValueError,IndexError):\n \n \n \n \n \n pass\n else:\n if _is_universal(mac):\n return mac\n first_local_mac=first_local_mac or mac\n return first_local_mac or None\n \n \ndef _parse_mac(word):\n\n\n\n\n\n\n parts=word.split(_MAC_DELIM)\n if len(parts)!=6:\n return\n if _MAC_OMITS_LEADING_ZEROES:\n \n \n \n \n if not all(1 <=len(part)<=2 for part in parts):\n return\n hexstr=b''.join(part.rjust(2,b'0')for part in parts)\n else:\n if not all(len(part)==2 for part in parts):\n return\n hexstr=b''.join(parts)\n try:\n return int(hexstr,16)\n except ValueError:\n return\n \n \ndef _find_mac_under_heading(command,args,heading):\n ''\n\n\n\n\n \n stdout=_get_command_stdout(command,args)\n if stdout is None:\n return None\n \n keywords=stdout.readline().rstrip().split()\n try:\n column_index=keywords.index(heading)\n except ValueError:\n return None\n \n first_local_mac=None\n for line in stdout:\n words=line.rstrip().split()\n try:\n word=words[column_index]\n except IndexError:\n continue\n \n mac=_parse_mac(word)\n if mac is None:\n continue\n if _is_universal(mac):\n return mac\n if first_local_mac is None:\n first_local_mac=mac\n \n return first_local_mac\n \n \n \n \ndef _ifconfig_getnode():\n ''\n \n keywords=(b'hwaddr',b'ether',b'address:',b'lladdr')\n for args in('','-a','-av'):\n mac=_find_mac_near_keyword('ifconfig',args,keywords,lambda i:i+1)\n if mac:\n return mac\n return None\n \ndef _ip_getnode():\n ''\n \n mac=_find_mac_near_keyword('ip','link',[b'link/ether'],lambda i:i+1)\n if mac:\n return mac\n return None\n \ndef _arp_getnode():\n ''\n import os,socket\n if not hasattr(socket,\"gethostbyname\"):\n return None\n try:\n ip_addr=socket.gethostbyname(socket.gethostname())\n except OSError:\n return None\n \n \n mac=_find_mac_near_keyword('arp','-an',[os.fsencode(ip_addr)],lambda i:-1)\n if mac:\n return mac\n \n \n mac=_find_mac_near_keyword('arp','-an',[os.fsencode(ip_addr)],lambda i:i+1)\n if mac:\n return mac\n \n \n mac=_find_mac_near_keyword('arp','-an',[os.fsencode('(%s)'%ip_addr)],\n lambda i:i+2)\n \n if mac:\n return mac\n return None\n \ndef _lanscan_getnode():\n ''\n \n return _find_mac_near_keyword('lanscan','-ai',[b'lan0'],lambda i:0)\n \ndef _netstat_getnode():\n ''\n \n return _find_mac_under_heading('netstat','-ian',b'Address')\n \n \n \ntry:\n import _uuid\n _generate_time_safe=getattr(_uuid,\"generate_time_safe\",None)\n _UuidCreate=getattr(_uuid,\"UuidCreate\",None)\nexcept ImportError:\n _uuid=None\n _generate_time_safe=None\n _UuidCreate=None\n \n \ndef _unix_getnode():\n ''\n if _generate_time_safe:\n uuid_time,_=_generate_time_safe()\n return UUID(bytes=uuid_time).node\n \ndef _windll_getnode():\n ''\n if _UuidCreate:\n uuid_bytes=_UuidCreate()\n return UUID(bytes_le=uuid_bytes).node\n \ndef _random_getnode():\n ''\n \n \n \n \n \n \n \n \n \n \n import random\n return random.getrandbits(48)|(1 <<40)\n \n \n \n \n \n \n \n \nif _LINUX:\n _OS_GETTERS=[_ip_getnode,_ifconfig_getnode]\nelif sys.platform =='darwin':\n _OS_GETTERS=[_ifconfig_getnode,_arp_getnode,_netstat_getnode]\nelif sys.platform =='win32':\n\n _OS_GETTERS=[]\nelif _AIX:\n _OS_GETTERS=[_netstat_getnode]\nelse:\n _OS_GETTERS=[_ifconfig_getnode,_ip_getnode,_arp_getnode,\n _netstat_getnode,_lanscan_getnode]\nif os.name =='posix':\n _GETTERS=[_unix_getnode]+_OS_GETTERS\nelif os.name =='nt':\n _GETTERS=[_windll_getnode]+_OS_GETTERS\nelse:\n _GETTERS=_OS_GETTERS\n \n_node=None\n\ndef getnode():\n ''\n\n\n\n\n\n \n global _node\n if _node is not None:\n return _node\n \n for getter in _GETTERS+[_random_getnode]:\n try:\n _node=getter()\n except:\n continue\n if(_node is not None)and(0 <=_node <(1 <<48)):\n return _node\n assert False,'_random_getnode() returned invalid value: {}'.format(_node)\n \n \n_last_timestamp=None\n\ndef uuid1(node=None,clock_seq=None):\n ''\n\n\n \n \n \n \n if _generate_time_safe is not None and node is clock_seq is None:\n uuid_time,safely_generated=_generate_time_safe()\n try:\n is_safe=SafeUUID(safely_generated)\n except ValueError:\n is_safe=SafeUUID.unknown\n return UUID(bytes=uuid_time,is_safe=is_safe)\n \n global _last_timestamp\n import time\n nanoseconds=time.time_ns()\n \n \n timestamp=nanoseconds //100+0x01b21dd213814000\n if _last_timestamp is not None and timestamp <=_last_timestamp:\n timestamp=_last_timestamp+1\n _last_timestamp=timestamp\n if clock_seq is None:\n import random\n clock_seq=random.getrandbits(14)\n time_low=timestamp&0xffffffff\n time_mid=(timestamp >>32)&0xffff\n time_hi_version=(timestamp >>48)&0x0fff\n clock_seq_low=clock_seq&0xff\n clock_seq_hi_variant=(clock_seq >>8)&0x3f\n if node is None:\n node=getnode()\n return UUID(fields=(time_low,time_mid,time_hi_version,\n clock_seq_hi_variant,clock_seq_low,node),version=1)\n \ndef uuid3(namespace,name):\n ''\n if isinstance(name,str):\n name=bytes(name,\"utf-8\")\n from hashlib import md5\n digest=md5(\n namespace.bytes+name,\n usedforsecurity=False\n ).digest()\n return UUID(bytes=digest[:16],version=3)\n \ndef uuid4():\n ''\n return UUID(bytes=os.urandom(16),version=4)\n \ndef uuid5(namespace,name):\n ''\n if isinstance(name,str):\n name=bytes(name,\"utf-8\")\n from hashlib import sha1\n hash=sha1(namespace.bytes+name).digest()\n return UUID(bytes=hash[:16],version=5)\n \n \ndef main():\n ''\n uuid_funcs={\n \"uuid1\":uuid1,\n \"uuid3\":uuid3,\n \"uuid4\":uuid4,\n \"uuid5\":uuid5\n }\n uuid_namespace_funcs=(\"uuid3\",\"uuid5\")\n namespaces={\n \"@dns\":NAMESPACE_DNS,\n \"@url\":NAMESPACE_URL,\n \"@oid\":NAMESPACE_OID,\n \"@x500\":NAMESPACE_X500\n }\n \n import argparse\n parser=argparse.ArgumentParser(\n description=\"Generates a uuid using the selected uuid function.\")\n parser.add_argument(\"-u\",\"--uuid\",choices=uuid_funcs.keys(),default=\"uuid4\",\n help=\"The function to use to generate the uuid. \"\n \"By default uuid4 function is used.\")\n parser.add_argument(\"-n\",\"--namespace\",\n help=\"The namespace is a UUID, or '@ns' where 'ns' is a \"\n \"well-known predefined UUID addressed by namespace name. \"\n \"Such as @dns, @url, @oid, and @x500. \"\n \"Only required for uuid3/uuid5 functions.\")\n parser.add_argument(\"-N\",\"--name\",\n help=\"The name used as part of generating the uuid. \"\n \"Only required for uuid3/uuid5 functions.\")\n \n args=parser.parse_args()\n uuid_func=uuid_funcs[args.uuid]\n namespace=args.namespace\n name=args.name\n \n if args.uuid in uuid_namespace_funcs:\n if not namespace or not name:\n parser.error(\n \"Incorrect number of arguments. \"\n f\"{args.uuid} requires a namespace and a name. \"\n \"Run 'python -m uuid -h' for more information.\"\n )\n namespace=namespaces[namespace]if namespace in namespaces else UUID(namespace)\n print(uuid_func(namespace,name))\n else:\n print(uuid_func())\n \n \n \n \nNAMESPACE_DNS=UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')\nNAMESPACE_URL=UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')\nNAMESPACE_OID=UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')\nNAMESPACE_X500=UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')\n\nif __name__ ==\"__main__\":\n main()\n", ["_uuid", "argparse", "enum", "hashlib", "io", "os", "platform", "random", "shutil", "socket", "subprocess", "sys", "time"]], "VFS_import": [".py", "import os\nimport sys\nfrom browser import doc\n\n\n\n\n\n\nVFS=dict(JSObject(__BRYTHON__.py_VFS))\nclass VFSModuleFinder:\n def __init__(self,path_entry):\n print(\"in VFSModuleFinder\")\n if path_entry.startswith('/libs')or path_entry.startswith('/Lib'):\n self.path_entry=path_entry\n else:\n raise ImportError()\n \n def __str__(self):\n return '<%s for \"%s\">'%(self.__class__.__name__,self.path_entry)\n \n def find_module(self,fullname,path=None):\n path=path or self.path_entry\n \n for _ext in['js','pyj','py']:\n _filepath=os.path.join(self.path_entry,'%s.%s'%(fullname,_ext))\n if _filepath in VFS:\n print(\"module found at %s:%s\"%(_filepath,fullname))\n return VFSModuleLoader(_filepath,fullname)\n \n print('module %s not found'%fullname)\n raise ImportError()\n return None\n \nclass VFSModuleLoader:\n ''\n \n def __init__(self,filepath,name):\n self._filepath=filepath\n self._name=name\n \n def get_source(self):\n if self._filepath in VFS:\n return JSObject(readFromVFS(self._filepath))\n \n raise ImportError('could not find source for %s'%fullname)\n \n def is_package(self):\n return '.'in self._name\n \n def load_module(self):\n if self._name in sys.modules:\n \n mod=sys.modules[self._name]\n return mod\n \n _src=self.get_source()\n if self._filepath.endswith('.js'):\n mod=JSObject(import_js_module(_src,self._filepath,self._name))\n elif self._filepath.endswith('.py'):\n mod=JSObject(import_py_module(_src,self._filepath,self._name))\n elif self._filepath.endswith('.pyj'):\n mod=JSObject(import_pyj_module(_src,self._filepath,self._name))\n else:\n raise ImportError('Invalid Module: %s'%self._filepath)\n \n \n mod.__file__=self._filepath\n mod.__name__=self._name\n mod.__path__=os.path.abspath(self._filepath)\n mod.__loader__=self\n mod.__package__='.'.join(self._name.split('.')[:-1])\n \n if self.is_package():\n print('adding path for package')\n \n \n mod.__path__=[self.path_entry]\n else:\n print('imported as regular module')\n \n print('creating a new module object for \"%s\"'%self._name)\n sys.modules.setdefault(self._name,mod)\n JSObject(__BRYTHON__.imported)[self._name]=mod\n \n return mod\n \nJSObject(__BRYTHON__.path_hooks.insert(0,VFSModuleFinder))\n", ["browser", "os", "sys"]], "warnings": [".py", "''\n\nimport sys\n\n\n__all__=[\"warn\",\"warn_explicit\",\"showwarning\",\n\"formatwarning\",\"filterwarnings\",\"simplefilter\",\n\"resetwarnings\",\"catch_warnings\",\"deprecated\"]\n\ndef showwarning(message,category,filename,lineno,file=None,line=None):\n ''\n msg=WarningMessage(message,category,filename,lineno,file,line)\n _showwarnmsg_impl(msg)\n \ndef formatwarning(message,category,filename,lineno,line=None):\n ''\n msg=WarningMessage(message,category,filename,lineno,None,line)\n return _formatwarnmsg_impl(msg)\n \ndef _showwarnmsg_impl(msg):\n file=msg.file\n if file is None:\n file=sys.stderr\n if file is None:\n \n \n return\n text=_formatwarnmsg(msg)\n try:\n file.write(text)\n except OSError:\n \n pass\n \ndef _formatwarnmsg_impl(msg):\n category=msg.category.__name__\n s=f\"{msg.filename}:{msg.lineno}: {category}: {msg.message}\\n\"\n \n if msg.line is None:\n try:\n import linecache\n line=linecache.getline(msg.filename,msg.lineno)\n except Exception:\n \n \n line=None\n linecache=None\n else:\n line=msg.line\n if line:\n line=line.strip()\n s +=\" %s\\n\"%line\n \n if msg.source is not None:\n try:\n import tracemalloc\n \n \n except Exception:\n \n suggest_tracemalloc=False\n tb=None\n else:\n try:\n suggest_tracemalloc=not tracemalloc.is_tracing()\n tb=tracemalloc.get_object_traceback(msg.source)\n except Exception:\n \n \n suggest_tracemalloc=False\n tb=None\n \n if tb is not None:\n s +='Object allocated at (most recent call last):\\n'\n for frame in tb:\n s +=(' File \"%s\", lineno %s\\n'\n %(frame.filename,frame.lineno))\n \n try:\n if linecache is not None:\n line=linecache.getline(frame.filename,frame.lineno)\n else:\n line=None\n except Exception:\n line=None\n if line:\n line=line.strip()\n s +=' %s\\n'%line\n elif suggest_tracemalloc:\n s +=(f'{category}: Enable tracemalloc to get the object '\n f'allocation traceback\\n')\n return s\n \n \n_showwarning_orig=showwarning\n\ndef _showwarnmsg(msg):\n ''\n try:\n sw=showwarning\n except NameError:\n pass\n else:\n if sw is not _showwarning_orig:\n \n if not callable(sw):\n raise TypeError(\"warnings.showwarning() must be set to a \"\n \"function or method\")\n \n sw(msg.message,msg.category,msg.filename,msg.lineno,\n msg.file,msg.line)\n return\n _showwarnmsg_impl(msg)\n \n \n_formatwarning_orig=formatwarning\n\ndef _formatwarnmsg(msg):\n ''\n try:\n fw=formatwarning\n except NameError:\n pass\n else:\n if fw is not _formatwarning_orig:\n \n return fw(msg.message,msg.category,\n msg.filename,msg.lineno,msg.line)\n return _formatwarnmsg_impl(msg)\n \ndef filterwarnings(action,message=\"\",category=Warning,module=\"\",lineno=0,\nappend=False):\n ''\n\n\n\n\n\n\n\n\n \n if action not in{\"error\",\"ignore\",\"always\",\"default\",\"module\",\"once\"}:\n raise ValueError(f\"invalid action: {action !r}\")\n if not isinstance(message,str):\n raise TypeError(\"message must be a string\")\n if not isinstance(category,type)or not issubclass(category,Warning):\n raise TypeError(\"category must be a Warning subclass\")\n if not isinstance(module,str):\n raise TypeError(\"module must be a string\")\n if not isinstance(lineno,int):\n raise TypeError(\"lineno must be an int\")\n if lineno <0:\n raise ValueError(\"lineno must be an int >= 0\")\n \n if message or module:\n import re\n \n if message:\n message=re.compile(message,re.I)\n else:\n message=None\n if module:\n module=re.compile(module)\n else:\n module=None\n \n _add_filter(action,message,category,module,lineno,append=append)\n \ndef simplefilter(action,category=Warning,lineno=0,append=False):\n ''\n\n\n\n\n\n\n\n \n if action not in{\"error\",\"ignore\",\"always\",\"default\",\"module\",\"once\"}:\n raise ValueError(f\"invalid action: {action !r}\")\n if not isinstance(lineno,int):\n raise TypeError(\"lineno must be an int\")\n if lineno <0:\n raise ValueError(\"lineno must be an int >= 0\")\n _add_filter(action,None,category,None,lineno,append=append)\n \ndef _add_filter(*item,append):\n\n\n if not append:\n try:\n filters.remove(item)\n except ValueError:\n pass\n filters.insert(0,item)\n else:\n if item not in filters:\n filters.append(item)\n _filters_mutated()\n \ndef resetwarnings():\n ''\n filters[:]=[]\n _filters_mutated()\n \nclass _OptionError(Exception):\n ''\n pass\n \n \ndef _processoptions(args):\n for arg in args:\n try:\n _setoption(arg)\n except _OptionError as msg:\n print(\"Invalid -W option ignored:\",msg,file=sys.stderr)\n \n \ndef _setoption(arg):\n parts=arg.split(':')\n if len(parts)>5:\n raise _OptionError(\"too many fields (max 5): %r\"%(arg,))\n while len(parts)<5:\n parts.append('')\n action,message,category,module,lineno=[s.strip()\n for s in parts]\n action=_getaction(action)\n category=_getcategory(category)\n if message or module:\n import re\n if message:\n message=re.escape(message)\n if module:\n module=re.escape(module)+r'\\Z'\n if lineno:\n try:\n lineno=int(lineno)\n if lineno <0:\n raise ValueError\n except(ValueError,OverflowError):\n raise _OptionError(\"invalid lineno %r\"%(lineno,))from None\n else:\n lineno=0\n filterwarnings(action,message,category,module,lineno)\n \n \ndef _getaction(action):\n if not action:\n return \"default\"\n if action ==\"all\":return \"always\"\n for a in('default','always','ignore','module','once','error'):\n if a.startswith(action):\n return a\n raise _OptionError(\"invalid action: %r\"%(action,))\n \n \ndef _getcategory(category):\n if not category:\n return Warning\n if '.'not in category:\n import builtins as m\n klass=category\n else:\n module,_,klass=category.rpartition('.')\n try:\n m=__import__(module,None,None,[klass])\n except ImportError:\n raise _OptionError(\"invalid module name: %r\"%(module,))from None\n try:\n cat=getattr(m,klass)\n except AttributeError:\n raise _OptionError(\"unknown warning category: %r\"%(category,))from None\n if not issubclass(cat,Warning):\n raise _OptionError(\"invalid warning category: %r\"%(category,))\n return cat\n \n \ndef _is_internal_filename(filename):\n return 'importlib'in filename and '_bootstrap'in filename\n \n \ndef _is_filename_to_skip(filename,skip_file_prefixes):\n return any(filename.startswith(prefix)for prefix in skip_file_prefixes)\n \n \ndef _is_internal_frame(frame):\n ''\n return _is_internal_filename(frame.f_code.co_filename)\n \n \ndef _next_external_frame(frame,skip_file_prefixes):\n ''\n frame=frame.f_back\n while frame is not None and(\n _is_internal_filename(filename :=frame.f_code.co_filename)or\n _is_filename_to_skip(filename,skip_file_prefixes)):\n frame=frame.f_back\n return frame\n \n \n \ndef warn(message,category=None,stacklevel=1,source=None,\n*,skip_file_prefixes=()):\n ''\n \n if isinstance(message,Warning):\n category=message.__class__\n \n if category is None:\n category=UserWarning\n if not(isinstance(category,type)and issubclass(category,Warning)):\n raise TypeError(\"category must be a Warning subclass, \"\n \"not '{:s}'\".format(type(category).__name__))\n if not isinstance(skip_file_prefixes,tuple):\n \n raise TypeError('skip_file_prefixes must be a tuple of strs.')\n if skip_file_prefixes:\n stacklevel=max(2,stacklevel)\n \n try:\n if stacklevel <=1 or _is_internal_frame(sys._getframe(1)):\n \n \n frame=sys._getframe(stacklevel)\n else:\n frame=sys._getframe(1)\n \n for x in range(stacklevel -1):\n frame=_next_external_frame(frame,skip_file_prefixes)\n if frame is None:\n raise ValueError\n except ValueError:\n globals=sys.__dict__\n filename=\"\"\n lineno=0\n else:\n globals=frame.f_globals\n filename=frame.f_code.co_filename\n lineno=frame.f_lineno\n if '__name__'in globals:\n module=globals['__name__']\n else:\n module=\"\"\n registry=globals.setdefault(\"__warningregistry__\",{})\n warn_explicit(message,category,filename,lineno,module,registry,\n globals,source)\n \ndef warn_explicit(message,category,filename,lineno,\nmodule=None,registry=None,module_globals=None,\nsource=None):\n lineno=int(lineno)\n if module is None:\n module=filename or \"\"\n if module[-3:].lower()==\".py\":\n module=module[:-3]\n if registry is None:\n registry={}\n if registry.get('version',0)!=_filters_version:\n registry.clear()\n registry['version']=_filters_version\n if isinstance(message,Warning):\n text=str(message)\n category=message.__class__\n else:\n text=message\n message=category(message)\n key=(text,category,lineno)\n \n if registry.get(key):\n return\n \n for item in filters:\n action,msg,cat,mod,ln=item\n if((msg is None or msg.match(text))and\n issubclass(category,cat)and\n (mod is None or mod.match(module))and\n (ln ==0 or lineno ==ln)):\n break\n else:\n action=defaultaction\n \n if action ==\"ignore\":\n return\n \n \n \n import linecache\n linecache.getlines(filename,module_globals)\n \n if action ==\"error\":\n raise message\n \n if action ==\"once\":\n registry[key]=1\n oncekey=(text,category)\n if onceregistry.get(oncekey):\n return\n onceregistry[oncekey]=1\n elif action ==\"always\":\n pass\n elif action ==\"module\":\n registry[key]=1\n altkey=(text,category,0)\n if registry.get(altkey):\n return\n registry[altkey]=1\n elif action ==\"default\":\n registry[key]=1\n else:\n \n raise RuntimeError(\n \"Unrecognized action (%r) in warnings.filters:\\n %s\"%\n (action,item))\n \n msg=WarningMessage(message,category,filename,lineno,source)\n _showwarnmsg(msg)\n \n \nclass WarningMessage(object):\n\n _WARNING_DETAILS=(\"message\",\"category\",\"filename\",\"lineno\",\"file\",\n \"line\",\"source\")\n \n def __init__(self,message,category,filename,lineno,file=None,\n line=None,source=None):\n self.message=message\n self.category=category\n self.filename=filename\n self.lineno=lineno\n self.file=file\n self.line=line\n self.source=source\n self._category_name=category.__name__ if category else None\n \n def __str__(self):\n return(\"{message : %r, category : %r, filename : %r, lineno : %s, \"\n \"line : %r}\"%(self.message,self._category_name,\n self.filename,self.lineno,self.line))\n \n \nclass catch_warnings(object):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,*,record=False,module=None,\n action=None,category=Warning,lineno=0,append=False):\n ''\n\n\n\n\n\n \n self._record=record\n self._module=sys.modules['warnings']if module is None else module\n self._entered=False\n if action is None:\n self._filter=None\n else:\n self._filter=(action,category,lineno,append)\n \n def __repr__(self):\n args=[]\n if self._record:\n args.append(\"record=True\")\n if self._module is not sys.modules['warnings']:\n args.append(\"module=%r\"%self._module)\n name=type(self).__name__\n return \"%s(%s)\"%(name,\", \".join(args))\n \n def __enter__(self):\n if self._entered:\n raise RuntimeError(\"Cannot enter %r twice\"%self)\n self._entered=True\n self._filters=self._module.filters\n self._module.filters=self._filters[:]\n self._module._filters_mutated()\n self._showwarning=self._module.showwarning\n self._showwarnmsg_impl=self._module._showwarnmsg_impl\n if self._filter is not None:\n simplefilter(*self._filter)\n if self._record:\n log=[]\n self._module._showwarnmsg_impl=log.append\n \n \n self._module.showwarning=self._module._showwarning_orig\n return log\n else:\n return None\n \n def __exit__(self,*exc_info):\n if not self._entered:\n raise RuntimeError(\"Cannot exit %r without entering first\"%self)\n self._module.filters=self._filters\n self._module._filters_mutated()\n self._module.showwarning=self._showwarning\n self._module._showwarnmsg_impl=self._showwarnmsg_impl\n \n \nclass deprecated:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(\n self,\n message:str,\n /,\n *,\n category:type[Warning]|None=DeprecationWarning,\n stacklevel:int=1,\n )->None:\n if not isinstance(message,str):\n raise TypeError(\n f\"Expected an object of type str for 'message', not {type(message).__name__ !r}\"\n )\n self.message=message\n self.category=category\n self.stacklevel=stacklevel\n \n def __call__(self,arg,/):\n \n \n msg=self.message\n category=self.category\n stacklevel=self.stacklevel\n if category is None:\n arg.__deprecated__=msg\n return arg\n elif isinstance(arg,type):\n import functools\n from types import MethodType\n \n original_new=arg.__new__\n \n @functools.wraps(original_new)\n def __new__(cls,*args,**kwargs):\n if cls is arg:\n warn(msg,category=category,stacklevel=stacklevel+1)\n if original_new is not object.__new__:\n return original_new(cls,*args,**kwargs)\n \n elif cls.__init__ is object.__init__ and(args or kwargs):\n raise TypeError(f\"{cls.__name__}() takes no arguments\")\n else:\n return original_new(cls)\n \n arg.__new__=staticmethod(__new__)\n \n original_init_subclass=arg.__init_subclass__\n \n \n if isinstance(original_init_subclass,MethodType):\n original_init_subclass=original_init_subclass.__func__\n \n @functools.wraps(original_init_subclass)\n def __init_subclass__(*args,**kwargs):\n warn(msg,category=category,stacklevel=stacklevel+1)\n return original_init_subclass(*args,**kwargs)\n \n arg.__init_subclass__=classmethod(__init_subclass__)\n \n \n else:\n @functools.wraps(original_init_subclass)\n def __init_subclass__(*args,**kwargs):\n warn(msg,category=category,stacklevel=stacklevel+1)\n return original_init_subclass(*args,**kwargs)\n \n arg.__init_subclass__=__init_subclass__\n \n arg.__deprecated__=__new__.__deprecated__=msg\n __init_subclass__.__deprecated__=msg\n return arg\n elif callable(arg):\n import functools\n \n @functools.wraps(arg)\n def wrapper(*args,**kwargs):\n warn(msg,category=category,stacklevel=stacklevel+1)\n return arg(*args,**kwargs)\n \n arg.__deprecated__=wrapper.__deprecated__=msg\n return wrapper\n else:\n raise TypeError(\n \"@deprecated decorator with non-None category must be applied to \"\n f\"a class or callable, not {arg !r}\"\n )\n \n \n_DEPRECATED_MSG=\"{name!r} is deprecated and slated for removal in Python {remove}\"\n\ndef _deprecated(name,message=_DEPRECATED_MSG,*,remove,_version=sys.version_info):\n ''\n\n\n\n\n\n\n\n \n remove_formatted=f\"{remove[0]}.{remove[1]}\"\n if(_version[:2]>remove)or(_version[:2]==remove and _version[3]!=\"alpha\"):\n msg=f\"{name !r} was slated for removal after Python {remove_formatted} alpha\"\n raise RuntimeError(msg)\n else:\n msg=message.format(name=name,remove=remove_formatted)\n warn(msg,DeprecationWarning,stacklevel=3)\n \n \n \ndef _warn_unawaited_coroutine(coro):\n msg_lines=[\n f\"coroutine '{coro.__qualname__}' was never awaited\\n\"\n ]\n if coro.cr_origin is not None:\n import linecache,traceback\n def extract():\n for filename,lineno,funcname in reversed(coro.cr_origin):\n line=linecache.getline(filename,lineno)\n yield(filename,lineno,funcname,line)\n msg_lines.append(\"Coroutine created at (most recent call last)\\n\")\n msg_lines +=traceback.format_list(list(extract()))\n msg=\"\".join(msg_lines).rstrip(\"\\n\")\n \n \n \n \n \n \n warn(msg,category=RuntimeWarning,stacklevel=2,source=coro)\n \n \n \n \n \n \n \n \n \n \ntry:\n from _warnings import(filters,_defaultaction,_onceregistry,\n warn,warn_explicit,_filters_mutated)\n defaultaction=_defaultaction\n onceregistry=_onceregistry\n _warnings_defaults=True\nexcept ImportError:\n filters=[]\n defaultaction=\"default\"\n onceregistry={}\n \n _filters_version=1\n \n def _filters_mutated():\n global _filters_version\n _filters_version +=1\n \n _warnings_defaults=False\n \n \n \n_processoptions(sys.warnoptions)\nif not _warnings_defaults:\n\n if not hasattr(sys,'gettotalrefcount'):\n filterwarnings(\"default\",category=DeprecationWarning,\n module=\"__main__\",append=1)\n simplefilter(\"ignore\",category=DeprecationWarning,append=1)\n simplefilter(\"ignore\",category=PendingDeprecationWarning,append=1)\n simplefilter(\"ignore\",category=ImportWarning,append=1)\n simplefilter(\"ignore\",category=ResourceWarning,append=1)\n \ndel _warnings_defaults\n", ["_warnings", "builtins", "functools", "linecache", "re", "sys", "traceback", "tracemalloc", "types"]], "weakref": [".py", "''\n\n\n\n\n\n\n\n\n\n\nfrom _weakref import(\ngetweakrefcount,\ngetweakrefs,\nref,\nproxy,\nCallableProxyType,\nProxyType,\nReferenceType,\n_remove_dead_weakref)\n\nfrom _weakrefset import WeakSet,_IterationGuard\n\nimport _collections_abc\nimport sys\nimport itertools\n\nProxyTypes=(ProxyType,CallableProxyType)\n\n__all__=[\"ref\",\"proxy\",\"getweakrefcount\",\"getweakrefs\",\n\"WeakKeyDictionary\",\"ReferenceType\",\"ProxyType\",\n\"CallableProxyType\",\"ProxyTypes\",\"WeakValueDictionary\",\n\"WeakSet\",\"WeakMethod\",\"finalize\"]\n\n\n_collections_abc.MutableSet.register(WeakSet)\n\nclass WeakMethod(ref):\n ''\n\n\n \n \n __slots__=\"_func_ref\",\"_meth_type\",\"_alive\",\"__weakref__\"\n \n def __new__(cls,meth,callback=None):\n try:\n obj=meth.__self__\n func=meth.__func__\n except AttributeError:\n raise TypeError(\"argument should be a bound method, not {}\"\n .format(type(meth)))from None\n def _cb(arg):\n \n \n self=self_wr()\n if self._alive:\n self._alive=False\n if callback is not None:\n callback(self)\n self=ref.__new__(cls,obj,_cb)\n self._func_ref=ref(func,_cb)\n self._meth_type=type(meth)\n self._alive=True\n self_wr=ref(self)\n return self\n \n def __call__(self):\n obj=super().__call__()\n func=self._func_ref()\n if obj is None or func is None:\n return None\n return self._meth_type(func,obj)\n \n def __eq__(self,other):\n if isinstance(other,WeakMethod):\n if not self._alive or not other._alive:\n return self is other\n return ref.__eq__(self,other)and self._func_ref ==other._func_ref\n return NotImplemented\n \n def __ne__(self,other):\n if isinstance(other,WeakMethod):\n if not self._alive or not other._alive:\n return self is not other\n return ref.__ne__(self,other)or self._func_ref !=other._func_ref\n return NotImplemented\n \n __hash__=ref.__hash__\n \n \nclass WeakValueDictionary(_collections_abc.MutableMapping):\n ''\n\n\n\n \n \n \n \n \n \n \n def __init__(self,other=(),/,**kw):\n def remove(wr,selfref=ref(self),_atomic_removal=_remove_dead_weakref):\n self=selfref()\n if self is not None:\n if self._iterating:\n self._pending_removals.append(wr.key)\n else:\n \n \n _atomic_removal(self.data,wr.key)\n self._remove=remove\n \n self._pending_removals=[]\n self._iterating=set()\n self.data={}\n self.update(other,**kw)\n \n def _commit_removals(self,_atomic_removal=_remove_dead_weakref):\n pop=self._pending_removals.pop\n d=self.data\n \n \n while True:\n try:\n key=pop()\n except IndexError:\n return\n _atomic_removal(d,key)\n \n def __getitem__(self,key):\n if self._pending_removals:\n self._commit_removals()\n o=self.data[key]()\n if o is None:\n raise KeyError(key)\n else:\n return o\n \n def __delitem__(self,key):\n if self._pending_removals:\n self._commit_removals()\n del self.data[key]\n \n def __len__(self):\n if self._pending_removals:\n self._commit_removals()\n return len(self.data)\n \n def __contains__(self,key):\n if self._pending_removals:\n self._commit_removals()\n try:\n o=self.data[key]()\n except KeyError:\n return False\n return o is not None\n \n def __repr__(self):\n return \"<%s at %#x>\"%(self.__class__.__name__,id(self))\n \n def __setitem__(self,key,value):\n if self._pending_removals:\n self._commit_removals()\n self.data[key]=KeyedRef(value,self._remove,key)\n \n def copy(self):\n if self._pending_removals:\n self._commit_removals()\n new=WeakValueDictionary()\n with _IterationGuard(self):\n for key,wr in self.data.items():\n o=wr()\n if o is not None:\n new[key]=o\n return new\n \n __copy__=copy\n \n def __deepcopy__(self,memo):\n from copy import deepcopy\n if self._pending_removals:\n self._commit_removals()\n new=self.__class__()\n with _IterationGuard(self):\n for key,wr in self.data.items():\n o=wr()\n if o is not None:\n new[deepcopy(key,memo)]=o\n return new\n \n def get(self,key,default=None):\n if self._pending_removals:\n self._commit_removals()\n try:\n wr=self.data[key]\n except KeyError:\n return default\n else:\n o=wr()\n if o is None:\n \n return default\n else:\n return o\n \n def items(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for k,wr in self.data.items():\n v=wr()\n if v is not None:\n yield k,v\n \n def keys(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for k,wr in self.data.items():\n if wr()is not None:\n yield k\n \n __iter__=keys\n \n def itervaluerefs(self):\n ''\n\n\n\n\n\n\n\n \n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n yield from self.data.values()\n \n def values(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for wr in self.data.values():\n obj=wr()\n if obj is not None:\n yield obj\n \n def popitem(self):\n if self._pending_removals:\n self._commit_removals()\n while True:\n key,wr=self.data.popitem()\n o=wr()\n if o is not None:\n return key,o\n \n def pop(self,key,*args):\n if self._pending_removals:\n self._commit_removals()\n try:\n o=self.data.pop(key)()\n except KeyError:\n o=None\n if o is None:\n if args:\n return args[0]\n else:\n raise KeyError(key)\n else:\n return o\n \n def setdefault(self,key,default=None):\n try:\n o=self.data[key]()\n except KeyError:\n o=None\n if o is None:\n if self._pending_removals:\n self._commit_removals()\n self.data[key]=KeyedRef(default,self._remove,key)\n return default\n else:\n return o\n \n def update(self,other=None,/,**kwargs):\n if self._pending_removals:\n self._commit_removals()\n d=self.data\n if other is not None:\n if not hasattr(other,\"items\"):\n other=dict(other)\n for key,o in other.items():\n d[key]=KeyedRef(o,self._remove,key)\n for key,o in kwargs.items():\n d[key]=KeyedRef(o,self._remove,key)\n \n def valuerefs(self):\n ''\n\n\n\n\n\n\n\n \n if self._pending_removals:\n self._commit_removals()\n return list(self.data.values())\n \n def __ior__(self,other):\n self.update(other)\n return self\n \n def __or__(self,other):\n if isinstance(other,_collections_abc.Mapping):\n c=self.copy()\n c.update(other)\n return c\n return NotImplemented\n \n def __ror__(self,other):\n if isinstance(other,_collections_abc.Mapping):\n c=self.__class__()\n c.update(other)\n c.update(self)\n return c\n return NotImplemented\n \n \nclass KeyedRef(ref):\n ''\n\n\n\n\n\n\n \n \n __slots__=\"key\",\n \n def __new__(type,ob,callback,key):\n self=ref.__new__(type,ob,callback)\n self.key=key\n return self\n \n def __init__(self,ob,callback,key):\n super().__init__(ob,callback)\n \n \nclass WeakKeyDictionary(_collections_abc.MutableMapping):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,dict=None):\n self.data={}\n def remove(k,selfref=ref(self)):\n self=selfref()\n if self is not None:\n if self._iterating:\n self._pending_removals.append(k)\n else:\n try:\n del self.data[k]\n except KeyError:\n pass\n self._remove=remove\n \n self._pending_removals=[]\n self._iterating=set()\n self._dirty_len=False\n if dict is not None:\n self.update(dict)\n \n def _commit_removals(self):\n \n \n \n \n pop=self._pending_removals.pop\n d=self.data\n while True:\n try:\n key=pop()\n except IndexError:\n return\n \n try:\n del d[key]\n except KeyError:\n pass\n \n def _scrub_removals(self):\n d=self.data\n self._pending_removals=[k for k in self._pending_removals if k in d]\n self._dirty_len=False\n \n def __delitem__(self,key):\n self._dirty_len=True\n del self.data[ref(key)]\n \n def __getitem__(self,key):\n return self.data[ref(key)]\n \n def __len__(self):\n if self._dirty_len and self._pending_removals:\n \n \n self._scrub_removals()\n return len(self.data)-len(self._pending_removals)\n \n def __repr__(self):\n return \"<%s at %#x>\"%(self.__class__.__name__,id(self))\n \n def __setitem__(self,key,value):\n self.data[ref(key,self._remove)]=value\n \n def copy(self):\n new=WeakKeyDictionary()\n with _IterationGuard(self):\n for key,value in self.data.items():\n o=key()\n if o is not None:\n new[o]=value\n return new\n \n __copy__=copy\n \n def __deepcopy__(self,memo):\n from copy import deepcopy\n new=self.__class__()\n with _IterationGuard(self):\n for key,value in self.data.items():\n o=key()\n if o is not None:\n new[o]=deepcopy(value,memo)\n return new\n \n def get(self,key,default=None):\n return self.data.get(ref(key),default)\n \n def __contains__(self,key):\n try:\n wr=ref(key)\n except TypeError:\n return False\n return wr in self.data\n \n def items(self):\n with _IterationGuard(self):\n for wr,value in self.data.items():\n key=wr()\n if key is not None:\n yield key,value\n \n def keys(self):\n with _IterationGuard(self):\n for wr in self.data:\n obj=wr()\n if obj is not None:\n yield obj\n \n __iter__=keys\n \n def values(self):\n with _IterationGuard(self):\n for wr,value in self.data.items():\n if wr()is not None:\n yield value\n \n def keyrefs(self):\n ''\n\n\n\n\n\n\n\n \n return list(self.data)\n \n def popitem(self):\n self._dirty_len=True\n while True:\n key,value=self.data.popitem()\n o=key()\n if o is not None:\n return o,value\n \n def pop(self,key,*args):\n self._dirty_len=True\n return self.data.pop(ref(key),*args)\n \n def setdefault(self,key,default=None):\n return self.data.setdefault(ref(key,self._remove),default)\n \n def update(self,dict=None,/,**kwargs):\n d=self.data\n if dict is not None:\n if not hasattr(dict,\"items\"):\n dict=type({})(dict)\n for key,value in dict.items():\n d[ref(key,self._remove)]=value\n if len(kwargs):\n self.update(kwargs)\n \n def __ior__(self,other):\n self.update(other)\n return self\n \n def __or__(self,other):\n if isinstance(other,_collections_abc.Mapping):\n c=self.copy()\n c.update(other)\n return c\n return NotImplemented\n \n def __ror__(self,other):\n if isinstance(other,_collections_abc.Mapping):\n c=self.__class__()\n c.update(other)\n c.update(self)\n return c\n return NotImplemented\n \n \nclass finalize:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n __slots__=()\n _registry={}\n _shutdown=False\n _index_iter=itertools.count()\n _dirty=False\n _registered_with_atexit=False\n \n class _Info:\n __slots__=(\"weakref\",\"func\",\"args\",\"kwargs\",\"atexit\",\"index\")\n \n def __init__(self,obj,func,/,*args,**kwargs):\n if not self._registered_with_atexit:\n \n \n import atexit\n atexit.register(self._exitfunc)\n finalize._registered_with_atexit=True\n info=self._Info()\n info.weakref=ref(obj,self)\n info.func=func\n info.args=args\n info.kwargs=kwargs or None\n info.atexit=True\n info.index=next(self._index_iter)\n self._registry[self]=info\n finalize._dirty=True\n \n def __call__(self,_=None):\n ''\n \n info=self._registry.pop(self,None)\n if info and not self._shutdown:\n return info.func(*info.args,**(info.kwargs or{}))\n \n def detach(self):\n ''\n \n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is not None and self._registry.pop(self,None):\n return(obj,info.func,info.args,info.kwargs or{})\n \n def peek(self):\n ''\n \n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is not None:\n return(obj,info.func,info.args,info.kwargs or{})\n \n @property\n def alive(self):\n ''\n return self in self._registry\n \n @property\n def atexit(self):\n ''\n info=self._registry.get(self)\n return bool(info)and info.atexit\n \n @atexit.setter\n def atexit(self,value):\n info=self._registry.get(self)\n if info:\n info.atexit=bool(value)\n \n def __repr__(self):\n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is None:\n return '<%s object at %#x; dead>'%(type(self).__name__,id(self))\n else:\n return '<%s object at %#x; for %r at %#x>'%\\\n (type(self).__name__,id(self),type(obj).__name__,id(obj))\n \n @classmethod\n def _select_for_exit(cls):\n \n L=[(f,i)for(f,i)in cls._registry.items()if i.atexit]\n L.sort(key=lambda item:item[1].index)\n return[f for(f,i)in L]\n \n @classmethod\n def _exitfunc(cls):\n \n \n \n reenable_gc=False\n try:\n if cls._registry:\n import gc\n if gc.isenabled():\n reenable_gc=True\n gc.disable()\n pending=None\n while True:\n if pending is None or finalize._dirty:\n pending=cls._select_for_exit()\n finalize._dirty=False\n if not pending:\n break\n f=pending.pop()\n try:\n \n \n \n \n f()\n except Exception:\n sys.excepthook(*sys.exc_info())\n assert f not in cls._registry\n finally:\n \n finalize._shutdown=True\n if reenable_gc:\n gc.enable()\n", ["_collections_abc", "_weakref", "_weakrefset", "atexit", "copy", "gc", "itertools", "sys"]], "webbrowser": [".py", "\n\nfrom browser import window\n\ndef open(url,new=0,autoraise=True):\n window.open(url)\n \ndef open_new(url):\n return window.open(url,\"_blank\")\n \ndef open_new_tab(url):\n return open(url)\n \n", ["browser"]], "zipfile": [".py", "''\n\n\n\n\nimport binascii\nimport importlib.util\nimport io\nimport itertools\nimport os\nimport posixpath\nimport shutil\nimport stat\nimport struct\nimport sys\nimport threading\nimport time\nimport contextlib\nimport pathlib\n\ntry:\n import zlib\n crc32=zlib.crc32\nexcept ImportError:\n zlib=None\n crc32=binascii.crc32\n \ntry:\n import bz2\nexcept ImportError:\n bz2=None\n \ntry:\n import lzma\nexcept ImportError:\n lzma=None\n \n__all__=[\"BadZipFile\",\"BadZipfile\",\"error\",\n\"ZIP_STORED\",\"ZIP_DEFLATED\",\"ZIP_BZIP2\",\"ZIP_LZMA\",\n\"is_zipfile\",\"ZipInfo\",\"ZipFile\",\"PyZipFile\",\"LargeZipFile\",\n\"Path\"]\n\nclass BadZipFile(Exception):\n pass\n \n \nclass LargeZipFile(Exception):\n ''\n\n\n \n \nerror=BadZipfile=BadZipFile\n\n\nZIP64_LIMIT=(1 <<31)-1\nZIP_FILECOUNT_LIMIT=(1 <<16)-1\nZIP_MAX_COMMENT=(1 <<16)-1\n\n\nZIP_STORED=0\nZIP_DEFLATED=8\nZIP_BZIP2=12\nZIP_LZMA=14\n\n\nDEFAULT_VERSION=20\nZIP64_VERSION=45\nBZIP2_VERSION=46\nLZMA_VERSION=63\n\nMAX_EXTRACT_VERSION=63\n\n\n\n\n\n\n\n\n\nstructEndArchive=b\"<4s4H2LH\"\nstringEndArchive=b\"PK\\005\\006\"\nsizeEndCentDir=struct.calcsize(structEndArchive)\n\n_ECD_SIGNATURE=0\n_ECD_DISK_NUMBER=1\n_ECD_DISK_START=2\n_ECD_ENTRIES_THIS_DISK=3\n_ECD_ENTRIES_TOTAL=4\n_ECD_SIZE=5\n_ECD_OFFSET=6\n_ECD_COMMENT_SIZE=7\n\n\n_ECD_COMMENT=8\n_ECD_LOCATION=9\n\n\n\nstructCentralDir=\"<4s4B4HL2L5H2L\"\nstringCentralDir=b\"PK\\001\\002\"\nsizeCentralDir=struct.calcsize(structCentralDir)\n\n\n_CD_SIGNATURE=0\n_CD_CREATE_VERSION=1\n_CD_CREATE_SYSTEM=2\n_CD_EXTRACT_VERSION=3\n_CD_EXTRACT_SYSTEM=4\n_CD_FLAG_BITS=5\n_CD_COMPRESS_TYPE=6\n_CD_TIME=7\n_CD_DATE=8\n_CD_CRC=9\n_CD_COMPRESSED_SIZE=10\n_CD_UNCOMPRESSED_SIZE=11\n_CD_FILENAME_LENGTH=12\n_CD_EXTRA_FIELD_LENGTH=13\n_CD_COMMENT_LENGTH=14\n_CD_DISK_NUMBER_START=15\n_CD_INTERNAL_FILE_ATTRIBUTES=16\n_CD_EXTERNAL_FILE_ATTRIBUTES=17\n_CD_LOCAL_HEADER_OFFSET=18\n\n\n\n_MASK_ENCRYPTED=1 <<0\n\n_MASK_COMPRESS_OPTION_1=1 <<1\n\n\n\n\n_MASK_USE_DATA_DESCRIPTOR=1 <<3\n\n\n_MASK_COMPRESSED_PATCH=1 <<5\n_MASK_STRONG_ENCRYPTION=1 <<6\n\n\n\n\n_MASK_UTF_FILENAME=1 <<11\n\n\n\n\n\n\n\n\n\nstructFileHeader=\"<4s2B4HL2L2H\"\nstringFileHeader=b\"PK\\003\\004\"\nsizeFileHeader=struct.calcsize(structFileHeader)\n\n_FH_SIGNATURE=0\n_FH_EXTRACT_VERSION=1\n_FH_EXTRACT_SYSTEM=2\n_FH_GENERAL_PURPOSE_FLAG_BITS=3\n_FH_COMPRESSION_METHOD=4\n_FH_LAST_MOD_TIME=5\n_FH_LAST_MOD_DATE=6\n_FH_CRC=7\n_FH_COMPRESSED_SIZE=8\n_FH_UNCOMPRESSED_SIZE=9\n_FH_FILENAME_LENGTH=10\n_FH_EXTRA_FIELD_LENGTH=11\n\n\nstructEndArchive64Locator=\"<4sLQL\"\nstringEndArchive64Locator=b\"PK\\x06\\x07\"\nsizeEndCentDir64Locator=struct.calcsize(structEndArchive64Locator)\n\n\n\nstructEndArchive64=\"<4sQ2H2L4Q\"\nstringEndArchive64=b\"PK\\x06\\x06\"\nsizeEndCentDir64=struct.calcsize(structEndArchive64)\n\n_CD64_SIGNATURE=0\n_CD64_DIRECTORY_RECSIZE=1\n_CD64_CREATE_VERSION=2\n_CD64_EXTRACT_VERSION=3\n_CD64_DISK_NUMBER=4\n_CD64_DISK_NUMBER_START=5\n_CD64_NUMBER_ENTRIES_THIS_DISK=6\n_CD64_NUMBER_ENTRIES_TOTAL=7\n_CD64_DIRECTORY_SIZE=8\n_CD64_OFFSET_START_CENTDIR=9\n\n_DD_SIGNATURE=0x08074b50\n\n_EXTRA_FIELD_STRUCT=struct.Struct('1:\n raise BadZipFile(\"zipfiles that span multiple disks are not supported\")\n \n \n fpin.seek(offset -sizeEndCentDir64Locator -sizeEndCentDir64,2)\n data=fpin.read(sizeEndCentDir64)\n if len(data)!=sizeEndCentDir64:\n return endrec\n sig,sz,create_version,read_version,disk_num,disk_dir,\\\n dircount,dircount2,dirsize,diroffset=\\\n struct.unpack(structEndArchive64,data)\n if sig !=stringEndArchive64:\n return endrec\n \n \n endrec[_ECD_SIGNATURE]=sig\n endrec[_ECD_DISK_NUMBER]=disk_num\n endrec[_ECD_DISK_START]=disk_dir\n endrec[_ECD_ENTRIES_THIS_DISK]=dircount\n endrec[_ECD_ENTRIES_TOTAL]=dircount2\n endrec[_ECD_SIZE]=dirsize\n endrec[_ECD_OFFSET]=diroffset\n return endrec\n \n \ndef _EndRecData(fpin):\n ''\n\n\n \n \n \n fpin.seek(0,2)\n filesize=fpin.tell()\n \n \n \n \n try:\n fpin.seek(-sizeEndCentDir,2)\n except OSError:\n return None\n data=fpin.read()\n if(len(data)==sizeEndCentDir and\n data[0:4]==stringEndArchive and\n data[-2:]==b\"\\000\\000\"):\n \n endrec=struct.unpack(structEndArchive,data)\n endrec=list(endrec)\n \n \n endrec.append(b\"\")\n endrec.append(filesize -sizeEndCentDir)\n \n \n return _EndRecData64(fpin,-sizeEndCentDir,endrec)\n \n \n \n \n \n \n maxCommentStart=max(filesize -(1 <<16)-sizeEndCentDir,0)\n fpin.seek(maxCommentStart,0)\n data=fpin.read()\n start=data.rfind(stringEndArchive)\n if start >=0:\n \n recData=data[start:start+sizeEndCentDir]\n if len(recData)!=sizeEndCentDir:\n \n return None\n endrec=list(struct.unpack(structEndArchive,recData))\n commentSize=endrec[_ECD_COMMENT_SIZE]\n comment=data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]\n endrec.append(comment)\n endrec.append(maxCommentStart+start)\n \n \n return _EndRecData64(fpin,maxCommentStart+start -filesize,\n endrec)\n \n \n return None\n \n \nclass ZipInfo(object):\n ''\n \n __slots__=(\n 'orig_filename',\n 'filename',\n 'date_time',\n 'compress_type',\n '_compresslevel',\n 'comment',\n 'extra',\n 'create_system',\n 'create_version',\n 'extract_version',\n 'reserved',\n 'flag_bits',\n 'volume',\n 'internal_attr',\n 'external_attr',\n 'header_offset',\n 'CRC',\n 'compress_size',\n 'file_size',\n '_raw_time',\n )\n \n def __init__(self,filename=\"NoName\",date_time=(1980,1,1,0,0,0)):\n self.orig_filename=filename\n \n \n \n null_byte=filename.find(chr(0))\n if null_byte >=0:\n filename=filename[0:null_byte]\n \n \n \n if os.sep !=\"/\"and os.sep in filename:\n filename=filename.replace(os.sep,\"/\")\n \n self.filename=filename\n self.date_time=date_time\n \n if date_time[0]<1980:\n raise ValueError('ZIP does not support timestamps before 1980')\n \n \n self.compress_type=ZIP_STORED\n self._compresslevel=None\n self.comment=b\"\"\n self.extra=b\"\"\n if sys.platform =='win32':\n self.create_system=0\n else:\n \n self.create_system=3\n self.create_version=DEFAULT_VERSION\n self.extract_version=DEFAULT_VERSION\n self.reserved=0\n self.flag_bits=0\n self.volume=0\n self.internal_attr=0\n self.external_attr=0\n self.compress_size=0\n self.file_size=0\n \n \n \n \n def __repr__(self):\n result=['<%s filename=%r'%(self.__class__.__name__,self.filename)]\n if self.compress_type !=ZIP_STORED:\n result.append(' compress_type=%s'%\n compressor_names.get(self.compress_type,\n self.compress_type))\n hi=self.external_attr >>16\n lo=self.external_attr&0xFFFF\n if hi:\n result.append(' filemode=%r'%stat.filemode(hi))\n if lo:\n result.append(' external_attr=%#x'%lo)\n isdir=self.is_dir()\n if not isdir or self.file_size:\n result.append(' file_size=%r'%self.file_size)\n if((not isdir or self.compress_size)and\n (self.compress_type !=ZIP_STORED or\n self.file_size !=self.compress_size)):\n result.append(' compress_size=%r'%self.compress_size)\n result.append('>')\n return ''.join(result)\n \n def FileHeader(self,zip64=None):\n ''\n dt=self.date_time\n dosdate=(dt[0]-1980)<<9 |dt[1]<<5 |dt[2]\n dostime=dt[3]<<11 |dt[4]<<5 |(dt[5]//2)\n if self.flag_bits&_MASK_USE_DATA_DESCRIPTOR:\n \n CRC=compress_size=file_size=0\n else:\n CRC=self.CRC\n compress_size=self.compress_size\n file_size=self.file_size\n \n extra=self.extra\n \n min_version=0\n if zip64 is None:\n zip64=file_size >ZIP64_LIMIT or compress_size >ZIP64_LIMIT\n if zip64:\n fmt='ZIP64_LIMIT or compress_size >ZIP64_LIMIT:\n if not zip64:\n raise LargeZipFile(\"Filesize would require ZIP64 extensions\")\n \n \n file_size=0xffffffff\n compress_size=0xffffffff\n min_version=ZIP64_VERSION\n \n if self.compress_type ==ZIP_BZIP2:\n min_version=max(BZIP2_VERSION,min_version)\n elif self.compress_type ==ZIP_LZMA:\n min_version=max(LZMA_VERSION,min_version)\n \n self.extract_version=max(min_version,self.extract_version)\n self.create_version=max(min_version,self.create_version)\n filename,flag_bits=self._encodeFilenameFlags()\n header=struct.pack(structFileHeader,stringFileHeader,\n self.extract_version,self.reserved,flag_bits,\n self.compress_type,dostime,dosdate,CRC,\n compress_size,file_size,\n len(filename),len(extra))\n return header+filename+extra\n \n def _encodeFilenameFlags(self):\n try:\n return self.filename.encode('ascii'),self.flag_bits\n except UnicodeEncodeError:\n return self.filename.encode('utf-8'),self.flag_bits |_MASK_UTF_FILENAME\n \n def _decodeExtra(self):\n \n extra=self.extra\n unpack=struct.unpack\n while len(extra)>=4:\n tp,ln=unpack('len(extra):\n raise BadZipFile(\"Corrupt extra field %04x (size=%d)\"%(tp,ln))\n if tp ==0x0001:\n data=extra[4:ln+4]\n \n try:\n if self.file_size in(0xFFFF_FFFF_FFFF_FFFF,0xFFFF_FFFF):\n field=\"File size\"\n self.file_size,=unpack('2107:\n date_time=(2107,12,31,23,59,59)\n \n if arcname is None:\n arcname=filename\n arcname=os.path.normpath(os.path.splitdrive(arcname)[1])\n while arcname[0]in(os.sep,os.altsep):\n arcname=arcname[1:]\n if isdir:\n arcname +='/'\n zinfo=cls(arcname,date_time)\n zinfo.external_attr=(st.st_mode&0xFFFF)<<16\n if isdir:\n zinfo.file_size=0\n zinfo.external_attr |=0x10\n else:\n zinfo.file_size=st.st_size\n \n return zinfo\n \n def is_dir(self):\n ''\n return self.filename[-1]=='/'\n \n \n \n \n \n \n_crctable=None\ndef _gen_crc(crc):\n for j in range(8):\n if crc&1:\n crc=(crc >>1)^0xEDB88320\n else:\n crc >>=1\n return crc\n \n \n \n \n \n \n \n \n \ndef _ZipDecrypter(pwd):\n key0=305419896\n key1=591751049\n key2=878082192\n \n global _crctable\n if _crctable is None:\n _crctable=list(map(_gen_crc,range(256)))\n crctable=_crctable\n \n def crc32(ch,crc):\n ''\n return(crc >>8)^crctable[(crc ^ch)&0xFF]\n \n def update_keys(c):\n nonlocal key0,key1,key2\n key0=crc32(c,key0)\n key1=(key1+(key0&0xFF))&0xFFFFFFFF\n key1=(key1 *134775813+1)&0xFFFFFFFF\n key2=crc32(key1 >>24,key2)\n \n for p in pwd:\n update_keys(p)\n \n def decrypter(data):\n ''\n result=bytearray()\n append=result.append\n for c in data:\n k=key2 |2\n c ^=((k *(k ^1))>>8)&0xFF\n update_keys(c)\n append(c)\n return bytes(result)\n \n return decrypter\n \n \nclass LZMACompressor:\n\n def __init__(self):\n self._comp=None\n \n def _init(self):\n props=lzma._encode_filter_properties({'id':lzma.FILTER_LZMA1})\n self._comp=lzma.LZMACompressor(lzma.FORMAT_RAW,filters=[\n lzma._decode_filter_properties(lzma.FILTER_LZMA1,props)\n ])\n return struct.pack('>8)&0xff\n else:\n \n check_byte=(zipinfo.CRC >>24)&0xff\n h=self._init_decrypter()\n if h !=check_byte:\n raise RuntimeError(\"Bad password for file %r\"%zipinfo.orig_filename)\n \n \n def _init_decrypter(self):\n self._decrypter=_ZipDecrypter(self._pwd)\n \n \n \n \n \n header=self._fileobj.read(12)\n self._compress_left -=12\n return self._decrypter(header)[11]\n \n def __repr__(self):\n result=['<%s.%s'%(self.__class__.__module__,\n self.__class__.__qualname__)]\n if not self.closed:\n result.append(' name=%r mode=%r'%(self.name,self.mode))\n if self._compress_type !=ZIP_STORED:\n result.append(' compress_type=%s'%\n compressor_names.get(self._compress_type,\n self._compress_type))\n else:\n result.append(' [closed]')\n result.append('>')\n return ''.join(result)\n \n def readline(self,limit=-1):\n ''\n\n\n \n \n if limit <0:\n \n i=self._readbuffer.find(b'\\n',self._offset)+1\n if i >0:\n line=self._readbuffer[self._offset:i]\n self._offset=i\n return line\n \n return io.BufferedIOBase.readline(self,limit)\n \n def peek(self,n=1):\n ''\n if n >len(self._readbuffer)-self._offset:\n chunk=self.read(n)\n if len(chunk)>self._offset:\n self._readbuffer=chunk+self._readbuffer[self._offset:]\n self._offset=0\n else:\n self._offset -=len(chunk)\n \n \n return self._readbuffer[self._offset:self._offset+512]\n \n def readable(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file.\")\n return True\n \n def read(self,n=-1):\n ''\n\n \n if self.closed:\n raise ValueError(\"read from closed file.\")\n if n is None or n <0:\n buf=self._readbuffer[self._offset:]\n self._readbuffer=b''\n self._offset=0\n while not self._eof:\n buf +=self._read1(self.MAX_N)\n return buf\n \n end=n+self._offset\n if end 0 and not self._eof:\n data=self._read1(n)\n if n 0:\n while not self._eof:\n data=self._read1(n)\n if n len(data):\n data +=self._read2(n -len(data))\n else:\n data=self._read2(n)\n \n if self._compress_type ==ZIP_STORED:\n self._eof=self._compress_left <=0\n elif self._compress_type ==ZIP_DEFLATED:\n n=max(n,self.MIN_READ_SIZE)\n data=self._decompressor.decompress(data,n)\n self._eof=(self._decompressor.eof or\n self._compress_left <=0 and\n not self._decompressor.unconsumed_tail)\n if self._eof:\n data +=self._decompressor.flush()\n else:\n data=self._decompressor.decompress(data)\n self._eof=self._decompressor.eof or self._compress_left <=0\n \n data=data[:self._left]\n self._left -=len(data)\n if self._left <=0:\n self._eof=True\n self._update_crc(data)\n return data\n \n def _read2(self,n):\n if self._compress_left <=0:\n return b''\n \n n=max(n,self.MIN_READ_SIZE)\n n=min(n,self._compress_left)\n \n data=self._fileobj.read(n)\n self._compress_left -=len(data)\n if not data:\n raise EOFError\n \n if self._decrypter is not None:\n data=self._decrypter(data)\n return data\n \n def close(self):\n try:\n if self._close_fileobj:\n self._fileobj.close()\n finally:\n super().close()\n \n def seekable(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file.\")\n return self._seekable\n \n def seek(self,offset,whence=0):\n if self.closed:\n raise ValueError(\"seek on closed file.\")\n if not self._seekable:\n raise io.UnsupportedOperation(\"underlying stream is not seekable\")\n curr_pos=self.tell()\n if whence ==0:\n new_pos=offset\n elif whence ==1:\n new_pos=curr_pos+offset\n elif whence ==2:\n new_pos=self._orig_file_size+offset\n else:\n raise ValueError(\"whence must be os.SEEK_SET (0), \"\n \"os.SEEK_CUR (1), or os.SEEK_END (2)\")\n \n if new_pos >self._orig_file_size:\n new_pos=self._orig_file_size\n \n if new_pos <0:\n new_pos=0\n \n read_offset=new_pos -curr_pos\n buff_offset=read_offset+self._offset\n \n if buff_offset >=0 and buff_offset 0:\n read_len=min(self.MAX_SEEK_READ,read_offset)\n self.read(read_len)\n read_offset -=read_len\n \n return self.tell()\n \n def tell(self):\n if self.closed:\n raise ValueError(\"tell on closed file.\")\n if not self._seekable:\n raise io.UnsupportedOperation(\"underlying stream is not seekable\")\n filepos=self._orig_file_size -self._left -len(self._readbuffer)+self._offset\n return filepos\n \n \nclass _ZipWriteFile(io.BufferedIOBase):\n def __init__(self,zf,zinfo,zip64):\n self._zinfo=zinfo\n self._zip64=zip64\n self._zipfile=zf\n self._compressor=_get_compressor(zinfo.compress_type,\n zinfo._compresslevel)\n self._file_size=0\n self._compress_size=0\n self._crc=0\n \n @property\n def _fileobj(self):\n return self._zipfile.fp\n \n def writable(self):\n return True\n \n def write(self,data):\n if self.closed:\n raise ValueError('I/O operation on closed file.')\n \n \n if isinstance(data,(bytes,bytearray)):\n nbytes=len(data)\n else:\n data=memoryview(data)\n nbytes=data.nbytes\n self._file_size +=nbytes\n \n self._crc=crc32(data,self._crc)\n if self._compressor:\n data=self._compressor.compress(data)\n self._compress_size +=len(data)\n self._fileobj.write(data)\n return nbytes\n \n def close(self):\n if self.closed:\n return\n try:\n super().close()\n \n if self._compressor:\n buf=self._compressor.flush()\n self._compress_size +=len(buf)\n self._fileobj.write(buf)\n self._zinfo.compress_size=self._compress_size\n else:\n self._zinfo.compress_size=self._file_size\n self._zinfo.CRC=self._crc\n self._zinfo.file_size=self._file_size\n \n \n if self._zinfo.flag_bits&_MASK_USE_DATA_DESCRIPTOR:\n \n fmt='ZIP64_LIMIT:\n raise RuntimeError(\n 'File size unexpectedly exceeded ZIP64 limit')\n if self._compress_size >ZIP64_LIMIT:\n raise RuntimeError(\n 'Compressed size unexpectedly exceeded ZIP64 limit')\n \n \n \n \n self._zipfile.start_dir=self._fileobj.tell()\n self._fileobj.seek(self._zinfo.header_offset)\n self._fileobj.write(self._zinfo.FileHeader(self._zip64))\n self._fileobj.seek(self._zipfile.start_dir)\n \n \n self._zipfile.filelist.append(self._zinfo)\n self._zipfile.NameToInfo[self._zinfo.filename]=self._zinfo\n finally:\n self._zipfile._writing=False\n \n \n \nclass ZipFile:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n fp=None\n _windows_illegal_name_trans_table=None\n \n def __init__(self,file,mode=\"r\",compression=ZIP_STORED,allowZip64=True,\n compresslevel=None,*,strict_timestamps=True,metadata_encoding=None):\n ''\n \n if mode not in('r','w','x','a'):\n raise ValueError(\"ZipFile requires mode 'r', 'w', 'x', or 'a'\")\n \n _check_compression(compression)\n \n self._allowZip64=allowZip64\n self._didModify=False\n self.debug=0\n self.NameToInfo={}\n self.filelist=[]\n self.compression=compression\n self.compresslevel=compresslevel\n self.mode=mode\n self.pwd=None\n self._comment=b''\n self._strict_timestamps=strict_timestamps\n self.metadata_encoding=metadata_encoding\n \n \n if self.metadata_encoding and mode !='r':\n raise ValueError(\n \"metadata_encoding is only supported for reading files\")\n \n \n if isinstance(file,os.PathLike):\n file=os.fspath(file)\n if isinstance(file,str):\n \n self._filePassed=0\n self.filename=file\n modeDict={'r':'rb','w':'w+b','x':'x+b','a':'r+b',\n 'r+b':'w+b','w+b':'wb','x+b':'xb'}\n filemode=modeDict[mode]\n while True:\n try:\n self.fp=io.open(file,filemode)\n except OSError:\n if filemode in modeDict:\n filemode=modeDict[filemode]\n continue\n raise\n break\n else:\n self._filePassed=1\n self.fp=file\n self.filename=getattr(file,'name',None)\n self._fileRefCnt=1\n self._lock=threading.RLock()\n self._seekable=True\n self._writing=False\n \n try:\n if mode =='r':\n self._RealGetContents()\n elif mode in('w','x'):\n \n \n self._didModify=True\n try:\n self.start_dir=self.fp.tell()\n except(AttributeError,OSError):\n self.fp=_Tellable(self.fp)\n self.start_dir=0\n self._seekable=False\n else:\n \n try:\n self.fp.seek(self.start_dir)\n except(AttributeError,OSError):\n self._seekable=False\n elif mode =='a':\n try:\n \n self._RealGetContents()\n \n self.fp.seek(self.start_dir)\n except BadZipFile:\n \n self.fp.seek(0,2)\n \n \n \n self._didModify=True\n self.start_dir=self.fp.tell()\n else:\n raise ValueError(\"Mode must be 'r', 'w', 'x', or 'a'\")\n except:\n fp=self.fp\n self.fp=None\n self._fpclose(fp)\n raise\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,traceback):\n self.close()\n \n def __repr__(self):\n result=['<%s.%s'%(self.__class__.__module__,\n self.__class__.__qualname__)]\n if self.fp is not None:\n if self._filePassed:\n result.append(' file=%r'%self.fp)\n elif self.filename is not None:\n result.append(' filename=%r'%self.filename)\n result.append(' mode=%r'%self.mode)\n else:\n result.append(' [closed]')\n result.append('>')\n return ''.join(result)\n \n def _RealGetContents(self):\n ''\n fp=self.fp\n try:\n endrec=_EndRecData(fp)\n except OSError:\n raise BadZipFile(\"File is not a zip file\")\n if not endrec:\n raise BadZipFile(\"File is not a zip file\")\n if self.debug >1:\n print(endrec)\n size_cd=endrec[_ECD_SIZE]\n offset_cd=endrec[_ECD_OFFSET]\n self._comment=endrec[_ECD_COMMENT]\n \n \n concat=endrec[_ECD_LOCATION]-size_cd -offset_cd\n if endrec[_ECD_SIGNATURE]==stringEndArchive64:\n \n concat -=(sizeEndCentDir64+sizeEndCentDir64Locator)\n \n if self.debug >2:\n inferred=concat+offset_cd\n print(\"given, inferred, offset\",offset_cd,inferred,concat)\n \n self.start_dir=offset_cd+concat\n if self.start_dir <0:\n raise BadZipFile(\"Bad offset for central directory\")\n fp.seek(self.start_dir,0)\n data=fp.read(size_cd)\n fp=io.BytesIO(data)\n total=0\n while total 2:\n print(centdir)\n filename=fp.read(centdir[_CD_FILENAME_LENGTH])\n flags=centdir[_CD_FLAG_BITS]\n if flags&_MASK_UTF_FILENAME:\n \n filename=filename.decode('utf-8')\n else:\n \n filename=filename.decode(self.metadata_encoding or 'cp437')\n \n x=ZipInfo(filename)\n x.extra=fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])\n x.comment=fp.read(centdir[_CD_COMMENT_LENGTH])\n x.header_offset=centdir[_CD_LOCAL_HEADER_OFFSET]\n (x.create_version,x.create_system,x.extract_version,x.reserved,\n x.flag_bits,x.compress_type,t,d,\n x.CRC,x.compress_size,x.file_size)=centdir[1:12]\n if x.extract_version >MAX_EXTRACT_VERSION:\n raise NotImplementedError(\"zip file version %.1f\"%\n (x.extract_version /10))\n x.volume,x.internal_attr,x.external_attr=centdir[15:18]\n \n x._raw_time=t\n x.date_time=((d >>9)+1980,(d >>5)&0xF,d&0x1F,\n t >>11,(t >>5)&0x3F,(t&0x1F)*2)\n \n x._decodeExtra()\n x.header_offset=x.header_offset+concat\n self.filelist.append(x)\n self.NameToInfo[x.filename]=x\n \n \n total=(total+sizeCentralDir+centdir[_CD_FILENAME_LENGTH]\n +centdir[_CD_EXTRA_FIELD_LENGTH]\n +centdir[_CD_COMMENT_LENGTH])\n \n if self.debug >2:\n print(\"total\",total)\n \n \n def namelist(self):\n ''\n return[data.filename for data in self.filelist]\n \n def infolist(self):\n ''\n \n return self.filelist\n \n def printdir(self,file=None):\n ''\n print(\"%-46s %19s %12s\"%(\"File Name\",\"Modified \",\"Size\"),\n file=file)\n for zinfo in self.filelist:\n date=\"%d-%02d-%02d %02d:%02d:%02d\"%zinfo.date_time[:6]\n print(\"%-46s %s %12d\"%(zinfo.filename,date,zinfo.file_size),\n file=file)\n \n def testzip(self):\n ''\n chunk_size=2 **20\n for zinfo in self.filelist:\n try:\n \n \n with self.open(zinfo.filename,\"r\")as f:\n while f.read(chunk_size):\n pass\n except BadZipFile:\n return zinfo.filename\n \n def getinfo(self,name):\n ''\n info=self.NameToInfo.get(name)\n if info is None:\n raise KeyError(\n 'There is no item named %r in the archive'%name)\n \n return info\n \n def setpassword(self,pwd):\n ''\n if pwd and not isinstance(pwd,bytes):\n raise TypeError(\"pwd: expected bytes, got %s\"%type(pwd).__name__)\n if pwd:\n self.pwd=pwd\n else:\n self.pwd=None\n \n @property\n def comment(self):\n ''\n return self._comment\n \n @comment.setter\n def comment(self,comment):\n if not isinstance(comment,bytes):\n raise TypeError(\"comment: expected bytes, got %s\"%type(comment).__name__)\n \n if len(comment)>ZIP_MAX_COMMENT:\n import warnings\n warnings.warn('Archive comment is too long; truncating to %d bytes'\n %ZIP_MAX_COMMENT,stacklevel=2)\n comment=comment[:ZIP_MAX_COMMENT]\n self._comment=comment\n self._didModify=True\n \n def read(self,name,pwd=None):\n ''\n with self.open(name,\"r\",pwd)as fp:\n return fp.read()\n \n def open(self,name,mode=\"r\",pwd=None,*,force_zip64=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if mode not in{\"r\",\"w\"}:\n raise ValueError('open() requires mode \"r\" or \"w\"')\n if pwd and(mode ==\"w\"):\n raise ValueError(\"pwd is only supported for reading files\")\n if not self.fp:\n raise ValueError(\n \"Attempt to use ZIP archive that was already closed\")\n \n \n if isinstance(name,ZipInfo):\n \n zinfo=name\n elif mode =='w':\n zinfo=ZipInfo(name)\n zinfo.compress_type=self.compression\n zinfo._compresslevel=self.compresslevel\n else:\n \n zinfo=self.getinfo(name)\n \n if mode =='w':\n return self._open_to_write(zinfo,force_zip64=force_zip64)\n \n if self._writing:\n raise ValueError(\"Can't read from the ZIP file while there \"\n \"is an open writing handle on it. \"\n \"Close the writing handle before trying to read.\")\n \n \n self._fileRefCnt +=1\n zef_file=_SharedFile(self.fp,zinfo.header_offset,\n self._fpclose,self._lock,lambda:self._writing)\n try:\n \n fheader=zef_file.read(sizeFileHeader)\n if len(fheader)!=sizeFileHeader:\n raise BadZipFile(\"Truncated file header\")\n fheader=struct.unpack(structFileHeader,fheader)\n if fheader[_FH_SIGNATURE]!=stringFileHeader:\n raise BadZipFile(\"Bad magic number for file header\")\n \n fname=zef_file.read(fheader[_FH_FILENAME_LENGTH])\n if fheader[_FH_EXTRA_FIELD_LENGTH]:\n zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])\n \n if zinfo.flag_bits&_MASK_COMPRESSED_PATCH:\n \n raise NotImplementedError(\"compressed patched data (flag bit 5)\")\n \n if zinfo.flag_bits&_MASK_STRONG_ENCRYPTION:\n \n raise NotImplementedError(\"strong encryption (flag bit 6)\")\n \n if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS]&_MASK_UTF_FILENAME:\n \n fname_str=fname.decode(\"utf-8\")\n else:\n fname_str=fname.decode(self.metadata_encoding or \"cp437\")\n \n if fname_str !=zinfo.orig_filename:\n raise BadZipFile(\n 'File name in directory %r and header %r differ.'\n %(zinfo.orig_filename,fname))\n \n \n is_encrypted=zinfo.flag_bits&_MASK_ENCRYPTED\n if is_encrypted:\n if not pwd:\n pwd=self.pwd\n if pwd and not isinstance(pwd,bytes):\n raise TypeError(\"pwd: expected bytes, got %s\"%type(pwd).__name__)\n if not pwd:\n raise RuntimeError(\"File %r is encrypted, password \"\n \"required for extraction\"%name)\n else:\n pwd=None\n \n return ZipExtFile(zef_file,mode,zinfo,pwd,True)\n except:\n zef_file.close()\n raise\n \n def _open_to_write(self,zinfo,force_zip64=False):\n if force_zip64 and not self._allowZip64:\n raise ValueError(\n \"force_zip64 is True, but allowZip64 was False when opening \"\n \"the ZIP file.\"\n )\n if self._writing:\n raise ValueError(\"Can't write to the ZIP file while there is \"\n \"another write handle open on it. \"\n \"Close the first handle before opening another.\")\n \n \n zinfo.compress_size=0\n zinfo.CRC=0\n \n zinfo.flag_bits=0x00\n if zinfo.compress_type ==ZIP_LZMA:\n \n zinfo.flag_bits |=_MASK_COMPRESS_OPTION_1\n if not self._seekable:\n zinfo.flag_bits |=_MASK_USE_DATA_DESCRIPTOR\n \n if not zinfo.external_attr:\n zinfo.external_attr=0o600 <<16\n \n \n zip64=self._allowZip64 and\\\n (force_zip64 or zinfo.file_size *1.05 >ZIP64_LIMIT)\n \n if self._seekable:\n self.fp.seek(self.start_dir)\n zinfo.header_offset=self.fp.tell()\n \n self._writecheck(zinfo)\n self._didModify=True\n \n self.fp.write(zinfo.FileHeader(zip64))\n \n self._writing=True\n return _ZipWriteFile(self,zinfo,zip64)\n \n def extract(self,member,path=None,pwd=None):\n ''\n\n\n\n \n if path is None:\n path=os.getcwd()\n else:\n path=os.fspath(path)\n \n return self._extract_member(member,path,pwd)\n \n def extractall(self,path=None,members=None,pwd=None):\n ''\n\n\n\n \n if members is None:\n members=self.namelist()\n \n if path is None:\n path=os.getcwd()\n else:\n path=os.fspath(path)\n \n for zipinfo in members:\n self._extract_member(zipinfo,path,pwd)\n \n @classmethod\n def _sanitize_windows_name(cls,arcname,pathsep):\n ''\n table=cls._windows_illegal_name_trans_table\n if not table:\n illegal=':<>|\"?*'\n table=str.maketrans(illegal,'_'*len(illegal))\n cls._windows_illegal_name_trans_table=table\n arcname=arcname.translate(table)\n \n arcname=(x.rstrip('.')for x in arcname.split(pathsep))\n \n arcname=pathsep.join(x for x in arcname if x)\n return arcname\n \n def _extract_member(self,member,targetpath,pwd):\n ''\n\n \n if not isinstance(member,ZipInfo):\n member=self.getinfo(member)\n \n \n \n arcname=member.filename.replace('/',os.path.sep)\n \n if os.path.altsep:\n arcname=arcname.replace(os.path.altsep,os.path.sep)\n \n \n arcname=os.path.splitdrive(arcname)[1]\n invalid_path_parts=('',os.path.curdir,os.path.pardir)\n arcname=os.path.sep.join(x for x in arcname.split(os.path.sep)\n if x not in invalid_path_parts)\n if os.path.sep =='\\\\':\n \n arcname=self._sanitize_windows_name(arcname,os.path.sep)\n \n targetpath=os.path.join(targetpath,arcname)\n targetpath=os.path.normpath(targetpath)\n \n \n upperdirs=os.path.dirname(targetpath)\n if upperdirs and not os.path.exists(upperdirs):\n os.makedirs(upperdirs)\n \n if member.is_dir():\n if not os.path.isdir(targetpath):\n os.mkdir(targetpath)\n return targetpath\n \n with self.open(member,pwd=pwd)as source,\\\n open(targetpath,\"wb\")as target:\n shutil.copyfileobj(source,target)\n \n return targetpath\n \n def _writecheck(self,zinfo):\n ''\n if zinfo.filename in self.NameToInfo:\n import warnings\n warnings.warn('Duplicate name: %r'%zinfo.filename,stacklevel=3)\n if self.mode not in('w','x','a'):\n raise ValueError(\"write() requires mode 'w', 'x', or 'a'\")\n if not self.fp:\n raise ValueError(\n \"Attempt to write ZIP archive that was already closed\")\n _check_compression(zinfo.compress_type)\n if not self._allowZip64:\n requires_zip64=None\n if len(self.filelist)>=ZIP_FILECOUNT_LIMIT:\n requires_zip64=\"Files count\"\n elif zinfo.file_size >ZIP64_LIMIT:\n requires_zip64=\"Filesize\"\n elif zinfo.header_offset >ZIP64_LIMIT:\n requires_zip64=\"Zipfile size\"\n if requires_zip64:\n raise LargeZipFile(requires_zip64+\n \" would require ZIP64 extensions\")\n \n def write(self,filename,arcname=None,\n compress_type=None,compresslevel=None):\n ''\n \n if not self.fp:\n raise ValueError(\n \"Attempt to write to ZIP archive that was already closed\")\n if self._writing:\n raise ValueError(\n \"Can't write to ZIP archive while an open writing handle exists\"\n )\n \n zinfo=ZipInfo.from_file(filename,arcname,\n strict_timestamps=self._strict_timestamps)\n \n if zinfo.is_dir():\n zinfo.compress_size=0\n zinfo.CRC=0\n self.mkdir(zinfo)\n else:\n if compress_type is not None:\n zinfo.compress_type=compress_type\n else:\n zinfo.compress_type=self.compression\n \n if compresslevel is not None:\n zinfo._compresslevel=compresslevel\n else:\n zinfo._compresslevel=self.compresslevel\n \n with open(filename,\"rb\")as src,self.open(zinfo,'w')as dest:\n shutil.copyfileobj(src,dest,1024 *8)\n \n def writestr(self,zinfo_or_arcname,data,\n compress_type=None,compresslevel=None):\n ''\n\n\n\n \n if isinstance(data,str):\n data=data.encode(\"utf-8\")\n if not isinstance(zinfo_or_arcname,ZipInfo):\n zinfo=ZipInfo(filename=zinfo_or_arcname,\n date_time=time.localtime(time.time())[:6])\n zinfo.compress_type=self.compression\n zinfo._compresslevel=self.compresslevel\n if zinfo.filename[-1]=='/':\n zinfo.external_attr=0o40775 <<16\n zinfo.external_attr |=0x10\n else:\n zinfo.external_attr=0o600 <<16\n else:\n zinfo=zinfo_or_arcname\n \n if not self.fp:\n raise ValueError(\n \"Attempt to write to ZIP archive that was already closed\")\n if self._writing:\n raise ValueError(\n \"Can't write to ZIP archive while an open writing handle exists.\"\n )\n \n if compress_type is not None:\n zinfo.compress_type=compress_type\n \n if compresslevel is not None:\n zinfo._compresslevel=compresslevel\n \n zinfo.file_size=len(data)\n with self._lock:\n with self.open(zinfo,mode='w')as dest:\n dest.write(data)\n \n def mkdir(self,zinfo_or_directory_name,mode=511):\n ''\n if isinstance(zinfo_or_directory_name,ZipInfo):\n zinfo=zinfo_or_directory_name\n if not zinfo.is_dir():\n raise ValueError(\"The given ZipInfo does not describe a directory\")\n elif isinstance(zinfo_or_directory_name,str):\n directory_name=zinfo_or_directory_name\n if not directory_name.endswith(\"/\"):\n directory_name +=\"/\"\n zinfo=ZipInfo(directory_name)\n zinfo.compress_size=0\n zinfo.CRC=0\n zinfo.external_attr=((0o40000 |mode)&0xFFFF)<<16\n zinfo.file_size=0\n zinfo.external_attr |=0x10\n else:\n raise TypeError(\"Expected type str or ZipInfo\")\n \n with self._lock:\n if self._seekable:\n self.fp.seek(self.start_dir)\n zinfo.header_offset=self.fp.tell()\n if zinfo.compress_type ==ZIP_LZMA:\n \n zinfo.flag_bits |=_MASK_COMPRESS_OPTION_1\n \n self._writecheck(zinfo)\n self._didModify=True\n \n self.filelist.append(zinfo)\n self.NameToInfo[zinfo.filename]=zinfo\n self.fp.write(zinfo.FileHeader(False))\n self.start_dir=self.fp.tell()\n \n def __del__(self):\n ''\n self.close()\n \n def close(self):\n ''\n \n if self.fp is None:\n return\n \n if self._writing:\n raise ValueError(\"Can't close the ZIP file while there is \"\n \"an open writing handle on it. \"\n \"Close the writing handle before closing the zip.\")\n \n try:\n if self.mode in('w','x','a')and self._didModify:\n with self._lock:\n if self._seekable:\n self.fp.seek(self.start_dir)\n self._write_end_record()\n finally:\n fp=self.fp\n self.fp=None\n self._fpclose(fp)\n \n def _write_end_record(self):\n for zinfo in self.filelist:\n dt=zinfo.date_time\n dosdate=(dt[0]-1980)<<9 |dt[1]<<5 |dt[2]\n dostime=dt[3]<<11 |dt[4]<<5 |(dt[5]//2)\n extra=[]\n if zinfo.file_size >ZIP64_LIMIT\\\n or zinfo.compress_size >ZIP64_LIMIT:\n extra.append(zinfo.file_size)\n extra.append(zinfo.compress_size)\n file_size=0xffffffff\n compress_size=0xffffffff\n else:\n file_size=zinfo.file_size\n compress_size=zinfo.compress_size\n \n if zinfo.header_offset >ZIP64_LIMIT:\n extra.append(zinfo.header_offset)\n header_offset=0xffffffff\n else:\n header_offset=zinfo.header_offset\n \n extra_data=zinfo.extra\n min_version=0\n if extra:\n \n extra_data=_strip_extra(extra_data,(1,))\n extra_data=struct.pack(\n 'ZIP_FILECOUNT_LIMIT:\n requires_zip64=\"Files count\"\n elif centDirOffset >ZIP64_LIMIT:\n requires_zip64=\"Central directory offset\"\n elif centDirSize >ZIP64_LIMIT:\n requires_zip64=\"Central directory size\"\n if requires_zip64:\n \n if not self._allowZip64:\n raise LargeZipFile(requires_zip64+\n \" would require ZIP64 extensions\")\n zip64endrec=struct.pack(\n structEndArchive64,stringEndArchive64,\n 44,45,45,0,0,centDirCount,centDirCount,\n centDirSize,centDirOffset)\n self.fp.write(zip64endrec)\n \n zip64locrec=struct.pack(\n structEndArchive64Locator,\n stringEndArchive64Locator,0,pos2,1)\n self.fp.write(zip64locrec)\n centDirCount=min(centDirCount,0xFFFF)\n centDirSize=min(centDirSize,0xFFFFFFFF)\n centDirOffset=min(centDirOffset,0xFFFFFFFF)\n \n endrec=struct.pack(structEndArchive,stringEndArchive,\n 0,0,centDirCount,centDirCount,\n centDirSize,centDirOffset,len(self._comment))\n self.fp.write(endrec)\n self.fp.write(self._comment)\n if self.mode ==\"a\":\n self.fp.truncate()\n self.fp.flush()\n \n def _fpclose(self,fp):\n assert self._fileRefCnt >0\n self._fileRefCnt -=1\n if not self._fileRefCnt and not self._filePassed:\n fp.close()\n \n \nclass PyZipFile(ZipFile):\n ''\n \n def __init__(self,file,mode=\"r\",compression=ZIP_STORED,\n allowZip64=True,optimize=-1):\n ZipFile.__init__(self,file,mode=mode,compression=compression,\n allowZip64=allowZip64)\n self._optimize=optimize\n \n def writepy(self,pathname,basename=\"\",filterfunc=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n pathname=os.fspath(pathname)\n if filterfunc and not filterfunc(pathname):\n if self.debug:\n label='path'if os.path.isdir(pathname)else 'file'\n print('%s %r skipped by filterfunc'%(label,pathname))\n return\n dir,name=os.path.split(pathname)\n if os.path.isdir(pathname):\n initname=os.path.join(pathname,\"__init__.py\")\n if os.path.isfile(initname):\n \n if basename:\n basename=\"%s/%s\"%(basename,name)\n else:\n basename=name\n if self.debug:\n print(\"Adding package in\",pathname,\"as\",basename)\n fname,arcname=self._get_codename(initname[0:-3],basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n dirlist=sorted(os.listdir(pathname))\n dirlist.remove(\"__init__.py\")\n \n for filename in dirlist:\n path=os.path.join(pathname,filename)\n root,ext=os.path.splitext(filename)\n if os.path.isdir(path):\n if os.path.isfile(os.path.join(path,\"__init__.py\")):\n \n self.writepy(path,basename,\n filterfunc=filterfunc)\n elif ext ==\".py\":\n if filterfunc and not filterfunc(path):\n if self.debug:\n print('file %r skipped by filterfunc'%path)\n continue\n fname,arcname=self._get_codename(path[0:-3],\n basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n else:\n \n if self.debug:\n print(\"Adding files from directory\",pathname)\n for filename in sorted(os.listdir(pathname)):\n path=os.path.join(pathname,filename)\n root,ext=os.path.splitext(filename)\n if ext ==\".py\":\n if filterfunc and not filterfunc(path):\n if self.debug:\n print('file %r skipped by filterfunc'%path)\n continue\n fname,arcname=self._get_codename(path[0:-3],\n basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n else:\n if pathname[-3:]!=\".py\":\n raise RuntimeError(\n 'Files added with writepy() must end with \".py\"')\n fname,arcname=self._get_codename(pathname[0:-3],basename)\n if self.debug:\n print(\"Adding file\",arcname)\n self.write(fname,arcname)\n \n def _get_codename(self,pathname,basename):\n ''\n\n\n\n\n \n def _compile(file,optimize=-1):\n import py_compile\n if self.debug:\n print(\"Compiling\",file)\n try:\n py_compile.compile(file,doraise=True,optimize=optimize)\n except py_compile.PyCompileError as err:\n print(err.msg)\n return False\n return True\n \n file_py=pathname+\".py\"\n file_pyc=pathname+\".pyc\"\n pycache_opt0=importlib.util.cache_from_source(file_py,optimization='')\n pycache_opt1=importlib.util.cache_from_source(file_py,optimization=1)\n pycache_opt2=importlib.util.cache_from_source(file_py,optimization=2)\n if self._optimize ==-1:\n \n if(os.path.isfile(file_pyc)and\n os.stat(file_pyc).st_mtime >=os.stat(file_py).st_mtime):\n \n arcname=fname=file_pyc\n elif(os.path.isfile(pycache_opt0)and\n os.stat(pycache_opt0).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt0\n arcname=file_pyc\n elif(os.path.isfile(pycache_opt1)and\n os.stat(pycache_opt1).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt1\n arcname=file_pyc\n elif(os.path.isfile(pycache_opt2)and\n os.stat(pycache_opt2).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt2\n arcname=file_pyc\n else:\n \n if _compile(file_py):\n if sys.flags.optimize ==0:\n fname=pycache_opt0\n elif sys.flags.optimize ==1:\n fname=pycache_opt1\n else:\n fname=pycache_opt2\n arcname=file_pyc\n else:\n fname=arcname=file_py\n else:\n \n if self._optimize ==0:\n fname=pycache_opt0\n arcname=file_pyc\n else:\n arcname=file_pyc\n if self._optimize ==1:\n fname=pycache_opt1\n elif self._optimize ==2:\n fname=pycache_opt2\n else:\n msg=\"invalid value for 'optimize': {!r}\".format(self._optimize)\n raise ValueError(msg)\n if not(os.path.isfile(fname)and\n os.stat(fname).st_mtime >=os.stat(file_py).st_mtime):\n if not _compile(file_py,optimize=self._optimize):\n fname=arcname=file_py\n archivename=os.path.split(arcname)[1]\n if basename:\n archivename=\"%s/%s\"%(basename,archivename)\n return(fname,archivename)\n \n \ndef _parents(path):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return itertools.islice(_ancestry(path),1,None)\n \n \ndef _ancestry(path):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n path=path.rstrip(posixpath.sep)\n while path and path !=posixpath.sep:\n yield path\n path,tail=posixpath.split(path)\n \n \n_dedupe=dict.fromkeys\n''\n\n\ndef _difference(minuend,subtrahend):\n ''\n\n\n \n return itertools.filterfalse(set(subtrahend).__contains__,minuend)\n \n \nclass CompleteDirs(ZipFile):\n ''\n\n\n \n \n @staticmethod\n def _implied_dirs(names):\n parents=itertools.chain.from_iterable(map(_parents,names))\n as_dirs=(p+posixpath.sep for p in parents)\n return _dedupe(_difference(as_dirs,names))\n \n def namelist(self):\n names=super(CompleteDirs,self).namelist()\n return names+list(self._implied_dirs(names))\n \n def _name_set(self):\n return set(self.namelist())\n \n def resolve_dir(self,name):\n ''\n\n\n \n names=self._name_set()\n dirname=name+'/'\n dir_match=name not in names and dirname in names\n return dirname if dir_match else name\n \n @classmethod\n def make(cls,source):\n ''\n\n\n \n if isinstance(source,CompleteDirs):\n return source\n \n if not isinstance(source,ZipFile):\n return cls(source)\n \n \n if 'r'not in source.mode:\n cls=CompleteDirs\n \n source.__class__=cls\n return source\n \n \nclass FastLookup(CompleteDirs):\n ''\n\n\n \n \n def namelist(self):\n with contextlib.suppress(AttributeError):\n return self.__names\n self.__names=super(FastLookup,self).namelist()\n return self.__names\n \n def _name_set(self):\n with contextlib.suppress(AttributeError):\n return self.__lookup\n self.__lookup=super(FastLookup,self)._name_set()\n return self.__lookup\n \n \nclass Path:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __repr=\"{self.__class__.__name__}({self.root.filename!r}, {self.at!r})\"\n \n def __init__(self,root,at=\"\"):\n ''\n\n\n\n\n\n\n\n \n self.root=FastLookup.make(root)\n self.at=at\n \n def open(self,mode='r',*args,pwd=None,**kwargs):\n ''\n\n\n\n \n if self.is_dir():\n raise IsADirectoryError(self)\n zip_mode=mode[0]\n if not self.exists()and zip_mode =='r':\n raise FileNotFoundError(self)\n stream=self.root.open(self.at,zip_mode,pwd=pwd)\n if 'b'in mode:\n if args or kwargs:\n raise ValueError(\"encoding args invalid for binary operation\")\n return stream\n else:\n kwargs[\"encoding\"]=io.text_encoding(kwargs.get(\"encoding\"))\n return io.TextIOWrapper(stream,*args,**kwargs)\n \n @property\n def name(self):\n return pathlib.Path(self.at).name or self.filename.name\n \n @property\n def suffix(self):\n return pathlib.Path(self.at).suffix or self.filename.suffix\n \n @property\n def suffixes(self):\n return pathlib.Path(self.at).suffixes or self.filename.suffixes\n \n @property\n def stem(self):\n return pathlib.Path(self.at).stem or self.filename.stem\n \n @property\n def filename(self):\n return pathlib.Path(self.root.filename).joinpath(self.at)\n \n def read_text(self,*args,**kwargs):\n kwargs[\"encoding\"]=io.text_encoding(kwargs.get(\"encoding\"))\n with self.open('r',*args,**kwargs)as strm:\n return strm.read()\n \n def read_bytes(self):\n with self.open('rb')as strm:\n return strm.read()\n \n def _is_child(self,path):\n return posixpath.dirname(path.at.rstrip(\"/\"))==self.at.rstrip(\"/\")\n \n def _next(self,at):\n return self.__class__(self.root,at)\n \n def is_dir(self):\n return not self.at or self.at.endswith(\"/\")\n \n def is_file(self):\n return self.exists()and not self.is_dir()\n \n def exists(self):\n return self.at in self.root._name_set()\n \n def iterdir(self):\n if not self.is_dir():\n raise ValueError(\"Can't listdir a file\")\n subs=map(self._next,self.root.namelist())\n return filter(self._is_child,subs)\n \n def __str__(self):\n return posixpath.join(self.root.filename,self.at)\n \n def __repr__(self):\n return self.__repr.format(self=self)\n \n def joinpath(self,*other):\n next=posixpath.join(self.at,*other)\n return self._next(self.root.resolve_dir(next))\n \n __truediv__=joinpath\n \n @property\n def parent(self):\n if not self.at:\n return self.filename.parent\n parent_at=posixpath.dirname(self.at.rstrip('/'))\n if parent_at:\n parent_at +='/'\n return self._next(parent_at)\n \n \ndef main(args=None):\n import argparse\n \n description='A simple command-line interface for zipfile module.'\n parser=argparse.ArgumentParser(description=description)\n group=parser.add_mutually_exclusive_group(required=True)\n group.add_argument('-l','--list',metavar='',\n help='Show listing of a zipfile')\n group.add_argument('-e','--extract',nargs=2,\n metavar=('',''),\n help='Extract zipfile into target dir')\n group.add_argument('-c','--create',nargs='+',\n metavar=('',''),\n help='Create zipfile from sources')\n group.add_argument('-t','--test',metavar='',\n help='Test if a zipfile is valid')\n parser.add_argument('--metadata-encoding',metavar='',\n help='Specify encoding of member names for -l, -e and -t')\n args=parser.parse_args(args)\n \n encoding=args.metadata_encoding\n \n if args.test is not None:\n src=args.test\n with ZipFile(src,'r',metadata_encoding=encoding)as zf:\n badfile=zf.testzip()\n if badfile:\n print(\"The following enclosed file is corrupted: {!r}\".format(badfile))\n print(\"Done testing\")\n \n elif args.list is not None:\n src=args.list\n with ZipFile(src,'r',metadata_encoding=encoding)as zf:\n zf.printdir()\n \n elif args.extract is not None:\n src,curdir=args.extract\n with ZipFile(src,'r',metadata_encoding=encoding)as zf:\n zf.extractall(curdir)\n \n elif args.create is not None:\n if encoding:\n print(\"Non-conforming encodings not supported with -c.\",\n file=sys.stderr)\n sys.exit(1)\n \n zip_name=args.create.pop(0)\n files=args.create\n \n def addToZip(zf,path,zippath):\n if os.path.isfile(path):\n zf.write(path,zippath,ZIP_DEFLATED)\n elif os.path.isdir(path):\n if zippath:\n zf.write(path,zippath)\n for nm in sorted(os.listdir(path)):\n addToZip(zf,\n os.path.join(path,nm),os.path.join(zippath,nm))\n \n \n with ZipFile(zip_name,'w')as zf:\n for path in files:\n zippath=os.path.basename(path)\n if not zippath:\n zippath=os.path.basename(os.path.dirname(path))\n if zippath in('',os.curdir,os.pardir):\n zippath=''\n addToZip(zf,path,zippath)\n \n \nif __name__ ==\"__main__\":\n main()\n", ["argparse", "binascii", "bz2", "contextlib", "importlib.util", "io", "itertools", "lzma", "os", "pathlib", "posixpath", "py_compile", "shutil", "stat", "struct", "sys", "threading", "time", "warnings", "zlib"]], "zipimport": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport _frozen_importlib_external as _bootstrap_external\nfrom _frozen_importlib_external import _unpack_uint16,_unpack_uint32,_unpack_uint64\nimport _frozen_importlib as _bootstrap\nimport _imp\nimport _io\nimport marshal\nimport sys\nimport time\nimport _warnings\n\n__all__=['ZipImportError','zipimporter']\n\n\npath_sep=_bootstrap_external.path_sep\nalt_path_sep=_bootstrap_external.path_separators[1:]\n\n\nclass ZipImportError(ImportError):\n pass\n \n \n_zip_directory_cache={}\n\n_module_type=type(sys)\n\nEND_CENTRAL_DIR_SIZE=22\nEND_CENTRAL_DIR_SIZE_64=56\nEND_CENTRAL_DIR_LOCATOR_SIZE_64=20\nSTRING_END_ARCHIVE=b'PK\\x05\\x06'\nSTRING_END_LOCATOR_64=b'PK\\x06\\x07'\nSTRING_END_ZIP_64=b'PK\\x06\\x06'\nMAX_COMMENT_LEN=(1 <<16)-1\nMAX_UINT32=0xffffffff\nZIP64_EXTRA_TAG=0x1\n\nclass zipimporter(_bootstrap_external._LoaderBasics):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n def __init__(self,path):\n if not isinstance(path,str):\n raise TypeError(f\"expected str, not {type(path)!r}\")\n if not path:\n raise ZipImportError('archive path is empty',path=path)\n if alt_path_sep:\n path=path.replace(alt_path_sep,path_sep)\n \n prefix=[]\n while True:\n try:\n st=_bootstrap_external._path_stat(path)\n except(OSError,ValueError):\n \n \n dirname,basename=_bootstrap_external._path_split(path)\n if dirname ==path:\n raise ZipImportError('not a Zip file',path=path)\n path=dirname\n prefix.append(basename)\n else:\n \n if(st.st_mode&0o170000)!=0o100000:\n \n raise ZipImportError('not a Zip file',path=path)\n break\n \n if path not in _zip_directory_cache:\n _zip_directory_cache[path]=_read_directory(path)\n self.archive=path\n \n self.prefix=_bootstrap_external._path_join(*prefix[::-1])\n if self.prefix:\n self.prefix +=path_sep\n \n \n def find_spec(self,fullname,target=None):\n ''\n\n\n \n module_info=_get_module_info(self,fullname)\n if module_info is not None:\n return _bootstrap.spec_from_loader(fullname,self,is_package=module_info)\n else:\n \n \n \n \n \n modpath=_get_module_path(self,fullname)\n if _is_dir(self,modpath):\n \n \n \n path=f'{self.archive}{path_sep}{modpath}'\n spec=_bootstrap.ModuleSpec(name=fullname,loader=None,\n is_package=True)\n spec.submodule_search_locations.append(path)\n return spec\n else:\n return None\n \n def get_code(self,fullname):\n ''\n\n\n\n \n code,ispackage,modpath=_get_module_code(self,fullname)\n return code\n \n \n def get_data(self,pathname):\n ''\n\n\n\n \n if alt_path_sep:\n pathname=pathname.replace(alt_path_sep,path_sep)\n \n key=pathname\n if pathname.startswith(self.archive+path_sep):\n key=pathname[len(self.archive+path_sep):]\n \n try:\n toc_entry=self._get_files()[key]\n except KeyError:\n raise OSError(0,'',key)\n return _get_data(self.archive,toc_entry)\n \n \n \n def get_filename(self,fullname):\n ''\n\n\n\n \n \n \n code,ispackage,modpath=_get_module_code(self,fullname)\n return modpath\n \n \n def get_source(self,fullname):\n ''\n\n\n\n\n \n mi=_get_module_info(self,fullname)\n if mi is None:\n raise ZipImportError(f\"can't find module {fullname !r}\",name=fullname)\n \n path=_get_module_path(self,fullname)\n if mi:\n fullpath=_bootstrap_external._path_join(path,'__init__.py')\n else:\n fullpath=f'{path}.py'\n \n try:\n toc_entry=self._get_files()[fullpath]\n except KeyError:\n \n return None\n return _get_data(self.archive,toc_entry).decode()\n \n \n \n def is_package(self,fullname):\n ''\n\n\n\n \n mi=_get_module_info(self,fullname)\n if mi is None:\n raise ZipImportError(f\"can't find module {fullname !r}\",name=fullname)\n return mi\n \n \n \n def load_module(self,fullname):\n ''\n\n\n\n\n\n\n \n msg=(\"zipimport.zipimporter.load_module() is deprecated and slated for \"\n \"removal in Python 3.12; use exec_module() instead\")\n _warnings.warn(msg,DeprecationWarning)\n code,ispackage,modpath=_get_module_code(self,fullname)\n mod=sys.modules.get(fullname)\n if mod is None or not isinstance(mod,_module_type):\n mod=_module_type(fullname)\n sys.modules[fullname]=mod\n mod.__loader__=self\n \n try:\n if ispackage:\n \n \n path=_get_module_path(self,fullname)\n fullpath=_bootstrap_external._path_join(self.archive,path)\n mod.__path__=[fullpath]\n \n if not hasattr(mod,'__builtins__'):\n mod.__builtins__=__builtins__\n _bootstrap_external._fix_up_module(mod.__dict__,fullname,modpath)\n exec(code,mod.__dict__)\n except:\n del sys.modules[fullname]\n raise\n \n try:\n mod=sys.modules[fullname]\n except KeyError:\n raise ImportError(f'Loaded module {fullname !r} not found in sys.modules')\n _bootstrap._verbose_message('import {} # loaded from Zip {}',fullname,modpath)\n return mod\n \n \n def get_resource_reader(self,fullname):\n ''\n\n\n\n \n try:\n if not self.is_package(fullname):\n return None\n except ZipImportError:\n return None\n from importlib.readers import ZipReader\n return ZipReader(self,fullname)\n \n \n def _get_files(self):\n ''\n try:\n files=_zip_directory_cache[self.archive]\n except KeyError:\n try:\n files=_zip_directory_cache[self.archive]=_read_directory(self.archive)\n except ZipImportError:\n files={}\n \n return files\n \n \n def invalidate_caches(self):\n ''\n _zip_directory_cache.pop(self.archive,None)\n \n \n def __repr__(self):\n return f''\n \n \n \n \n \n \n \n_zip_searchorder=(\n(path_sep+'__init__.pyc',True,True),\n(path_sep+'__init__.py',False,True),\n('.pyc',True,False),\n('.py',False,False),\n)\n\n\n\ndef _get_module_path(self,fullname):\n return self.prefix+fullname.rpartition('.')[2]\n \n \ndef _is_dir(self,path):\n\n\n\n dirpath=path+path_sep\n \n return dirpath in self._get_files()\n \n \ndef _get_module_info(self,fullname):\n path=_get_module_path(self,fullname)\n for suffix,isbytecode,ispackage in _zip_searchorder:\n fullpath=path+suffix\n if fullpath in self._get_files():\n return ispackage\n return None\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef _read_directory(archive):\n try:\n fp=_io.open_code(archive)\n except OSError:\n raise ZipImportError(f\"can't open Zip file: {archive !r}\",path=archive)\n \n with fp:\n \n \n \n start_offset=fp.tell()\n try:\n \n try:\n fp.seek(0,2)\n file_size=fp.tell()\n except OSError:\n raise ZipImportError(f\"can't read Zip file: {archive !r}\",\n path=archive)\n max_comment_plus_dirs_size=(\n MAX_COMMENT_LEN+END_CENTRAL_DIR_SIZE+\n END_CENTRAL_DIR_SIZE_64+END_CENTRAL_DIR_LOCATOR_SIZE_64)\n max_comment_start=max(file_size -max_comment_plus_dirs_size,0)\n try:\n fp.seek(max_comment_start)\n data=fp.read(max_comment_plus_dirs_size)\n except OSError:\n raise ZipImportError(f\"can't read Zip file: {archive !r}\",\n path=archive)\n pos=data.rfind(STRING_END_ARCHIVE)\n pos64=data.rfind(STRING_END_ZIP_64)\n \n if(pos64 >=0 and pos64+END_CENTRAL_DIR_SIZE_64+END_CENTRAL_DIR_LOCATOR_SIZE_64 ==pos):\n \n buffer=data[pos64:pos64+END_CENTRAL_DIR_SIZE_64]\n if len(buffer)!=END_CENTRAL_DIR_SIZE_64:\n raise ZipImportError(\n f\"corrupt Zip64 file: Expected {END_CENTRAL_DIR_SIZE_64} byte \"\n f\"zip64 central directory, but read {len(buffer)} bytes.\",\n path=archive)\n header_position=file_size -len(data)+pos64\n \n central_directory_size=_unpack_uint64(buffer[40:48])\n central_directory_position=_unpack_uint64(buffer[48:56])\n num_entries=_unpack_uint64(buffer[24:32])\n elif pos >=0:\n buffer=data[pos:pos+END_CENTRAL_DIR_SIZE]\n if len(buffer)!=END_CENTRAL_DIR_SIZE:\n raise ZipImportError(f\"corrupt Zip file: {archive !r}\",\n path=archive)\n \n header_position=file_size -len(data)+pos\n \n \n \n central_directory_size=_unpack_uint32(buffer[12:16])\n central_directory_position=_unpack_uint32(buffer[16:20])\n num_entries=_unpack_uint16(buffer[8:10])\n \n \n \n else:\n raise ZipImportError(f'not a Zip file: {archive !r}',\n path=archive)\n \n \n \n \n \n if header_position 3:\n raise ZipImportError(f\"can't read header extra: {archive !r}\",path=archive)\n import struct\n values=list(struct.unpack_from(f\"<{min(num_extra_values,3)}Q\",\n extra_data,offset=4))\n \n \n \n \n if file_size ==MAX_UINT32:\n file_size=values.pop(0)\n if data_size ==MAX_UINT32:\n data_size=values.pop(0)\n if file_offset ==MAX_UINT32:\n file_offset=values.pop(0)\n \n break\n \n \n \n extra_data=extra_data[4+size:]\n else:\n _bootstrap._verbose_message(\n \"zipimport: suspected zip64 but no zip64 extra for {!r}\",\n path,\n )\n \n \n \n \n \n if file_offset >central_directory_position:\n raise ZipImportError(f'bad local header offset: {archive !r}',path=archive)\n file_offset +=arc_offset\n \n t=(path,compress,data_size,file_size,file_offset,time,date,crc)\n files[name]=t\n count +=1\n finally:\n fp.seek(start_offset)\n _bootstrap._verbose_message('zipimport: found {} names in {!r}',count,archive)\n return files\n \n \n \n \n \n \n \ncp437_table=(\n\n'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f'\n'\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f'\n' !\"#$%&\\'()*+,-./'\n'0123456789:;<=>?'\n'@ABCDEFGHIJKLMNO'\n'PQRSTUVWXYZ[\\\\]^_'\n'`abcdefghijklmno'\n'pqrstuvwxyz{|}~\\x7f'\n\n'\\xc7\\xfc\\xe9\\xe2\\xe4\\xe0\\xe5\\xe7'\n'\\xea\\xeb\\xe8\\xef\\xee\\xec\\xc4\\xc5'\n'\\xc9\\xe6\\xc6\\xf4\\xf6\\xf2\\xfb\\xf9'\n'\\xff\\xd6\\xdc\\xa2\\xa3\\xa5\\u20a7\\u0192'\n'\\xe1\\xed\\xf3\\xfa\\xf1\\xd1\\xaa\\xba'\n'\\xbf\\u2310\\xac\\xbd\\xbc\\xa1\\xab\\xbb'\n'\\u2591\\u2592\\u2593\\u2502\\u2524\\u2561\\u2562\\u2556'\n'\\u2555\\u2563\\u2551\\u2557\\u255d\\u255c\\u255b\\u2510'\n'\\u2514\\u2534\\u252c\\u251c\\u2500\\u253c\\u255e\\u255f'\n'\\u255a\\u2554\\u2569\\u2566\\u2560\\u2550\\u256c\\u2567'\n'\\u2568\\u2564\\u2565\\u2559\\u2558\\u2552\\u2553\\u256b'\n'\\u256a\\u2518\\u250c\\u2588\\u2584\\u258c\\u2590\\u2580'\n'\\u03b1\\xdf\\u0393\\u03c0\\u03a3\\u03c3\\xb5\\u03c4'\n'\\u03a6\\u0398\\u03a9\\u03b4\\u221e\\u03c6\\u03b5\\u2229'\n'\\u2261\\xb1\\u2265\\u2264\\u2320\\u2321\\xf7\\u2248'\n'\\xb0\\u2219\\xb7\\u221a\\u207f\\xb2\\u25a0\\xa0'\n)\n\n_importing_zlib=False\n\n\n\n\ndef _get_decompress_func():\n global _importing_zlib\n if _importing_zlib:\n \n \n _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')\n raise ZipImportError(\"can't decompress data; zlib not available\")\n \n _importing_zlib=True\n try:\n from zlib import decompress\n except Exception:\n _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')\n raise ZipImportError(\"can't decompress data; zlib not available\")\n finally:\n _importing_zlib=False\n \n _bootstrap._verbose_message('zipimport: zlib available')\n return decompress\n \n \ndef _get_data(archive,toc_entry):\n datapath,compress,data_size,file_size,file_offset,time,date,crc=toc_entry\n if data_size <0:\n raise ZipImportError('negative data size')\n \n with _io.open_code(archive)as fp:\n \n try:\n fp.seek(file_offset)\n except OSError:\n raise ZipImportError(f\"can't read Zip file: {archive !r}\",path=archive)\n buffer=fp.read(30)\n if len(buffer)!=30:\n raise EOFError('EOF read where not expected')\n \n if buffer[:4]!=b'PK\\x03\\x04':\n \n raise ZipImportError(f'bad local file header: {archive !r}',path=archive)\n \n name_size=_unpack_uint16(buffer[26:28])\n extra_size=_unpack_uint16(buffer[28:30])\n header_size=30+name_size+extra_size\n file_offset +=header_size\n try:\n fp.seek(file_offset)\n except OSError:\n raise ZipImportError(f\"can't read Zip file: {archive !r}\",path=archive)\n raw_data=fp.read(data_size)\n if len(raw_data)!=data_size:\n raise OSError(\"zipimport: can't read data\")\n \n if compress ==0:\n \n return raw_data\n \n \n try:\n decompress=_get_decompress_func()\n except Exception:\n raise ZipImportError(\"can't decompress data; zlib not available\")\n return decompress(raw_data,-15)\n \n \n \n \n \ndef _eq_mtime(t1,t2):\n\n return abs(t1 -t2)<=1\n \n \n \n \n \ndef _unmarshal_code(self,pathname,fullpath,fullname,data):\n exc_details={\n 'name':fullname,\n 'path':fullpath,\n }\n \n flags=_bootstrap_external._classify_pyc(data,fullname,exc_details)\n \n hash_based=flags&0b1 !=0\n if hash_based:\n check_source=flags&0b10 !=0\n if(_imp.check_hash_based_pycs !='never'and\n (check_source or _imp.check_hash_based_pycs =='always')):\n source_bytes=_get_pyc_source(self,fullpath)\n if source_bytes is not None:\n source_hash=_imp.source_hash(\n _bootstrap_external._RAW_MAGIC_NUMBER,\n source_bytes,\n )\n \n _bootstrap_external._validate_hash_pyc(\n data,source_hash,fullname,exc_details)\n else:\n source_mtime,source_size=\\\n _get_mtime_and_size_of_source(self,fullpath)\n \n if source_mtime:\n \n \n if(not _eq_mtime(_unpack_uint32(data[8:12]),source_mtime)or\n _unpack_uint32(data[12:16])!=source_size):\n _bootstrap._verbose_message(\n f'bytecode is stale for {fullname !r}')\n return None\n \n code=marshal.loads(data[16:])\n if not isinstance(code,_code_type):\n raise TypeError(f'compiled module {pathname !r} is not a code object')\n return code\n \n_code_type=type(_unmarshal_code.__code__)\n\n\n\n\ndef _normalize_line_endings(source):\n source=source.replace(b'\\r\\n',b'\\n')\n source=source.replace(b'\\r',b'\\n')\n return source\n \n \n \ndef _compile_source(pathname,source):\n source=_normalize_line_endings(source)\n return compile(source,pathname,'exec',dont_inherit=True)\n \n \n \ndef _parse_dostime(d,t):\n return time.mktime((\n (d >>9)+1980,\n (d >>5)&0xF,\n d&0x1F,\n t >>11,\n (t >>5)&0x3F,\n (t&0x1F)*2,\n -1,-1,-1))\n \n \n \n \ndef _get_mtime_and_size_of_source(self,path):\n try:\n \n assert path[-1:]in('c','o')\n path=path[:-1]\n toc_entry=self._get_files()[path]\n \n \n time=toc_entry[5]\n date=toc_entry[6]\n uncompressed_size=toc_entry[3]\n return _parse_dostime(date,time),uncompressed_size\n except(KeyError,IndexError,TypeError):\n return 0,0\n \n \n \n \n \ndef _get_pyc_source(self,path):\n\n assert path[-1:]in('c','o')\n path=path[:-1]\n \n try:\n toc_entry=self._get_files()[path]\n except KeyError:\n return None\n else:\n return _get_data(self.archive,toc_entry)\n \n \n \n \ndef _get_module_code(self,fullname):\n path=_get_module_path(self,fullname)\n import_error=None\n for suffix,isbytecode,ispackage in _zip_searchorder:\n fullpath=path+suffix\n _bootstrap._verbose_message('trying {}{}{}',self.archive,path_sep,fullpath,verbosity=2)\n try:\n toc_entry=self._get_files()[fullpath]\n except KeyError:\n pass\n else:\n modpath=toc_entry[0]\n data=_get_data(self.archive,toc_entry)\n code=None\n if isbytecode:\n try:\n code=_unmarshal_code(self,modpath,fullpath,fullname,data)\n except ImportError as exc:\n import_error=exc\n else:\n code=_compile_source(modpath,data)\n if code is None:\n \n \n continue\n modpath=toc_entry[0]\n return code,ispackage,modpath\n else:\n if import_error:\n msg=f\"module load failed: {import_error}\"\n raise ZipImportError(msg,name=fullname)from import_error\n else:\n raise ZipImportError(f\"can't find module {fullname !r}\",name=fullname)\n", ["_frozen_importlib", "_frozen_importlib_external", "_imp", "_io", "_warnings", "importlib.readers", "marshal", "struct", "sys", "time", "zlib"]], "zlib": [".py", "''\n\n\n\nfrom _zlib_utils import lz_generator,crc32\n\nDEFLATED=8\nDEF_BUF_SIZE=16384\nDEF_MEM_LEVEL=8\nMAX_WBITS=15\nZLIB_RUNTIME_VERSION='1.2.11'\nZLIB_VERSION='1.2.11'\nZ_BEST_COMPRESSION=9\nZ_BEST_SPEED=1\nZ_BLOCK=5\nZ_DEFAULT_COMPRESSION=-1\nZ_DEFAULT_STRATEGY=0\nZ_FILTERED=1\nZ_FINISH=4\nZ_FIXED=4\nZ_FULL_FLUSH=3\nZ_HUFFMAN_ONLY=2\nZ_NO_COMPRESSION=0\nZ_NO_FLUSH=0\nZ_PARTIAL_FLUSH=1\nZ_RLE=3\nZ_SYNC_FLUSH=2\nZ_TREES=6\n\nclass BitIO:\n\n def __init__(self,bytestream=None):\n self.bytestream=bytearray(bytestream or[])\n self.bytenum=0\n self.bitnum=0\n self.revbits=0\n self.position=0\n self.bitcoef=1\n \n @property\n def pos(self):\n return self.bytenum *8+self.bitnum\n \n def read(self,nb,order=\"lsf\",trace=False):\n result=0\n coef=1 if order ==\"lsf\"else 2 **(nb -1)\n for _ in range(nb):\n if self.bitnum ==8:\n if self.bytenum ==len(self.bytestream)-1:\n return None\n self.bytenum +=1\n self.bitnum=0\n mask=2 **self.bitnum\n if trace:\n print(\"byte\",self.bytenum,\"bitnum\",self.bitnum,\n \"bit\",int(bool(mask&self.bytestream[self.bytenum])))\n result +=coef *bool(mask&self.bytestream[self.bytenum])\n self.bitnum +=1\n if order ==\"lsf\":\n coef *=2\n else:\n coef //=2\n return result\n \n def move(self,nb):\n if nb ==0:\n return\n elif nb >0:\n bitpos=self.bitnum+nb\n while bitpos >7:\n self.bytenum +=1\n if self.bytenum ==len(self.bytestream):\n raise Exception(\"can't move {} bits\".format(nb))\n bitpos -=8\n self.bitnum=bitpos\n else:\n bitpos=self.bitnum+nb\n while bitpos <0:\n self.bytenum -=1\n if self.bytenum ==-1:\n raise Exception(\"can't move {} bits\".format(nb))\n bitpos +=8\n self.bitnum=bitpos\n \n def show(self):\n res=\"\"\n for x in self.bytestream:\n s=str(bin(x))[2:]\n s=\"0\"*(8 -len(s))+s\n res +=s+\" \"\n return res\n \n def write(self,*bits):\n for bit in bits:\n self.write_bit(bit)\n \n def write_int(self,value,nb,order=\"lsf\"):\n ''\n v=value\n if value >=2 **nb:\n raise ValueError(\"can't write value on {} bits\".format(nb))\n bits=[]\n while value:\n bits.append(value&1)\n value >>=1\n \n bits=bits+[0]*(nb -len(bits))\n if order !=\"lsf\":\n bits.reverse()\n assert len(bits)==nb\n self.write(*bits)\n \n def write_bit(self,v):\n self.revbits +=self.bitcoef *v\n self.bitcoef *=2\n if self.bitcoef ==256:\n self.flush()\n \n def pad_last(self):\n if self.bitcoef !=1:\n self.flush()\n \n def flush(self):\n self.bytestream.append(self.revbits)\n self.bitcoef=1\n self.revbits=0\n \nclass Error(Exception):\n pass\n \n \nclass ResizeError(Exception):\n pass\n \n \nclass Node:\n\n def __init__(self,char=None,weight=0,level=0):\n self.char=char\n self.is_leaf=char is not None\n self.level=level\n self.weight=weight\n \n def add(self,children):\n self.children=children\n for child in self.children:\n child.parent=self\n child.level=self.level+1\n \n def __repr__(self):\n return f\"\"\n \nclass Tree:\n\n def __init__(self,root):\n self.root=root\n \n def length(self):\n self.root.level=0\n node=self.root\n nb_levels=0\n def set_level(node):\n nonlocal nb_levels\n for child in node.children:\n child.level=node.level+1\n nb_levels=max(nb_levels,child.level)\n if not child.is_leaf:\n set_level(child)\n set_level(self.root)\n return nb_levels\n \n def reduce_tree(self):\n ''\n\n\n \n currentlen=self.length()\n deepest=self.nodes_at(currentlen)\n deepest_leaves=[node for node in deepest if node.is_leaf]\n rightmost_leaf=deepest_leaves[-1]\n sibling=rightmost_leaf.parent.children[0]\n \n \n parent=rightmost_leaf.parent\n grand_parent=parent.parent\n rank=grand_parent.children.index(parent)\n children=grand_parent.children\n children[rank]=rightmost_leaf\n grand_parent.add(children)\n \n \n up_level=rightmost_leaf.level -2\n while up_level >0:\n nodes=self.nodes_at(up_level)\n leaf_nodes=[node for node in nodes if node.is_leaf]\n if leaf_nodes:\n leftmost_leaf=leaf_nodes[0]\n \n parent=leftmost_leaf.parent\n rank=parent.children.index(leftmost_leaf)\n new_node=Node()\n new_node.level=leftmost_leaf.level\n children=[sibling,leftmost_leaf]\n new_node.add(children)\n parent.children[rank]=new_node\n new_node.parent=parent\n break\n else:\n up_level -=1\n if up_level ==0:\n raise ResizeError\n \n def nodes_at(self,level,top=None):\n ''\n res=[]\n if top is None:\n top=self.root\n if top.level ==level:\n res=[top]\n elif not top.is_leaf:\n for child in top.children:\n res +=self.nodes_at(level,child)\n return res\n \n def reduce(self,maxlevels):\n ''\n while self.length()>maxlevels:\n self.reduce_tree()\n \n def codes(self,node=None,code=''):\n ''\n \n if node is None:\n self.dic={}\n node=self.root\n if node.is_leaf:\n self.dic[node.char]=code\n else:\n for i,child in enumerate(node.children):\n self.codes(child,code+str(i))\n return self.dic\n \n \ndef codelengths_from_frequencies(freqs):\n ''\n\n\n\n \n freqs=sorted(freqs.items(),\n key=lambda item:(item[1],-item[0]),reverse=True)\n nodes=[Node(char=key,weight=value)for(key,value)in freqs]\n while len(nodes)>1:\n right,left=nodes.pop(),nodes.pop()\n node=Node(weight=right.weight+left.weight)\n node.add([left,right])\n if not nodes:\n nodes.append(node)\n else:\n pos=0\n while pos node.weight:\n pos +=1\n nodes.insert(pos,node)\n \n top=nodes[0]\n tree=Tree(top)\n tree.reduce(15)\n \n codes=tree.codes()\n \n code_items=list(codes.items())\n code_items.sort(key=lambda item:(len(item[1]),item[0]))\n return[(car,len(value))for car,value in code_items]\n \ndef normalized(codelengths):\n car,codelength=codelengths[0]\n value=0\n codes={car:\"0\"*codelength}\n \n for(newcar,nbits)in codelengths[1:]:\n value +=1\n bvalue=str(bin(value))[2:]\n bvalue=\"0\"*(codelength -len(bvalue))+bvalue\n if nbits >codelength:\n codelength=nbits\n bvalue +=\"0\"*(codelength -len(bvalue))\n value=int(bvalue,2)\n assert len(bvalue)==nbits,(len(bvalue),'!=',nbits,'for',newcar,nbits)\n codes[newcar]=bvalue\n \n return codes\n \ndef make_tree(node,codes):\n if not hasattr(node,\"parent\"):\n node.code=''\n children=[]\n for bit in '01':\n next_code=node.code+bit\n if next_code in codes:\n child=Node(char=codes[next_code])\n else:\n child=Node()\n child.code=next_code\n children.append(child)\n node.add(children)\n for child in children:\n if not child.is_leaf:\n make_tree(child,codes)\n \ndef decompresser(codelengths):\n lengths=list(codelengths.items())\n \n lengths=[x for x in lengths if x[1]>0]\n lengths.sort(key=lambda item:(item[1],item[0]))\n codes=normalized(lengths)\n codes={value:key for key,value in codes.items()}\n root=Node()\n make_tree(root,codes)\n return{\"root\":root,\"codes\":codes}\n \ndef tree_from_codelengths(codelengths):\n return decompresser(codelengths)[\"root\"]\n \nclass error(Exception):\n pass\n \n \nfixed_codelengths={}\nfor car in range(144):\n fixed_codelengths[car]=8\nfor car in range(144,256):\n fixed_codelengths[car]=9\nfor car in range(256,280):\n fixed_codelengths[car]=7\nfor car in range(280,288):\n fixed_codelengths[car]=8\n \nfixed_decomp=decompresser(fixed_codelengths)\nfixed_lit_len_tree=fixed_decomp[\"root\"]\nfixed_lit_len_codes={value:key\nfor(key,value)in fixed_decomp[\"codes\"].items()}\n\ndef decomp_repeat(n):\n if n <=6:\n return[n]\n elif n <=9:\n return[n -3,3]\n elif n <=12:\n return[6,n -6]\n t=[]\n while n >12:\n t.append(6)\n n -=6\n t +=decomp(n)\n return t\n \ndef cl_encode(lengths):\n ''\n \n dic={char:len(code)for(char,code)in lengths.items()}\n items=[dic.get(i,0)for i in range(max(dic)+1)]\n pos=0\n while pos 256:\n \n if child.char <265:\n length=child.char -254\n elif child.char <269:\n length=11+2 *(child.char -265)+reader.read(1)\n elif child.char <273:\n length=19+4 *(child.char -269)+reader.read(2)\n elif child.char <277:\n length=35+8 *(child.char -273)+reader.read(3)\n elif child.char <281:\n length=67+16 *(child.char -277)+reader.read(4)\n elif child.char <285:\n length=131+32 *(child.char -281)+reader.read(5)\n elif child.char ==285:\n length=258\n return(\"length\",length)\n else:\n node=child\n \ndef adler32(source):\n a=1\n b=0\n for byte in source:\n a +=byte\n a %=65521\n b +=a\n b %=65521\n return a,b\n \n \ndef compress_dynamic(out,source,store,lit_len_count,distance_count):\n write_int=out.write_int\n \n \n lit_len_count[256]=1\n \n \n \n \n \n \n lengths=codelengths_from_frequencies(lit_len_count)\n lit_len_codes=normalized(lengths)\n \n HLIT=1+max(lit_len_codes)-257\n \n \n \n \n \n \n coded_lit_len=list(cl_encode(lit_len_codes))\n \n \n distance_codes=normalized(codelengths_from_frequencies(distance_count))\n HDIST=max(distance_codes)\n coded_distance=list(cl_encode(distance_codes))\n \n \n codelengths_count={}\n for coded in coded_lit_len,coded_distance:\n for item in coded:\n length=item[0]if isinstance(item,tuple)else item\n codelengths_count[length]=codelengths_count.get(length,0)+1\n \n \n codelengths_codes=normalized(\n codelengths_from_frequencies(codelengths_count))\n codelengths_dict={char:len(value)\n for(char,value)in codelengths_codes.items()}\n \n alphabet=(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,\n 15)\n \n \n codelengths_list=[codelengths_dict.get(car,0)for car in alphabet]\n \n while codelengths_list[-1]==0:\n codelengths_list.pop()\n HCLEN=len(codelengths_list)-4\n \n out.write(0,1)\n \n write_int(HLIT,5)\n write_int(HDIST,5)\n write_int(HCLEN,4)\n \n \n for length,car in zip(codelengths_list,alphabet):\n write_int(length,3)\n \n \n t=[]\n pr=lambda *args:t.append(args)\n for item in coded_lit_len+coded_distance:\n if isinstance(item,tuple):\n length,extra=item\n code=codelengths_codes[length]\n value,nbits=int(code,2),len(code)\n write_int(value,nbits,order=\"msf\")\n if length ==16:\n write_int(extra,2)\n elif length ==17:\n write_int(extra,3)\n elif length ==18:\n write_int(extra,7)\n else:\n code=codelengths_codes[item]\n value,nbits=int(code,2),len(code)\n write_int(value,nbits,order=\"msf\")\n \n \n for item in store:\n if isinstance(item,tuple):\n length,extra_length,distance,extra_distance=item\n \n code=lit_len_codes[length]\n value,nb=int(code,2),len(code)\n write_int(value,nb,order=\"msf\")\n \n value,nb=extra_length\n if nb:\n write_int(value,nb)\n \n code=distance_codes[distance]\n value,nb=int(code,2),len(code)\n write_int(value,nb,order=\"msf\")\n \n value,nb=extra_distance\n if nb:\n write_int(value,nb)\n else:\n literal=item\n code=lit_len_codes[item]\n value,nb=int(code,2),len(code)\n write_int(value,nb,order=\"msf\")\n \ndef compress_fixed(out,source,items):\n ''\n out.write(1,0)\n \n for item in items:\n if isinstance(item,tuple):\n length,extra_length,distance,extra_distance=item\n \n code=fixed_lit_len_codes[length]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \n value,nb=extra_length\n if nb:\n out.write_int(value,nb)\n \n out.write_int(distance,5,order=\"msf\")\n \n value,nb=extra_distance\n if nb:\n out.write_int(value,nb)\n else:\n literal=item\n code=fixed_lit_len_codes[item]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \ndef compress(data,/,level=-1,wbits=MAX_WBITS):\n\n window_size=32 *1024\n \n \n out=BitIO()\n \n \n out.write_int(8,4)\n size=window_size >>8\n nb=0\n while size >1:\n size >>=1\n nb +=1\n out.write_int(nb,4)\n out.write_int(0x9c,8)\n header=out.bytestream\n compressor=_Compressor(level)\n payload=compressor.compress(data)+compressor.flush()\n a,b=adler32(data)\n checksum=divmod(b,256)+divmod(a,256)\n return header+payload+bytes(checksum)\n \ndef convert32bits(n):\n result=[]\n for _ in range(4):\n n,rest=divmod(n,256)\n result.append(rest)\n return result\n \nclass _Compressor:\n\n def __init__(self,level=-1,method=DEFLATED,wbits=MAX_WBITS,\n memLevel=DEF_MEM_LEVEL,strategy=Z_DEFAULT_STRATEGY,\n zdict=None):\n self.level=level\n self.method=method\n self.wbits=wbits\n self.window_size=32 *1024\n self.memLevel=memLevel\n self.strategy=strategy\n self.zdict=zdict\n self._flushed=False\n \n def compress(self,source):\n \n \n lit_len_count={}\n \n \n distance_count={}\n \n store=[]\n replaced=0\n nb_tuples=0\n \n for item in lz_generator(source,self.window_size):\n if isinstance(item,tuple):\n nb_tuples +=1\n length,distance=item\n replaced +=length\n \n \n length_code,*extra_length=length_to_code(length)\n \n lit_len_count[length_code]=lit_len_count.get(length_code,0)+1\n \n \n \n distance_code,*extra_dist=distance_to_code(distance)\n \n distance_count[distance_code]=\\\n distance_count.get(distance_code,0)+1\n \n \n store.append((length_code,extra_length,distance_code,\n extra_dist))\n else:\n literal=item\n lit_len_count[literal]=lit_len_count.get(literal,0)+1\n store.append(literal)\n \n store.append(256)\n \n \n \n \n score=replaced -100 -(nb_tuples *20 //8)\n \n \n out=BitIO()\n \n out.write(1)\n \n if score <0:\n compress_fixed(out,source,store)\n else:\n compress_dynamic(out,source,store,lit_len_count,distance_count)\n \n \n out.pad_last()\n \n self._compressed=bytes(out.bytestream)\n \n return b''\n \n def flush(self,mode=Z_FINISH):\n if self._flushed:\n raise Error('inconsistent flush state')\n self._flushed=True\n return self._compressed\n \n \ndef compressobj(level=-1,method=DEFLATED,wbits=MAX_WBITS,\nmemLevel=DEF_MEM_LEVEL,strategy=Z_DEFAULT_STRATEGY,\nzdict=None):\n return _Compressor(level,method,wbits,memLevel,strategy,zdict)\n \n \ndef decompress(data,/,wbits=MAX_WBITS,bufsize=DEF_BUF_SIZE):\n if wbits >0:\n decompressor=_Decompressor(wbits,bufsize)\n source=BitIO(data)\n assert source.read(4)==8\n nb=source.read(4)\n window_size=2 **(nb+8)\n assert source.read(8)==0x9c\n checksum=data[-4:]\n a=256 *checksum[2]+checksum[3]\n b=256 *checksum[0]+checksum[1]\n assert a,b ==adler32(data)\n return decompressor.decompress(data[2:-4])\n else:\n decompressor=_Decompressor(-wbits,bufsize)\n return decompressor.decompress(data)\n \nclass _Decompressor:\n\n def __init__(self,wbits=MAX_WBITS,bufsize=DEF_BUF_SIZE,zdict=None):\n self.wbits=wbits\n self.bufsize=bufsize\n self.zdict=zdict\n self.eof=False\n self.unconsumed_tail=b''\n self.unused_data=b''\n \n def decompress(self,data,max_length=0):\n self.data=data\n if data ==b'':\n return data\n \n reader=self._reader=BitIO(data)\n \n result=bytearray()\n \n while True:\n BFINAL=reader.read(1)\n \n BTYPE=reader.read(2)\n \n if BTYPE ==0b01:\n \n \n root=fixed_lit_len_tree\n \n while True:\n \n _type,value=read_literal_or_length(reader,root)\n if _type =='eob':\n break\n elif _type =='literal':\n result.append(value)\n elif _type =='length':\n length=value\n \n dist_code=reader.read(5,\"msf\")\n if dist_code <3:\n distance=dist_code+1\n else:\n nb=(dist_code //2)-1\n extra=reader.read(nb)\n half,delta=divmod(dist_code,2)\n distance=(1+(2 **half)+\n delta *(2 **(half -1))+extra)\n for _ in range(length):\n result.append(result[-distance])\n \n node=root\n else:\n node=child\n elif BTYPE ==0b10:\n \n \n \n lit_len_tree,distance_tree=dynamic_trees(reader)\n \n t=[]\n while True:\n \n _type,value=read_literal_or_length(reader,lit_len_tree)\n if _type =='eob':\n break\n elif _type =='literal':\n result.append(value)\n t.append(value)\n elif _type =='length':\n \n length=value\n distance=read_distance(reader,distance_tree)\n t.append([length,distance])\n for _ in range(length):\n result.append(result[-distance])\n \n if BFINAL:\n rank=reader.bytenum\n self.unused_data=bytes(data[rank+1:])\n self.eof=True\n return bytes(result)\n \ndef decompressobj(wbits=MAX_WBITS,zdict=None):\n return _Decompressor(wbits,zdict)\n", ["_zlib_utils"]], "_aio": [".py", "from browser.aio import run,sleep,Future\n\n\ndef _task(coro,Id,block):\n async def _task():\n block[Id]=None\n try:\n block[Id]=await coro\n except Exception as e:\n block[Id]=e\n \n if not block[Id]:\n del block[Id]\n return _task()\n \n \nasync def gather(*coros,rate=0):\n dones={}\n counts=0\n for c in coros:\n run(_task(c,f'task{counts}',dones))\n counts +=1\n while not all(dones.values()):\n await sleep(rate)\n return dones\n \n \nclass QueueEmpty(Exception):\n pass\n \n \nclass QueueFull(Exception):\n pass\n \n \nclass Queue(object):\n\n def __init__(self,maxsize=0):\n from collections import deque\n self.maxsize=maxsize\n self.data=deque(maxlen=maxsize or None)\n self.readers=deque()\n self.writers=deque()\n self.joiners=deque()\n self.tasks=0\n \n def qsize(self):\n return len(self.data)\n \n def empty(self):\n return self.qsize()==0\n \n def full(self):\n return self.maxsize and self.qsize()==self.maxsize\n \n async def get(self):\n if self.empty():\n future=Future()\n def reader(val):\n future.set_result(val)\n self.readers.append(reader)\n return await future\n \n item=self.get_nowait()\n if self.writers:\n \n writer=self.writers.popleft()\n writer()\n return item\n \n def get_nowait(self):\n try:\n return self.data.popleft()\n except IndexError:\n raise QueueEmpty()\n \n async def put(self,item):\n if self.full():\n future=Future()\n def writer():\n self.put_nowait(item)\n future.set_result(True)\n self.writers.append(writer)\n await future\n return\n \n if self.readers:\n \n self.tasks +=1\n reader=self.readers.popleft()\n reader(item)\n else:\n \n self.put_nowait(item)\n \n def put_nowait(self,item):\n if self.full():\n raise QueueFull()\n self.data.append(item)\n self.tasks +=1\n \n async def join(self):\n if self.tasks >0:\n future=Future()\n def setres():\n future.set_result(True)\n await future\n \n def task_done(self):\n if self.tasks ==0:\n raise ValueError(\"no tasks\")\n self.tasks -=1\n if tasks ==0:\n for joiner in self.joiners:\n joiner()\n", ["browser.aio", "collections"]], "_codecs": [".py", "\ndef ascii_decode(*args,**kw):\n pass\n \ndef ascii_encode(*args,**kw):\n pass\n \ndef charbuffer_encode(*args,**kw):\n pass\n \ndef charmap_build(decoding_table):\n return{car:i for(i,car)in enumerate(decoding_table)}\n \ndef charmap_decode(input,errors,decoding_table):\n res=''\n for car in input:\n code=decoding_table[car]\n if code is None:\n raise UnicodeDecodeError(input)\n res +=code\n return res,len(input)\n \ndef charmap_encode(input,errors,encoding_table):\n t=[]\n for car in input:\n code=encoding_table.get(car)\n if code is None:\n raise UnicodeEncodeError(input)\n t.append(code)\n return bytes(t),len(input)\n \ndef decode(obj,encoding=\"utf-8\",errors=\"strict\"):\n ''\n\n\n\n\n\n \n return __BRYTHON__.decode(obj,encoding,errors)\n \ndef encode(obj,encoding=\"utf-8\",errors=\"strict\"):\n ''\n\n\n\n\n\n \n return __BRYTHON__.encode(obj,encoding,errors)\n \ndef escape_decode(*args,**kw):\n pass\n \ndef escape_encode(*args,**kw):\n pass\n \ndef latin_1_decode(*args,**kw):\n pass\n \ndef latin_1_encode(*args,**kw):\n pass\n \ndef lookup(encoding):\n ''\n\n \n if encoding in('utf-8','utf_8'):\n import encodings.utf_8\n return encodings.utf_8.getregentry()\n \n LookupError(encoding)\n \ndef lookup_error(*args,**kw):\n ''\n\n \n pass\n \ndef mbcs_decode(*args,**kw):\n pass\n \ndef mbcs_encode(*args,**kw):\n pass\n \ndef raw_unicode_escape_decode(*args,**kw):\n pass\n \ndef raw_unicode_escape_encode(*args,**kw):\n pass\n \ndef readbuffer_encode(*args,**kw):\n pass\n \ndef register(*args,**kw):\n ''\n\n\n\n \n pass\n \ndef register_error(*args,**kw):\n ''\n\n\n\n\n \n pass\n \ndef unicode_escape_decode(*args,**kw):\n pass\n \ndef unicode_escape_encode(*args,**kw):\n pass\n \ndef unicode_internal_decode(*args,**kw):\n pass\n \ndef unicode_internal_encode(*args,**kw):\n pass\n \ndef _reader(b,nb,endian):\n pos=0\n while pos 2 **16:\n \n code=cp -2 **16\n hi=0xD800 |(code >>10)\n lo=0xDC00 |(code&0x3FF)\n t +=divmod(hi,256)\n t +=divmod(lo,256)\n else:\n t.append(0)\n t.append(cp)\n \n return bytes(t),len(arg)\n \ndef utf_16_decode(b,errors,*args):\n if b[0]==0xfe and b[1]==0xff:\n return utf_16_le_decode(b[2:],errors,*args)\n return utf_16_le_decode(b,errors,*args)\n \ndef utf_16_encode(arg):\n b=utf_16_le_encode(arg)[0]\n return bytes([0xfe,0xff])+b,len(arg)\n \ndef utf_16_ex_decode(*args,**kw):\n pass\n \ndef utf_16_le_decode(b,errors,*args):\n t=[]\n reader=_reader(b,2,'little')\n for cp in reader:\n if cp <0xd800:\n t.append(chr(cp))\n else:\n hi=cp\n lo=next(reader)\n t.append(chr(_to_codepoint(lo,hi)))\n return ''.join(t),len(t)\n \ndef utf_16_le_encode(arg):\n t=[]\n for char in arg:\n cp=ord(char)\n if cp >2 **16:\n \n code=cp -2 **16\n hi=0xD800 |(code >>10)\n lo=0xDC00 |(code&0x3FF)\n t +=reversed(divmod(hi,256))\n t +=reversed(divmod(lo,256))\n else:\n t.append(cp)\n t.append(0)\n return bytes(t),len(arg)\n \ndef utf_32_be_decode(b,errors,*args):\n t=[]\n reader=_reader(b,4,'big')\n for cp in reader:\n t.append(chr(cp))\n return ''.join(t),len(t)\n \ndef utf_32_be_encode(s):\n res=[]\n for char in s:\n t=[]\n x=ord(char)\n for i in range(4):\n x,y=divmod(x,256)\n t.append(y)\n res +=reversed(t)\n return bytes(res),len(s)\n \ndef utf_32_decode(*args,**kw):\n pass\n \ndef utf_32_encode(*args,**kw):\n pass\n \ndef utf_32_ex_decode(*args,**kw):\n pass\n \ndef utf_32_le_decode(b,errors,*args):\n t=[]\n reader=_reader(b,4,'little')\n for cp in reader:\n t.append(chr(cp))\n return ''.join(t),len(t)\n \ndef utf_32_le_encode(s):\n res=[]\n for char in s:\n t=[]\n x=ord(char)\n for i in range(4):\n x,y=divmod(x,256)\n t.append(y)\n res +=t\n return bytes(res),len(s)\n \ndef utf_7_decode(*args,**kw):\n pass\n \ndef utf_7_encode(*args,**kw):\n pass\n \ndef utf_8_decode(decoder,bytes_obj,errors,*args):\n return(bytes_obj.decode(\"utf-8\"),len(bytes_obj))\n \ndef utf_8_encode(*args,**kw):\n input=args[0]\n if len(args)==2:\n errors=args[1]\n else:\n errors=kw.get('errors','strict')\n \n \n return(bytes(input,'utf-8'),len(input))\n", ["encodings.utf_8"]], "_codecs_jp": [".py", "from encoding_cp932 import encoding_table,decoding_table\n\n\n\nclass Codec:\n\n def encode(self,input,errors='strict'):\n b=[]\n for pos,car in enumerate(input):\n cp=ord(car)\n try:\n code=encoding_table[cp]\n high=((code >>8)&0xff)\n low=code&0xff\n if high:\n b.append(high)\n b.append(low)\n except IndexError:\n raise UnicodeEncodeError(pos)\n return[bytes(b),len(input)]\n \n def decode(self,input,errors='strict'):\n i=0\n string=''\n while i self.maxlen:\n self.popleft()\n \n def appendleft(self,x):\n self.state +=1\n self.leftndx -=1\n if self.leftndx ==-1:\n newblock=[None]*BLOCKSIZ\n self.left[LFTLNK]=newblock\n newblock[RGTLNK]=self.left\n self.left=newblock\n self.leftndx=n -1\n self.length +=1\n self.left[self.leftndx]=x\n if self.maxlen is not None and self.length >self.maxlen:\n self.pop()\n \n def extend(self,iterable):\n if iterable is self:\n iterable=list(iterable)\n for elem in iterable:\n self.append(elem)\n \n def extendleft(self,iterable):\n if iterable is self:\n iterable=list(iterable)\n for elem in iterable:\n self.appendleft(elem)\n \n def pop(self):\n if self.left is self.right and self.leftndx >self.rightndx:\n \n raise IndexError(\"pop from an empty deque\")\n x=self.right[self.rightndx]\n self.right[self.rightndx]=None\n self.length -=1\n self.rightndx -=1\n self.state +=1\n if self.rightndx ==-1:\n prevblock=self.right[LFTLNK]\n if prevblock is None:\n \n self.rightndx=n //2\n self.leftndx=n //2+1\n else:\n prevblock[RGTLNK]=None\n self.right[LFTLNK]=None\n self.right=prevblock\n self.rightndx=n -1\n return x\n \n def popleft(self):\n if self.left is self.right and self.leftndx >self.rightndx:\n \n raise IndexError(\"pop from an empty deque\")\n x=self.left[self.leftndx]\n self.left[self.leftndx]=None\n self.length -=1\n self.leftndx +=1\n self.state +=1\n if self.leftndx ==n:\n prevblock=self.left[RGTLNK]\n if prevblock is None:\n \n self.rightndx=n //2\n self.leftndx=n //2+1\n else:\n prevblock[LFTLNK]=None\n self.left[RGTLNK]=None\n self.left=prevblock\n self.leftndx=0\n return x\n \n def count(self,value):\n c=0\n for item in self:\n if item ==value:\n c +=1\n return c\n \n def remove(self,value):\n \n for i in range(len(self)):\n if self[i]==value:\n del self[i]\n return\n raise ValueError(\"deque.remove(x): x not in deque\")\n \n def rotate(self,n=1):\n length=len(self)\n if length ==0:\n return\n halflen=(length+1)>>1\n if n >halflen or n <-halflen:\n n %=length\n if n >halflen:\n n -=length\n elif n <-halflen:\n n +=length\n while n >0:\n self.appendleft(self.pop())\n n -=1\n while n <0:\n self.append(self.popleft())\n n +=1\n \n def reverse(self):\n ''\n leftblock=self.left\n rightblock=self.right\n leftindex=self.leftndx\n rightindex=self.rightndx\n for i in range(self.length //2):\n \n assert leftblock !=rightblock or leftindex =0:\n block=self.left\n while block:\n l,r=0,n\n if block is self.left:\n l=self.leftndx\n if block is self.right:\n r=self.rightndx+1\n span=r -l\n if index =negative_span:\n return block,r+index\n index -=negative_span\n block=block[LFTLNK]\n raise IndexError(\"deque index out of range\")\n \n def __getitem__(self,index):\n block,index=self.__getref(index)\n return block[index]\n \n def __setitem__(self,index,value):\n block,index=self.__getref(index)\n block[index]=value\n \n def __delitem__(self,index):\n length=len(self)\n if index >=0:\n if index >=length:\n raise IndexError(\"deque index out of range\")\n self.rotate(-index)\n self.popleft()\n self.rotate(index)\n else:\n \n index=index ^(2 **31)\n if index >=length:\n raise IndexError(\"deque index out of range\")\n self.rotate(index)\n self.pop()\n self.rotate(-index)\n \n def __reduce_ex__(self,proto):\n return type(self),(list(self),self.maxlen)\n \n def __hash__(self):\n \n raise TypeError(\"deque objects are unhashable\")\n \n def __copy__(self):\n return self.__class__(self,self.maxlen)\n \n \n def __eq__(self,other):\n if isinstance(other,deque):\n return list(self)==list(other)\n else:\n return NotImplemented\n \n def __ne__(self,other):\n if isinstance(other,deque):\n return list(self)!=list(other)\n else:\n return NotImplemented\n \n def __lt__(self,other):\n if isinstance(other,deque):\n return list(self)list(other)\n else:\n return NotImplemented\n \n def __ge__(self,other):\n if isinstance(other,deque):\n return list(self)>=list(other)\n else:\n return NotImplemented\n \n def __iadd__(self,other):\n self.extend(other)\n return self\n \n \nclass deque_iterator(object):\n\n def __init__(self,deq,itergen):\n self.counter=len(deq)\n def giveup():\n self.counter=0\n \n raise RuntimeError(\"deque mutated during iteration\")\n self._gen=itergen(deq.state,giveup)\n \n def __next__(self):\n res=self._gen.__next__()\n self.counter -=1\n return res\n \n def __iter__(self):\n return self\n \nclass defaultdict(dict):\n\n def __init__(self,*args,**kwds):\n if len(args)>0:\n default_factory=args[0]\n args=args[1:]\n if not callable(default_factory)and default_factory is not None:\n raise TypeError(\"first argument must be callable\")\n else:\n default_factory=None\n dict.__init__(self,*args,**kwds)\n self.default_factory=default_factory\n self.update(*args,**kwds)\n super(defaultdict,self).__init__(*args,**kwds)\n \n def __missing__(self,key):\n \n if self.default_factory is None:\n raise KeyError(key)\n self[key]=value=self.default_factory()\n return value\n \n def __repr__(self,recurse=set()):\n if id(self)in recurse:\n return \"defaultdict(...)\"\n try:\n recurse.add(id(self))\n return \"defaultdict(%s, %s)\"%(repr(self.default_factory),super(defaultdict,self).__repr__())\n finally:\n recurse.remove(id(self))\n \n def copy(self):\n return type(self)(self.default_factory,self)\n \n def __copy__(self):\n return self.copy()\n \n def __reduce__(self):\n \n \n \n \n \n \n \n \n \n \n \n return(type(self),(self.default_factory,),None,None,self.items())\n \nfrom operator import itemgetter as _itemgetter\nfrom keyword import iskeyword as _iskeyword\nimport sys as _sys\n\ndef namedtuple(typename,field_names,verbose=False,rename=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n if isinstance(field_names,str):\n field_names=field_names.replace(',',' ').split()\n field_names=tuple(map(str,field_names))\n if rename:\n names=list(field_names)\n seen=set()\n for i,name in enumerate(names):\n if(not min(c.isalnum()or c =='_'for c in name)or _iskeyword(name)\n or not name or name[0].isdigit()or name.startswith('_')\n or name in seen):\n names[i]='_%d'%i\n seen.add(name)\n field_names=tuple(names)\n for name in(typename,)+field_names:\n if not min(c.isalnum()or c =='_'for c in name):\n raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r'%name)\n if _iskeyword(name):\n raise ValueError('Type names and field names cannot be a keyword: %r'%name)\n if name[0].isdigit():\n raise ValueError('Type names and field names cannot start with a number: %r'%name)\n seen_names=set()\n for name in field_names:\n if name.startswith('_')and not rename:\n raise ValueError('Field names cannot start with an underscore: %r'%name)\n if name in seen_names:\n raise ValueError('Encountered duplicate field name: %r'%name)\n seen_names.add(name)\n \n \n numfields=len(field_names)\n argtxt=repr(field_names).replace(\"'\",\"\")[1:-1]\n reprtxt=', '.join('%s=%%r'%name for name in field_names)\n \n template='''class %(typename)s(tuple):\n '%(typename)s(%(argtxt)s)' \\n\n __slots__ = () \\n\n _fields = %(field_names)r \\n\n def __new__(_cls, %(argtxt)s):\n return tuple.__new__(_cls, (%(argtxt)s)) \\n\n @classmethod\n def _make(cls, iterable, new=tuple.__new__, len=len):\n 'Make a new %(typename)s object from a sequence or iterable'\n result = new(cls, iterable)\n if len(result) != %(numfields)d:\n raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))\n return result \\n\n def __repr__(self):\n return '%(typename)s(%(reprtxt)s)' %% self \\n\n def _asdict(self):\n 'Return a new dict which maps field names to their values'\n return dict(zip(self._fields, self)) \\n\n def _replace(_self, **kwds):\n 'Return a new %(typename)s object replacing specified fields with new values'\n result = _self._make(map(kwds.pop, %(field_names)r, _self))\n if kwds:\n raise ValueError('Got unexpected field names: %%r' %% kwds.keys())\n return result \\n\n def __getnewargs__(self):\n return tuple(self) \\n\\n'''%locals()\n for i,name in enumerate(field_names):\n template +=' %s = _property(_itemgetter(%d))\\n'%(name,i)\n \n if verbose:\n print(template)\n \n \n namespace=dict(_itemgetter=_itemgetter,__name__='namedtuple_%s'%typename,\n _property=property,_tuple=tuple)\n try:\n exec(template,namespace)\n except SyntaxError as e:\n raise SyntaxError(e.message+':\\n'+template)\n result=namespace[typename]\n \n \n \n \n \n try:\n result.__module__=_sys._getframe(1).f_globals.get('__name__','__main__')\n except(AttributeError,ValueError):\n pass\n \n return result\n \nif __name__ =='__main__':\n Point=namedtuple('Point',['x','y'])\n p=Point(11,y=22)\n print(p[0]+p[1])\n x,y=p\n print(x,y)\n print(p.x+p.y)\n print(p)\n", ["keyword", "operator", "sys"]], "_collections_abc": [".py", "\n\n\n\"\"\"Abstract Base Classes (ABCs) for collections, according to PEP 3119.\n\nUnit tests are in test_collections.\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom abc import ABCMeta,abstractmethod\nimport sys\n\nGenericAlias=type(list[int])\nEllipsisType=type(...)\ndef _f():pass\nFunctionType=type(_f)\ndel _f\n\n__all__=[\"Awaitable\",\"Coroutine\",\n\"AsyncIterable\",\"AsyncIterator\",\"AsyncGenerator\",\n\"Hashable\",\"Iterable\",\"Iterator\",\"Generator\",\"Reversible\",\n\"Sized\",\"Container\",\"Callable\",\"Collection\",\n\"Set\",\"MutableSet\",\n\"Mapping\",\"MutableMapping\",\n\"MappingView\",\"KeysView\",\"ItemsView\",\"ValuesView\",\n\"Sequence\",\"MutableSequence\",\n\"ByteString\",\"Buffer\",\n]\n\n\n\n\n\n__name__=\"collections.abc\"\n\n\n\n\n\n\n\n\nbytes_iterator=type(iter(b''))\nbytearray_iterator=type(iter(bytearray()))\n\ndict_keyiterator=type(iter({}.keys()))\ndict_valueiterator=type(iter({}.values()))\ndict_itemiterator=type(iter({}.items()))\nlist_iterator=type(iter([]))\nlist_reverseiterator=type(iter(reversed([])))\nrange_iterator=type(iter(range(0)))\nlongrange_iterator=type(iter(range(1 <<1000)))\nset_iterator=type(iter(set()))\nstr_iterator=type(iter(\"\"))\ntuple_iterator=type(iter(()))\nzip_iterator=type(iter(zip()))\n\ndict_keys=type({}.keys())\ndict_values=type({}.values())\ndict_items=type({}.items())\n\nmappingproxy=type(type.__dict__)\ngenerator=type((lambda:(yield))())\n\nasync def _coro():pass\n_coro=_coro()\ncoroutine=type(_coro)\n_coro.close()\ndel _coro\n\nasync def _ag():yield\n_ag=_ag()\nasync_generator=type(_ag)\ndel _ag\n\n\n\n\ndef _check_methods(C,*methods):\n mro=C.__mro__\n for method in methods:\n for B in mro:\n if method in B.__dict__:\n if B.__dict__[method]is None:\n return NotImplemented\n break\n else:\n return NotImplemented\n return True\n \nclass Hashable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __hash__(self):\n return 0\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Hashable:\n return _check_methods(C,\"__hash__\")\n return NotImplemented\n \n \nclass Awaitable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __await__(self):\n yield\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Awaitable:\n return _check_methods(C,\"__await__\")\n return NotImplemented\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass Coroutine(Awaitable):\n\n __slots__=()\n \n @abstractmethod\n def send(self,value):\n ''\n\n \n raise StopIteration\n \n @abstractmethod\n def throw(self,typ,val=None,tb=None):\n ''\n\n \n if val is None:\n if tb is None:\n raise typ\n val=typ()\n if tb is not None:\n val=val.with_traceback(tb)\n raise val\n \n def close(self):\n ''\n \n try:\n self.throw(GeneratorExit)\n except(GeneratorExit,StopIteration):\n pass\n else:\n raise RuntimeError(\"coroutine ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Coroutine:\n return _check_methods(C,'__await__','send','throw','close')\n return NotImplemented\n \n \nCoroutine.register(coroutine)\n\n\nclass AsyncIterable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __aiter__(self):\n return AsyncIterator()\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncIterable:\n return _check_methods(C,\"__aiter__\")\n return NotImplemented\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass AsyncIterator(AsyncIterable):\n\n __slots__=()\n \n @abstractmethod\n async def __anext__(self):\n ''\n raise StopAsyncIteration\n \n def __aiter__(self):\n return self\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncIterator:\n return _check_methods(C,\"__anext__\",\"__aiter__\")\n return NotImplemented\n \n \nclass AsyncGenerator(AsyncIterator):\n\n __slots__=()\n \n async def __anext__(self):\n ''\n\n \n return await self.asend(None)\n \n @abstractmethod\n async def asend(self,value):\n ''\n\n \n raise StopAsyncIteration\n \n @abstractmethod\n async def athrow(self,typ,val=None,tb=None):\n ''\n\n \n if val is None:\n if tb is None:\n raise typ\n val=typ()\n if tb is not None:\n val=val.with_traceback(tb)\n raise val\n \n async def aclose(self):\n ''\n \n try:\n await self.athrow(GeneratorExit)\n except(GeneratorExit,StopAsyncIteration):\n pass\n else:\n raise RuntimeError(\"asynchronous generator ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncGenerator:\n return _check_methods(C,'__aiter__','__anext__',\n 'asend','athrow','aclose')\n return NotImplemented\n \n \nAsyncGenerator.register(async_generator)\n\n\nclass Iterable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __iter__(self):\n while False:\n yield None\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Iterable:\n return _check_methods(C,\"__iter__\")\n return NotImplemented\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass Iterator(Iterable):\n\n __slots__=()\n \n @abstractmethod\n def __next__(self):\n ''\n raise StopIteration\n \n def __iter__(self):\n return self\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Iterator:\n return _check_methods(C,'__iter__','__next__')\n return NotImplemented\n \n \nIterator.register(bytes_iterator)\nIterator.register(bytearray_iterator)\n\nIterator.register(dict_keyiterator)\nIterator.register(dict_valueiterator)\nIterator.register(dict_itemiterator)\nIterator.register(list_iterator)\nIterator.register(list_reverseiterator)\nIterator.register(range_iterator)\nIterator.register(longrange_iterator)\nIterator.register(set_iterator)\nIterator.register(str_iterator)\nIterator.register(tuple_iterator)\nIterator.register(zip_iterator)\n\n\nclass Reversible(Iterable):\n\n __slots__=()\n \n @abstractmethod\n def __reversed__(self):\n while False:\n yield None\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Reversible:\n return _check_methods(C,\"__reversed__\",\"__iter__\")\n return NotImplemented\n \n \nclass Generator(Iterator):\n\n __slots__=()\n \n def __next__(self):\n ''\n\n \n return self.send(None)\n \n @abstractmethod\n def send(self,value):\n ''\n\n \n raise StopIteration\n \n @abstractmethod\n def throw(self,typ,val=None,tb=None):\n ''\n\n \n if val is None:\n if tb is None:\n raise typ\n val=typ()\n if tb is not None:\n val=val.with_traceback(tb)\n raise val\n \n def close(self):\n ''\n \n try:\n self.throw(GeneratorExit)\n except(GeneratorExit,StopIteration):\n pass\n else:\n raise RuntimeError(\"generator ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Generator:\n return _check_methods(C,'__iter__','__next__',\n 'send','throw','close')\n return NotImplemented\n \n \nGenerator.register(generator)\n\n\nclass Sized(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __len__(self):\n return 0\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Sized:\n return _check_methods(C,\"__len__\")\n return NotImplemented\n \n \nclass Container(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __contains__(self,x):\n return False\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Container:\n return _check_methods(C,\"__contains__\")\n return NotImplemented\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass Collection(Sized,Iterable,Container):\n\n __slots__=()\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Collection:\n return _check_methods(C,\"__len__\",\"__iter__\",\"__contains__\")\n return NotImplemented\n \n \nclass Buffer(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __buffer__(self,flags:int,/)->memoryview:\n raise NotImplementedError\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Buffer:\n return _check_methods(C,\"__buffer__\")\n return NotImplemented\n \n \nclass _CallableGenericAlias(GenericAlias):\n ''\n\n\n\n\n\n\n \n \n __slots__=()\n \n def __new__(cls,origin,args):\n if not(isinstance(args,tuple)and len(args)==2):\n raise TypeError(\n \"Callable must be used as Callable[[arg, ...], result].\")\n t_args,t_result=args\n if isinstance(t_args,(tuple,list)):\n args=(*t_args,t_result)\n elif not _is_param_expr(t_args):\n raise TypeError(f\"Expected a list of types, an ellipsis, \"\n f\"ParamSpec, or Concatenate. Got {t_args}\")\n return super().__new__(cls,origin,args)\n \n def __repr__(self):\n if len(self.__args__)==2 and _is_param_expr(self.__args__[0]):\n return super().__repr__()\n return(f'collections.abc.Callable'\n f'[[{\", \".join([_type_repr(a)for a in self.__args__[:-1]])}], '\n f'{_type_repr(self.__args__[-1])}]')\n \n def __reduce__(self):\n args=self.__args__\n if not(len(args)==2 and _is_param_expr(args[0])):\n args=list(args[:-1]),args[-1]\n return _CallableGenericAlias,(Callable,args)\n \n def __getitem__(self,item):\n \n \n \n \n if not isinstance(item,tuple):\n item=(item,)\n \n new_args=super().__getitem__(item).__args__\n \n \n if not isinstance(new_args[0],(tuple,list)):\n t_result=new_args[-1]\n t_args=new_args[:-1]\n new_args=(t_args,t_result)\n return _CallableGenericAlias(Callable,tuple(new_args))\n \ndef _is_param_expr(obj):\n ''\n\n \n if obj is Ellipsis:\n return True\n if isinstance(obj,list):\n return True\n obj=type(obj)\n names=('ParamSpec','_ConcatenateGenericAlias')\n return obj.__module__ =='typing'and any(obj.__name__ ==name for name in names)\n \ndef _type_repr(obj):\n ''\n\n\n\n\n \n if isinstance(obj,type):\n if obj.__module__ =='builtins':\n return obj.__qualname__\n return f'{obj.__module__}.{obj.__qualname__}'\n if obj is Ellipsis:\n return '...'\n if isinstance(obj,FunctionType):\n return obj.__name__\n return repr(obj)\n \n \nclass Callable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __call__(self,*args,**kwds):\n return False\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Callable:\n return _check_methods(C,\"__call__\")\n return NotImplemented\n \n __class_getitem__=classmethod(_CallableGenericAlias)\n \n \n \n \n \nclass Set(Collection):\n ''\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n def __le__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n if len(self)>len(other):\n return False\n for elem in self:\n if elem not in other:\n return False\n return True\n \n def __lt__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n return len(self)len(other)and self.__ge__(other)\n \n def __ge__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n if len(self)>11)^(h >>25)\n h=h *69069+907133923\n h &=MASK\n if h >MAX:\n h -=MASK+1\n if h ==-1:\n h=590923713\n return h\n \n \nSet.register(frozenset)\n\n\nclass MutableSet(Set):\n ''\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def add(self,value):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def discard(self,value):\n ''\n raise NotImplementedError\n \n def remove(self,value):\n ''\n if value not in self:\n raise KeyError(value)\n self.discard(value)\n \n def pop(self):\n ''\n it=iter(self)\n try:\n value=next(it)\n except StopIteration:\n raise KeyError from None\n self.discard(value)\n return value\n \n def clear(self):\n ''\n try:\n while True:\n self.pop()\n except KeyError:\n pass\n \n def __ior__(self,it):\n for value in it:\n self.add(value)\n return self\n \n def __iand__(self,it):\n for value in(self -it):\n self.discard(value)\n return self\n \n def __ixor__(self,it):\n if it is self:\n self.clear()\n else:\n if not isinstance(it,Set):\n it=self._from_iterable(it)\n for value in it:\n if value in self:\n self.discard(value)\n else:\n self.add(value)\n return self\n \n def __isub__(self,it):\n if it is self:\n self.clear()\n else:\n for value in it:\n self.discard(value)\n return self\n \n \nMutableSet.register(set)\n\n\n\n\nclass Mapping(Collection):\n ''\n\n\n\n\n \n \n __slots__=()\n \n \n __abc_tpflags__=1 <<6\n \n @abstractmethod\n def __getitem__(self,key):\n raise KeyError\n \n def get(self,key,default=None):\n ''\n try:\n return self[key]\n except KeyError:\n return default\n \n def __contains__(self,key):\n try:\n self[key]\n except KeyError:\n return False\n else:\n return True\n \n def keys(self):\n ''\n return KeysView(self)\n \n def items(self):\n ''\n return ItemsView(self)\n \n def values(self):\n ''\n return ValuesView(self)\n \n def __eq__(self,other):\n if not isinstance(other,Mapping):\n return NotImplemented\n return dict(self.items())==dict(other.items())\n \n __reversed__=None\n \nMapping.register(mappingproxy)\n\n\nclass MappingView(Sized):\n\n __slots__='_mapping',\n \n def __init__(self,mapping):\n self._mapping=mapping\n \n def __len__(self):\n return len(self._mapping)\n \n def __repr__(self):\n return '{0.__class__.__name__}({0._mapping!r})'.format(self)\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass KeysView(MappingView,Set):\n\n __slots__=()\n \n @classmethod\n def _from_iterable(cls,it):\n return set(it)\n \n def __contains__(self,key):\n return key in self._mapping\n \n def __iter__(self):\n yield from self._mapping\n \n \nKeysView.register(dict_keys)\n\n\nclass ItemsView(MappingView,Set):\n\n __slots__=()\n \n @classmethod\n def _from_iterable(cls,it):\n return set(it)\n \n def __contains__(self,item):\n key,value=item\n try:\n v=self._mapping[key]\n except KeyError:\n return False\n else:\n return v is value or v ==value\n \n def __iter__(self):\n for key in self._mapping:\n yield(key,self._mapping[key])\n \n \nItemsView.register(dict_items)\n\n\nclass ValuesView(MappingView,Collection):\n\n __slots__=()\n \n def __contains__(self,value):\n for key in self._mapping:\n v=self._mapping[key]\n if v is value or v ==value:\n return True\n return False\n \n def __iter__(self):\n for key in self._mapping:\n yield self._mapping[key]\n \n \nValuesView.register(dict_values)\n\n\nclass MutableMapping(Mapping):\n ''\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __setitem__(self,key,value):\n raise KeyError\n \n @abstractmethod\n def __delitem__(self,key):\n raise KeyError\n \n __marker=object()\n \n def pop(self,key,default=__marker):\n ''\n\n \n try:\n value=self[key]\n except KeyError:\n if default is self.__marker:\n raise\n return default\n else:\n del self[key]\n return value\n \n def popitem(self):\n ''\n\n \n try:\n key=next(iter(self))\n except StopIteration:\n raise KeyError from None\n value=self[key]\n del self[key]\n return key,value\n \n def clear(self):\n ''\n try:\n while True:\n self.popitem()\n except KeyError:\n pass\n \n def update(self,other=(),/,**kwds):\n ''\n\n\n\n \n if isinstance(other,Mapping):\n for key in other:\n self[key]=other[key]\n elif hasattr(other,\"keys\"):\n for key in other.keys():\n self[key]=other[key]\n else:\n for key,value in other:\n self[key]=value\n for key,value in kwds.items():\n self[key]=value\n \n def setdefault(self,key,default=None):\n ''\n try:\n return self[key]\n except KeyError:\n self[key]=default\n return default\n \n \nMutableMapping.register(dict)\n\n\n\n\nclass Sequence(Reversible,Collection):\n ''\n\n\n\n \n \n __slots__=()\n \n \n __abc_tpflags__=1 <<5\n \n @abstractmethod\n def __getitem__(self,index):\n raise IndexError\n \n def __iter__(self):\n i=0\n try:\n while True:\n v=self[i]\n yield v\n i +=1\n except IndexError:\n return\n \n def __contains__(self,value):\n for v in self:\n if v is value or v ==value:\n return True\n return False\n \n def __reversed__(self):\n for i in reversed(range(len(self))):\n yield self[i]\n \n def index(self,value,start=0,stop=None):\n ''\n\n\n\n\n \n if start is not None and start <0:\n start=max(len(self)+start,0)\n if stop is not None and stop <0:\n stop +=len(self)\n \n i=start\n while stop is None or i ANSIColors:\n if colorize or can_colorize():\n return ANSIColors()\n else:\n return NoColors\n \n \ndef can_colorize()->bool:\n if sys.platform ==\"win32\":\n try:\n import nt\n \n if not nt._supports_virtual_terminal():\n return False\n except(ImportError,AttributeError):\n return False\n if not sys.flags.ignore_environment:\n if os.environ.get(\"PYTHON_COLORS\")==\"0\":\n return False\n if os.environ.get(\"PYTHON_COLORS\")==\"1\":\n return True\n if \"NO_COLOR\"in os.environ:\n return False\n if not COLORIZE:\n return False\n if not sys.flags.ignore_environment:\n if \"FORCE_COLOR\"in os.environ:\n return True\n if os.environ.get(\"TERM\")==\"dumb\":\n return False\n \n if not hasattr(sys.stderr,\"fileno\"):\n return False\n \n try:\n return os.isatty(sys.stderr.fileno())\n except io.UnsupportedOperation:\n return sys.stderr.isatty()\n", ["io", "nt", "os", "sys"]], "_compat_pickle": [".py", "\n\n\n\n\n\n\nIMPORT_MAPPING={\n'__builtin__':'builtins',\n'copy_reg':'copyreg',\n'Queue':'queue',\n'SocketServer':'socketserver',\n'ConfigParser':'configparser',\n'repr':'reprlib',\n'tkFileDialog':'tkinter.filedialog',\n'tkSimpleDialog':'tkinter.simpledialog',\n'tkColorChooser':'tkinter.colorchooser',\n'tkCommonDialog':'tkinter.commondialog',\n'Dialog':'tkinter.dialog',\n'Tkdnd':'tkinter.dnd',\n'tkFont':'tkinter.font',\n'tkMessageBox':'tkinter.messagebox',\n'ScrolledText':'tkinter.scrolledtext',\n'Tkconstants':'tkinter.constants',\n'ttk':'tkinter.ttk',\n'Tkinter':'tkinter',\n'markupbase':'_markupbase',\n'_winreg':'winreg',\n'thread':'_thread',\n'dummy_thread':'_dummy_thread',\n'dbhash':'dbm.bsd',\n'dumbdbm':'dbm.dumb',\n'dbm':'dbm.ndbm',\n'gdbm':'dbm.gnu',\n'xmlrpclib':'xmlrpc.client',\n'SimpleXMLRPCServer':'xmlrpc.server',\n'httplib':'http.client',\n'htmlentitydefs':'html.entities',\n'HTMLParser':'html.parser',\n'Cookie':'http.cookies',\n'cookielib':'http.cookiejar',\n'BaseHTTPServer':'http.server',\n'test.test_support':'test.support',\n'commands':'subprocess',\n'urlparse':'urllib.parse',\n'robotparser':'urllib.robotparser',\n'urllib2':'urllib.request',\n'anydbm':'dbm',\n'_abcoll':'collections.abc',\n}\n\n\n\n\n\nNAME_MAPPING={\n('__builtin__','xrange'):('builtins','range'),\n('__builtin__','reduce'):('functools','reduce'),\n('__builtin__','intern'):('sys','intern'),\n('__builtin__','unichr'):('builtins','chr'),\n('__builtin__','unicode'):('builtins','str'),\n('__builtin__','long'):('builtins','int'),\n('itertools','izip'):('builtins','zip'),\n('itertools','imap'):('builtins','map'),\n('itertools','ifilter'):('builtins','filter'),\n('itertools','ifilterfalse'):('itertools','filterfalse'),\n('itertools','izip_longest'):('itertools','zip_longest'),\n('UserDict','IterableUserDict'):('collections','UserDict'),\n('UserList','UserList'):('collections','UserList'),\n('UserString','UserString'):('collections','UserString'),\n('whichdb','whichdb'):('dbm','whichdb'),\n('_socket','fromfd'):('socket','fromfd'),\n('_multiprocessing','Connection'):('multiprocessing.connection','Connection'),\n('multiprocessing.process','Process'):('multiprocessing.context','Process'),\n('multiprocessing.forking','Popen'):('multiprocessing.popen_fork','Popen'),\n('urllib','ContentTooShortError'):('urllib.error','ContentTooShortError'),\n('urllib','getproxies'):('urllib.request','getproxies'),\n('urllib','pathname2url'):('urllib.request','pathname2url'),\n('urllib','quote_plus'):('urllib.parse','quote_plus'),\n('urllib','quote'):('urllib.parse','quote'),\n('urllib','unquote_plus'):('urllib.parse','unquote_plus'),\n('urllib','unquote'):('urllib.parse','unquote'),\n('urllib','url2pathname'):('urllib.request','url2pathname'),\n('urllib','urlcleanup'):('urllib.request','urlcleanup'),\n('urllib','urlencode'):('urllib.parse','urlencode'),\n('urllib','urlopen'):('urllib.request','urlopen'),\n('urllib','urlretrieve'):('urllib.request','urlretrieve'),\n('urllib2','HTTPError'):('urllib.error','HTTPError'),\n('urllib2','URLError'):('urllib.error','URLError'),\n}\n\nPYTHON2_EXCEPTIONS=(\n\"ArithmeticError\",\n\"AssertionError\",\n\"AttributeError\",\n\"BaseException\",\n\"BufferError\",\n\"BytesWarning\",\n\"DeprecationWarning\",\n\"EOFError\",\n\"EnvironmentError\",\n\"Exception\",\n\"FloatingPointError\",\n\"FutureWarning\",\n\"GeneratorExit\",\n\"IOError\",\n\"ImportError\",\n\"ImportWarning\",\n\"IndentationError\",\n\"IndexError\",\n\"KeyError\",\n\"KeyboardInterrupt\",\n\"LookupError\",\n\"MemoryError\",\n\"NameError\",\n\"NotImplementedError\",\n\"OSError\",\n\"OverflowError\",\n\"PendingDeprecationWarning\",\n\"ReferenceError\",\n\"RuntimeError\",\n\"RuntimeWarning\",\n\n\"StopIteration\",\n\"SyntaxError\",\n\"SyntaxWarning\",\n\"SystemError\",\n\"SystemExit\",\n\"TabError\",\n\"TypeError\",\n\"UnboundLocalError\",\n\"UnicodeDecodeError\",\n\"UnicodeEncodeError\",\n\"UnicodeError\",\n\"UnicodeTranslateError\",\n\"UnicodeWarning\",\n\"UserWarning\",\n\"ValueError\",\n\"Warning\",\n\"ZeroDivisionError\",\n)\n\ntry:\n WindowsError\nexcept NameError:\n pass\nelse:\n PYTHON2_EXCEPTIONS +=(\"WindowsError\",)\n \nfor excname in PYTHON2_EXCEPTIONS:\n NAME_MAPPING[(\"exceptions\",excname)]=(\"builtins\",excname)\n \nMULTIPROCESSING_EXCEPTIONS=(\n'AuthenticationError',\n'BufferTooShort',\n'ProcessError',\n'TimeoutError',\n)\n\nfor excname in MULTIPROCESSING_EXCEPTIONS:\n NAME_MAPPING[(\"multiprocessing\",excname)]=(\"multiprocessing.context\",excname)\n \n \nREVERSE_IMPORT_MAPPING=dict((v,k)for(k,v)in IMPORT_MAPPING.items())\nassert len(REVERSE_IMPORT_MAPPING)==len(IMPORT_MAPPING)\nREVERSE_NAME_MAPPING=dict((v,k)for(k,v)in NAME_MAPPING.items())\nassert len(REVERSE_NAME_MAPPING)==len(NAME_MAPPING)\n\n\n\nIMPORT_MAPPING.update({\n'cPickle':'pickle',\n'_elementtree':'xml.etree.ElementTree',\n'FileDialog':'tkinter.filedialog',\n'SimpleDialog':'tkinter.simpledialog',\n'DocXMLRPCServer':'xmlrpc.server',\n'SimpleHTTPServer':'http.server',\n'CGIHTTPServer':'http.server',\n\n'UserDict':'collections',\n'UserList':'collections',\n'UserString':'collections',\n'whichdb':'dbm',\n'StringIO':'io',\n'cStringIO':'io',\n})\n\nREVERSE_IMPORT_MAPPING.update({\n'_bz2':'bz2',\n'_dbm':'dbm',\n'_functools':'functools',\n'_gdbm':'gdbm',\n'_pickle':'pickle',\n})\n\nNAME_MAPPING.update({\n('__builtin__','basestring'):('builtins','str'),\n('exceptions','StandardError'):('builtins','Exception'),\n('UserDict','UserDict'):('collections','UserDict'),\n('socket','_socketobject'):('socket','SocketType'),\n})\n\nREVERSE_NAME_MAPPING.update({\n('_functools','reduce'):('__builtin__','reduce'),\n('tkinter.filedialog','FileDialog'):('FileDialog','FileDialog'),\n('tkinter.filedialog','LoadFileDialog'):('FileDialog','LoadFileDialog'),\n('tkinter.filedialog','SaveFileDialog'):('FileDialog','SaveFileDialog'),\n('tkinter.simpledialog','SimpleDialog'):('SimpleDialog','SimpleDialog'),\n('xmlrpc.server','ServerHTMLDoc'):('DocXMLRPCServer','ServerHTMLDoc'),\n('xmlrpc.server','XMLRPCDocGenerator'):\n('DocXMLRPCServer','XMLRPCDocGenerator'),\n('xmlrpc.server','DocXMLRPCRequestHandler'):\n('DocXMLRPCServer','DocXMLRPCRequestHandler'),\n('xmlrpc.server','DocXMLRPCServer'):\n('DocXMLRPCServer','DocXMLRPCServer'),\n('xmlrpc.server','DocCGIXMLRPCRequestHandler'):\n('DocXMLRPCServer','DocCGIXMLRPCRequestHandler'),\n('http.server','SimpleHTTPRequestHandler'):\n('SimpleHTTPServer','SimpleHTTPRequestHandler'),\n('http.server','CGIHTTPRequestHandler'):\n('CGIHTTPServer','CGIHTTPRequestHandler'),\n('_socket','socket'):('socket','_socketobject'),\n})\n\nPYTHON3_OSERROR_EXCEPTIONS=(\n'BrokenPipeError',\n'ChildProcessError',\n'ConnectionAbortedError',\n'ConnectionError',\n'ConnectionRefusedError',\n'ConnectionResetError',\n'FileExistsError',\n'FileNotFoundError',\n'InterruptedError',\n'IsADirectoryError',\n'NotADirectoryError',\n'PermissionError',\n'ProcessLookupError',\n'TimeoutError',\n)\n\nfor excname in PYTHON3_OSERROR_EXCEPTIONS:\n REVERSE_NAME_MAPPING[('builtins',excname)]=('exceptions','OSError')\n \nPYTHON3_IMPORTERROR_EXCEPTIONS=(\n'ModuleNotFoundError',\n)\n\nfor excname in PYTHON3_IMPORTERROR_EXCEPTIONS:\n REVERSE_NAME_MAPPING[('builtins',excname)]=('exceptions','ImportError')\ndel excname\n", []], "_compression": [".py", "''\n\nimport io\nimport sys\n\nBUFFER_SIZE=io.DEFAULT_BUFFER_SIZE\n\n\nclass BaseStream(io.BufferedIOBase):\n ''\n \n def _check_not_closed(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file\")\n \n def _check_can_read(self):\n if not self.readable():\n raise io.UnsupportedOperation(\"File not open for reading\")\n \n def _check_can_write(self):\n if not self.writable():\n raise io.UnsupportedOperation(\"File not open for writing\")\n \n def _check_can_seek(self):\n if not self.readable():\n raise io.UnsupportedOperation(\"Seeking is only supported \"\n \"on files open for reading\")\n if not self.seekable():\n raise io.UnsupportedOperation(\"The underlying file object \"\n \"does not support seeking\")\n \n \nclass DecompressReader(io.RawIOBase):\n ''\n \n def readable(self):\n return True\n \n def __init__(self,fp,decomp_factory,trailing_error=(),**decomp_args):\n self._fp=fp\n self._eof=False\n self._pos=0\n \n \n self._size=-1\n \n \n \n \n \n self._decomp_factory=decomp_factory\n self._decomp_args=decomp_args\n self._decompressor=self._decomp_factory(**self._decomp_args)\n \n \n \n self._trailing_error=trailing_error\n \n def close(self):\n self._decompressor=None\n return super().close()\n \n def seekable(self):\n return self._fp.seekable()\n \n def readinto(self,b):\n with memoryview(b)as view,view.cast(\"B\")as byte_view:\n data=self.read(len(byte_view))\n byte_view[:len(data)]=data\n return len(data)\n \n def read(self,size=-1):\n if size <0:\n return self.readall()\n \n if not size or self._eof:\n return b\"\"\n data=None\n \n \n while True:\n if self._decompressor.eof:\n rawblock=(self._decompressor.unused_data or\n self._fp.read(BUFFER_SIZE))\n if not rawblock:\n break\n \n self._decompressor=self._decomp_factory(\n **self._decomp_args)\n try:\n data=self._decompressor.decompress(rawblock,size)\n except self._trailing_error:\n \n break\n else:\n if self._decompressor.needs_input:\n rawblock=self._fp.read(BUFFER_SIZE)\n if not rawblock:\n raise EOFError(\"Compressed file ended before the \"\n \"end-of-stream marker was reached\")\n else:\n rawblock=b\"\"\n data=self._decompressor.decompress(rawblock,size)\n if data:\n break\n if not data:\n self._eof=True\n self._size=self._pos\n return b\"\"\n self._pos +=len(data)\n return data\n \n def readall(self):\n chunks=[]\n \n \n \n while data :=self.read(sys.maxsize):\n chunks.append(data)\n \n return b\"\".join(chunks)\n \n \n def _rewind(self):\n self._fp.seek(0)\n self._eof=False\n self._pos=0\n self._decompressor=self._decomp_factory(**self._decomp_args)\n \n def seek(self,offset,whence=io.SEEK_SET):\n \n if whence ==io.SEEK_SET:\n pass\n elif whence ==io.SEEK_CUR:\n offset=self._pos+offset\n elif whence ==io.SEEK_END:\n \n if self._size <0:\n while self.read(io.DEFAULT_BUFFER_SIZE):\n pass\n offset=self._size+offset\n else:\n raise ValueError(\"Invalid value for whence: {}\".format(whence))\n \n \n if offset 0:\n data=self.read(min(io.DEFAULT_BUFFER_SIZE,offset))\n if not data:\n break\n offset -=len(data)\n \n return self._pos\n \n def tell(self):\n ''\n return self._pos\n", ["io", "sys"]], "_contextvars": [".py", "''\n\n\nclass Context(object):\n\n __contains__=\"\"\n \n copy=\"\"\n \n def get(self,*args):\n pass\n \n items=\"\"\n \n keys=\"\"\n \n run=\"\"\n \n values=\"\"\n \nclass ContextVar:\n\n def __init__(self,name,**kw):\n ''\n self.name=name\n if \"default\"in kw:\n self.default=kw[\"default\"]\n \n def get(self,*args):\n if hasattr(self,\"value\"):\n return self.value\n elif len(args)==1:\n return args[0]\n elif hasattr(self,\"default\"):\n return self.default\n raise LookupError(self.name)\n \n def reset(self,token):\n if token.old_value ==Token.MISSING:\n del self.value\n else:\n self.value=token.old_value\n \n def set(self,value):\n self.value=value\n return Token(self)\n \nclass Token(object):\n\n MISSING=\"\"\n \n def __init__(self,contextvar):\n self.var=contextvar\n try:\n self.old_value=contextvar.get()\n except LookupError:\n self.old_value=Token.MISSING\n \ndef copy_context(*args,**kw):\n pass\n", []], "_csv": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__=\"1.0\"\n\nQUOTE_MINIMAL,QUOTE_ALL,QUOTE_NONNUMERIC,QUOTE_NONE,QUOTE_STRINGS,QUOTE_NOTNULL=range(6)\n_dialects={}\n_field_limit=128 *1024\n\nclass Error(Exception):\n pass\n \nclass Dialect(object):\n ''\n\n \n \n __slots__=[\"_delimiter\",\"_doublequote\",\"_escapechar\",\n \"_lineterminator\",\"_quotechar\",\"_quoting\",\n \"_skipinitialspace\",\"_strict\"]\n \n def __new__(cls,dialect,**kwargs):\n \n for name in kwargs:\n if '_'+name not in Dialect.__slots__:\n raise TypeError(\"unexpected keyword argument '%s'\"%\n (name,))\n \n if dialect is not None:\n if isinstance(dialect,str):\n dialect=get_dialect(dialect)\n \n \n if(isinstance(dialect,Dialect)\n and all(value is None for value in kwargs.values())):\n return dialect\n \n self=object.__new__(cls)\n \n \n def set_char(x):\n if x is None:\n return None\n if isinstance(x,str)and len(x)<=1:\n return x\n raise TypeError(\"%r must be a 1-character string\"%(name,))\n def set_str(x):\n if isinstance(x,str):\n return x\n raise TypeError(\"%r must be a string\"%(name,))\n def set_quoting(x):\n if x in range(4):\n return x\n raise TypeError(\"bad 'quoting' value\")\n \n attributes={\"delimiter\":(',',set_char),\n \"doublequote\":(True,bool),\n \"escapechar\":(None,set_char),\n \"lineterminator\":(\"\\r\\n\",set_str),\n \"quotechar\":('\"',set_char),\n \"quoting\":(QUOTE_MINIMAL,set_quoting),\n \"skipinitialspace\":(False,bool),\n \"strict\":(False,bool),\n }\n \n \n notset=object()\n for name in Dialect.__slots__:\n name=name[1:]\n value=notset\n if name in kwargs:\n value=kwargs[name]\n elif dialect is not None:\n value=getattr(dialect,name,notset)\n \n \n if value is notset:\n value=attributes[name][0]\n if name =='quoting'and not self.quotechar:\n value=QUOTE_NONE\n else:\n converter=attributes[name][1]\n if converter:\n value=converter(value)\n \n setattr(self,'_'+name,value)\n \n if not self.delimiter:\n raise TypeError(\"delimiter must be set\")\n \n if self.quoting !=QUOTE_NONE and not self.quotechar:\n raise TypeError(\"quotechar must be set if quoting enabled\")\n \n if not self.lineterminator:\n raise TypeError(\"lineterminator must be set\")\n \n return self\n \n delimiter=property(lambda self:self._delimiter)\n doublequote=property(lambda self:self._doublequote)\n escapechar=property(lambda self:self._escapechar)\n lineterminator=property(lambda self:self._lineterminator)\n quotechar=property(lambda self:self._quotechar)\n quoting=property(lambda self:self._quoting)\n skipinitialspace=property(lambda self:self._skipinitialspace)\n strict=property(lambda self:self._strict)\n \n \ndef _call_dialect(dialect_inst,kwargs):\n return Dialect(dialect_inst,**kwargs)\n \ndef register_dialect(name,dialect=None,**kwargs):\n ''\n \n if not isinstance(name,str):\n raise TypeError(\"dialect name must be a string or unicode\")\n \n dialect=_call_dialect(dialect,kwargs)\n _dialects[name]=dialect\n \ndef unregister_dialect(name):\n ''\n \n try:\n del _dialects[name]\n except KeyError:\n raise Error(\"unknown dialect\")\n \ndef get_dialect(name):\n ''\n \n try:\n return _dialects[name]\n except KeyError:\n raise Error(\"unknown dialect\")\n \ndef list_dialects():\n ''\n \n return list(_dialects)\n \nclass Reader(object):\n ''\n\n\n \n \n \n (START_RECORD,START_FIELD,ESCAPED_CHAR,IN_FIELD,\n IN_QUOTED_FIELD,ESCAPE_IN_QUOTED_FIELD,QUOTE_IN_QUOTED_FIELD,\n EAT_CRNL)=range(8)\n \n def __init__(self,iterator,dialect=None,**kwargs):\n self.dialect=_call_dialect(dialect,kwargs)\n \n \n \n self._delimiter=self.dialect.delimiter if self.dialect.delimiter else '\\0'\n self._quotechar=self.dialect.quotechar if self.dialect.quotechar else '\\0'\n self._escapechar=self.dialect.escapechar if self.dialect.escapechar else '\\0'\n self._doublequote=self.dialect.doublequote\n self._quoting=self.dialect.quoting\n self._skipinitialspace=self.dialect.skipinitialspace\n self._strict=self.dialect.strict\n \n self.input_iter=iter(iterator)\n self.line_num=0\n \n self._parse_reset()\n \n def _parse_reset(self):\n self.field=''\n self.fields=[]\n self.state=self.START_RECORD\n self.numeric_field=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n self._parse_reset()\n while True:\n try:\n line=next(self.input_iter)\n except StopIteration:\n \n if len(self.field)>0:\n raise Error(\"newline inside string\")\n raise\n \n self.line_num +=1\n \n if '\\0'in line:\n raise Error(\"line contains NULL byte\")\n self._parse_process_char(line)\n self._parse_eol()\n \n if self.state ==self.START_RECORD:\n break\n \n fields=self.fields\n self.fields=[]\n return fields\n \n def _parse_process_char(self,line):\n pos=0\n while pos pos:\n self._parse_add_str(line[pos:pos2])\n pos=pos2\n self._parse_save_field()\n self.state=self.EAT_CRNL\n break\n elif line[pos2]==self._escapechar[0]:\n \n if pos2 >pos:\n self._parse_add_str(line[pos:pos2])\n pos=pos2\n self.state=self.ESCAPED_CHAR\n break\n elif line[pos2]==self._delimiter[0]:\n \n if pos2 >pos:\n self._parse_add_str(line[pos:pos2])\n pos=pos2\n self._parse_save_field()\n self.state=self.START_FIELD\n break\n \n pos2 +=1\n else:\n if pos2 >pos:\n self._parse_add_str(line[pos:pos2])\n pos=pos2\n continue\n \n elif self.state ==self.START_RECORD:\n if line[pos]=='\\n'or line[pos]=='\\r':\n self.state=self.EAT_CRNL\n else:\n self.state=self.START_FIELD\n \n continue\n \n elif self.state ==self.START_FIELD:\n if line[pos]=='\\n'or line[pos]=='\\r':\n \n self._parse_save_field()\n self.state=self.EAT_CRNL\n elif(line[pos]==self._quotechar[0]\n and self._quoting !=QUOTE_NONE):\n \n self.state=self.IN_QUOTED_FIELD\n elif line[pos]==self._escapechar[0]:\n \n self.state=self.ESCAPED_CHAR\n elif self._skipinitialspace and line[pos]==' ':\n \n pass\n elif line[pos]==self._delimiter[0]:\n \n self._parse_save_field()\n else:\n \n if self._quoting ==QUOTE_NONNUMERIC:\n self.numeric_field=True\n self.state=self.IN_FIELD\n continue\n \n elif self.state ==self.ESCAPED_CHAR:\n self._parse_add_char(line[pos])\n self.state=self.IN_FIELD\n \n elif self.state ==self.IN_QUOTED_FIELD:\n if line[pos]==self._escapechar:\n \n self.state=self.ESCAPE_IN_QUOTED_FIELD\n elif(line[pos]==self._quotechar\n and self._quoting !=QUOTE_NONE):\n if self._doublequote:\n \n self.state=self.QUOTE_IN_QUOTED_FIELD\n else:\n \n self.state=self.IN_FIELD\n else:\n \n self._parse_add_char(line[pos])\n \n elif self.state ==self.ESCAPE_IN_QUOTED_FIELD:\n self._parse_add_char(line[pos])\n self.state=self.IN_QUOTED_FIELD\n \n elif self.state ==self.QUOTE_IN_QUOTED_FIELD:\n \n if(line[pos]==self._quotechar\n and self._quoting !=QUOTE_NONE):\n \n self._parse_add_char(line[pos])\n self.state=self.IN_QUOTED_FIELD\n elif line[pos]==self._delimiter[0]:\n \n self._parse_save_field()\n self.state=self.START_FIELD\n elif line[pos]=='\\r'or line[pos]=='\\n':\n \n self._parse_save_field()\n self.state=self.EAT_CRNL\n elif not self._strict:\n self._parse_add_char(line[pos])\n self.state=self.IN_FIELD\n else:\n raise Error(\"'%c' expected after '%c'\"%\n (self._delimiter,self._quotechar))\n \n elif self.state ==self.EAT_CRNL:\n if line[pos]=='\\r'or line[pos]=='\\n':\n pass\n else:\n raise Error(\"new-line character seen in unquoted field - \"\n \"do you need to open the file \"\n \"in universal-newline mode?\")\n \n else:\n raise RuntimeError(\"unknown state: %r\"%(self.state,))\n \n pos +=1\n \n def _parse_eol(self):\n if self.state ==self.EAT_CRNL:\n self.state=self.START_RECORD\n elif self.state ==self.START_RECORD:\n \n pass\n elif self.state ==self.IN_FIELD:\n \n \n self._parse_save_field()\n self.state=self.START_RECORD\n elif self.state ==self.START_FIELD:\n \n self._parse_save_field()\n self.state=self.START_RECORD\n elif self.state ==self.ESCAPED_CHAR:\n self._parse_add_char('\\n')\n self.state=self.IN_FIELD\n elif self.state ==self.IN_QUOTED_FIELD:\n pass\n elif self.state ==self.ESCAPE_IN_QUOTED_FIELD:\n self._parse_add_char('\\n')\n self.state=self.IN_QUOTED_FIELD\n elif self.state ==self.QUOTE_IN_QUOTED_FIELD:\n \n self._parse_save_field()\n self.state=self.START_RECORD\n else:\n raise RuntimeError(\"unknown state: %r\"%(self.state,))\n \n def _parse_save_field(self):\n field,self.field=self.field,''\n if self.numeric_field:\n self.numeric_field=False\n field=float(field)\n self.fields.append(field)\n \n def _parse_add_char(self,c):\n if len(self.field)+1 >_field_limit:\n raise Error(\"field larget than field limit (%d)\"%(_field_limit))\n self.field +=c\n \n def _parse_add_str(self,s):\n if len(self.field)+len(s)>_field_limit:\n raise Error(\"field larget than field limit (%d)\"%(_field_limit))\n self.field +=s\n \n \nclass Writer(object):\n ''\n\n\n \n \n def __init__(self,file,dialect=None,**kwargs):\n if not(hasattr(file,'write')and callable(file.write)):\n raise TypeError(\"argument 1 must have a 'write' method\")\n self.writeline=file.write\n self.dialect=_call_dialect(dialect,kwargs)\n \n def _join_reset(self):\n self.rec=[]\n self.num_fields=0\n \n def _join_append(self,field,quoted,quote_empty):\n dialect=self.dialect\n \n if self.num_fields >0:\n self.rec.append(dialect.delimiter)\n \n if dialect.quoting ==QUOTE_NONE:\n need_escape=tuple(dialect.lineterminator)+(\n dialect.escapechar,\n dialect.delimiter,dialect.quotechar)\n \n else:\n for c in tuple(dialect.lineterminator)+(\n dialect.delimiter,dialect.escapechar):\n if c and c in field:\n quoted=True\n \n need_escape=()\n if dialect.quotechar in field:\n if dialect.doublequote:\n field=field.replace(dialect.quotechar,\n dialect.quotechar *2)\n quoted=True\n else:\n need_escape=(dialect.quotechar,)\n \n \n for c in need_escape:\n if c and c in field:\n if not dialect.escapechar:\n raise Error(\"need to escape, but no escapechar set\")\n field=field.replace(c,dialect.escapechar+c)\n \n \n if field ==''and quote_empty:\n if dialect.quoting ==QUOTE_NONE:\n raise Error(\"single empty field record must be quoted\")\n quoted=1\n \n if quoted:\n field=dialect.quotechar+field+dialect.quotechar\n \n self.rec.append(field)\n self.num_fields +=1\n \n \n \n def writerow(self,row):\n dialect=self.dialect\n try:\n rowlen=len(row)\n except TypeError:\n raise Error(\"sequence expected\")\n \n \n self._join_reset()\n \n for field in row:\n quoted=False\n if dialect.quoting ==QUOTE_NONNUMERIC:\n try:\n float(field)\n except:\n quoted=True\n \n \n elif dialect.quoting ==QUOTE_ALL:\n quoted=True\n \n if field is None:\n self._join_append(\"\",quoted,rowlen ==1)\n else:\n self._join_append(str(field),quoted,rowlen ==1)\n \n \n self.rec.append(dialect.lineterminator)\n \n self.writeline(''.join(self.rec))\n \n def writerows(self,rows):\n for row in rows:\n self.writerow(row)\n \ndef reader(*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n return Reader(*args,**kwargs)\n \ndef writer(*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n return Writer(*args,**kwargs)\n \n \nundefined=object()\ndef field_size_limit(limit=undefined):\n ''\n\n\n\n \n \n global _field_limit\n old_limit=_field_limit\n \n if limit is not undefined:\n if not isinstance(limit,(int,long)):\n raise TypeError(\"int expected, got %s\"%\n (limit.__class__.__name__,))\n _field_limit=limit\n \n return old_limit\n", []], "_dummy_thread": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['error','start_new_thread','exit','get_ident','allocate_lock',\n'interrupt_main','LockType','RLock']\n\n\nTIMEOUT_MAX=2 **31\n\n\n\n\n\n\nerror=RuntimeError\n\ndef start_new_thread(function,args,kwargs={}):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if type(args)!=type(tuple()):\n raise TypeError(\"2nd arg must be a tuple\")\n if type(kwargs)!=type(dict()):\n raise TypeError(\"3rd arg must be a dict\")\n global _main\n _main=False\n try:\n function(*args,**kwargs)\n except SystemExit:\n pass\n except:\n import traceback\n traceback.print_exc()\n _main=True\n global _interrupt\n if _interrupt:\n _interrupt=False\n raise KeyboardInterrupt\n \ndef exit():\n ''\n raise SystemExit\n \ndef get_ident():\n ''\n\n\n\n\n \n return 1\n \ndef allocate_lock():\n ''\n return LockType()\n \ndef stack_size(size=None):\n ''\n if size is not None:\n raise error(\"setting thread stack size not supported\")\n return 0\n \ndef _set_sentinel():\n ''\n return LockType()\n \nclass LockType(object):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self):\n self.locked_status=False\n \n def acquire(self,waitflag=None,timeout=-1):\n ''\n\n\n\n\n\n\n\n\n \n if waitflag is None or waitflag:\n self.locked_status=True\n return True\n else:\n if not self.locked_status:\n self.locked_status=True\n return True\n else:\n if timeout >0:\n import time\n time.sleep(timeout)\n return False\n \n __enter__=acquire\n \n def __exit__(self,typ,val,tb):\n self.release()\n \n def release(self):\n ''\n \n \n if not self.locked_status:\n raise error\n self.locked_status=False\n return True\n \n def locked(self):\n return self.locked_status\n \n def __repr__(self):\n return \"<%s %s.%s object at %s>\"%(\n \"locked\"if self.locked_status else \"unlocked\",\n self.__class__.__module__,\n self.__class__.__qualname__,\n hex(id(self))\n )\n \n \nclass RLock(LockType):\n ''\n\n\n\n\n\n \n def __init__(self):\n super().__init__()\n self._levels=0\n \n def acquire(self,waitflag=None,timeout=-1):\n ''\n \n locked=super().acquire(waitflag,timeout)\n if locked:\n self._levels +=1\n return locked\n \n def release(self):\n ''\n \n if self._levels ==0:\n raise error\n if self._levels ==1:\n super().release()\n self._levels -=1\n \n \n_interrupt=False\n\n_main=True\n\ndef interrupt_main():\n ''\n \n if _main:\n raise KeyboardInterrupt\n else:\n global _interrupt\n _interrupt=True\n", ["time", "traceback"]], "_frozen_importlib": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_bootstrap_external=None\n_thread=None\nimport _weakref\n\nimport _imp\nimport sys\n\ndef _wrap(new,old):\n ''\n for replace in['__module__','__name__','__qualname__','__doc__']:\n if hasattr(old,replace):\n setattr(new,replace,getattr(old,replace))\n new.__dict__.update(old.__dict__)\n \n \ndef _new_module(name):\n return type(sys)(name)\n \n \n \n \n \n \n_module_locks={}\n\n_blocking_on={}\n\n\nclass _DeadlockError(RuntimeError):\n pass\n \n \nclass _ModuleLock:\n ''\n\n\n \n \n def __init__(self,name):\n self.lock=_thread.allocate_lock()\n self.wakeup=_thread.allocate_lock()\n self.name=name\n self.owner=None\n self.count=0\n self.waiters=0\n \n def has_deadlock(self):\n \n me=_thread.get_ident()\n tid=self.owner\n while True:\n lock=_blocking_on.get(tid)\n if lock is None:\n return False\n tid=lock.owner\n if tid ==me:\n return True\n \n def acquire(self):\n ''\n\n\n\n \n tid=_thread.get_ident()\n _blocking_on[tid]=self\n try:\n while True:\n with self.lock:\n if self.count ==0 or self.owner ==tid:\n self.owner=tid\n self.count +=1\n return True\n if self.has_deadlock():\n raise _DeadlockError('deadlock detected by %r'%self)\n if self.wakeup.acquire(False):\n self.waiters +=1\n \n self.wakeup.acquire()\n self.wakeup.release()\n finally:\n del _blocking_on[tid]\n \n def release(self):\n tid=_thread.get_ident()\n with self.lock:\n if self.owner !=tid:\n raise RuntimeError('cannot release un-acquired lock')\n assert self.count >0\n self.count -=1\n if self.count ==0:\n self.owner=None\n if self.waiters:\n self.waiters -=1\n self.wakeup.release()\n \n def __repr__(self):\n return '_ModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _DummyModuleLock:\n ''\n \n \n def __init__(self,name):\n self.name=name\n self.count=0\n \n def acquire(self):\n self.count +=1\n return True\n \n def release(self):\n if self.count ==0:\n raise RuntimeError('cannot release un-acquired lock')\n self.count -=1\n \n def __repr__(self):\n return '_DummyModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _ModuleLockManager:\n\n def __init__(self,name):\n self._name=name\n self._lock=None\n \n def __enter__(self):\n self._lock=_get_module_lock(self._name)\n self._lock.acquire()\n \n def __exit__(self,*args,**kwargs):\n self._lock.release()\n \n \n \n \ndef _get_module_lock(name):\n ''\n\n\n \n \n _imp.acquire_lock()\n try:\n try:\n lock=_module_locks[name]()\n except KeyError:\n lock=None\n \n if lock is None:\n if _thread is None:\n lock=_DummyModuleLock(name)\n else:\n lock=_ModuleLock(name)\n \n def cb(ref,name=name):\n _imp.acquire_lock()\n try:\n \n \n \n if _module_locks.get(name)is ref:\n del _module_locks[name]\n finally:\n _imp.release_lock()\n \n _module_locks[name]=_weakref.ref(lock,cb)\n finally:\n _imp.release_lock()\n \n return lock\n \n \ndef _lock_unlock_module(name):\n ''\n\n\n\n \n lock=_get_module_lock(name)\n try:\n lock.acquire()\n except _DeadlockError:\n \n \n pass\n else:\n lock.release()\n \n \ndef _call_with_frames_removed(f,*args,**kwds):\n ''\n\n\n\n\n\n \n return f(*args,**kwds)\n \n \ndef _verbose_message(message,*args,verbosity=1):\n ''\n if sys.flags.verbose >=verbosity:\n if not message.startswith(('#','import ')):\n message='# '+message\n print(message.format(*args),file=sys.stderr)\n \n \ndef _requires_builtin(fxn):\n ''\n def _requires_builtin_wrapper(self,fullname):\n if fullname not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_builtin_wrapper,fxn)\n return _requires_builtin_wrapper\n \n \ndef _requires_frozen(fxn):\n ''\n def _requires_frozen_wrapper(self,fullname):\n if not _imp.is_frozen(fullname):\n raise ImportError('{!r} is not a frozen module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_frozen_wrapper,fxn)\n return _requires_frozen_wrapper\n \n \n \ndef _load_module_shim(self,fullname):\n ''\n\n\n\n \n spec=spec_from_loader(fullname,self)\n if fullname in sys.modules:\n module=sys.modules[fullname]\n _exec(spec,module)\n return sys.modules[fullname]\n else:\n return _load(spec)\n \n \n \ndef _module_repr(module):\n\n loader=getattr(module,'__loader__',None)\n if hasattr(loader,'module_repr'):\n \n \n \n try:\n return loader.module_repr(module)\n except Exception:\n pass\n try:\n spec=module.__spec__\n except AttributeError:\n pass\n else:\n if spec is not None:\n return _module_repr_from_spec(spec)\n \n \n \n try:\n name=module.__name__\n except AttributeError:\n name='?'\n try:\n filename=module.__file__\n except AttributeError:\n if loader is None:\n return ''.format(name)\n else:\n return ''.format(name,loader)\n else:\n return ''.format(name,filename)\n \n \nclass _installed_safely:\n\n def __init__(self,module):\n self._module=module\n self._spec=module.__spec__\n \n def __enter__(self):\n \n \n \n self._spec._initializing=True\n sys.modules[self._spec.name]=self._module\n \n def __exit__(self,*args):\n try:\n spec=self._spec\n if any(arg is not None for arg in args):\n try:\n del sys.modules[spec.name]\n except KeyError:\n pass\n else:\n _verbose_message('import {!r} # {!r}',spec.name,spec.loader)\n finally:\n self._spec._initializing=False\n \n \nclass ModuleSpec:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,name,loader,*,origin=None,loader_state=None,\n is_package=None):\n self.name=name\n self.loader=loader\n self.origin=origin\n self.loader_state=loader_state\n self.submodule_search_locations=[]if is_package else None\n \n \n self._set_fileattr=False\n self._cached=None\n \n def __repr__(self):\n args=['name={!r}'.format(self.name),\n 'loader={!r}'.format(self.loader)]\n if self.origin is not None:\n args.append('origin={!r}'.format(self.origin))\n if self.submodule_search_locations is not None:\n args.append('submodule_search_locations={}'\n .format(self.submodule_search_locations))\n return '{}({})'.format(self.__class__.__name__,', '.join(args))\n \n def __eq__(self,other):\n smsl=self.submodule_search_locations\n try:\n return(self.name ==other.name and\n self.loader ==other.loader and\n self.origin ==other.origin and\n smsl ==other.submodule_search_locations and\n self.cached ==other.cached and\n self.has_location ==other.has_location)\n except AttributeError:\n return False\n \n @property\n def cached(self):\n if self._cached is None:\n if self.origin is not None and self._set_fileattr:\n if _bootstrap_external is None:\n raise NotImplementedError\n self._cached=_bootstrap_external._get_cached(self.origin)\n return self._cached\n \n @cached.setter\n def cached(self,cached):\n self._cached=cached\n \n @property\n def parent(self):\n ''\n if self.submodule_search_locations is None:\n return self.name.rpartition('.')[0]\n else:\n return self.name\n \n @property\n def has_location(self):\n return self._set_fileattr\n \n @has_location.setter\n def has_location(self,value):\n self._set_fileattr=bool(value)\n \n \ndef spec_from_loader(name,loader,*,origin=None,is_package=None):\n ''\n if hasattr(loader,'get_filename'):\n if _bootstrap_external is None:\n raise NotImplementedError\n spec_from_file_location=_bootstrap_external.spec_from_file_location\n \n if is_package is None:\n return spec_from_file_location(name,loader=loader)\n search=[]if is_package else None\n return spec_from_file_location(name,loader=loader,\n submodule_search_locations=search)\n \n if is_package is None:\n if hasattr(loader,'is_package'):\n try:\n is_package=loader.is_package(name)\n except ImportError:\n is_package=None\n else:\n \n is_package=False\n \n return ModuleSpec(name,loader,origin=origin,is_package=is_package)\n \n \ndef _spec_from_module(module,loader=None,origin=None):\n\n try:\n spec=module.__spec__\n except AttributeError:\n pass\n else:\n if spec is not None:\n return spec\n \n name=module.__name__\n if loader is None:\n try:\n loader=module.__loader__\n except AttributeError:\n \n pass\n try:\n location=module.__file__\n except AttributeError:\n location=None\n if origin is None:\n if location is None:\n try:\n origin=loader._ORIGIN\n except AttributeError:\n origin=None\n else:\n origin=location\n try:\n cached=module.__cached__\n except AttributeError:\n cached=None\n try:\n submodule_search_locations=list(module.__path__)\n except AttributeError:\n submodule_search_locations=None\n \n spec=ModuleSpec(name,loader,origin=origin)\n spec._set_fileattr=False if location is None else True\n spec.cached=cached\n spec.submodule_search_locations=submodule_search_locations\n return spec\n \n \ndef _init_module_attrs(spec,module,*,override=False):\n\n\n\n if(override or getattr(module,'__name__',None)is None):\n try:\n module.__name__=spec.name\n except AttributeError:\n pass\n \n if override or getattr(module,'__loader__',None)is None:\n loader=spec.loader\n if loader is None:\n \n if spec.submodule_search_locations is not None:\n if _bootstrap_external is None:\n raise NotImplementedError\n _NamespaceLoader=_bootstrap_external._NamespaceLoader\n \n loader=_NamespaceLoader.__new__(_NamespaceLoader)\n loader._path=spec.submodule_search_locations\n spec.loader=loader\n \n \n \n \n \n \n \n \n \n \n module.__file__=None\n try:\n module.__loader__=loader\n except AttributeError:\n pass\n \n if override or getattr(module,'__package__',None)is None:\n try:\n module.__package__=spec.parent\n except AttributeError:\n pass\n \n try:\n module.__spec__=spec\n except AttributeError:\n pass\n \n if override or getattr(module,'__path__',None)is None:\n if spec.submodule_search_locations is not None:\n try:\n module.__path__=spec.submodule_search_locations\n except AttributeError:\n pass\n \n if spec.has_location:\n if override or getattr(module,'__file__',None)is None:\n try:\n module.__file__=spec.origin\n except AttributeError:\n pass\n \n if override or getattr(module,'__cached__',None)is None:\n if spec.cached is not None:\n try:\n module.__cached__=spec.cached\n except AttributeError:\n pass\n return module\n \n \ndef module_from_spec(spec):\n ''\n \n module=None\n if hasattr(spec.loader,'create_module'):\n \n \n module=spec.loader.create_module(spec)\n elif hasattr(spec.loader,'exec_module'):\n raise ImportError('loaders that define exec_module() '\n 'must also define create_module()')\n if module is None:\n module=_new_module(spec.name)\n _init_module_attrs(spec,module)\n return module\n \n \ndef _module_repr_from_spec(spec):\n ''\n \n name='?'if spec.name is None else spec.name\n if spec.origin is None:\n if spec.loader is None:\n return ''.format(name)\n else:\n return ''.format(name,spec.loader)\n else:\n if spec.has_location:\n return ''.format(name,spec.origin)\n else:\n return ''.format(spec.name,spec.origin)\n \n \n \ndef _exec(spec,module):\n ''\n name=spec.name\n with _ModuleLockManager(name):\n if sys.modules.get(name)is not module:\n msg='module {!r} not in sys.modules'.format(name)\n raise ImportError(msg,name=name)\n if spec.loader is None:\n if spec.submodule_search_locations is None:\n raise ImportError('missing loader',name=spec.name)\n \n _init_module_attrs(spec,module,override=True)\n return module\n _init_module_attrs(spec,module,override=True)\n if not hasattr(spec.loader,'exec_module'):\n \n \n \n spec.loader.load_module(name)\n else:\n spec.loader.exec_module(module)\n return sys.modules[name]\n \n \ndef _load_backward_compatible(spec):\n\n\n\n spec.loader.load_module(spec.name)\n \n module=sys.modules[spec.name]\n if getattr(module,'__loader__',None)is None:\n try:\n module.__loader__=spec.loader\n except AttributeError:\n pass\n if getattr(module,'__package__',None)is None:\n try:\n \n \n \n module.__package__=module.__name__\n if not hasattr(module,'__path__'):\n module.__package__=spec.name.rpartition('.')[0]\n except AttributeError:\n pass\n if getattr(module,'__spec__',None)is None:\n try:\n module.__spec__=spec\n except AttributeError:\n pass\n return module\n \ndef _load_unlocked(spec):\n\n if spec.loader is not None:\n \n if not hasattr(spec.loader,'exec_module'):\n return _load_backward_compatible(spec)\n \n module=module_from_spec(spec)\n with _installed_safely(module):\n if spec.loader is None:\n if spec.submodule_search_locations is None:\n raise ImportError('missing loader',name=spec.name)\n \n else:\n spec.loader.exec_module(module)\n \n \n \n \n return sys.modules[spec.name]\n \n \n \ndef _load(spec):\n ''\n\n\n\n\n\n\n \n with _ModuleLockManager(spec.name):\n return _load_unlocked(spec)\n \n \n \n \nclass BuiltinImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(module):\n ''\n\n\n\n \n return ''.format(module.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n if path is not None:\n return None\n if _imp.is_builtin(fullname):\n return spec_from_loader(fullname,cls,origin='built-in')\n else:\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None):\n ''\n\n\n\n\n\n \n spec=cls.find_spec(fullname,path)\n return spec.loader if spec is not None else None\n \n @classmethod\n def create_module(self,spec):\n ''\n if spec.name not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(spec.name),\n name=spec.name)\n return _call_with_frames_removed(_imp.create_builtin,spec)\n \n @classmethod\n def exec_module(self,module):\n ''\n _call_with_frames_removed(_imp.exec_builtin,module)\n \n @classmethod\n @_requires_builtin\n def get_code(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def is_package(cls,fullname):\n ''\n return False\n \n load_module=classmethod(_load_module_shim)\n \n \nclass FrozenImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(m):\n ''\n\n\n\n \n return ''.format(m.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n if _imp.is_frozen(fullname):\n return spec_from_loader(fullname,cls,origin='frozen')\n else:\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None):\n ''\n\n\n\n \n return cls if _imp.is_frozen(fullname)else None\n \n @classmethod\n def create_module(cls,spec):\n ''\n \n @staticmethod\n def exec_module(module):\n name=module.__spec__.name\n if not _imp.is_frozen(name):\n raise ImportError('{!r} is not a frozen module'.format(name),\n name=name)\n code=_call_with_frames_removed(_imp.get_frozen_object,name)\n exec(code,module.__dict__)\n \n @classmethod\n def load_module(cls,fullname):\n ''\n\n\n\n \n return _load_module_shim(cls,fullname)\n \n @classmethod\n @_requires_frozen\n def get_code(cls,fullname):\n ''\n return _imp.get_frozen_object(fullname)\n \n @classmethod\n @_requires_frozen\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_frozen\n def is_package(cls,fullname):\n ''\n return _imp.is_frozen_package(fullname)\n \n \n \n \nclass _ImportLockContext:\n\n ''\n \n def __enter__(self):\n ''\n _imp.acquire_lock()\n \n def __exit__(self,exc_type,exc_value,exc_traceback):\n ''\n _imp.release_lock()\n \n \ndef _resolve_name(name,package,level):\n ''\n bits=package.rsplit('.',level -1)\n if len(bits)= 0')\n if level >0:\n if not isinstance(package,str):\n raise TypeError('__package__ not set to a string')\n elif not package:\n raise ImportError('attempted relative import with no known parent '\n 'package')\n if not name and level ==0:\n raise ValueError('Empty module name')\n \n \n_ERR_MSG_PREFIX='No module named '\n_ERR_MSG=_ERR_MSG_PREFIX+'{!r}'\n\ndef _find_and_load_unlocked(name,import_):\n path=None\n parent=name.rpartition('.')[0]\n if parent:\n if parent not in sys.modules:\n _call_with_frames_removed(import_,parent)\n \n if name in sys.modules:\n return sys.modules[name]\n parent_module=sys.modules[parent]\n try:\n path=parent_module.__path__\n except AttributeError:\n msg=(_ERR_MSG+'; {!r} is not a package').format(name,parent)\n raise ModuleNotFoundError(msg,name=name)from None\n spec=_find_spec(name,path)\n if spec is None:\n raise ModuleNotFoundError(_ERR_MSG.format(name),name=name)\n else:\n module=_load_unlocked(spec)\n if parent:\n \n parent_module=sys.modules[parent]\n setattr(parent_module,name.rpartition('.')[2],module)\n return module\n \n \n_NEEDS_LOADING=object()\n\n\ndef _find_and_load(name,import_):\n ''\n with _ModuleLockManager(name):\n module=sys.modules.get(name,_NEEDS_LOADING)\n if module is _NEEDS_LOADING:\n return _find_and_load_unlocked(name,import_)\n \n if module is None:\n message=('import of {} halted; '\n 'None in sys.modules'.format(name))\n raise ModuleNotFoundError(message,name=name)\n \n _lock_unlock_module(name)\n return module\n \n \ndef _gcd_import(name,package=None,level=0):\n ''\n\n\n\n\n\n\n \n _sanity_check(name,package,level)\n if level >0:\n name=_resolve_name(name,package,level)\n return _find_and_load(name,_gcd_import)\n \n \ndef _handle_fromlist(module,fromlist,import_,*,recursive=False):\n ''\n\n\n\n\n\n \n \n \n if hasattr(module,'__path__'):\n for x in fromlist:\n if not isinstance(x,str):\n if recursive:\n where=module.__name__+'.__all__'\n else:\n where=\"``from list''\"\n raise TypeError(f\"Item in {where} must be str, \"\n f\"not {type(x).__name__}\")\n elif x =='*':\n if not recursive and hasattr(module,'__all__'):\n _handle_fromlist(module,module.__all__,import_,\n recursive=True)\n elif not hasattr(module,x):\n from_name='{}.{}'.format(module.__name__,x)\n try:\n _call_with_frames_removed(import_,from_name)\n except ModuleNotFoundError as exc:\n \n \n \n if(exc.name ==from_name and\n sys.modules.get(from_name,_NEEDS_LOADING)is not None):\n continue\n raise\n return module\n \n \ndef _calc___package__(globals):\n ''\n\n\n\n\n \n package=globals.get('__package__')\n spec=globals.get('__spec__')\n if package is not None:\n if spec is not None and package !=spec.parent:\n _warnings.warn(\"__package__ != __spec__.parent \"\n f\"({package !r} != {spec.parent !r})\",\n ImportWarning,stacklevel=3)\n return package\n elif spec is not None:\n return spec.parent\n else:\n _warnings.warn(\"can't resolve package from __spec__ or __package__, \"\n \"falling back on __name__ and __path__\",\n ImportWarning,stacklevel=3)\n package=globals['__name__']\n if '__path__'not in globals:\n package=package.rpartition('.')[0]\n return package\n \n \ndef __import__(name,globals=None,locals=None,fromlist=(),level=0):\n ''\n\n\n\n\n\n\n\n\n \n if level ==0:\n module=_gcd_import(name)\n else:\n globals_=globals if globals is not None else{}\n package=_calc___package__(globals_)\n module=_gcd_import(name,package,level)\n if not fromlist:\n \n \n if level ==0:\n return _gcd_import(name.partition('.')[0])\n elif not name:\n return module\n else:\n \n \n cut_off=len(name)-len(name.partition('.')[0])\n \n \n return sys.modules[module.__name__[:len(module.__name__)-cut_off]]\n else:\n return _handle_fromlist(module,fromlist,_gcd_import)\n \n \ndef _builtin_from_name(name):\n spec=BuiltinImporter.find_spec(name)\n if spec is None:\n raise ImportError('no built-in module named '+name)\n return _load_unlocked(spec)\n \n \nmodule_type=type(sys)\nfor name,module in sys.modules.items():\n if isinstance(module,module_type):\n if name in sys.builtin_module_names:\n loader=BuiltinImporter\n elif _imp.is_frozen(name):\n loader=FrozenImporter\n else:\n continue\n spec=_spec_from_module(module,loader)\n _init_module_attrs(spec,module)\n \n \nself_module=sys.modules[__name__]\n\n\nfor builtin_name in('_warnings',):\n if builtin_name not in sys.modules:\n builtin_module=_builtin_from_name(builtin_name)\n else:\n builtin_module=sys.modules[builtin_name]\n setattr(self_module,builtin_name,builtin_module)\n \n \ndef _install(sys_module,_imp_module):\n ''\n _setup(sys_module,_imp_module)\n \n sys.meta_path.append(BuiltinImporter)\n sys.meta_path.append(FrozenImporter)\n \n \ndef _install_external_importers():\n ''\n global _bootstrap_external\n import _frozen_importlib_external\n _bootstrap_external=_frozen_importlib_external\n _frozen_importlib_external._install(sys.modules[__name__])\n \n", ["_frozen_importlib_external", "_imp", "_weakref", "sys"]], "_functools": [".py", "from reprlib import recursive_repr\n\nclass partial:\n ''\n\n \n \n __slots__=\"func\",\"args\",\"keywords\",\"__dict__\",\"__weakref__\"\n \n def __new__(*args,**keywords):\n if not args:\n raise TypeError(\"descriptor '__new__' of partial needs an argument\")\n if len(args)<2:\n raise TypeError(\"type 'partial' takes at least one argument\")\n cls,func,*args=args\n if not callable(func):\n raise TypeError(\"the first argument must be callable\")\n args=tuple(args)\n \n if hasattr(func,\"func\")and isinstance(func.args,tuple):\n args=func.args+args\n tmpkw=func.keywords.copy()\n tmpkw.update(keywords)\n keywords=tmpkw\n del tmpkw\n func=func.func\n \n self=super(partial,cls).__new__(cls)\n \n self.func=func\n self.args=args\n self.keywords=keywords\n return self\n \n def __call__(*args,**keywords):\n if not args:\n raise TypeError(\"descriptor '__call__' of partial needs an argument\")\n self,*args=args\n newkeywords=self.keywords.copy()\n newkeywords.update(keywords)\n return self.func(*self.args,*args,**newkeywords)\n \n @recursive_repr()\n def __repr__(self):\n qualname=type(self).__qualname__\n args=[repr(self.func)]\n args.extend(repr(x)for x in self.args)\n args.extend(f\"{k}={v !r}\"for(k,v)in self.keywords.items())\n if type(self).__module__ ==\"functools\":\n return f\"functools.{qualname}({', '.join(args)})\"\n return f\"{qualname}({', '.join(args)})\"\n \n def __reduce__(self):\n return type(self),(self.func,),(self.func,self.args,\n self.keywords or None,self.__dict__ or None)\n \n def __setstate__(self,state):\n if not isinstance(state,tuple):\n raise TypeError(\"argument to __setstate__ must be a tuple\")\n if len(state)!=4:\n raise TypeError(f\"expected 4 items in state, got {len(state)}\")\n func,args,kwds,namespace=state\n if(not callable(func)or not isinstance(args,tuple)or\n (kwds is not None and not isinstance(kwds,dict))or\n (namespace is not None and not isinstance(namespace,dict))):\n raise TypeError(\"invalid partial state\")\n \n args=tuple(args)\n if kwds is None:\n kwds={}\n elif type(kwds)is not dict:\n kwds=dict(kwds)\n if namespace is None:\n namespace={}\n \n self.__dict__=namespace\n self.func=func\n self.args=args\n self.keywords=kwds\n \ndef reduce(func,iterable,initializer=None):\n args=iter(iterable)\n if initializer is not None:\n res=initializer\n else:\n res=next(args)\n while True:\n try:\n res=func(res,next(args))\n except StopIteration:\n return res\n", ["reprlib"]], "_imp": [".py", "''\nimport sys\n\ndef _fix_co_filename(*args,**kw):\n ''\n\n\n\n \n pass\n \ndef acquire_lock(*args,**kw):\n ''\n\n \n pass\n \ncheck_hash_based_pycs=\"\"\"default\"\"\"\n\ndef create_builtin(spec):\n ''\n return __import__(spec.name)\n \ndef create_dynamic(*args,**kw):\n ''\n pass\n \ndef exec_builtin(*args,**kw):\n ''\n pass\n \ndef exec_dynamic(*args,**kw):\n ''\n pass\n \ndef extension_suffixes(*args,**kw):\n ''\n return[]\n \ndef get_frozen_object(*args,**kw):\n ''\n pass\n \ndef init_frozen(*args,**kw):\n ''\n pass\n \ndef is_builtin(module_name):\n\n return module_name in __BRYTHON__.builtin_module_names\n \ndef is_frozen(*args,**kw):\n ''\n return False\n \ndef is_frozen_package(*args,**kw):\n ''\n pass\n \ndef lock_held(*args,**kw):\n ''\n \n return False\n \ndef release_lock(*args,**kw):\n ''\n \n pass\n \ndef source_hash(*args,**kw):\n pass\n", ["sys"]], "_io": [".py", "''\n\n\n\nimport os\nimport abc\nimport codecs\nimport errno\n\ntry:\n from _thread import allocate_lock as Lock\nexcept ImportError:\n from _dummy_thread import allocate_lock as Lock\n \n \nfrom _io_classes import *\nimport _io_classes\n_IOBase=_io_classes._IOBase\n_RawIOBase=_io_classes._RawIOBase\n_BufferedIOBase=_io_classes._BufferedIOBase\n_TextIOBase=_io_classes._TextIOBase\n\nSEEK_SET=0\nSEEK_CUR=1\nSEEK_END=2\n\nvalid_seek_flags={0,1,2}\nif hasattr(os,'SEEK_HOLE'):\n valid_seek_flags.add(os.SEEK_HOLE)\n valid_seek_flags.add(os.SEEK_DATA)\n \n \nDEFAULT_BUFFER_SIZE=8 *1024\n\n\n\n\n\n\nBlockingIOError=BlockingIOError\n\n\ndef __open(file,mode=\"r\",buffering=-1,encoding=None,errors=None,\nnewline=None,closefd=True,opener=None):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not isinstance(file,(str,bytes,int)):\n raise TypeError(\"invalid file: %r\"%file)\n if not isinstance(mode,str):\n raise TypeError(\"invalid mode: %r\"%mode)\n if not isinstance(buffering,int):\n raise TypeError(\"invalid buffering: %r\"%buffering)\n if encoding is not None and not isinstance(encoding,str):\n raise TypeError(\"invalid encoding: %r\"%encoding)\n if errors is not None and not isinstance(errors,str):\n raise TypeError(\"invalid errors: %r\"%errors)\n modes=set(mode)\n if modes -set(\"axrwb+tU\")or len(mode)>len(modes):\n raise ValueError(\"invalid mode: %r\"%mode)\n creating=\"x\"in modes\n reading=\"r\"in modes\n writing=\"w\"in modes\n appending=\"a\"in modes\n updating=\"+\"in modes\n text=\"t\"in modes\n binary=\"b\"in modes\n if \"U\"in modes:\n if creating or writing or appending:\n raise ValueError(\"can't use U and writing mode at once\")\n reading=True\n if text and binary:\n raise ValueError(\"can't have text and binary mode at once\")\n if creating+reading+writing+appending >1:\n raise ValueError(\"can't have read/write/append mode at once\")\n if not(creating or reading or writing or appending):\n raise ValueError(\"must have exactly one of read/write/append mode\")\n if binary and encoding is not None:\n raise ValueError(\"binary mode doesn't take an encoding argument\")\n if binary and errors is not None:\n raise ValueError(\"binary mode doesn't take an errors argument\")\n if binary and newline is not None:\n raise ValueError(\"binary mode doesn't take a newline argument\")\n raw=FileIO(file,\n (creating and \"x\"or \"\")+\n (reading and \"r\"or \"\")+\n (writing and \"w\"or \"\")+\n (appending and \"a\"or \"\")+\n (updating and \"+\"or \"\"),\n closefd,opener=opener)\n line_buffering=False\n if buffering ==1 or buffering <0 and raw.isatty():\n buffering=-1\n line_buffering=True\n if buffering <0:\n buffering=DEFAULT_BUFFER_SIZE\n try:\n bs=os.fstat(raw.fileno()).st_blksize\n except(os.error,AttributeError):\n pass\n else:\n if bs >1:\n buffering=bs\n if buffering <0:\n raise ValueError(\"invalid buffering size\")\n if buffering ==0:\n if binary:\n return raw\n raise ValueError(\"can't have unbuffered text I/O\")\n if updating:\n buffer=BufferedRandom(raw,buffering)\n elif creating or writing or appending:\n buffer=BufferedWriter(raw,buffering)\n elif reading:\n buffer=BufferedReader(raw,buffering)\n else:\n raise ValueError(\"unknown mode: %r\"%mode)\n if binary:\n return buffer\n text=TextIOWrapper(buffer,encoding,errors,newline,line_buffering)\n text.mode=mode\n return text\n \nopen=__open\n\ndef open_code(file):\n return __builtins__.open(file,encoding=\"utf-8\")\n \ndef text_encoding(encoding,stacklevel=2):\n if encoding is None:\n return \"locale\"\n return encoding\n \nclass DocDescriptor:\n ''\n \n def __get__(self,obj,typ):\n return(\n \"open(file, mode='r', buffering=-1, encoding=None, \"\n \"errors=None, newline=None, closefd=True)\\n\\n\"+\n open.__doc__)\n \nclass OpenWrapper:\n ''\n\n\n\n\n\n \n __doc__=DocDescriptor()\n \n def __new__(cls,*args,**kwargs):\n return open(*args,**kwargs)\n \n \n \n \nclass UnsupportedOperation(ValueError,IOError):\n pass\n \n", ["_dummy_thread", "_io_classes", "_thread", "abc", "codecs", "errno", "os"]], "_markupbase": [".py", "''\n\n\n\n\n\n\nimport re\n\n_declname_match=re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\\s*').match\n_declstringlit_match=re.compile(r'(\\'[^\\']*\\'|\"[^\"]*\")\\s*').match\n_commentclose=re.compile(r'--\\s*>')\n_markedsectionclose=re.compile(r']\\s*]\\s*>')\n\n\n\n\n_msmarkedsectionclose=re.compile(r']\\s*>')\n\ndel re\n\n\nclass ParserBase:\n ''\n \n \n def __init__(self):\n if self.__class__ is ParserBase:\n raise RuntimeError(\n \"_markupbase.ParserBase must be subclassed\")\n \n def reset(self):\n self.lineno=1\n self.offset=0\n \n def getpos(self):\n ''\n return self.lineno,self.offset\n \n \n \n \n \n def updatepos(self,i,j):\n if i >=j:\n return j\n rawdata=self.rawdata\n nlines=rawdata.count(\"\\n\",i,j)\n if nlines:\n self.lineno=self.lineno+nlines\n pos=rawdata.rindex(\"\\n\",i,j)\n self.offset=j -(pos+1)\n else:\n self.offset=self.offset+j -i\n return j\n \n _decl_otherchars=''\n \n \n def parse_declaration(self,i):\n \n \n \n \n \n \n \n \n \n \n rawdata=self.rawdata\n j=i+2\n assert rawdata[i:j]==\"\":\n \n return j+1\n if rawdata[j:j+1]in(\"-\",\"\"):\n \n \n return -1\n \n n=len(rawdata)\n if rawdata[j:j+2]=='--':\n \n return self.parse_comment(i)\n elif rawdata[j]=='[':\n \n \n \n \n return self.parse_marked_section(i)\n else:\n decltype,j=self._scan_name(j,i)\n if j <0:\n return j\n if decltype ==\"doctype\":\n self._decl_otherchars=''\n while j \":\n \n data=rawdata[i+2:j]\n if decltype ==\"doctype\":\n self.handle_decl(data)\n else:\n \n \n \n \n self.unknown_decl(data)\n return j+1\n if c in \"\\\"'\":\n m=_declstringlit_match(rawdata,j)\n if not m:\n return -1\n j=m.end()\n elif c in \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\":\n name,j=self._scan_name(j,i)\n elif c in self._decl_otherchars:\n j=j+1\n elif c ==\"[\":\n \n if decltype ==\"doctype\":\n j=self._parse_doctype_subset(j+1,i)\n elif decltype in{\"attlist\",\"linktype\",\"link\",\"element\"}:\n \n \n \n \n raise AssertionError(\"unsupported '[' char in %s declaration\"%decltype)\n else:\n raise AssertionError(\"unexpected '[' char in declaration\")\n else:\n raise AssertionError(\"unexpected %r char in declaration\"%rawdata[j])\n if j <0:\n return j\n return -1\n \n \n \n def parse_marked_section(self,i,report=1):\n rawdata=self.rawdata\n assert rawdata[i:i+3]=='n:\n \n return -1\n if rawdata[j:j+4]==\"\n \n \"\"\"%(self.OutputString(attrs).replace('\"',r'\\\"'))\n \n def OutputString(self,attrs=None):\n \n \n result=[]\n append=result.append\n \n \n append(\"%s=%s\"%(self.key,self.coded_value))\n \n \n if attrs is None:\n attrs=self._reserved\n items=sorted(self.items())\n for key,value in items:\n if value ==\"\":\n continue\n if key not in attrs:\n continue\n if key ==\"expires\"and isinstance(value,int):\n append(\"%s=%s\"%(self._reserved[key],_getdate(value)))\n elif key ==\"max-age\"and isinstance(value,int):\n append(\"%s=%d\"%(self._reserved[key],value))\n elif key ==\"comment\"and isinstance(value,str):\n append(\"%s=%s\"%(self._reserved[key],_quote(value)))\n elif key in self._flags:\n if value:\n append(str(self._reserved[key]))\n else:\n append(\"%s=%s\"%(self._reserved[key],value))\n \n \n return _semispacejoin(result)\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \n \n \n \n \n \n \n \n \n \n_LegalKeyChars=r\"\\w\\d!#%&'~_`><@,:/\\$\\*\\+\\-\\.\\^\\|\\)\\(\\?\\}\\{\\=\"\n_LegalValueChars=_LegalKeyChars+r'\\[\\]'\n_CookiePattern=re.compile(r\"\"\"\n \\s* # Optional whitespace at start of cookie\n (?P # Start of group 'key'\n [\"\"\"+_LegalKeyChars+r\"\"\"]+? # Any word of at least one letter\n ) # End of group 'key'\n ( # Optional group: there may not be a value.\n \\s*=\\s* # Equal Sign\n (?P # Start of group 'val'\n \"(?:[^\\\\\"]|\\\\.)*\" # Any doublequoted string\n | # or\n \\w{3},\\s[\\w\\d\\s-]{9,11}\\s[\\d:]{8}\\sGMT # Special case for \"expires\" attr\n | # or\n [\"\"\"+_LegalValueChars+r\"\"\"]* # Any word or empty string\n ) # End of group 'val'\n )? # End of optional value group\n \\s* # Any number of spaces.\n (\\s+|;|$) # Ending either at space, semicolon, or EOS.\n \"\"\",re.ASCII |re.VERBOSE)\n\n\n\n\n\nclass BaseCookie(dict):\n ''\n \n def value_decode(self,val):\n ''\n\n\n\n\n \n return val,val\n \n def value_encode(self,val):\n ''\n\n\n\n \n strval=str(val)\n return strval,strval\n \n def __init__(self,input=None):\n if input:\n self.load(input)\n \n def __set(self,key,real_value,coded_value):\n ''\n M=self.get(key,Morsel())\n M.set(key,real_value,coded_value)\n dict.__setitem__(self,key,M)\n \n def __setitem__(self,key,value):\n ''\n if isinstance(value,Morsel):\n \n dict.__setitem__(self,key,value)\n else:\n rval,cval=self.value_encode(value)\n self.__set(key,rval,cval)\n \n def output(self,attrs=None,header=\"Set-Cookie:\",sep=\"\\015\\012\"):\n ''\n result=[]\n items=sorted(self.items())\n for key,value in items:\n result.append(value.output(attrs,header))\n return sep.join(result)\n \n __str__=output\n \n def __repr__(self):\n l=[]\n items=sorted(self.items())\n for key,value in items:\n l.append('%s=%s'%(key,repr(value.value)))\n return '<%s: %s>'%(self.__class__.__name__,_spacejoin(l))\n \n def js_output(self,attrs=None):\n ''\n result=[]\n items=sorted(self.items())\n for key,value in items:\n result.append(value.js_output(attrs))\n return _nulljoin(result)\n \n def load(self,rawdata):\n ''\n\n\n\n \n if isinstance(rawdata,str):\n self.__parse_string(rawdata)\n else:\n \n for key,value in rawdata.items():\n self[key]=value\n return\n \n def __parse_string(self,str,patt=_CookiePattern):\n i=0\n n=len(str)\n parsed_items=[]\n morsel_seen=False\n \n TYPE_ATTRIBUTE=1\n TYPE_KEYVALUE=2\n \n \n \n \n while 0 <=i \"%(self.__class__.__name__,self._name_)\n \n CONNECT='CONNECT','Establish a connection to the server.'\n DELETE='DELETE','Remove the target.'\n GET='GET','Retrieve the target.'\n HEAD='HEAD','Same as GET, but only retrieve the status line and header section.'\n OPTIONS='OPTIONS','Describe the communication options for the target.'\n PATCH='PATCH','Apply partial modifications to a target.'\n POST='POST','Perform target-specific processing with the request payload.'\n PUT='PUT','Replace the target with the request payload.'\n TRACE='TRACE','Perform a message loop-back test along the path to the target.'\n", ["enum"], 1], "importlib.abc": [".py", "''\nfrom. import _bootstrap_external\nfrom. import machinery\ntry:\n import _frozen_importlib\nexcept ImportError as exc:\n if exc.name !='_frozen_importlib':\n raise\n _frozen_importlib=None\ntry:\n import _frozen_importlib_external\nexcept ImportError:\n _frozen_importlib_external=_bootstrap_external\nfrom._abc import Loader\nimport abc\nimport warnings\n\nfrom.resources import abc as _resources_abc\n\n\n__all__=[\n'Loader','MetaPathFinder','PathEntryFinder',\n'ResourceLoader','InspectLoader','ExecutionLoader',\n'FileLoader','SourceLoader',\n]\n\n\ndef __getattr__(name):\n ''\n\n\n \n if name in _resources_abc.__all__:\n obj=getattr(_resources_abc,name)\n warnings._deprecated(f\"{__name__}.{name}\",remove=(3,14))\n globals()[name]=obj\n return obj\n raise AttributeError(f'module {__name__ !r} has no attribute {name !r}')\n \n \ndef _register(abstract_cls,*classes):\n for cls in classes:\n abstract_cls.register(cls)\n if _frozen_importlib is not None:\n try:\n frozen_cls=getattr(_frozen_importlib,cls.__name__)\n except AttributeError:\n frozen_cls=getattr(_frozen_importlib_external,cls.__name__)\n abstract_cls.register(frozen_cls)\n \n \nclass MetaPathFinder(metaclass=abc.ABCMeta):\n\n ''\n \n \n \n \n def invalidate_caches(self):\n ''\n\n \n \n_register(MetaPathFinder,machinery.BuiltinImporter,machinery.FrozenImporter,\nmachinery.PathFinder,machinery.WindowsRegistryFinder)\n\n\nclass PathEntryFinder(metaclass=abc.ABCMeta):\n\n ''\n \n def invalidate_caches(self):\n ''\n\n \n \n_register(PathEntryFinder,machinery.FileFinder)\n\n\nclass ResourceLoader(Loader):\n\n ''\n\n\n\n\n \n \n @abc.abstractmethod\n def get_data(self,path):\n ''\n \n raise OSError\n \n \nclass InspectLoader(Loader):\n\n ''\n\n\n\n\n \n \n def is_package(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n def get_code(self,fullname):\n ''\n\n\n\n\n\n \n source=self.get_source(fullname)\n if source is None:\n return None\n return self.source_to_code(source)\n \n @abc.abstractmethod\n def get_source(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n @staticmethod\n def source_to_code(data,path=''):\n ''\n\n\n \n return compile(data,path,'exec',dont_inherit=True)\n \n exec_module=_bootstrap_external._LoaderBasics.exec_module\n load_module=_bootstrap_external._LoaderBasics.load_module\n \n_register(InspectLoader,machinery.BuiltinImporter,machinery.FrozenImporter,machinery.NamespaceLoader)\n\n\nclass ExecutionLoader(InspectLoader):\n\n ''\n\n\n\n\n \n \n @abc.abstractmethod\n def get_filename(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n def get_code(self,fullname):\n ''\n\n\n\n \n source=self.get_source(fullname)\n if source is None:\n return None\n try:\n path=self.get_filename(fullname)\n except ImportError:\n return self.source_to_code(source)\n else:\n return self.source_to_code(source,path)\n \n_register(\nExecutionLoader,\nmachinery.ExtensionFileLoader,\nmachinery.AppleFrameworkLoader,\n)\n\n\nclass FileLoader(_bootstrap_external.FileLoader,ResourceLoader,ExecutionLoader):\n\n ''\n \n \n_register(FileLoader,machinery.SourceFileLoader,\nmachinery.SourcelessFileLoader)\n\n\nclass SourceLoader(_bootstrap_external.SourceLoader,ResourceLoader,ExecutionLoader):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def path_mtime(self,path):\n ''\n if self.path_stats.__func__ is SourceLoader.path_stats:\n raise OSError\n return int(self.path_stats(path)['mtime'])\n \n def path_stats(self,path):\n ''\n\n\n\n\n \n if self.path_mtime.__func__ is SourceLoader.path_mtime:\n raise OSError\n return{'mtime':self.path_mtime(path)}\n \n def set_data(self,path,data):\n ''\n\n\n\n\n\n\n \n \n_register(SourceLoader,machinery.SourceFileLoader)\n", ["_frozen_importlib", "_frozen_importlib_external", "abc", "importlib", "importlib._abc", "importlib._bootstrap_external", "importlib.machinery", "importlib.resources", "importlib.resources.abc", "warnings"]], "importlib.machinery": [".py", "''\n\nfrom._bootstrap import ModuleSpec\nfrom._bootstrap import BuiltinImporter\nfrom._bootstrap import FrozenImporter\nfrom._bootstrap_external import(SOURCE_SUFFIXES,DEBUG_BYTECODE_SUFFIXES,\nOPTIMIZED_BYTECODE_SUFFIXES,BYTECODE_SUFFIXES,\nEXTENSION_SUFFIXES)\nfrom._bootstrap_external import WindowsRegistryFinder\nfrom._bootstrap_external import PathFinder\nfrom._bootstrap_external import FileFinder\nfrom._bootstrap_external import SourceFileLoader\nfrom._bootstrap_external import SourcelessFileLoader\nfrom._bootstrap_external import ExtensionFileLoader\nfrom._bootstrap_external import AppleFrameworkLoader\nfrom._bootstrap_external import NamespaceLoader\n\n\ndef all_suffixes():\n ''\n return SOURCE_SUFFIXES+BYTECODE_SUFFIXES+EXTENSION_SUFFIXES\n", ["importlib._bootstrap", "importlib._bootstrap_external"]], "importlib.readers": [".py", "''\n\n\n\n\n\n\nfrom.resources.readers import(\nFileReader,ZipReader,MultiplexedPath,NamespaceReader,\n)\n\n__all__=['FileReader','ZipReader','MultiplexedPath','NamespaceReader']\n", ["importlib.resources.readers"]], "importlib.simple": [".py", "''\n\n\n\n\n\n\nfrom.resources.simple import(\nSimpleReader,ResourceHandle,ResourceContainer,TraversableReader,\n)\n\n__all__=[\n'SimpleReader','ResourceHandle','ResourceContainer','TraversableReader',\n]\n", ["importlib.resources.simple"]], "importlib.util": [".py", "''\nfrom._abc import Loader\nfrom._bootstrap import module_from_spec\nfrom._bootstrap import _resolve_name\nfrom._bootstrap import spec_from_loader\nfrom._bootstrap import _find_spec\nfrom._bootstrap_external import MAGIC_NUMBER\nfrom._bootstrap_external import _RAW_MAGIC_NUMBER\nfrom._bootstrap_external import cache_from_source\nfrom._bootstrap_external import decode_source\nfrom._bootstrap_external import source_from_cache\nfrom._bootstrap_external import spec_from_file_location\n\nfrom contextlib import contextmanager\nimport _imp\nimport functools\nimport sys\nimport types\nimport warnings\n\n\ndef source_hash(source_bytes):\n ''\n return _imp.source_hash(_RAW_MAGIC_NUMBER,source_bytes)\n \n \ndef resolve_name(name,package):\n ''\n if not name.startswith('.'):\n return name\n elif not package:\n raise ImportError(f'no package specified for {repr(name)} '\n '(required for relative module names)')\n level=0\n for character in name:\n if character !='.':\n break\n level +=1\n return _resolve_name(name[level:],package,level)\n \n \ndef _find_spec_from_path(name,path=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if name not in sys.modules:\n return _find_spec(name,path)\n else:\n module=sys.modules[name]\n if module is None:\n return None\n try:\n spec=module.__spec__\n except AttributeError:\n raise ValueError('{}.__spec__ is not set'.format(name))from None\n else:\n if spec is None:\n raise ValueError('{}.__spec__ is None'.format(name))\n return spec\n \n \ndef find_spec(name,package=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n fullname=resolve_name(name,package)if name.startswith('.')else name\n if fullname not in sys.modules:\n parent_name=fullname.rpartition('.')[0]\n if parent_name:\n parent=__import__(parent_name,fromlist=['__path__'])\n try:\n parent_path=parent.__path__\n except AttributeError as e:\n raise ModuleNotFoundError(\n f\"__path__ attribute not found on {parent_name !r} \"\n f\"while trying to find {fullname !r}\",name=fullname)from e\n else:\n parent_path=None\n return _find_spec(fullname,parent_path)\n else:\n module=sys.modules[fullname]\n if module is None:\n return None\n try:\n spec=module.__spec__\n except AttributeError:\n raise ValueError('{}.__spec__ is not set'.format(name))from None\n else:\n if spec is None:\n raise ValueError('{}.__spec__ is None'.format(name))\n return spec\n \n \n@contextmanager\ndef _module_to_load(name):\n is_reload=name in sys.modules\n \n module=sys.modules.get(name)\n if not is_reload:\n \n \n \n module=type(sys)(name)\n \n \n module.__initializing__=True\n sys.modules[name]=module\n try:\n yield module\n except Exception:\n if not is_reload:\n try:\n del sys.modules[name]\n except KeyError:\n pass\n finally:\n module.__initializing__=False\n \n \ndef set_package(fxn):\n ''\n\n\n\n \n @functools.wraps(fxn)\n def set_package_wrapper(*args,**kwargs):\n warnings.warn('The import system now takes care of this automatically; '\n 'this decorator is slated for removal in Python 3.12',\n DeprecationWarning,stacklevel=2)\n module=fxn(*args,**kwargs)\n if getattr(module,'__package__',None)is None:\n module.__package__=module.__name__\n if not hasattr(module,'__path__'):\n module.__package__=module.__package__.rpartition('.')[0]\n return module\n return set_package_wrapper\n \n \ndef set_loader(fxn):\n ''\n\n\n\n \n @functools.wraps(fxn)\n def set_loader_wrapper(self,*args,**kwargs):\n warnings.warn('The import system now takes care of this automatically; '\n 'this decorator is slated for removal in Python 3.12',\n DeprecationWarning,stacklevel=2)\n module=fxn(self,*args,**kwargs)\n if getattr(module,'__loader__',None)is None:\n module.__loader__=self\n return module\n return set_loader_wrapper\n \n \ndef module_for_loader(fxn):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n warnings.warn('The import system now takes care of this automatically; '\n 'this decorator is slated for removal in Python 3.12',\n DeprecationWarning,stacklevel=2)\n @functools.wraps(fxn)\n def module_for_loader_wrapper(self,fullname,*args,**kwargs):\n with _module_to_load(fullname)as module:\n module.__loader__=self\n try:\n is_package=self.is_package(fullname)\n except(ImportError,AttributeError):\n pass\n else:\n if is_package:\n module.__package__=fullname\n else:\n module.__package__=fullname.rpartition('.')[0]\n \n return fxn(self,module,*args,**kwargs)\n \n return module_for_loader_wrapper\n \n \nclass _LazyModule(types.ModuleType):\n\n ''\n \n def __getattribute__(self,attr):\n ''\n \n \n \n self.__class__=types.ModuleType\n \n \n original_name=self.__spec__.name\n \n \n attrs_then=self.__spec__.loader_state['__dict__']\n attrs_now=self.__dict__\n attrs_updated={}\n for key,value in attrs_now.items():\n \n \n if key not in attrs_then:\n attrs_updated[key]=value\n elif id(attrs_now[key])!=id(attrs_then[key]):\n attrs_updated[key]=value\n self.__spec__.loader.exec_module(self)\n \n \n if original_name in sys.modules:\n if id(self)!=id(sys.modules[original_name]):\n raise ValueError(f\"module object for {original_name !r} \"\n \"substituted in sys.modules during a lazy \"\n \"load\")\n \n \n self.__dict__.update(attrs_updated)\n return getattr(self,attr)\n \n def __delattr__(self,attr):\n ''\n \n \n self.__getattribute__(attr)\n delattr(self,attr)\n \n \nclass LazyLoader(Loader):\n\n ''\n \n @staticmethod\n def __check_eager_loader(loader):\n if not hasattr(loader,'exec_module'):\n raise TypeError('loader must define exec_module()')\n \n @classmethod\n def factory(cls,loader):\n ''\n cls.__check_eager_loader(loader)\n return lambda *args,**kwargs:cls(loader(*args,**kwargs))\n \n def __init__(self,loader):\n self.__check_eager_loader(loader)\n self.loader=loader\n \n def create_module(self,spec):\n return self.loader.create_module(spec)\n \n def exec_module(self,module):\n ''\n module.__spec__.loader=self.loader\n module.__loader__=self.loader\n \n \n \n \n loader_state={}\n loader_state['__dict__']=module.__dict__.copy()\n loader_state['__class__']=module.__class__\n module.__spec__.loader_state=loader_state\n module.__class__=_LazyModule\n", ["_imp", "contextlib", "functools", "importlib._abc", "importlib._bootstrap", "importlib._bootstrap_external", "sys", "types", "warnings"]], "importlib._abc": [".py", "''\nfrom. import _bootstrap\nimport abc\n\n\nclass Loader(metaclass=abc.ABCMeta):\n\n ''\n \n def create_module(self,spec):\n ''\n\n\n\n\n \n \n return None\n \n \n \n \n def load_module(self,fullname):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not hasattr(self,'exec_module'):\n raise ImportError\n \n return _bootstrap._load_module_shim(self,fullname)\n", ["abc", "importlib", "importlib._bootstrap"]], "importlib._bootstrap": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_bootstrap_external=None\n_thread=None\nimport _weakref\n\ndef _wrap(new,old):\n ''\n for replace in['__module__','__name__','__qualname__','__doc__']:\n if hasattr(old,replace):\n setattr(new,replace,getattr(old,replace))\n new.__dict__.update(old.__dict__)\n \n \ndef _new_module(name):\n return type(sys)(name)\n \n \n \n \n \n \n_module_locks={}\n\n_blocking_on={}\n\n\nclass _DeadlockError(RuntimeError):\n pass\n \n \nclass _ModuleLock:\n ''\n\n\n \n \n def __init__(self,name):\n self.lock=_thread.allocate_lock()\n self.wakeup=_thread.allocate_lock()\n self.name=name\n self.owner=None\n self.count=0\n self.waiters=0\n \n def has_deadlock(self):\n \n me=_thread.get_ident()\n tid=self.owner\n while True:\n lock=_blocking_on.get(tid)\n if lock is None:\n return False\n tid=lock.owner\n if tid ==me:\n return True\n \n def acquire(self):\n ''\n\n\n\n \n tid=_thread.get_ident()\n _blocking_on[tid]=self\n try:\n while True:\n with self.lock:\n if self.count ==0 or self.owner ==tid:\n self.owner=tid\n self.count +=1\n return True\n if self.has_deadlock():\n raise _DeadlockError('deadlock detected by %r'%self)\n if self.wakeup.acquire(False):\n self.waiters +=1\n \n self.wakeup.acquire()\n self.wakeup.release()\n finally:\n del _blocking_on[tid]\n \n def release(self):\n tid=_thread.get_ident()\n with self.lock:\n if self.owner !=tid:\n raise RuntimeError('cannot release un-acquired lock')\n assert self.count >0\n self.count -=1\n if self.count ==0:\n self.owner=None\n if self.waiters:\n self.waiters -=1\n self.wakeup.release()\n \n def __repr__(self):\n return '_ModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _DummyModuleLock:\n ''\n \n \n def __init__(self,name):\n self.name=name\n self.count=0\n \n def acquire(self):\n self.count +=1\n return True\n \n def release(self):\n if self.count ==0:\n raise RuntimeError('cannot release un-acquired lock')\n self.count -=1\n \n def __repr__(self):\n return '_DummyModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _ModuleLockManager:\n\n def __init__(self,name):\n self._name=name\n self._lock=None\n \n def __enter__(self):\n self._lock=_get_module_lock(self._name)\n self._lock.acquire()\n \n def __exit__(self,*args,**kwargs):\n self._lock.release()\n \n \n \n \ndef _get_module_lock(name):\n ''\n\n\n \n \n _imp.acquire_lock()\n try:\n try:\n lock=_module_locks[name]()\n except KeyError:\n lock=None\n \n if lock is None:\n if _thread is None:\n lock=_DummyModuleLock(name)\n else:\n lock=_ModuleLock(name)\n \n def cb(ref,name=name):\n _imp.acquire_lock()\n try:\n \n \n \n if _module_locks.get(name)is ref:\n del _module_locks[name]\n finally:\n _imp.release_lock()\n \n _module_locks[name]=_weakref.ref(lock,cb)\n finally:\n _imp.release_lock()\n \n return lock\n \n \ndef _lock_unlock_module(name):\n ''\n\n\n\n \n lock=_get_module_lock(name)\n try:\n lock.acquire()\n except _DeadlockError:\n \n \n pass\n else:\n lock.release()\n \n \ndef _call_with_frames_removed(f,*args,**kwds):\n ''\n\n\n\n\n\n \n return f(*args,**kwds)\n \n \ndef _verbose_message(message,*args,verbosity=1):\n ''\n if sys.flags.verbose >=verbosity:\n if not message.startswith(('#','import ')):\n message='# '+message\n print(message.format(*args),file=sys.stderr)\n \n \ndef _requires_builtin(fxn):\n ''\n def _requires_builtin_wrapper(self,fullname):\n if fullname not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_builtin_wrapper,fxn)\n return _requires_builtin_wrapper\n \n \ndef _requires_frozen(fxn):\n ''\n def _requires_frozen_wrapper(self,fullname):\n if not _imp.is_frozen(fullname):\n raise ImportError('{!r} is not a frozen module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_frozen_wrapper,fxn)\n return _requires_frozen_wrapper\n \n \n \ndef _load_module_shim(self,fullname):\n ''\n\n\n\n \n spec=spec_from_loader(fullname,self)\n if fullname in sys.modules:\n module=sys.modules[fullname]\n _exec(spec,module)\n return sys.modules[fullname]\n else:\n return _load(spec)\n \n \n \ndef _module_repr(module):\n\n loader=getattr(module,'__loader__',None)\n if hasattr(loader,'module_repr'):\n \n \n \n try:\n return loader.module_repr(module)\n except Exception:\n pass\n try:\n spec=module.__spec__\n except AttributeError:\n pass\n else:\n if spec is not None:\n return _module_repr_from_spec(spec)\n \n \n \n try:\n name=module.__name__\n except AttributeError:\n name='?'\n try:\n filename=module.__file__\n except AttributeError:\n if loader is None:\n return ''.format(name)\n else:\n return ''.format(name,loader)\n else:\n return ''.format(name,filename)\n \n \nclass _installed_safely:\n\n def __init__(self,module):\n self._module=module\n self._spec=module.__spec__\n \n def __enter__(self):\n \n \n \n self._spec._initializing=True\n sys.modules[self._spec.name]=self._module\n \n def __exit__(self,*args):\n try:\n spec=self._spec\n if any(arg is not None for arg in args):\n try:\n del sys.modules[spec.name]\n except KeyError:\n pass\n else:\n _verbose_message('import {!r} # {!r}',spec.name,spec.loader)\n finally:\n self._spec._initializing=False\n \n \nclass ModuleSpec:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,name,loader,*,origin=None,loader_state=None,\n is_package=None):\n self.name=name\n self.loader=loader\n self.origin=origin\n self.loader_state=loader_state\n self.submodule_search_locations=[]if is_package else None\n \n \n self._set_fileattr=False\n self._cached=None\n \n def __repr__(self):\n args=['name={!r}'.format(self.name),\n 'loader={!r}'.format(self.loader)]\n if self.origin is not None:\n args.append('origin={!r}'.format(self.origin))\n if self.submodule_search_locations is not None:\n args.append('submodule_search_locations={}'\n .format(self.submodule_search_locations))\n return '{}({})'.format(self.__class__.__name__,', '.join(args))\n \n def __eq__(self,other):\n smsl=self.submodule_search_locations\n try:\n return(self.name ==other.name and\n self.loader ==other.loader and\n self.origin ==other.origin and\n smsl ==other.submodule_search_locations and\n self.cached ==other.cached and\n self.has_location ==other.has_location)\n except AttributeError:\n return False\n \n @property\n def cached(self):\n if self._cached is None:\n if self.origin is not None and self._set_fileattr:\n if _bootstrap_external is None:\n raise NotImplementedError\n self._cached=_bootstrap_external._get_cached(self.origin)\n return self._cached\n \n @cached.setter\n def cached(self,cached):\n self._cached=cached\n \n @property\n def parent(self):\n ''\n if self.submodule_search_locations is None:\n return self.name.rpartition('.')[0]\n else:\n return self.name\n \n @property\n def has_location(self):\n return self._set_fileattr\n \n @has_location.setter\n def has_location(self,value):\n self._set_fileattr=bool(value)\n \n \ndef spec_from_loader(name,loader,*,origin=None,is_package=None):\n ''\n if hasattr(loader,'get_filename'):\n if _bootstrap_external is None:\n raise NotImplementedError\n spec_from_file_location=_bootstrap_external.spec_from_file_location\n \n if is_package is None:\n return spec_from_file_location(name,loader=loader)\n search=[]if is_package else None\n return spec_from_file_location(name,loader=loader,\n submodule_search_locations=search)\n \n if is_package is None:\n if hasattr(loader,'is_package'):\n try:\n is_package=loader.is_package(name)\n except ImportError:\n is_package=None\n else:\n \n is_package=False\n \n return ModuleSpec(name,loader,origin=origin,is_package=is_package)\n \n \ndef _spec_from_module(module,loader=None,origin=None):\n\n try:\n spec=module.__spec__\n except AttributeError:\n pass\n else:\n if spec is not None:\n return spec\n \n name=module.__name__\n if loader is None:\n try:\n loader=module.__loader__\n except AttributeError:\n \n pass\n try:\n location=module.__file__\n except AttributeError:\n location=None\n if origin is None:\n if location is None:\n try:\n origin=loader._ORIGIN\n except AttributeError:\n origin=None\n else:\n origin=location\n try:\n cached=module.__cached__\n except AttributeError:\n cached=None\n try:\n submodule_search_locations=list(module.__path__)\n except AttributeError:\n submodule_search_locations=None\n \n spec=ModuleSpec(name,loader,origin=origin)\n spec._set_fileattr=False if location is None else True\n spec.cached=cached\n spec.submodule_search_locations=submodule_search_locations\n return spec\n \n \ndef _init_module_attrs(spec,module,*,override=False):\n\n\n\n if(override or getattr(module,'__name__',None)is None):\n try:\n module.__name__=spec.name\n except AttributeError:\n pass\n \n if override or getattr(module,'__loader__',None)is None:\n loader=spec.loader\n if loader is None:\n \n if spec.submodule_search_locations is not None:\n if _bootstrap_external is None:\n raise NotImplementedError\n _NamespaceLoader=_bootstrap_external._NamespaceLoader\n \n loader=_NamespaceLoader.__new__(_NamespaceLoader)\n loader._path=spec.submodule_search_locations\n spec.loader=loader\n \n \n \n \n \n \n \n \n \n \n module.__file__=None\n try:\n module.__loader__=loader\n except AttributeError:\n pass\n \n if override or getattr(module,'__package__',None)is None:\n try:\n module.__package__=spec.parent\n except AttributeError:\n pass\n \n try:\n module.__spec__=spec\n except AttributeError:\n pass\n \n if override or getattr(module,'__path__',None)is None:\n if spec.submodule_search_locations is not None:\n try:\n module.__path__=spec.submodule_search_locations\n except AttributeError:\n pass\n \n if spec.has_location:\n if override or getattr(module,'__file__',None)is None:\n try:\n module.__file__=spec.origin\n except AttributeError:\n pass\n \n if override or getattr(module,'__cached__',None)is None:\n if spec.cached is not None:\n try:\n module.__cached__=spec.cached\n except AttributeError:\n pass\n return module\n \n \ndef module_from_spec(spec):\n ''\n \n module=None\n if hasattr(spec.loader,'create_module'):\n \n \n module=spec.loader.create_module(spec)\n elif hasattr(spec.loader,'exec_module'):\n raise ImportError('loaders that define exec_module() '\n 'must also define create_module()')\n if module is None:\n module=_new_module(spec.name)\n _init_module_attrs(spec,module)\n return module\n \n \ndef _module_repr_from_spec(spec):\n ''\n \n name='?'if spec.name is None else spec.name\n if spec.origin is None:\n if spec.loader is None:\n return ''.format(name)\n else:\n return ''.format(name,spec.loader)\n else:\n if spec.has_location:\n return ''.format(name,spec.origin)\n else:\n return ''.format(spec.name,spec.origin)\n \n \n \ndef _exec(spec,module):\n ''\n name=spec.name\n with _ModuleLockManager(name):\n if sys.modules.get(name)is not module:\n msg='module {!r} not in sys.modules'.format(name)\n raise ImportError(msg,name=name)\n if spec.loader is None:\n if spec.submodule_search_locations is None:\n raise ImportError('missing loader',name=spec.name)\n \n _init_module_attrs(spec,module,override=True)\n return module\n _init_module_attrs(spec,module,override=True)\n if not hasattr(spec.loader,'exec_module'):\n \n \n \n spec.loader.load_module(name)\n else:\n spec.loader.exec_module(module)\n return sys.modules[name]\n \n \ndef _load_backward_compatible(spec):\n\n\n\n spec.loader.load_module(spec.name)\n \n module=sys.modules[spec.name]\n if getattr(module,'__loader__',None)is None:\n try:\n module.__loader__=spec.loader\n except AttributeError:\n pass\n if getattr(module,'__package__',None)is None:\n try:\n \n \n \n module.__package__=module.__name__\n if not hasattr(module,'__path__'):\n module.__package__=spec.name.rpartition('.')[0]\n except AttributeError:\n pass\n if getattr(module,'__spec__',None)is None:\n try:\n module.__spec__=spec\n except AttributeError:\n pass\n return module\n \ndef _load_unlocked(spec):\n\n if spec.loader is not None:\n \n if not hasattr(spec.loader,'exec_module'):\n return _load_backward_compatible(spec)\n \n module=module_from_spec(spec)\n with _installed_safely(module):\n if spec.loader is None:\n if spec.submodule_search_locations is None:\n raise ImportError('missing loader',name=spec.name)\n \n else:\n spec.loader.exec_module(module)\n \n \n \n \n return sys.modules[spec.name]\n \n \n \ndef _load(spec):\n ''\n\n\n\n\n\n\n \n with _ModuleLockManager(spec.name):\n return _load_unlocked(spec)\n \n \n \n \nclass BuiltinImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(module):\n ''\n\n\n\n \n return ''.format(module.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n if path is not None:\n return None\n if _imp.is_builtin(fullname):\n return spec_from_loader(fullname,cls,origin='built-in')\n else:\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None):\n ''\n\n\n\n\n\n \n spec=cls.find_spec(fullname,path)\n return spec.loader if spec is not None else None\n \n @classmethod\n def create_module(self,spec):\n ''\n if spec.name not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(spec.name),\n name=spec.name)\n return _call_with_frames_removed(_imp.create_builtin,spec)\n \n @classmethod\n def exec_module(self,module):\n ''\n _call_with_frames_removed(_imp.exec_builtin,module)\n \n @classmethod\n @_requires_builtin\n def get_code(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def is_package(cls,fullname):\n ''\n return False\n \n load_module=classmethod(_load_module_shim)\n \n \nclass FrozenImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(m):\n ''\n\n\n\n \n return ''.format(m.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n if _imp.is_frozen(fullname):\n return spec_from_loader(fullname,cls,origin='frozen')\n else:\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None):\n ''\n\n\n\n \n return cls if _imp.is_frozen(fullname)else None\n \n @classmethod\n def create_module(cls,spec):\n ''\n \n @staticmethod\n def exec_module(module):\n name=module.__spec__.name\n if not _imp.is_frozen(name):\n raise ImportError('{!r} is not a frozen module'.format(name),\n name=name)\n code=_call_with_frames_removed(_imp.get_frozen_object,name)\n exec(code,module.__dict__)\n \n @classmethod\n def load_module(cls,fullname):\n ''\n\n\n\n \n return _load_module_shim(cls,fullname)\n \n @classmethod\n @_requires_frozen\n def get_code(cls,fullname):\n ''\n return _imp.get_frozen_object(fullname)\n \n @classmethod\n @_requires_frozen\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_frozen\n def is_package(cls,fullname):\n ''\n return _imp.is_frozen_package(fullname)\n \n \n \n \nclass _ImportLockContext:\n\n ''\n \n def __enter__(self):\n ''\n _imp.acquire_lock()\n \n def __exit__(self,exc_type,exc_value,exc_traceback):\n ''\n _imp.release_lock()\n \n \ndef _resolve_name(name,package,level):\n ''\n bits=package.rsplit('.',level -1)\n if len(bits)= 0')\n if level >0:\n if not isinstance(package,str):\n raise TypeError('__package__ not set to a string')\n elif not package:\n raise ImportError('attempted relative import with no known parent '\n 'package')\n if not name and level ==0:\n raise ValueError('Empty module name')\n \n \n_ERR_MSG_PREFIX='No module named '\n_ERR_MSG=_ERR_MSG_PREFIX+'{!r}'\n\ndef _find_and_load_unlocked(name,import_):\n path=None\n parent=name.rpartition('.')[0]\n if parent:\n if parent not in sys.modules:\n _call_with_frames_removed(import_,parent)\n \n if name in sys.modules:\n return sys.modules[name]\n parent_module=sys.modules[parent]\n try:\n path=parent_module.__path__\n except AttributeError:\n msg=(_ERR_MSG+'; {!r} is not a package').format(name,parent)\n raise ModuleNotFoundError(msg,name=name)from None\n spec=_find_spec(name,path)\n if spec is None:\n raise ModuleNotFoundError(_ERR_MSG.format(name),name=name)\n else:\n module=_load_unlocked(spec)\n if parent:\n \n parent_module=sys.modules[parent]\n setattr(parent_module,name.rpartition('.')[2],module)\n return module\n \n \n_NEEDS_LOADING=object()\n\n\ndef _find_and_load(name,import_):\n ''\n with _ModuleLockManager(name):\n module=sys.modules.get(name,_NEEDS_LOADING)\n if module is _NEEDS_LOADING:\n return _find_and_load_unlocked(name,import_)\n \n if module is None:\n message=('import of {} halted; '\n 'None in sys.modules'.format(name))\n raise ModuleNotFoundError(message,name=name)\n \n _lock_unlock_module(name)\n return module\n \n \ndef _gcd_import(name,package=None,level=0):\n ''\n\n\n\n\n\n\n \n _sanity_check(name,package,level)\n if level >0:\n name=_resolve_name(name,package,level)\n return _find_and_load(name,_gcd_import)\n \n \ndef _handle_fromlist(module,fromlist,import_,*,recursive=False):\n ''\n\n\n\n\n\n \n \n \n if hasattr(module,'__path__'):\n for x in fromlist:\n if not isinstance(x,str):\n if recursive:\n where=module.__name__+'.__all__'\n else:\n where=\"``from list''\"\n raise TypeError(f\"Item in {where} must be str, \"\n f\"not {type(x).__name__}\")\n elif x =='*':\n if not recursive and hasattr(module,'__all__'):\n _handle_fromlist(module,module.__all__,import_,\n recursive=True)\n elif not hasattr(module,x):\n from_name='{}.{}'.format(module.__name__,x)\n try:\n _call_with_frames_removed(import_,from_name)\n except ModuleNotFoundError as exc:\n \n \n \n if(exc.name ==from_name and\n sys.modules.get(from_name,_NEEDS_LOADING)is not None):\n continue\n raise\n return module\n \n \ndef _calc___package__(globals):\n ''\n\n\n\n\n \n package=globals.get('__package__')\n spec=globals.get('__spec__')\n if package is not None:\n if spec is not None and package !=spec.parent:\n _warnings.warn(\"__package__ != __spec__.parent \"\n f\"({package !r} != {spec.parent !r})\",\n ImportWarning,stacklevel=3)\n return package\n elif spec is not None:\n return spec.parent\n else:\n _warnings.warn(\"can't resolve package from __spec__ or __package__, \"\n \"falling back on __name__ and __path__\",\n ImportWarning,stacklevel=3)\n package=globals['__name__']\n if '__path__'not in globals:\n package=package.rpartition('.')[0]\n return package\n \n \ndef __import__(name,globals=None,locals=None,fromlist=(),level=0):\n ''\n\n\n\n\n\n\n\n\n \n if level ==0:\n module=_gcd_import(name)\n else:\n globals_=globals if globals is not None else{}\n package=_calc___package__(globals_)\n module=_gcd_import(name,package,level)\n if not fromlist:\n \n \n if level ==0:\n return _gcd_import(name.partition('.')[0])\n elif not name:\n return module\n else:\n \n \n cut_off=len(name)-len(name.partition('.')[0])\n \n \n return sys.modules[module.__name__[:len(module.__name__)-cut_off]]\n else:\n return _handle_fromlist(module,fromlist,_gcd_import)\n \n \ndef _builtin_from_name(name):\n spec=BuiltinImporter.find_spec(name)\n if spec is None:\n raise ImportError('no built-in module named '+name)\n return _load_unlocked(spec)\n \n \ndef _setup(sys_module,_imp_module):\n ''\n\n\n\n\n\n \n global _imp,sys\n _imp=_imp_module\n sys=sys_module\n \n \n module_type=type(sys)\n for name,module in sys.modules.items():\n if isinstance(module,module_type):\n if name in sys.builtin_module_names:\n loader=BuiltinImporter\n elif _imp.is_frozen(name):\n loader=FrozenImporter\n else:\n continue\n spec=_spec_from_module(module,loader)\n _init_module_attrs(spec,module)\n \n \n self_module=sys.modules[__name__]\n \n \n for builtin_name in('_warnings',):\n if builtin_name not in sys.modules:\n builtin_module=_builtin_from_name(builtin_name)\n else:\n builtin_module=sys.modules[builtin_name]\n setattr(self_module,builtin_name,builtin_module)\n \n \ndef _install(sys_module,_imp_module):\n ''\n _setup(sys_module,_imp_module)\n \n sys.meta_path.append(BuiltinImporter)\n sys.meta_path.append(FrozenImporter)\n \n \ndef _install_external_importers():\n ''\n global _bootstrap_external\n import _frozen_importlib_external\n _bootstrap_external=_frozen_importlib_external\n _frozen_importlib_external._install(sys.modules[__name__])\n", ["_frozen_importlib_external", "_weakref"]], "importlib._bootstrap_external": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_bootstrap=None\n\n\nimport _imp\nimport _io\nimport sys\nimport _warnings\nimport marshal\n\n\n_MS_WINDOWS=(sys.platform =='win32')\nif _MS_WINDOWS:\n import nt as _os\n import winreg\nelse:\n import posix as _os\n \n \nif _MS_WINDOWS:\n path_separators=['\\\\','/']\nelse:\n path_separators=['/']\n \nassert all(len(sep)==1 for sep in path_separators)\npath_sep=path_separators[0]\npath_sep_tuple=tuple(path_separators)\npath_separators=''.join(path_separators)\n_pathseps_with_colon={f':{s}'for s in path_separators}\n\n\n\n_CASE_INSENSITIVE_PLATFORMS_STR_KEY='win',\n_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY='cygwin','darwin','ios','tvos','watchos'\n_CASE_INSENSITIVE_PLATFORMS=(_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY\n+_CASE_INSENSITIVE_PLATFORMS_STR_KEY)\n\n\ndef _make_relax_case():\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY):\n key='PYTHONCASEOK'\n else:\n key=b'PYTHONCASEOK'\n \n def _relax_case():\n ''\n return not sys.flags.ignore_environment and key in _os.environ\n else:\n def _relax_case():\n ''\n return False\n return _relax_case\n \n_relax_case=_make_relax_case()\n\n\ndef _pack_uint32(x):\n ''\n return(int(x)&0xFFFFFFFF).to_bytes(4,'little')\n \n \ndef _unpack_uint64(data):\n ''\n assert len(data)==8\n return int.from_bytes(data,'little')\n \ndef _unpack_uint32(data):\n ''\n assert len(data)==4\n return int.from_bytes(data,'little')\n \ndef _unpack_uint16(data):\n ''\n assert len(data)==2\n return int.from_bytes(data,'little')\n \n \nif _MS_WINDOWS:\n def _path_join(*path_parts):\n ''\n if not path_parts:\n return \"\"\n if len(path_parts)==1:\n return path_parts[0]\n root=\"\"\n path=[]\n for new_root,tail in map(_os._path_splitroot,path_parts):\n if new_root.startswith(path_sep_tuple)or new_root.endswith(path_sep_tuple):\n root=new_root.rstrip(path_separators)or root\n path=[path_sep+tail]\n elif new_root.endswith(':'):\n if root.casefold()!=new_root.casefold():\n \n \n root=new_root\n path=[tail]\n else:\n path.append(tail)\n else:\n root=new_root or root\n path.append(tail)\n path=[p.rstrip(path_separators)for p in path if p]\n if len(path)==1 and not path[0]:\n \n return root+path_sep\n return root+path_sep.join(path)\n \nelse:\n def _path_join(*path_parts):\n ''\n return path_sep.join([part.rstrip(path_separators)\n for part in path_parts if part])\n \n \ndef _path_split(path):\n ''\n i=max(path.rfind(p)for p in path_separators)\n if i <0:\n return '',path\n return path[:i],path[i+1:]\n \n \ndef _path_stat(path):\n ''\n\n\n\n\n \n return _os.stat(path)\n \n \ndef _path_is_mode_type(path,mode):\n ''\n try:\n stat_info=_path_stat(path)\n except OSError:\n return False\n return(stat_info.st_mode&0o170000)==mode\n \n \ndef _path_isfile(path):\n ''\n return _path_is_mode_type(path,0o100000)\n \n \ndef _path_isdir(path):\n ''\n if not path:\n path=_os.getcwd()\n return _path_is_mode_type(path,0o040000)\n \n \nif _MS_WINDOWS:\n def _path_isabs(path):\n ''\n if not path:\n return False\n root=_os._path_splitroot(path)[0].replace('/','\\\\')\n return len(root)>1 and(root.startswith('\\\\\\\\')or root.endswith('\\\\'))\n \nelse:\n def _path_isabs(path):\n ''\n return path.startswith(path_separators)\n \n \ndef _path_abspath(path):\n ''\n if not _path_isabs(path):\n for sep in path_separators:\n path=path.removeprefix(f\".{sep}\")\n return _path_join(_os.getcwd(),path)\n else:\n return path\n \n \ndef _write_atomic(path,data,mode=0o666):\n ''\n\n \n \n path_tmp=f'{path}.{id(path)}'\n fd=_os.open(path_tmp,\n _os.O_EXCL |_os.O_CREAT |_os.O_WRONLY,mode&0o666)\n try:\n \n \n with _io.FileIO(fd,'wb')as file:\n file.write(data)\n _os.replace(path_tmp,path)\n except OSError:\n try:\n _os.unlink(path_tmp)\n except OSError:\n pass\n raise\n \n \n_code_type=type(_write_atomic.__code__)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nMAGIC_NUMBER=(3570).to_bytes(2,'little')+b'\\r\\n'\n\n_RAW_MAGIC_NUMBER=int.from_bytes(MAGIC_NUMBER,'little')\n\n_PYCACHE='__pycache__'\n_OPT='opt-'\n\nSOURCE_SUFFIXES=['.py']\nif _MS_WINDOWS:\n SOURCE_SUFFIXES.append('.pyw')\n \nEXTENSION_SUFFIXES=_imp.extension_suffixes()\n\nBYTECODE_SUFFIXES=['.pyc']\n\nDEBUG_BYTECODE_SUFFIXES=OPTIMIZED_BYTECODE_SUFFIXES=BYTECODE_SUFFIXES\n\ndef cache_from_source(path,debug_override=None,*,optimization=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if debug_override is not None:\n _warnings.warn('the debug_override parameter is deprecated; use '\n \"'optimization' instead\",DeprecationWarning)\n if optimization is not None:\n message='debug_override or optimization must be set to None'\n raise TypeError(message)\n optimization=''if debug_override else 1\n path=_os.fspath(path)\n head,tail=_path_split(path)\n base,sep,rest=tail.rpartition('.')\n tag=sys.implementation.cache_tag\n if tag is None:\n raise NotImplementedError('sys.implementation.cache_tag is None')\n almost_filename=''.join([(base if base else rest),sep,tag])\n if optimization is None:\n if sys.flags.optimize ==0:\n optimization=''\n else:\n optimization=sys.flags.optimize\n optimization=str(optimization)\n if optimization !='':\n if not optimization.isalnum():\n raise ValueError(f'{optimization !r} is not alphanumeric')\n almost_filename=f'{almost_filename}.{_OPT}{optimization}'\n filename=almost_filename+BYTECODE_SUFFIXES[0]\n if sys.pycache_prefix is not None:\n \n \n \n \n \n \n \n \n head=_path_abspath(head)\n \n \n \n \n if head[1]==':'and head[0]not in path_separators:\n head=head[2:]\n \n \n \n return _path_join(\n sys.pycache_prefix,\n head.lstrip(path_separators),\n filename,\n )\n return _path_join(head,_PYCACHE,filename)\n \n \ndef source_from_cache(path):\n ''\n\n\n\n\n\n\n \n if sys.implementation.cache_tag is None:\n raise NotImplementedError('sys.implementation.cache_tag is None')\n path=_os.fspath(path)\n head,pycache_filename=_path_split(path)\n found_in_pycache_prefix=False\n if sys.pycache_prefix is not None:\n stripped_path=sys.pycache_prefix.rstrip(path_separators)\n if head.startswith(stripped_path+path_sep):\n head=head[len(stripped_path):]\n found_in_pycache_prefix=True\n if not found_in_pycache_prefix:\n head,pycache=_path_split(head)\n if pycache !=_PYCACHE:\n raise ValueError(f'{_PYCACHE} not bottom-level directory in '\n f'{path !r}')\n dot_count=pycache_filename.count('.')\n if dot_count not in{2,3}:\n raise ValueError(f'expected only 2 or 3 dots in {pycache_filename !r}')\n elif dot_count ==3:\n optimization=pycache_filename.rsplit('.',2)[-2]\n if not optimization.startswith(_OPT):\n raise ValueError(\"optimization portion of filename does not start \"\n f\"with {_OPT !r}\")\n opt_level=optimization[len(_OPT):]\n if not opt_level.isalnum():\n raise ValueError(f\"optimization level {optimization !r} is not an \"\n \"alphanumeric value\")\n base_filename=pycache_filename.partition('.')[0]\n return _path_join(head,base_filename+SOURCE_SUFFIXES[0])\n \n \ndef _get_sourcefile(bytecode_path):\n ''\n\n\n\n\n \n if len(bytecode_path)==0:\n return None\n rest,_,extension=bytecode_path.rpartition('.')\n if not rest or extension.lower()[-3:-1]!='py':\n return bytecode_path\n try:\n source_path=source_from_cache(bytecode_path)\n except(NotImplementedError,ValueError):\n source_path=bytecode_path[:-1]\n return source_path if _path_isfile(source_path)else bytecode_path\n \n \ndef _get_cached(filename):\n if filename.endswith(tuple(SOURCE_SUFFIXES)):\n try:\n return cache_from_source(filename)\n except NotImplementedError:\n pass\n elif filename.endswith(tuple(BYTECODE_SUFFIXES)):\n return filename\n else:\n return None\n \n \ndef _calc_mode(path):\n ''\n try:\n mode=_path_stat(path).st_mode\n except OSError:\n mode=0o666\n \n \n mode |=0o200\n return mode\n \n \ndef _check_name(method):\n ''\n\n\n\n\n\n \n def _check_name_wrapper(self,name=None,*args,**kwargs):\n if name is None:\n name=self.name\n elif self.name !=name:\n raise ImportError('loader for %s cannot handle %s'%\n (self.name,name),name=name)\n return method(self,name,*args,**kwargs)\n \n \n \n if _bootstrap is not None:\n _wrap=_bootstrap._wrap\n else:\n def _wrap(new,old):\n for replace in['__module__','__name__','__qualname__','__doc__']:\n if hasattr(old,replace):\n setattr(new,replace,getattr(old,replace))\n new.__dict__.update(old.__dict__)\n \n _wrap(_check_name_wrapper,method)\n return _check_name_wrapper\n \n \ndef _classify_pyc(data,name,exc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n magic=data[:4]\n if magic !=MAGIC_NUMBER:\n message=f'bad magic number in {name !r}: {magic !r}'\n _bootstrap._verbose_message('{}',message)\n raise ImportError(message,**exc_details)\n if len(data)<16:\n message=f'reached EOF while reading pyc header of {name !r}'\n _bootstrap._verbose_message('{}',message)\n raise EOFError(message)\n flags=_unpack_uint32(data[4:8])\n \n if flags&~0b11:\n message=f'invalid flags {flags !r} in {name !r}'\n raise ImportError(message,**exc_details)\n return flags\n \n \ndef _validate_timestamp_pyc(data,source_mtime,source_size,name,\nexc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if _unpack_uint32(data[8:12])!=(source_mtime&0xFFFFFFFF):\n message=f'bytecode is stale for {name !r}'\n _bootstrap._verbose_message('{}',message)\n raise ImportError(message,**exc_details)\n if(source_size is not None and\n _unpack_uint32(data[12:16])!=(source_size&0xFFFFFFFF)):\n raise ImportError(f'bytecode is stale for {name !r}',**exc_details)\n \n \ndef _validate_hash_pyc(data,source_hash,name,exc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if data[8:16]!=source_hash:\n raise ImportError(\n f'hash in bytecode doesn\\'t match hash of source {name !r}',\n **exc_details,\n )\n \n \ndef _compile_bytecode(data,name=None,bytecode_path=None,source_path=None):\n ''\n code=marshal.loads(data)\n if isinstance(code,_code_type):\n _bootstrap._verbose_message('code object from {!r}',bytecode_path)\n if source_path is not None:\n _imp._fix_co_filename(code,source_path)\n return code\n else:\n raise ImportError(f'Non-code object in {bytecode_path !r}',\n name=name,path=bytecode_path)\n \n \ndef _code_to_timestamp_pyc(code,mtime=0,source_size=0):\n ''\n data=bytearray(MAGIC_NUMBER)\n data.extend(_pack_uint32(0))\n data.extend(_pack_uint32(mtime))\n data.extend(_pack_uint32(source_size))\n data.extend(marshal.dumps(code))\n return data\n \n \ndef _code_to_hash_pyc(code,source_hash,checked=True):\n ''\n data=bytearray(MAGIC_NUMBER)\n flags=0b1 |checked <<1\n data.extend(_pack_uint32(flags))\n assert len(source_hash)==8\n data.extend(source_hash)\n data.extend(marshal.dumps(code))\n return data\n \n \ndef decode_source(source_bytes):\n ''\n\n\n \n import tokenize\n source_bytes_readline=_io.BytesIO(source_bytes).readline\n encoding=tokenize.detect_encoding(source_bytes_readline)\n newline_decoder=_io.IncrementalNewlineDecoder(None,True)\n return newline_decoder.decode(source_bytes.decode(encoding[0]))\n \n \n \n \n_POPULATE=object()\n\n\ndef spec_from_file_location(name,location=None,*,loader=None,\nsubmodule_search_locations=_POPULATE):\n ''\n\n\n\n\n\n\n\n\n \n if location is None:\n \n \n \n location=''\n if hasattr(loader,'get_filename'):\n \n try:\n location=loader.get_filename(name)\n except ImportError:\n pass\n else:\n location=_os.fspath(location)\n try:\n location=_path_abspath(location)\n except OSError:\n pass\n \n \n \n \n \n \n \n spec=_bootstrap.ModuleSpec(name,loader,origin=location)\n spec._set_fileattr=True\n \n \n if loader is None:\n for loader_class,suffixes in _get_supported_file_loaders():\n if location.endswith(tuple(suffixes)):\n loader=loader_class(name,location)\n spec.loader=loader\n break\n else:\n return None\n \n \n if submodule_search_locations is _POPULATE:\n \n if hasattr(loader,'is_package'):\n try:\n is_package=loader.is_package(name)\n except ImportError:\n pass\n else:\n if is_package:\n spec.submodule_search_locations=[]\n else:\n spec.submodule_search_locations=submodule_search_locations\n if spec.submodule_search_locations ==[]:\n if location:\n dirname=_path_split(location)[0]\n spec.submodule_search_locations.append(dirname)\n \n return spec\n \n \ndef _bless_my_loader(module_globals):\n ''\n\n\n \n \n \n \n \n \n \n \n if not isinstance(module_globals,dict):\n return None\n \n missing=object()\n loader=module_globals.get('__loader__',None)\n spec=module_globals.get('__spec__',missing)\n \n if loader is None:\n if spec is missing:\n \n \n return None\n elif spec is None:\n raise ValueError('Module globals is missing a __spec__.loader')\n \n spec_loader=getattr(spec,'loader',missing)\n \n if spec_loader in(missing,None):\n if loader is None:\n exc=AttributeError if spec_loader is missing else ValueError\n raise exc('Module globals is missing a __spec__.loader')\n _warnings.warn(\n 'Module globals is missing a __spec__.loader',\n DeprecationWarning)\n spec_loader=loader\n \n assert spec_loader is not None\n if loader is not None and loader !=spec_loader:\n _warnings.warn(\n 'Module globals; __loader__ != __spec__.loader',\n DeprecationWarning)\n return loader\n \n return spec_loader\n \n \n \n \nclass WindowsRegistryFinder:\n\n ''\n \n REGISTRY_KEY=(\n 'Software\\\\Python\\\\PythonCore\\\\{sys_version}'\n '\\\\Modules\\\\{fullname}')\n REGISTRY_KEY_DEBUG=(\n 'Software\\\\Python\\\\PythonCore\\\\{sys_version}'\n '\\\\Modules\\\\{fullname}\\\\Debug')\n DEBUG_BUILD=(_MS_WINDOWS and '_d.pyd'in EXTENSION_SUFFIXES)\n \n @staticmethod\n def _open_registry(key):\n try:\n return winreg.OpenKey(winreg.HKEY_CURRENT_USER,key)\n except OSError:\n return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,key)\n \n @classmethod\n def _search_registry(cls,fullname):\n if cls.DEBUG_BUILD:\n registry_key=cls.REGISTRY_KEY_DEBUG\n else:\n registry_key=cls.REGISTRY_KEY\n key=registry_key.format(fullname=fullname,\n sys_version='%d.%d'%sys.version_info[:2])\n try:\n with cls._open_registry(key)as hkey:\n filepath=winreg.QueryValue(hkey,'')\n except OSError:\n return None\n return filepath\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n filepath=cls._search_registry(fullname)\n if filepath is None:\n return None\n try:\n _path_stat(filepath)\n except OSError:\n return None\n for loader,suffixes in _get_supported_file_loaders():\n if filepath.endswith(tuple(suffixes)):\n spec=_bootstrap.spec_from_loader(fullname,\n loader(fullname,filepath),\n origin=filepath)\n return spec\n \n \nclass _LoaderBasics:\n\n ''\n \n \n def is_package(self,fullname):\n ''\n \n filename=_path_split(self.get_filename(fullname))[1]\n filename_base=filename.rsplit('.',1)[0]\n tail_name=fullname.rpartition('.')[2]\n return filename_base =='__init__'and tail_name !='__init__'\n \n def create_module(self,spec):\n ''\n \n def exec_module(self,module):\n ''\n code=self.get_code(module.__name__)\n if code is None:\n raise ImportError(f'cannot load module {module.__name__ !r} when '\n 'get_code() returns None')\n _bootstrap._call_with_frames_removed(exec,code,module.__dict__)\n \n def load_module(self,fullname):\n ''\n \n return _bootstrap._load_module_shim(self,fullname)\n \n \nclass SourceLoader(_LoaderBasics):\n\n def path_mtime(self,path):\n ''\n\n\n\n \n raise OSError\n \n def path_stats(self,path):\n ''\n\n\n\n\n\n\n\n\n\n \n return{'mtime':self.path_mtime(path)}\n \n def _cache_bytecode(self,source_path,cache_path,data):\n ''\n\n\n\n\n \n \n return self.set_data(cache_path,data)\n \n def set_data(self,path,data):\n ''\n\n\n \n \n \n def get_source(self,fullname):\n ''\n path=self.get_filename(fullname)\n try:\n source_bytes=self.get_data(path)\n except OSError as exc:\n raise ImportError('source not available through get_data()',\n name=fullname)from exc\n return decode_source(source_bytes)\n \n def source_to_code(self,data,path,*,_optimize=-1):\n ''\n\n\n \n return _bootstrap._call_with_frames_removed(compile,data,path,'exec',\n dont_inherit=True,optimize=_optimize)\n \n def get_code(self,fullname):\n ''\n\n\n\n\n \n source_path=self.get_filename(fullname)\n source_mtime=None\n source_bytes=None\n source_hash=None\n hash_based=False\n check_source=True\n try:\n bytecode_path=cache_from_source(source_path)\n except NotImplementedError:\n bytecode_path=None\n else:\n try:\n st=self.path_stats(source_path)\n except OSError:\n pass\n else:\n source_mtime=int(st['mtime'])\n try:\n data=self.get_data(bytecode_path)\n except OSError:\n pass\n else:\n exc_details={\n 'name':fullname,\n 'path':bytecode_path,\n }\n try:\n flags=_classify_pyc(data,fullname,exc_details)\n bytes_data=memoryview(data)[16:]\n hash_based=flags&0b1 !=0\n if hash_based:\n check_source=flags&0b10 !=0\n if(_imp.check_hash_based_pycs !='never'and\n (check_source or\n _imp.check_hash_based_pycs =='always')):\n source_bytes=self.get_data(source_path)\n source_hash=_imp.source_hash(\n _RAW_MAGIC_NUMBER,\n source_bytes,\n )\n _validate_hash_pyc(data,source_hash,fullname,\n exc_details)\n else:\n _validate_timestamp_pyc(\n data,\n source_mtime,\n st['size'],\n fullname,\n exc_details,\n )\n except(ImportError,EOFError):\n pass\n else:\n _bootstrap._verbose_message('{} matches {}',bytecode_path,\n source_path)\n return _compile_bytecode(bytes_data,name=fullname,\n bytecode_path=bytecode_path,\n source_path=source_path)\n if source_bytes is None:\n source_bytes=self.get_data(source_path)\n code_object=self.source_to_code(source_bytes,source_path)\n _bootstrap._verbose_message('code object from {}',source_path)\n if(not sys.dont_write_bytecode and bytecode_path is not None and\n source_mtime is not None):\n if hash_based:\n if source_hash is None:\n source_hash=_imp.source_hash(_RAW_MAGIC_NUMBER,\n source_bytes)\n data=_code_to_hash_pyc(code_object,source_hash,check_source)\n else:\n data=_code_to_timestamp_pyc(code_object,source_mtime,\n len(source_bytes))\n try:\n self._cache_bytecode(source_path,bytecode_path,data)\n except NotImplementedError:\n pass\n return code_object\n \n \nclass FileLoader:\n\n ''\n \n \n def __init__(self,fullname,path):\n ''\n \n self.name=fullname\n self.path=path\n \n def __eq__(self,other):\n return(self.__class__ ==other.__class__ and\n self.__dict__ ==other.__dict__)\n \n def __hash__(self):\n return hash(self.name)^hash(self.path)\n \n @_check_name\n def load_module(self,fullname):\n ''\n\n\n\n \n \n \n \n return super(FileLoader,self).load_module(fullname)\n \n @_check_name\n def get_filename(self,fullname):\n ''\n return self.path\n \n def get_data(self,path):\n ''\n if isinstance(self,(SourceLoader,ExtensionFileLoader)):\n with _io.open_code(str(path))as file:\n return file.read()\n else:\n with _io.FileIO(path,'r')as file:\n return file.read()\n \n @_check_name\n def get_resource_reader(self,module):\n from importlib.readers import FileReader\n return FileReader(self)\n \n \nclass SourceFileLoader(FileLoader,SourceLoader):\n\n ''\n \n def path_stats(self,path):\n ''\n st=_path_stat(path)\n return{'mtime':st.st_mtime,'size':st.st_size}\n \n def _cache_bytecode(self,source_path,bytecode_path,data):\n \n mode=_calc_mode(source_path)\n return self.set_data(bytecode_path,data,_mode=mode)\n \n def set_data(self,path,data,*,_mode=0o666):\n ''\n parent,filename=_path_split(path)\n path_parts=[]\n \n while parent and not _path_isdir(parent):\n parent,part=_path_split(parent)\n path_parts.append(part)\n \n for part in reversed(path_parts):\n parent=_path_join(parent,part)\n try:\n _os.mkdir(parent)\n except FileExistsError:\n \n continue\n except OSError as exc:\n \n \n _bootstrap._verbose_message('could not create {!r}: {!r}',\n parent,exc)\n return\n try:\n _write_atomic(path,data,_mode)\n _bootstrap._verbose_message('created {!r}',path)\n except OSError as exc:\n \n _bootstrap._verbose_message('could not create {!r}: {!r}',path,\n exc)\n \n \nclass SourcelessFileLoader(FileLoader,_LoaderBasics):\n\n ''\n \n def get_code(self,fullname):\n path=self.get_filename(fullname)\n data=self.get_data(path)\n \n \n exc_details={\n 'name':fullname,\n 'path':path,\n }\n _classify_pyc(data,fullname,exc_details)\n return _compile_bytecode(\n memoryview(data)[16:],\n name=fullname,\n bytecode_path=path,\n )\n \n def get_source(self,fullname):\n ''\n return None\n \n \nclass ExtensionFileLoader(FileLoader,_LoaderBasics):\n\n ''\n\n\n\n \n \n def __init__(self,name,path):\n self.name=name\n self.path=path\n \n def __eq__(self,other):\n return(self.__class__ ==other.__class__ and\n self.__dict__ ==other.__dict__)\n \n def __hash__(self):\n return hash(self.name)^hash(self.path)\n \n def create_module(self,spec):\n ''\n module=_bootstrap._call_with_frames_removed(\n _imp.create_dynamic,spec)\n _bootstrap._verbose_message('extension module {!r} loaded from {!r}',\n spec.name,self.path)\n return module\n \n def exec_module(self,module):\n ''\n _bootstrap._call_with_frames_removed(_imp.exec_dynamic,module)\n _bootstrap._verbose_message('extension module {!r} executed from {!r}',\n self.name,self.path)\n \n def is_package(self,fullname):\n ''\n file_name=_path_split(self.path)[1]\n return any(file_name =='__init__'+suffix\n for suffix in EXTENSION_SUFFIXES)\n \n def get_code(self,fullname):\n ''\n return None\n \n def get_source(self,fullname):\n ''\n return None\n \n @_check_name\n def get_filename(self,fullname):\n ''\n return self.path\n \n \nclass _NamespacePath:\n ''\n\n\n\n \n \n \n \n _epoch=0\n \n def __init__(self,name,path,path_finder):\n self._name=name\n self._path=path\n self._last_parent_path=tuple(self._get_parent_path())\n self._last_epoch=self._epoch\n self._path_finder=path_finder\n \n def _find_parent_path_names(self):\n ''\n parent,dot,me=self._name.rpartition('.')\n if dot =='':\n \n return 'sys','path'\n \n \n return parent,'__path__'\n \n def _get_parent_path(self):\n parent_module_name,path_attr_name=self._find_parent_path_names()\n return getattr(sys.modules[parent_module_name],path_attr_name)\n \n def _recalculate(self):\n \n parent_path=tuple(self._get_parent_path())\n if parent_path !=self._last_parent_path or self._epoch !=self._last_epoch:\n spec=self._path_finder(self._name,parent_path)\n \n \n if spec is not None and spec.loader is None:\n if spec.submodule_search_locations:\n self._path=spec.submodule_search_locations\n self._last_parent_path=parent_path\n self._last_epoch=self._epoch\n return self._path\n \n def __iter__(self):\n return iter(self._recalculate())\n \n def __getitem__(self,index):\n return self._recalculate()[index]\n \n def __setitem__(self,index,path):\n self._path[index]=path\n \n def __len__(self):\n return len(self._recalculate())\n \n def __repr__(self):\n return f'_NamespacePath({self._path !r})'\n \n def __contains__(self,item):\n return item in self._recalculate()\n \n def append(self,item):\n self._path.append(item)\n \n \n \n \n \nclass NamespaceLoader:\n def __init__(self,name,path,path_finder):\n self._path=_NamespacePath(name,path,path_finder)\n \n def is_package(self,fullname):\n return True\n \n def get_source(self,fullname):\n return ''\n \n def get_code(self,fullname):\n return compile('','','exec',dont_inherit=True)\n \n def create_module(self,spec):\n ''\n \n def exec_module(self,module):\n pass\n \n def load_module(self,fullname):\n ''\n\n\n\n \n \n _bootstrap._verbose_message('namespace module loaded with path {!r}',\n self._path)\n \n return _bootstrap._load_module_shim(self,fullname)\n \n def get_resource_reader(self,module):\n from importlib.readers import NamespaceReader\n return NamespaceReader(self._path)\n \n \n \n_NamespaceLoader=NamespaceLoader\n\n\n\n\nclass PathFinder:\n\n ''\n \n @staticmethod\n def invalidate_caches():\n ''\n \n for name,finder in list(sys.path_importer_cache.items()):\n \n \n if finder is None or not _path_isabs(name):\n del sys.path_importer_cache[name]\n elif hasattr(finder,'invalidate_caches'):\n finder.invalidate_caches()\n \n \n _NamespacePath._epoch +=1\n \n from importlib.metadata import MetadataPathFinder\n MetadataPathFinder.invalidate_caches()\n \n @staticmethod\n def _path_hooks(path):\n ''\n if sys.path_hooks is not None and not sys.path_hooks:\n _warnings.warn('sys.path_hooks is empty',ImportWarning)\n for hook in sys.path_hooks:\n try:\n return hook(path)\n except ImportError:\n continue\n else:\n return None\n \n @classmethod\n def _path_importer_cache(cls,path):\n ''\n\n\n\n\n \n if path =='':\n try:\n path=_os.getcwd()\n except FileNotFoundError:\n \n \n return None\n try:\n finder=sys.path_importer_cache[path]\n except KeyError:\n finder=cls._path_hooks(path)\n sys.path_importer_cache[path]=finder\n return finder\n \n @classmethod\n def _get_spec(cls,fullname,path,target=None):\n ''\n \n \n namespace_path=[]\n for entry in path:\n if not isinstance(entry,str):\n continue\n finder=cls._path_importer_cache(entry)\n if finder is not None:\n spec=finder.find_spec(fullname,target)\n if spec is None:\n continue\n if spec.loader is not None:\n return spec\n portions=spec.submodule_search_locations\n if portions is None:\n raise ImportError('spec missing loader')\n \n \n \n \n namespace_path.extend(portions)\n else:\n spec=_bootstrap.ModuleSpec(fullname,None)\n spec.submodule_search_locations=namespace_path\n return spec\n \n @classmethod\n def find_spec(cls,fullname,path=None,target=None):\n ''\n\n\n \n if path is None:\n path=sys.path\n spec=cls._get_spec(fullname,path,target)\n if spec is None:\n return None\n elif spec.loader is None:\n namespace_path=spec.submodule_search_locations\n if namespace_path:\n \n \n spec.origin=None\n spec.submodule_search_locations=_NamespacePath(fullname,namespace_path,cls._get_spec)\n return spec\n else:\n return None\n else:\n return spec\n \n @staticmethod\n def find_distributions(*args,**kwargs):\n ''\n\n\n\n\n\n\n \n from importlib.metadata import MetadataPathFinder\n return MetadataPathFinder.find_distributions(*args,**kwargs)\n \n \nclass FileFinder:\n\n ''\n\n\n\n\n \n \n def __init__(self,path,*loader_details):\n ''\n\n \n loaders=[]\n for loader,suffixes in loader_details:\n loaders.extend((suffix,loader)for suffix in suffixes)\n self._loaders=loaders\n \n if not path or path =='.':\n self.path=_os.getcwd()\n else:\n self.path=_path_abspath(path)\n self._path_mtime=-1\n self._path_cache=set()\n self._relaxed_path_cache=set()\n \n def invalidate_caches(self):\n ''\n self._path_mtime=-1\n \n def _get_spec(self,loader_class,fullname,path,smsl,target):\n loader=loader_class(fullname,path)\n return spec_from_file_location(fullname,path,loader=loader,\n submodule_search_locations=smsl)\n \n def find_spec(self,fullname,target=None):\n ''\n\n\n \n is_namespace=False\n tail_module=fullname.rpartition('.')[2]\n try:\n mtime=_path_stat(self.path or _os.getcwd()).st_mtime\n except OSError:\n mtime=-1\n if mtime !=self._path_mtime:\n self._fill_cache()\n self._path_mtime=mtime\n \n if _relax_case():\n cache=self._relaxed_path_cache\n cache_module=tail_module.lower()\n else:\n cache=self._path_cache\n cache_module=tail_module\n \n if cache_module in cache:\n base_path=_path_join(self.path,tail_module)\n for suffix,loader_class in self._loaders:\n init_filename='__init__'+suffix\n full_path=_path_join(base_path,init_filename)\n if _path_isfile(full_path):\n return self._get_spec(loader_class,fullname,full_path,[base_path],target)\n else:\n \n \n is_namespace=_path_isdir(base_path)\n \n for suffix,loader_class in self._loaders:\n try:\n full_path=_path_join(self.path,tail_module+suffix)\n except ValueError:\n return None\n _bootstrap._verbose_message('trying {}',full_path,verbosity=2)\n if cache_module+suffix in cache:\n if _path_isfile(full_path):\n return self._get_spec(loader_class,fullname,full_path,\n None,target)\n if is_namespace:\n _bootstrap._verbose_message('possible namespace for {}',base_path)\n spec=_bootstrap.ModuleSpec(fullname,None)\n spec.submodule_search_locations=[base_path]\n return spec\n return None\n \n def _fill_cache(self):\n ''\n path=self.path\n try:\n contents=_os.listdir(path or _os.getcwd())\n except(FileNotFoundError,PermissionError,NotADirectoryError):\n \n \n contents=[]\n \n \n if not sys.platform.startswith('win'):\n self._path_cache=set(contents)\n else:\n \n \n \n \n \n lower_suffix_contents=set()\n for item in contents:\n name,dot,suffix=item.partition('.')\n if dot:\n new_name=f'{name}.{suffix.lower()}'\n else:\n new_name=name\n lower_suffix_contents.add(new_name)\n self._path_cache=lower_suffix_contents\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):\n self._relaxed_path_cache={fn.lower()for fn in contents}\n \n @classmethod\n def path_hook(cls,*loader_details):\n ''\n\n\n\n\n\n\n \n def path_hook_for_FileFinder(path):\n ''\n if not _path_isdir(path):\n raise ImportError('only directories are supported',path=path)\n return cls(path,*loader_details)\n \n return path_hook_for_FileFinder\n \n def __repr__(self):\n return f'FileFinder({self.path !r})'\n \n \nclass AppleFrameworkLoader(ExtensionFileLoader):\n ''\n\n \n def create_module(self,spec):\n \n \n \n \n if spec.origin.endswith(\".fwork\"):\n with _io.FileIO(spec.origin,'r')as file:\n framework_binary=file.read().decode().strip()\n bundle_path=_path_split(sys.executable)[0]\n spec.origin=_path_join(bundle_path,framework_binary)\n \n \n \n \n if self.path.endswith(\".fwork\"):\n path=self.path\n else:\n with _io.FileIO(self.path+\".origin\",'r')as file:\n origin=file.read().decode().strip()\n bundle_path=_path_split(sys.executable)[0]\n path=_path_join(bundle_path,origin)\n \n module=_bootstrap._call_with_frames_removed(_imp.create_dynamic,spec)\n \n _bootstrap._verbose_message(\n \"Apple framework extension module {!r} loaded from {!r} (path {!r})\",\n spec.name,\n spec.origin,\n path,\n )\n \n \n module.__file__=path\n \n return module\n \n \n \ndef _fix_up_module(ns,name,pathname,cpathname=None):\n\n loader=ns.get('__loader__')\n spec=ns.get('__spec__')\n if not loader:\n if spec:\n loader=spec.loader\n elif pathname ==cpathname:\n loader=SourcelessFileLoader(name,pathname)\n else:\n loader=SourceFileLoader(name,pathname)\n if not spec:\n spec=spec_from_file_location(name,pathname,loader=loader)\n if cpathname:\n spec.cached=_path_abspath(cpathname)\n try:\n ns['__spec__']=spec\n ns['__loader__']=loader\n ns['__file__']=pathname\n ns['__cached__']=cpathname\n except Exception:\n \n pass\n \n \ndef _get_supported_file_loaders():\n ''\n\n\n \n if sys.platform in{\"ios\",\"tvos\",\"watchos\"}:\n extension_loaders=[(AppleFrameworkLoader,[\n suffix.replace(\".so\",\".fwork\")\n for suffix in _imp.extension_suffixes()\n ])]\n else:\n extension_loaders=[]\n extension_loaders.append((ExtensionFileLoader,_imp.extension_suffixes()))\n source=SourceFileLoader,SOURCE_SUFFIXES\n bytecode=SourcelessFileLoader,BYTECODE_SUFFIXES\n return extension_loaders+[source,bytecode]\n \n \ndef _set_bootstrap_module(_bootstrap_module):\n global _bootstrap\n _bootstrap=_bootstrap_module\n \n \ndef _install(_bootstrap_module):\n ''\n _set_bootstrap_module(_bootstrap_module)\n supported_loaders=_get_supported_file_loaders()\n sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])\n sys.meta_path.append(PathFinder)\n", ["_imp", "_io", "_warnings", "importlib.metadata", "importlib.readers", "marshal", "nt", "posix", "sys", "tokenize", "winreg"]], "importlib": [".py", "''\n__all__=['__import__','import_module','invalidate_caches','reload']\n\n\n\n\n\n\n\n\n\nimport _imp\nimport sys\n\ntry:\n import _frozen_importlib as _bootstrap\nexcept ImportError:\n from. import _bootstrap\n _bootstrap._setup(sys,_imp)\nelse:\n\n\n _bootstrap.__name__='importlib._bootstrap'\n _bootstrap.__package__='importlib'\n try:\n _bootstrap.__file__=__file__.replace('__init__.py','_bootstrap.py')\n except NameError:\n \n \n pass\n sys.modules['importlib._bootstrap']=_bootstrap\n \ntry:\n import _frozen_importlib_external as _bootstrap_external\nexcept ImportError:\n from. import _bootstrap_external\n _bootstrap_external._set_bootstrap_module(_bootstrap)\n _bootstrap._bootstrap_external=_bootstrap_external\nelse:\n _bootstrap_external.__name__='importlib._bootstrap_external'\n _bootstrap_external.__package__='importlib'\n try:\n _bootstrap_external.__file__=__file__.replace('__init__.py','_bootstrap_external.py')\n except NameError:\n \n \n pass\n sys.modules['importlib._bootstrap_external']=_bootstrap_external\n \n \n_pack_uint32=_bootstrap_external._pack_uint32\n_unpack_uint32=_bootstrap_external._unpack_uint32\n\n\n\n\n\n\n\nfrom._bootstrap import __import__\n\n\ndef invalidate_caches():\n ''\n \n for finder in sys.meta_path:\n if hasattr(finder,'invalidate_caches'):\n finder.invalidate_caches()\n \n \ndef import_module(name,package=None):\n ''\n\n\n\n\n\n \n level=0\n if name.startswith('.'):\n if not package:\n raise TypeError(\"the 'package' argument is required to perform a \"\n f\"relative import for {name !r}\")\n for character in name:\n if character !='.':\n break\n level +=1\n return _bootstrap._gcd_import(name[level:],package,level)\n \n \n_RELOADING={}\n\n\ndef reload(module):\n ''\n\n\n\n \n try:\n name=module.__spec__.name\n except AttributeError:\n try:\n name=module.__name__\n except AttributeError:\n raise TypeError(\"reload() argument must be a module\")\n \n if sys.modules.get(name)is not module:\n raise ImportError(f\"module {name} not in sys.modules\",name=name)\n if name in _RELOADING:\n return _RELOADING[name]\n _RELOADING[name]=module\n try:\n parent_name=name.rpartition('.')[0]\n if parent_name:\n try:\n parent=sys.modules[parent_name]\n except KeyError:\n raise ImportError(f\"parent {parent_name !r} not in sys.modules\",\n name=parent_name)from None\n else:\n pkgpath=parent.__path__\n else:\n pkgpath=None\n target=module\n spec=module.__spec__=_bootstrap._find_spec(name,pkgpath,target)\n if spec is None:\n raise ModuleNotFoundError(f\"spec not found for the module {name !r}\",name=name)\n _bootstrap._exec(spec,module)\n \n return sys.modules[name]\n finally:\n try:\n del _RELOADING[name]\n except KeyError:\n pass\n", ["_frozen_importlib", "_frozen_importlib_external", "_imp", "importlib", "importlib._bootstrap", "importlib._bootstrap_external", "sys"], 1], "importlib.metadata._adapters": [".py", "import functools\nimport warnings\nimport re\nimport textwrap\nimport email.message\n\nfrom._text import FoldedCase\n\n\n\n_warn=functools.partial(\nwarnings.warn,\n\"Implicit None on return values is deprecated and will raise KeyErrors.\",\nDeprecationWarning,\nstacklevel=2,\n)\n\n\nclass Message(email.message.Message):\n multiple_use_keys=set(\n map(\n FoldedCase,\n [\n 'Classifier',\n 'Obsoletes-Dist',\n 'Platform',\n 'Project-URL',\n 'Provides-Dist',\n 'Provides-Extra',\n 'Requires-Dist',\n 'Requires-External',\n 'Supported-Platform',\n 'Dynamic',\n ],\n )\n )\n ''\n\n \n \n def __new__(cls,orig:email.message.Message):\n res=super().__new__(cls)\n vars(res).update(vars(orig))\n return res\n \n def __init__(self,*args,**kwargs):\n self._headers=self._repair_headers()\n \n \n def __iter__(self):\n return super().__iter__()\n \n def __getitem__(self,item):\n ''\n\n\n \n res=super().__getitem__(item)\n if res is None:\n _warn()\n return res\n \n def _repair_headers(self):\n def redent(value):\n ''\n if not value or '\\n'not in value:\n return value\n return textwrap.dedent(' '*8+value)\n \n headers=[(key,redent(value))for key,value in vars(self)['_headers']]\n if self._payload:\n headers.append(('Description',self.get_payload()))\n return headers\n \n @property\n def json(self):\n ''\n\n\n \n \n def transform(key):\n value=self.get_all(key)if key in self.multiple_use_keys else self[key]\n if key =='Keywords':\n value=re.split(r'\\s+',value)\n tk=key.lower().replace('-','_')\n return tk,value\n \n return dict(map(transform,map(FoldedCase,self)))\n", ["email.message", "functools", "importlib.metadata._text", "re", "textwrap", "warnings"]], "importlib.metadata._collections": [".py", "import collections\n\n\n\nclass FreezableDefaultDict(collections.defaultdict):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __missing__(self,key):\n return getattr(self,'_frozen',super().__missing__)(key)\n \n def freeze(self):\n self._frozen=lambda key:self.default_factory()\n \n \nclass Pair(collections.namedtuple('Pair','name value')):\n @classmethod\n def parse(cls,text):\n return cls(*map(str.strip,text.split(\"=\",1)))\n", ["collections"]], "importlib.metadata._functools": [".py", "import types\nimport functools\n\n\n\ndef method_cache(method,cache_wrapper=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n cache_wrapper=cache_wrapper or functools.lru_cache()\n \n def wrapper(self,*args,**kwargs):\n \n bound_method=types.MethodType(method,self)\n cached_method=cache_wrapper(bound_method)\n setattr(self,method.__name__,cached_method)\n return cached_method(*args,**kwargs)\n \n \n wrapper.cache_clear=lambda:None\n \n return wrapper\n \n \n \ndef pass_none(func):\n ''\n\n\n\n\n\n\n \n \n @functools.wraps(func)\n def wrapper(param,*args,**kwargs):\n if param is not None:\n return func(param,*args,**kwargs)\n \n return wrapper\n", ["functools", "types"]], "importlib.metadata._itertools": [".py", "from itertools import filterfalse\n\n\ndef unique_everseen(iterable,key=None):\n ''\n \n \n seen=set()\n seen_add=seen.add\n if key is None:\n for element in filterfalse(seen.__contains__,iterable):\n seen_add(element)\n yield element\n else:\n for element in iterable:\n k=key(element)\n if k not in seen:\n seen_add(k)\n yield element\n \n \n \ndef always_iterable(obj,base_type=(str,bytes)):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if obj is None:\n return iter(())\n \n if(base_type is not None)and isinstance(obj,base_type):\n return iter((obj,))\n \n try:\n return iter(obj)\n except TypeError:\n return iter((obj,))\n", ["itertools"]], "importlib.metadata._meta": [".py", "from __future__ import annotations\n\nimport os\nfrom typing import Protocol\nfrom typing import Any,Dict,Iterator,List,Optional,TypeVar,Union,overload\n\n\n_T=TypeVar(\"_T\")\n\n\nclass PackageMetadata(Protocol):\n def __len__(self)->int:...\n \n def __contains__(self,item:str)->bool:...\n \n def __getitem__(self,key:str)->str:...\n \n def __iter__(self)->Iterator[str]:...\n \n @overload\n def get(\n self,name:str,failobj:None=None\n )->Optional[str]:...\n \n @overload\n def get(self,name:str,failobj:_T)->Union[str,_T]:...\n \n \n @overload\n def get_all(\n self,name:str,failobj:None=None\n )->Optional[List[Any]]:...\n \n @overload\n def get_all(self,name:str,failobj:_T)->Union[List[Any],_T]:\n ''\n\n \n \n @property\n def json(self)->Dict[str,Union[str,List[str]]]:\n ''\n\n \n \n \nclass SimplePath(Protocol):\n ''\n\n \n \n def joinpath(\n self,other:Union[str,os.PathLike[str]]\n )->SimplePath:...\n \n def __truediv__(\n self,other:Union[str,os.PathLike[str]]\n )->SimplePath:...\n \n @property\n def parent(self)->SimplePath:...\n \n def read_text(self,encoding=None)->str:...\n \n def read_bytes(self)->bytes:...\n \n def exists(self)->bool:...\n", ["__future__", "os", "typing"]], "importlib.metadata._text": [".py", "import re\n\nfrom._functools import method_cache\n\n\n\nclass FoldedCase(str):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __lt__(self,other):\n return self.lower()other.lower()\n \n def __eq__(self,other):\n return self.lower()==other.lower()\n \n def __ne__(self,other):\n return self.lower()!=other.lower()\n \n def __hash__(self):\n return hash(self.lower())\n \n def __contains__(self,other):\n return super().lower().__contains__(other.lower())\n \n def in_(self,other):\n ''\n return self in FoldedCase(other)\n \n \n @method_cache\n def lower(self):\n return super().lower()\n \n def index(self,sub):\n return self.lower().index(sub.lower())\n \n def split(self,splitter=' ',maxsplit=0):\n pattern=re.compile(re.escape(splitter),re.I)\n return pattern.split(self,maxsplit)\n", ["importlib.metadata._functools", "re"]], "importlib.metadata": [".py", "from __future__ import annotations\n\nimport os\nimport re\nimport abc\nimport sys\nimport json\nimport email\nimport types\nimport inspect\nimport pathlib\nimport zipfile\nimport operator\nimport textwrap\nimport warnings\nimport functools\nimport itertools\nimport posixpath\nimport collections\n\nfrom. import _meta\nfrom._collections import FreezableDefaultDict,Pair\nfrom._functools import method_cache,pass_none\nfrom._itertools import always_iterable,unique_everseen\nfrom._meta import PackageMetadata,SimplePath\n\nfrom contextlib import suppress\nfrom importlib import import_module\nfrom importlib.abc import MetaPathFinder\nfrom itertools import starmap\nfrom typing import Any,Iterable,List,Mapping,Match,Optional,Set,cast\n\n__all__=[\n'Distribution',\n'DistributionFinder',\n'PackageMetadata',\n'PackageNotFoundError',\n'distribution',\n'distributions',\n'entry_points',\n'files',\n'metadata',\n'packages_distributions',\n'requires',\n'version',\n]\n\n\nclass PackageNotFoundError(ModuleNotFoundError):\n ''\n \n def __str__(self)->str:\n return f\"No package metadata was found for {self.name}\"\n \n @property\n def name(self)->str:\n (name,)=self.args\n return name\n \n \nclass Sectioned:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n _sample=textwrap.dedent(\n \"\"\"\n [sec1]\n # comments ignored\n a = 1\n b = 2\n\n [sec2]\n a = 2\n \"\"\"\n ).lstrip()\n \n @classmethod\n def section_pairs(cls,text):\n return(\n section._replace(value=Pair.parse(section.value))\n for section in cls.read(text,filter_=cls.valid)\n if section.name is not None\n )\n \n @staticmethod\n def read(text,filter_=None):\n lines=filter(filter_,map(str.strip,text.splitlines()))\n name=None\n for value in lines:\n section_match=value.startswith('[')and value.endswith(']')\n if section_match:\n name=value.strip('[]')\n continue\n yield Pair(name,value)\n \n @staticmethod\n def valid(line:str):\n return line and not line.startswith('#')\n \n \nclass EntryPoint:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n pattern=re.compile(\n r'(?P[\\w.]+)\\s*'\n r'(:\\s*(?P[\\w.]+)\\s*)?'\n r'((?P\\[.*\\])\\s*)?$'\n )\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n name:str\n value:str\n group:str\n \n dist:Optional[Distribution]=None\n \n def __init__(self,name:str,value:str,group:str)->None:\n vars(self).update(name=name,value=value,group=group)\n \n def load(self)->Any:\n ''\n\n\n \n match=cast(Match,self.pattern.match(self.value))\n module=import_module(match.group('module'))\n attrs=filter(None,(match.group('attr')or '').split('.'))\n return functools.reduce(getattr,attrs,module)\n \n @property\n def module(self)->str:\n match=self.pattern.match(self.value)\n assert match is not None\n return match.group('module')\n \n @property\n def attr(self)->str:\n match=self.pattern.match(self.value)\n assert match is not None\n return match.group('attr')\n \n @property\n def extras(self)->List[str]:\n match=self.pattern.match(self.value)\n assert match is not None\n return re.findall(r'\\w+',match.group('extras')or '')\n \n def _for(self,dist):\n vars(self).update(dist=dist)\n return self\n \n def matches(self,**params):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n attrs=(getattr(self,param)for param in params)\n return all(map(operator.eq,params.values(),attrs))\n \n def _key(self):\n return self.name,self.value,self.group\n \n def __lt__(self,other):\n return self._key()int:\n return hash(self._key())\n \n \nclass EntryPoints(tuple):\n ''\n\n \n \n __slots__=()\n \n def __getitem__(self,name:str)->EntryPoint:\n ''\n\n \n try:\n return next(iter(self.select(name=name)))\n except StopIteration:\n raise KeyError(name)\n \n def __repr__(self):\n ''\n\n\n \n return '%s(%r)'%(self.__class__.__name__,tuple(self))\n \n def select(self,**params)->EntryPoints:\n ''\n\n\n \n return EntryPoints(ep for ep in self if ep.matches(**params))\n \n @property\n def names(self)->Set[str]:\n ''\n\n \n return{ep.name for ep in self}\n \n @property\n def groups(self)->Set[str]:\n ''\n\n \n return{ep.group for ep in self}\n \n @classmethod\n def _from_text_for(cls,text,dist):\n return cls(ep._for(dist)for ep in cls._from_text(text))\n \n @staticmethod\n def _from_text(text):\n return(\n EntryPoint(name=item.value.name,value=item.value.value,group=item.name)\n for item in Sectioned.section_pairs(text or '')\n )\n \n \nclass PackagePath(pathlib.PurePosixPath):\n ''\n \n hash:Optional[FileHash]\n size:int\n dist:Distribution\n \n def read_text(self,encoding:str='utf-8')->str:\n return self.locate().read_text(encoding=encoding)\n \n def read_binary(self)->bytes:\n return self.locate().read_bytes()\n \n def locate(self)->SimplePath:\n ''\n return self.dist.locate_file(self)\n \n \nclass FileHash:\n def __init__(self,spec:str)->None:\n self.mode,_,self.value=spec.partition('=')\n \n def __repr__(self)->str:\n return f''\n \n \nclass DeprecatedNonAbstract:\n\n def __new__(cls,*args,**kwargs):\n all_names={\n name for subclass in inspect.getmro(cls)for name in vars(subclass)\n }\n abstract={\n name\n for name in all_names\n if getattr(getattr(cls,name),'__isabstractmethod__',False)\n }\n if abstract:\n warnings.warn(\n f\"Unimplemented abstract methods {abstract}\",\n DeprecationWarning,\n stacklevel=2,\n )\n return super().__new__(cls)\n \n \nclass Distribution(DeprecatedNonAbstract):\n ''\n\n\n\n\n\n\n\n \n \n @abc.abstractmethod\n def read_text(self,filename)->Optional[str]:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n @abc.abstractmethod\n def locate_file(self,path:str |os.PathLike[str])->SimplePath:\n ''\n\n\n \n \n @classmethod\n def from_name(cls,name:str)->Distribution:\n ''\n\n\n\n\n\n\n\n \n if not name:\n raise ValueError(\"A distribution name is required.\")\n try:\n return next(iter(cls.discover(name=name)))\n except StopIteration:\n raise PackageNotFoundError(name)\n \n @classmethod\n def discover(\n cls,*,context:Optional[DistributionFinder.Context]=None,**kwargs\n )->Iterable[Distribution]:\n ''\n\n\n\n\n\n\n\n \n if context and kwargs:\n raise ValueError(\"cannot accept context and kwargs\")\n context=context or DistributionFinder.Context(**kwargs)\n return itertools.chain.from_iterable(\n resolver(context)for resolver in cls._discover_resolvers()\n )\n \n @staticmethod\n def at(path:str |os.PathLike[str])->Distribution:\n ''\n\n\n\n \n return PathDistribution(pathlib.Path(path))\n \n @staticmethod\n def _discover_resolvers():\n ''\n declared=(\n getattr(finder,'find_distributions',None)for finder in sys.meta_path\n )\n return filter(None,declared)\n \n @property\n def metadata(self)->_meta.PackageMetadata:\n ''\n\n\n\n\n\n\n\n \n \n from. import _adapters\n \n opt_text=(\n self.read_text('METADATA')\n or self.read_text('PKG-INFO')\n \n \n \n or self.read_text('')\n )\n text=cast(str,opt_text)\n return _adapters.Message(email.message_from_string(text))\n \n @property\n def name(self)->str:\n ''\n return self.metadata['Name']\n \n @property\n def _normalized_name(self):\n ''\n return Prepared.normalize(self.name)\n \n @property\n def version(self)->str:\n ''\n return self.metadata['Version']\n \n @property\n def entry_points(self)->EntryPoints:\n ''\n\n\n\n\n \n return EntryPoints._from_text_for(self.read_text('entry_points.txt'),self)\n \n @property\n def files(self)->Optional[List[PackagePath]]:\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n def make_file(name,hash=None,size_str=None):\n result=PackagePath(name)\n result.hash=FileHash(hash)if hash else None\n result.size=int(size_str)if size_str else None\n result.dist=self\n return result\n \n @pass_none\n def make_files(lines):\n \n \n import csv\n \n return starmap(make_file,csv.reader(lines))\n \n @pass_none\n def skip_missing_files(package_paths):\n return list(filter(lambda path:path.locate().exists(),package_paths))\n \n return skip_missing_files(\n make_files(\n self._read_files_distinfo()\n or self._read_files_egginfo_installed()\n or self._read_files_egginfo_sources()\n )\n )\n \n def _read_files_distinfo(self):\n ''\n\n \n text=self.read_text('RECORD')\n return text and text.splitlines()\n \n def _read_files_egginfo_installed(self):\n ''\n\n\n\n\n\n\n\n\n \n text=self.read_text('installed-files.txt')\n \n \n \n subdir=getattr(self,'_path',None)\n if not text or not subdir:\n return\n \n paths=(\n (subdir /name)\n .resolve()\n .relative_to(self.locate_file('').resolve())\n .as_posix()\n for name in text.splitlines()\n )\n return map('\"{}\"'.format,paths)\n \n def _read_files_egginfo_sources(self):\n ''\n\n\n\n\n\n\n\n\n\n \n text=self.read_text('SOURCES.txt')\n return text and map('\"{}\"'.format,text.splitlines())\n \n @property\n def requires(self)->Optional[List[str]]:\n ''\n reqs=self._read_dist_info_reqs()or self._read_egg_info_reqs()\n return reqs and list(reqs)\n \n def _read_dist_info_reqs(self):\n return self.metadata.get_all('Requires-Dist')\n \n def _read_egg_info_reqs(self):\n source=self.read_text('requires.txt')\n return pass_none(self._deps_from_requires_text)(source)\n \n @classmethod\n def _deps_from_requires_text(cls,source):\n return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))\n \n @staticmethod\n def _convert_egg_info_reqs_to_simple_reqs(sections):\n ''\n\n\n\n\n\n\n\n \n \n def make_condition(name):\n return name and f'extra == \"{name}\"'\n \n def quoted_marker(section):\n section=section or ''\n extra,sep,markers=section.partition(':')\n if extra and markers:\n markers=f'({markers})'\n conditions=list(filter(None,[markers,make_condition(extra)]))\n return '; '+' and '.join(conditions)if conditions else ''\n \n def url_req_space(req):\n ''\n\n\n \n \n return ' '*('@'in req)\n \n for section in sections:\n space=url_req_space(section.value)\n yield section.value+space+quoted_marker(section.name)\n \n @property\n def origin(self):\n return self._load_json('direct_url.json')\n \n def _load_json(self,filename):\n return pass_none(json.loads)(\n self.read_text(filename),\n object_hook=lambda data:types.SimpleNamespace(**data),\n )\n \n \nclass DistributionFinder(MetaPathFinder):\n ''\n\n\n\n\n \n \n class Context:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n name=None\n ''\n\n\n \n \n def __init__(self,**kwargs):\n vars(self).update(kwargs)\n \n @property\n def path(self)->List[str]:\n ''\n\n\n\n\n\n \n return vars(self).get('path',sys.path)\n \n @abc.abstractmethod\n def find_distributions(self,context=Context())->Iterable[Distribution]:\n ''\n\n\n\n\n\n \n \n \nclass FastPath:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n @functools.lru_cache()\n def __new__(cls,root):\n return super().__new__(cls)\n \n def __init__(self,root):\n self.root=root\n \n def joinpath(self,child):\n return pathlib.Path(self.root,child)\n \n def children(self):\n with suppress(Exception):\n return os.listdir(self.root or '.')\n with suppress(Exception):\n return self.zip_children()\n return[]\n \n def zip_children(self):\n zip_path=zipfile.Path(self.root)\n names=zip_path.root.namelist()\n self.joinpath=zip_path.joinpath\n \n return dict.fromkeys(child.split(posixpath.sep,1)[0]for child in names)\n \n def search(self,name):\n return self.lookup(self.mtime).search(name)\n \n @property\n def mtime(self):\n with suppress(OSError):\n return os.stat(self.root).st_mtime\n self.lookup.cache_clear()\n \n @method_cache\n def lookup(self,mtime):\n return Lookup(self)\n \n \nclass Lookup:\n ''\n\n \n \n def __init__(self,path:FastPath):\n ''\n\n\n\n\n\n \n \n base=os.path.basename(path.root).lower()\n base_is_egg=base.endswith(\".egg\")\n self.infos=FreezableDefaultDict(list)\n self.eggs=FreezableDefaultDict(list)\n \n for child in path.children():\n low=child.lower()\n if low.endswith((\".dist-info\",\".egg-info\")):\n \n name=low.rpartition(\".\")[0].partition(\"-\")[0]\n normalized=Prepared.normalize(name)\n self.infos[normalized].append(path.joinpath(child))\n elif base_is_egg and low ==\"egg-info\":\n name=base.rpartition(\".\")[0].partition(\"-\")[0]\n legacy_normalized=Prepared.legacy_normalize(name)\n self.eggs[legacy_normalized].append(path.joinpath(child))\n \n self.infos.freeze()\n self.eggs.freeze()\n \n def search(self,prepared:Prepared):\n ''\n\n \n infos=(\n self.infos[prepared.normalized]\n if prepared\n else itertools.chain.from_iterable(self.infos.values())\n )\n eggs=(\n self.eggs[prepared.legacy_normalized]\n if prepared\n else itertools.chain.from_iterable(self.eggs.values())\n )\n return itertools.chain(infos,eggs)\n \n \nclass Prepared:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n normalized=None\n legacy_normalized=None\n \n def __init__(self,name:Optional[str]):\n self.name=name\n if name is None:\n return\n self.normalized=self.normalize(name)\n self.legacy_normalized=self.legacy_normalize(name)\n \n @staticmethod\n def normalize(name):\n ''\n\n \n return re.sub(r\"[-_.]+\",\"-\",name).lower().replace('-','_')\n \n @staticmethod\n def legacy_normalize(name):\n ''\n\n\n \n return name.lower().replace('-','_')\n \n def __bool__(self):\n return bool(self.name)\n \n \nclass MetadataPathFinder(DistributionFinder):\n @classmethod\n def find_distributions(\n cls,context=DistributionFinder.Context()\n )->Iterable[PathDistribution]:\n ''\n\n\n\n\n\n\n \n found=cls._search_paths(context.name,context.path)\n return map(PathDistribution,found)\n \n @classmethod\n def _search_paths(cls,name,paths):\n ''\n prepared=Prepared(name)\n return itertools.chain.from_iterable(\n path.search(prepared)for path in map(FastPath,paths)\n )\n \n @classmethod\n def invalidate_caches(cls)->None:\n FastPath.__new__.cache_clear()\n \n \nclass PathDistribution(Distribution):\n def __init__(self,path:SimplePath)->None:\n ''\n\n\n \n self._path=path\n \n def read_text(self,filename:str |os.PathLike[str])->Optional[str]:\n with suppress(\n FileNotFoundError,\n IsADirectoryError,\n KeyError,\n NotADirectoryError,\n PermissionError,\n ):\n return self._path.joinpath(filename).read_text(encoding='utf-8')\n \n return None\n \n read_text.__doc__=Distribution.read_text.__doc__\n \n def locate_file(self,path:str |os.PathLike[str])->SimplePath:\n return self._path.parent /path\n \n @property\n def _normalized_name(self):\n ''\n\n\n \n stem=os.path.basename(str(self._path))\n return(\n pass_none(Prepared.normalize)(self._name_from_stem(stem))\n or super()._normalized_name\n )\n \n @staticmethod\n def _name_from_stem(stem):\n ''\n\n\n\n\n\n\n\n \n filename,ext=os.path.splitext(stem)\n if ext not in('.dist-info','.egg-info'):\n return\n name,sep,rest=filename.partition('-')\n return name\n \n \ndef distribution(distribution_name:str)->Distribution:\n ''\n\n\n\n \n return Distribution.from_name(distribution_name)\n \n \ndef distributions(**kwargs)->Iterable[Distribution]:\n ''\n\n\n \n return Distribution.discover(**kwargs)\n \n \ndef metadata(distribution_name:str)->_meta.PackageMetadata:\n ''\n\n\n\n \n return Distribution.from_name(distribution_name).metadata\n \n \ndef version(distribution_name:str)->str:\n ''\n\n\n\n\n \n return distribution(distribution_name).version\n \n \n_unique=functools.partial(\nunique_everseen,\nkey=operator.attrgetter('_normalized_name'),\n)\n''\n\n\n\n\ndef entry_points(**params)->EntryPoints:\n ''\n\n\n\n\n\n\n \n eps=itertools.chain.from_iterable(\n dist.entry_points for dist in _unique(distributions())\n )\n return EntryPoints(eps).select(**params)\n \n \ndef files(distribution_name:str)->Optional[List[PackagePath]]:\n ''\n\n\n\n \n return distribution(distribution_name).files\n \n \ndef requires(distribution_name:str)->Optional[List[str]]:\n ''\n\n\n\n\n \n return distribution(distribution_name).requires\n \n \ndef packages_distributions()->Mapping[str,List[str]]:\n ''\n\n\n\n\n\n\n\n \n pkg_to_dist=collections.defaultdict(list)\n for dist in distributions():\n for pkg in _top_level_declared(dist)or _top_level_inferred(dist):\n pkg_to_dist[pkg].append(dist.metadata['Name'])\n return dict(pkg_to_dist)\n \n \ndef _top_level_declared(dist):\n return(dist.read_text('top_level.txt')or '').split()\n \n \ndef _topmost(name:PackagePath)->Optional[str]:\n ''\n\n \n top,*rest=name.parts\n return top if rest else None\n \n \ndef _get_toplevel_name(name:PackagePath)->str:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _topmost(name)or(\n \n inspect.getmodulename(name)\n or str(name)\n )\n \n \ndef _top_level_inferred(dist):\n opt_names=set(map(_get_toplevel_name,always_iterable(dist.files)))\n \n def importable_name(name):\n return '.'not in name\n \n return filter(importable_name,opt_names)\n", ["__future__", "abc", "collections", "contextlib", "csv", "email", "functools", "importlib", "importlib.abc", "importlib.metadata", "importlib.metadata._adapters", "importlib.metadata._collections", "importlib.metadata._functools", "importlib.metadata._itertools", "importlib.metadata._meta", "inspect", "itertools", "json", "operator", "os", "pathlib", "posixpath", "re", "sys", "textwrap", "types", "typing", "warnings", "zipfile"], 1], "importlib.resources.abc": [".py", "import abc\nimport io\nimport itertools\nimport os\nimport pathlib\nfrom typing import Any,BinaryIO,Iterable,Iterator,NoReturn,Text,Optional\nfrom typing import runtime_checkable,Protocol\nfrom typing import Union\n\n\nStrPath=Union[str,os.PathLike[str]]\n\n__all__=[\"ResourceReader\",\"Traversable\",\"TraversableResources\"]\n\n\nclass ResourceReader(metaclass=abc.ABCMeta):\n ''\n \n @abc.abstractmethod\n def open_resource(self,resource:Text)->BinaryIO:\n ''\n\n\n\n \n \n \n \n raise FileNotFoundError\n \n @abc.abstractmethod\n def resource_path(self,resource:Text)->Text:\n ''\n\n\n\n\n \n \n \n \n raise FileNotFoundError\n \n @abc.abstractmethod\n def is_resource(self,path:Text)->bool:\n ''\n\n\n \n raise FileNotFoundError\n \n @abc.abstractmethod\n def contents(self)->Iterable[str]:\n ''\n raise FileNotFoundError\n \n \nclass TraversalError(Exception):\n pass\n \n \n@runtime_checkable\nclass Traversable(Protocol):\n ''\n\n\n\n\n\n \n \n @abc.abstractmethod\n def iterdir(self)->Iterator[\"Traversable\"]:\n ''\n\n \n \n def read_bytes(self)->bytes:\n ''\n\n \n with self.open('rb')as strm:\n return strm.read()\n \n def read_text(self,encoding:Optional[str]=None)->str:\n ''\n\n \n with self.open(encoding=encoding)as strm:\n return strm.read()\n \n @abc.abstractmethod\n def is_dir(self)->bool:\n ''\n\n \n \n @abc.abstractmethod\n def is_file(self)->bool:\n ''\n\n \n \n def joinpath(self,*descendants:StrPath)->\"Traversable\":\n ''\n\n\n\n\n\n \n if not descendants:\n return self\n names=itertools.chain.from_iterable(\n path.parts for path in map(pathlib.PurePosixPath,descendants)\n )\n target=next(names)\n matches=(\n traversable for traversable in self.iterdir()if traversable.name ==target\n )\n try:\n match=next(matches)\n except StopIteration:\n raise TraversalError(\n \"Target not found during traversal.\",target,list(names)\n )\n return match.joinpath(*names)\n \n def __truediv__(self,child:StrPath)->\"Traversable\":\n ''\n\n \n return self.joinpath(child)\n \n @abc.abstractmethod\n def open(self,mode='r',*args,**kwargs):\n ''\n\n\n\n\n\n \n \n @property\n @abc.abstractmethod\n def name(self)->str:\n ''\n\n \n \n \nclass TraversableResources(ResourceReader):\n ''\n\n\n \n \n @abc.abstractmethod\n def files(self)->\"Traversable\":\n ''\n \n def open_resource(self,resource:StrPath)->io.BufferedReader:\n return self.files().joinpath(resource).open('rb')\n \n def resource_path(self,resource:Any)->NoReturn:\n raise FileNotFoundError(resource)\n \n def is_resource(self,path:StrPath)->bool:\n return self.files().joinpath(path).is_file()\n \n def contents(self)->Iterator[str]:\n return(item.name for item in self.files().iterdir())\n", ["abc", "io", "itertools", "os", "pathlib", "typing"]], "importlib.resources.readers": [".py", "import collections\nimport itertools\nimport pathlib\nimport operator\nimport zipfile\n\nfrom. import abc\n\nfrom._itertools import only\n\n\ndef remove_duplicates(items):\n return iter(collections.OrderedDict.fromkeys(items))\n \n \nclass FileReader(abc.TraversableResources):\n def __init__(self,loader):\n self.path=pathlib.Path(loader.path).parent\n \n def resource_path(self,resource):\n ''\n\n\n\n \n return str(self.path.joinpath(resource))\n \n def files(self):\n return self.path\n \n \nclass ZipReader(abc.TraversableResources):\n def __init__(self,loader,module):\n _,_,name=module.rpartition('.')\n self.prefix=loader.prefix.replace('\\\\','/')+name+'/'\n self.archive=loader.archive\n \n def open_resource(self,resource):\n try:\n return super().open_resource(resource)\n except KeyError as exc:\n raise FileNotFoundError(exc.args[0])\n \n def is_resource(self,path):\n ''\n\n\n \n target=self.files().joinpath(path)\n return target.is_file()and target.exists()\n \n def files(self):\n return zipfile.Path(self.archive,self.prefix)\n \n \nclass MultiplexedPath(abc.Traversable):\n ''\n\n\n\n\n \n \n def __init__(self,*paths):\n self._paths=list(map(pathlib.Path,remove_duplicates(paths)))\n if not self._paths:\n message='MultiplexedPath must contain at least one path'\n raise FileNotFoundError(message)\n if not all(path.is_dir()for path in self._paths):\n raise NotADirectoryError('MultiplexedPath only supports directories')\n \n def iterdir(self):\n children=(child for path in self._paths for child in path.iterdir())\n by_name=operator.attrgetter('name')\n groups=itertools.groupby(sorted(children,key=by_name),key=by_name)\n return map(self._follow,(locs for name,locs in groups))\n \n def read_bytes(self):\n raise FileNotFoundError(f'{self} is not a file')\n \n def read_text(self,*args,**kwargs):\n raise FileNotFoundError(f'{self} is not a file')\n \n def is_dir(self):\n return True\n \n def is_file(self):\n return False\n \n def joinpath(self,*descendants):\n try:\n return super().joinpath(*descendants)\n except abc.TraversalError:\n \n \n return self._paths[0].joinpath(*descendants)\n \n @classmethod\n def _follow(cls,children):\n ''\n\n\n\n\n\n \n subdirs,one_dir,one_file=itertools.tee(children,3)\n \n try:\n return only(one_dir)\n except ValueError:\n try:\n return cls(*subdirs)\n except NotADirectoryError:\n return next(one_file)\n \n def open(self,*args,**kwargs):\n raise FileNotFoundError(f'{self} is not a file')\n \n @property\n def name(self):\n return self._paths[0].name\n \n def __repr__(self):\n paths=', '.join(f\"'{path}'\"for path in self._paths)\n return f'MultiplexedPath({paths})'\n \n \nclass NamespaceReader(abc.TraversableResources):\n def __init__(self,namespace_path):\n if 'NamespacePath'not in str(namespace_path):\n raise ValueError('Invalid path')\n self.path=MultiplexedPath(*list(namespace_path))\n \n def resource_path(self,resource):\n ''\n\n\n\n \n return str(self.path.joinpath(resource))\n \n def files(self):\n return self.path\n", ["collections", "importlib.resources", "importlib.resources._itertools", "importlib.resources.abc", "itertools", "operator", "pathlib", "zipfile"]], "importlib.resources.simple": [".py", "''\n\n\n\nimport abc\nimport io\nimport itertools\nfrom typing import BinaryIO,List\n\nfrom.abc import Traversable,TraversableResources\n\n\nclass SimpleReader(abc.ABC):\n ''\n\n\n \n \n @property\n @abc.abstractmethod\n def package(self)->str:\n ''\n\n \n \n @abc.abstractmethod\n def children(self)->List['SimpleReader']:\n ''\n\n\n \n \n @abc.abstractmethod\n def resources(self)->List[str]:\n ''\n\n \n \n @abc.abstractmethod\n def open_binary(self,resource:str)->BinaryIO:\n ''\n\n \n \n @property\n def name(self):\n return self.package.split('.')[-1]\n \n \nclass ResourceContainer(Traversable):\n ''\n\n \n \n def __init__(self,reader:SimpleReader):\n self.reader=reader\n \n def is_dir(self):\n return True\n \n def is_file(self):\n return False\n \n def iterdir(self):\n files=(ResourceHandle(self,name)for name in self.reader.resources)\n dirs=map(ResourceContainer,self.reader.children())\n return itertools.chain(files,dirs)\n \n def open(self,*args,**kwargs):\n raise IsADirectoryError()\n \n \nclass ResourceHandle(Traversable):\n ''\n\n \n \n def __init__(self,parent:ResourceContainer,name:str):\n self.parent=parent\n self.name=name\n \n def is_file(self):\n return True\n \n def is_dir(self):\n return False\n \n def open(self,mode='r',*args,**kwargs):\n stream=self.parent.reader.open_binary(self.name)\n if 'b'not in mode:\n stream=io.TextIOWrapper(stream,*args,**kwargs)\n return stream\n \n def joinpath(self,name):\n raise RuntimeError(\"Cannot traverse into a resource\")\n \n \nclass TraversableReader(TraversableResources,SimpleReader):\n ''\n\n\n\n \n \n def files(self):\n return ResourceContainer(self)\n", ["abc", "importlib.resources.abc", "io", "itertools", "typing"]], "importlib.resources._adapters": [".py", "from contextlib import suppress\nfrom io import TextIOWrapper\n\nfrom. import abc\n\n\nclass SpecLoaderAdapter:\n ''\n\n \n \n def __init__(self,spec,adapter=lambda spec:spec.loader):\n self.spec=spec\n self.loader=adapter(spec)\n \n def __getattr__(self,name):\n return getattr(self.spec,name)\n \n \nclass TraversableResourcesLoader:\n ''\n\n \n \n def __init__(self,spec):\n self.spec=spec\n \n def get_resource_reader(self,name):\n return CompatibilityFiles(self.spec)._native()\n \n \ndef _io_wrapper(file,mode='r',*args,**kwargs):\n if mode =='r':\n return TextIOWrapper(file,*args,**kwargs)\n elif mode =='rb':\n return file\n raise ValueError(f\"Invalid mode value '{mode}', only 'r' and 'rb' are supported\")\n \n \nclass CompatibilityFiles:\n ''\n\n\n \n \n class SpecPath(abc.Traversable):\n ''\n\n\n \n \n def __init__(self,spec,reader):\n self._spec=spec\n self._reader=reader\n \n def iterdir(self):\n if not self._reader:\n return iter(())\n return iter(\n CompatibilityFiles.ChildPath(self._reader,path)\n for path in self._reader.contents()\n )\n \n def is_file(self):\n return False\n \n is_dir=is_file\n \n def joinpath(self,other):\n if not self._reader:\n return CompatibilityFiles.OrphanPath(other)\n return CompatibilityFiles.ChildPath(self._reader,other)\n \n @property\n def name(self):\n return self._spec.name\n \n def open(self,mode='r',*args,**kwargs):\n return _io_wrapper(self._reader.open_resource(None),mode,*args,**kwargs)\n \n class ChildPath(abc.Traversable):\n ''\n\n\n \n \n def __init__(self,reader,name):\n self._reader=reader\n self._name=name\n \n def iterdir(self):\n return iter(())\n \n def is_file(self):\n return self._reader.is_resource(self.name)\n \n def is_dir(self):\n return not self.is_file()\n \n def joinpath(self,other):\n return CompatibilityFiles.OrphanPath(self.name,other)\n \n @property\n def name(self):\n return self._name\n \n def open(self,mode='r',*args,**kwargs):\n return _io_wrapper(\n self._reader.open_resource(self.name),mode,*args,**kwargs\n )\n \n class OrphanPath(abc.Traversable):\n ''\n\n\n \n \n def __init__(self,*path_parts):\n if len(path_parts)<1:\n raise ValueError('Need at least one path part to construct a path')\n self._path=path_parts\n \n def iterdir(self):\n return iter(())\n \n def is_file(self):\n return False\n \n is_dir=is_file\n \n def joinpath(self,other):\n return CompatibilityFiles.OrphanPath(*self._path,other)\n \n @property\n def name(self):\n return self._path[-1]\n \n def open(self,mode='r',*args,**kwargs):\n raise FileNotFoundError(\"Can't open orphan path\")\n \n def __init__(self,spec):\n self.spec=spec\n \n @property\n def _reader(self):\n with suppress(AttributeError):\n return self.spec.loader.get_resource_reader(self.spec.name)\n \n def _native(self):\n ''\n\n \n reader=self._reader\n return reader if hasattr(reader,'files')else self\n \n def __getattr__(self,attr):\n return getattr(self._reader,attr)\n \n def files(self):\n return CompatibilityFiles.SpecPath(self.spec,self._reader)\n \n \ndef wrap_spec(package):\n ''\n\n\n \n return SpecLoaderAdapter(package.__spec__,TraversableResourcesLoader)\n", ["contextlib", "importlib.resources", "importlib.resources.abc", "io"]], "importlib.resources._common": [".py", "import os\nimport pathlib\nimport tempfile\nimport functools\nimport contextlib\nimport types\nimport importlib\nimport inspect\nimport warnings\nimport itertools\n\nfrom typing import Union,Optional,cast\nfrom.abc import ResourceReader,Traversable\n\nPackage=Union[types.ModuleType,str]\nAnchor=Package\n\n\ndef package_to_anchor(func):\n ''\n\n\n\n\n\n\n\n \n undefined=object()\n \n @functools.wraps(func)\n def wrapper(anchor=undefined,package=undefined):\n if package is not undefined:\n if anchor is not undefined:\n return func(anchor,package)\n warnings.warn(\n \"First parameter to files is renamed to 'anchor'\",\n DeprecationWarning,\n stacklevel=2,\n )\n return func(package)\n elif anchor is undefined:\n return func()\n return func(anchor)\n \n return wrapper\n \n \n@package_to_anchor\ndef files(anchor:Optional[Anchor]=None)->Traversable:\n ''\n\n \n return from_package(resolve(anchor))\n \n \ndef get_resource_reader(package:types.ModuleType)->Optional[ResourceReader]:\n ''\n\n \n \n \n \n \n \n spec=package.__spec__\n reader=getattr(spec.loader,'get_resource_reader',None)\n if reader is None:\n return None\n return reader(spec.name)\n \n \n@functools.singledispatch\ndef resolve(cand:Optional[Anchor])->types.ModuleType:\n return cast(types.ModuleType,cand)\n \n \n@resolve.register\ndef _(cand:str)->types.ModuleType:\n return importlib.import_module(cand)\n \n \n@resolve.register\ndef _(cand:None)->types.ModuleType:\n return resolve(_infer_caller().f_globals['__name__'])\n \n \ndef _infer_caller():\n ''\n\n \n \n def is_this_file(frame_info):\n return frame_info.filename ==__file__\n \n def is_wrapper(frame_info):\n return frame_info.function =='wrapper'\n \n not_this_file=itertools.filterfalse(is_this_file,inspect.stack())\n \n callers=itertools.filterfalse(is_wrapper,not_this_file)\n return next(callers).frame\n \n \ndef from_package(package:types.ModuleType):\n ''\n\n\n \n \n from._adapters import wrap_spec\n \n spec=wrap_spec(package)\n reader=spec.loader.get_resource_reader(spec.name)\n return reader.files()\n \n \n@contextlib.contextmanager\ndef _tempfile(\nreader,\nsuffix='',\n\n\n*,\n_os_remove=os.remove,\n):\n\n\n\n fd,raw_path=tempfile.mkstemp(suffix=suffix)\n try:\n try:\n os.write(fd,reader())\n finally:\n os.close(fd)\n del reader\n yield pathlib.Path(raw_path)\n finally:\n try:\n _os_remove(raw_path)\n except FileNotFoundError:\n pass\n \n \ndef _temp_file(path):\n return _tempfile(path.read_bytes,suffix=path.name)\n \n \ndef _is_present_dir(path:Traversable)->bool:\n ''\n\n\n\n\n\n \n with contextlib.suppress(FileNotFoundError):\n return path.is_dir()\n return False\n \n \n@functools.singledispatch\ndef as_file(path):\n ''\n\n\n \n return _temp_dir(path)if _is_present_dir(path)else _temp_file(path)\n \n \n@as_file.register(pathlib.Path)\n@contextlib.contextmanager\ndef _(path):\n ''\n\n \n yield path\n \n \n@contextlib.contextmanager\ndef _temp_path(dir:tempfile.TemporaryDirectory):\n ''\n\n \n with dir as result:\n yield pathlib.Path(result)\n \n \n@contextlib.contextmanager\ndef _temp_dir(path):\n ''\n\n\n \n assert path.is_dir()\n with _temp_path(tempfile.TemporaryDirectory())as temp_dir:\n yield _write_contents(temp_dir,path)\n \n \ndef _write_contents(target,source):\n child=target.joinpath(source.name)\n if source.is_dir():\n child.mkdir()\n for item in source.iterdir():\n _write_contents(child,item)\n else:\n child.write_bytes(source.read_bytes())\n return child\n", ["contextlib", "functools", "importlib", "importlib.resources._adapters", "importlib.resources.abc", "inspect", "itertools", "os", "pathlib", "tempfile", "types", "typing", "warnings"]], "importlib.resources._itertools": [".py", "\ndef only(iterable,default=None,too_long=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n it=iter(iterable)\n first_value=next(it,default)\n \n try:\n second_value=next(it)\n except StopIteration:\n pass\n else:\n msg=(\n 'Expected exactly one item in iterable, but got {!r}, {!r}, '\n 'and perhaps more.'.format(first_value,second_value)\n )\n raise too_long or ValueError(msg)\n \n return first_value\n", []], "importlib.resources._legacy": [".py", "import functools\nimport os\nimport pathlib\nimport types\nimport warnings\n\nfrom typing import Union,Iterable,ContextManager,BinaryIO,TextIO,Any\n\nfrom. import _common\n\nPackage=Union[types.ModuleType,str]\nResource=str\n\n\ndef deprecated(func):\n @functools.wraps(func)\n def wrapper(*args,**kwargs):\n warnings.warn(\n f\"{func.__name__} is deprecated. Use files() instead. \"\n \"Refer to https://importlib-resources.readthedocs.io\"\n \"/en/latest/using.html#migrating-from-legacy for migration advice.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return func(*args,**kwargs)\n \n return wrapper\n \n \ndef normalize_path(path:Any)->str:\n ''\n\n\n \n str_path=str(path)\n parent,file_name=os.path.split(str_path)\n if parent:\n raise ValueError(f'{path !r} must be only a file name')\n return file_name\n \n \n@deprecated\ndef open_binary(package:Package,resource:Resource)->BinaryIO:\n ''\n return(_common.files(package)/normalize_path(resource)).open('rb')\n \n \n@deprecated\ndef read_binary(package:Package,resource:Resource)->bytes:\n ''\n return(_common.files(package)/normalize_path(resource)).read_bytes()\n \n \n@deprecated\ndef open_text(\npackage:Package,\nresource:Resource,\nencoding:str='utf-8',\nerrors:str='strict',\n)->TextIO:\n ''\n return(_common.files(package)/normalize_path(resource)).open(\n 'r',encoding=encoding,errors=errors\n )\n \n \n@deprecated\ndef read_text(\npackage:Package,\nresource:Resource,\nencoding:str='utf-8',\nerrors:str='strict',\n)->str:\n ''\n\n\n\n \n with open_text(package,resource,encoding,errors)as fp:\n return fp.read()\n \n \n@deprecated\ndef contents(package:Package)->Iterable[str]:\n ''\n\n\n\n\n \n return[path.name for path in _common.files(package).iterdir()]\n \n \n@deprecated\ndef is_resource(package:Package,name:str)->bool:\n ''\n\n\n \n resource=normalize_path(name)\n return any(\n traversable.name ==resource and traversable.is_file()\n for traversable in _common.files(package).iterdir()\n )\n \n \n@deprecated\ndef path(\npackage:Package,\nresource:Resource,\n)->ContextManager[pathlib.Path]:\n ''\n\n\n\n\n\n\n \n return _common.as_file(_common.files(package)/normalize_path(resource))\n", ["functools", "importlib.resources", "importlib.resources._common", "os", "pathlib", "types", "typing", "warnings"]], "importlib.resources": [".py", "''\n\nfrom._common import(\nas_file,\nfiles,\nPackage,\nAnchor,\n)\n\nfrom._functional import(\ncontents,\nis_resource,\nopen_binary,\nopen_text,\npath,\nread_binary,\nread_text,\n)\n\nfrom.abc import ResourceReader\n\n\n__all__=[\n'Package',\n'Anchor',\n'ResourceReader',\n'as_file',\n'files',\n'contents',\n'is_resource',\n'open_binary',\n'open_text',\n'path',\n'read_binary',\n'read_text',\n]\n", ["importlib.resources._common", "importlib.resources._functional", "importlib.resources.abc"], 1], "json.encoder": [".py", "''\n\nimport re\n\ntry:\n from _json import encode_basestring_ascii as c_encode_basestring_ascii\nexcept ImportError:\n c_encode_basestring_ascii=None\ntry:\n from _json import encode_basestring as c_encode_basestring\nexcept ImportError:\n c_encode_basestring=None\ntry:\n from _json import make_encoder as c_make_encoder\nexcept ImportError:\n c_make_encoder=None\n \nESCAPE=re.compile(r'[\\x00-\\x1f\\\\\"\\b\\f\\n\\r\\t]')\nESCAPE_ASCII=re.compile(r'([\\\\\"]|[^\\ -~])')\nHAS_UTF8=re.compile(b'[\\x80-\\xff]')\nESCAPE_DCT={\n'\\\\':'\\\\\\\\',\n'\"':'\\\\\"',\n'\\b':'\\\\b',\n'\\f':'\\\\f',\n'\\n':'\\\\n',\n'\\r':'\\\\r',\n'\\t':'\\\\t',\n}\nfor i in range(0x20):\n ESCAPE_DCT.setdefault(chr(i),'\\\\u{0:04x}'.format(i))\n \ndel i\n\nINFINITY=float('inf')\n\ndef py_encode_basestring(s):\n ''\n\n \n def replace(match):\n return ESCAPE_DCT[match.group(0)]\n return '\"'+ESCAPE.sub(replace,s)+'\"'\n \n \nencode_basestring=(c_encode_basestring or py_encode_basestring)\n\n\ndef py_encode_basestring_ascii(s):\n ''\n\n \n def replace(match):\n s=match.group(0)\n try:\n return ESCAPE_DCT[s]\n except KeyError:\n n=ord(s)\n if n <0x10000:\n return '\\\\u{0:04x}'.format(n)\n \n else:\n \n n -=0x10000\n s1=0xd800 |((n >>10)&0x3ff)\n s2=0xdc00 |(n&0x3ff)\n return '\\\\u{0:04x}\\\\u{1:04x}'.format(s1,s2)\n return '\"'+ESCAPE_ASCII.sub(replace,s)+'\"'\n \n \nencode_basestring_ascii=(\nc_encode_basestring_ascii or py_encode_basestring_ascii)\n\nclass JSONEncoder(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item_separator=', '\n key_separator=': '\n def __init__(self,*,skipkeys=False,ensure_ascii=True,\n check_circular=True,allow_nan=True,sort_keys=False,\n indent=None,separators=None,default=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.skipkeys=skipkeys\n self.ensure_ascii=ensure_ascii\n self.check_circular=check_circular\n self.allow_nan=allow_nan\n self.sort_keys=sort_keys\n self.indent=indent\n if separators is not None:\n self.item_separator,self.key_separator=separators\n elif indent is not None:\n self.item_separator=','\n if default is not None:\n self.default=default\n \n def default(self,o):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f'Object of type {o.__class__.__name__} '\n f'is not JSON serializable')\n \n def encode(self,o):\n ''\n\n\n\n\n\n \n \n if isinstance(o,str):\n if self.ensure_ascii:\n return encode_basestring_ascii(o)\n else:\n return encode_basestring(o)\n \n \n \n chunks=self.iterencode(o,_one_shot=True)\n if not isinstance(chunks,(list,tuple)):\n chunks=list(chunks)\n return ''.join(chunks)\n \n def iterencode(self,o,_one_shot=False):\n ''\n\n\n\n\n\n\n\n \n if self.check_circular:\n markers={}\n else:\n markers=None\n if self.ensure_ascii:\n _encoder=encode_basestring_ascii\n else:\n _encoder=encode_basestring\n \n def floatstr(o,allow_nan=self.allow_nan,\n _repr=float.__repr__,_inf=INFINITY,_neginf=-INFINITY):\n \n \n \n \n if o !=o:\n text='NaN'\n elif o ==_inf:\n text='Infinity'\n elif o ==_neginf:\n text='-Infinity'\n else:\n return _repr(o)\n \n if not allow_nan:\n raise ValueError(\n \"Out of range float values are not JSON compliant: \"+\n repr(o))\n \n return text\n \n \n if(_one_shot and c_make_encoder is not None\n and self.indent is None):\n _iterencode=c_make_encoder(\n markers,self.default,_encoder,self.indent,\n self.key_separator,self.item_separator,self.sort_keys,\n self.skipkeys,self.allow_nan)\n else:\n _iterencode=_make_iterencode(\n markers,self.default,_encoder,self.indent,floatstr,\n self.key_separator,self.item_separator,self.sort_keys,\n self.skipkeys,_one_shot)\n return _iterencode(o,0)\n \ndef _make_iterencode(markers,_default,_encoder,_indent,_floatstr,\n_key_separator,_item_separator,_sort_keys,_skipkeys,_one_shot,\n\nValueError=ValueError,\ndict=dict,\nfloat=float,\nid=id,\nint=int,\nisinstance=isinstance,\nlist=list,\nstr=str,\ntuple=tuple,\n_intstr=int.__repr__,\n):\n\n if _indent is not None and not isinstance(_indent,str):\n _indent=' '*_indent\n \n def _iterencode_list(lst,_current_indent_level):\n if not lst:\n yield '[]'\n return\n if markers is not None:\n markerid=id(lst)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=lst\n buf='['\n if _indent is not None:\n _current_indent_level +=1\n newline_indent='\\n'+_indent *_current_indent_level\n separator=_item_separator+newline_indent\n buf +=newline_indent\n else:\n newline_indent=None\n separator=_item_separator\n first=True\n for value in lst:\n if first:\n first=False\n else:\n buf=separator\n if isinstance(value,str):\n yield buf+_encoder(value)\n elif value is None:\n yield buf+'null'\n elif value is True:\n yield buf+'true'\n elif value is False:\n yield buf+'false'\n elif isinstance(value,int):\n \n \n \n yield buf+_intstr(value)\n elif isinstance(value,float):\n \n yield buf+_floatstr(value)\n else:\n yield buf\n if isinstance(value,(list,tuple)):\n chunks=_iterencode_list(value,_current_indent_level)\n elif isinstance(value,dict):\n chunks=_iterencode_dict(value,_current_indent_level)\n else:\n chunks=_iterencode(value,_current_indent_level)\n yield from chunks\n if newline_indent is not None:\n _current_indent_level -=1\n yield '\\n'+_indent *_current_indent_level\n yield ']'\n if markers is not None:\n del markers[markerid]\n \n def _iterencode_dict(dct,_current_indent_level):\n if not dct:\n yield '{}'\n return\n if markers is not None:\n markerid=id(dct)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=dct\n yield '{'\n if _indent is not None:\n _current_indent_level +=1\n newline_indent='\\n'+_indent *_current_indent_level\n item_separator=_item_separator+newline_indent\n yield newline_indent\n else:\n newline_indent=None\n item_separator=_item_separator\n first=True\n if _sort_keys:\n items=sorted(dct.items())\n else:\n items=dct.items()\n for key,value in items:\n if isinstance(key,str):\n pass\n \n \n elif isinstance(key,float):\n \n key=_floatstr(key)\n elif key is True:\n key='true'\n elif key is False:\n key='false'\n elif key is None:\n key='null'\n elif isinstance(key,int):\n \n key=_intstr(key)\n elif _skipkeys:\n continue\n else:\n raise TypeError(f'keys must be str, int, float, bool or None, '\n f'not {key.__class__.__name__}')\n if first:\n first=False\n else:\n yield item_separator\n yield _encoder(key)\n yield _key_separator\n if isinstance(value,str):\n yield _encoder(value)\n elif value is None:\n yield 'null'\n elif value is True:\n yield 'true'\n elif value is False:\n yield 'false'\n elif isinstance(value,int):\n \n yield _intstr(value)\n elif isinstance(value,float):\n \n yield _floatstr(value)\n else:\n if isinstance(value,(list,tuple)):\n chunks=_iterencode_list(value,_current_indent_level)\n elif isinstance(value,dict):\n chunks=_iterencode_dict(value,_current_indent_level)\n else:\n chunks=_iterencode(value,_current_indent_level)\n yield from chunks\n if newline_indent is not None:\n _current_indent_level -=1\n yield '\\n'+_indent *_current_indent_level\n yield '}'\n if markers is not None:\n del markers[markerid]\n \n def _iterencode(o,_current_indent_level):\n if isinstance(o,str):\n yield _encoder(o)\n elif o is None:\n yield 'null'\n elif o is True:\n yield 'true'\n elif o is False:\n yield 'false'\n elif isinstance(o,int):\n \n yield _intstr(o)\n elif isinstance(o,float):\n \n yield _floatstr(o)\n elif isinstance(o,(list,tuple)):\n yield from _iterencode_list(o,_current_indent_level)\n elif isinstance(o,dict):\n yield from _iterencode_dict(o,_current_indent_level)\n else:\n if markers is not None:\n markerid=id(o)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=o\n o=_default(o)\n yield from _iterencode(o,_current_indent_level)\n if markers is not None:\n del markers[markerid]\n return _iterencode\n", ["_json", "re"]], "json": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__='2.0.9'\n__all__=[\n'dump','dumps','load','loads',\n'JSONDecoder','JSONDecodeError','JSONEncoder',\n]\n\n__author__='Bob Ippolito '\n\n\n\n\n\nclass codecs:\n\n BOM_UTF8=b'\\xef\\xbb\\xbf'\n BOM_LE=BOM_UTF16_LE=b'\\xff\\xfe'\n BOM_BE=BOM_UTF16_BE=b'\\xfe\\xff'\n BOM_UTF32_LE=b'\\xff\\xfe\\x00\\x00'\n BOM_UTF32_BE=b'\\x00\\x00\\xfe\\xff'\n \n \nimport _json\nfrom.encoder import JSONEncoder\n\nJSONDecoder=_json.JSONDecoder\n\nclass decoder:\n JSONDecoder=_json.JSONDecoder\n \nclass JSONDecodeError(ValueError):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,msg,doc,pos):\n lineno=doc.count('\\n',0,pos)+1\n colno=pos -doc.rfind('\\n',0,pos)\n errmsg='%s: line %d column %d (char %d)'%(msg,lineno,colno,pos)\n ValueError.__init__(self,errmsg)\n self.msg=msg\n self.doc=doc\n self.pos=pos\n self.lineno=lineno\n self.colno=colno\n \n def __reduce__(self):\n return self.__class__,(self.msg,self.doc,self.pos)\n \ndef dump(obj,fp,**kw):\n fp.write(dumps(obj,**kw))\n \ndef dumps(obj,*,skipkeys=False,ensure_ascii=True,check_circular=True,\nallow_nan=True,cls=None,indent=None,separators=None,\ndefault=None,sort_keys=False,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if cls is None:\n return _json.dumps(obj,1,\n skipkeys=skipkeys,ensure_ascii=ensure_ascii,\n check_circular=check_circular,allow_nan=allow_nan,indent=indent,\n separators=separators,default=default,sort_keys=sort_keys,\n **kw)\n return cls(\n skipkeys=skipkeys,ensure_ascii=ensure_ascii,\n check_circular=check_circular,allow_nan=allow_nan,indent=indent,\n separators=separators,default=default,sort_keys=sort_keys,\n **kw).encode(obj)\n \ndef detect_encoding(b):\n bstartswith=b.startswith\n if bstartswith((codecs.BOM_UTF32_BE,codecs.BOM_UTF32_LE)):\n return 'utf-32'\n if bstartswith((codecs.BOM_UTF16_BE,codecs.BOM_UTF16_LE)):\n return 'utf-16'\n if bstartswith(codecs.BOM_UTF8):\n return 'utf-8-sig'\n \n if len(b)>=4:\n if not b[0]:\n \n \n return 'utf-16-be'if b[1]else 'utf-32-be'\n if not b[1]:\n \n \n \n return 'utf-16-le'if b[2]or b[3]else 'utf-32-le'\n elif len(b)==2:\n if not b[0]:\n \n return 'utf-16-be'\n if not b[1]:\n \n return 'utf-16-le'\n \n return 'utf-8'\n \n \ndef load(fp,*,cls=None,object_hook=None,parse_float=None,\nparse_int=None,parse_constant=None,object_pairs_hook=None,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return loads(fp.read(),\n cls=cls,object_hook=object_hook,\n parse_float=parse_float,parse_int=parse_int,\n parse_constant=parse_constant,object_pairs_hook=object_pairs_hook,**kw)\n \n \ndef loads(s,*,cls=None,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(s,str):\n if s.startswith('\\ufeff'):\n raise JSONDecodeError(\"Unexpected UTF-8 BOM (decode using utf-8-sig)\",\n s,0)\n else:\n if not isinstance(s,(bytes,bytearray)):\n raise TypeError(f'the JSON object must be str, bytes or bytearray, '\n f'not {s.__class__.__name__}')\n s=s.decode(detect_encoding(s),'surrogatepass')\n \n \n if \"encoding\"in kw:\n import warnings\n warnings.warn(\n \"'encoding' is ignored and deprecated. It will be removed in Python 3.9\",\n DeprecationWarning,\n stacklevel=2\n )\n del kw['encoding']\n \n if cls is None:\n \n \n return _json.loads(s,**kw)\n if object_hook is not None:\n kw['object_hook']=object_hook\n if object_pairs_hook is not None:\n kw['object_pairs_hook']=object_pairs_hook\n if parse_float is not None:\n kw['parse_float']=parse_float\n if parse_int is not None:\n kw['parse_int']=parse_int\n if parse_constant is not None:\n kw['parse_constant']=parse_constant\n return cls(**kw).decode(s)\n", ["_json", "json.encoder", "warnings"], 1], "logging.brython_handlers": [".py", "import logging\n\nfrom browser.ajax import ajax\n\n\nclass XMLHTTPHandler(logging.Handler):\n ''\n\n\n \n def __init__(self,url,method=\"GET\"):\n ''\n\n\n \n logging.Handler.__init__(self)\n method=method.upper()\n if method not in[\"GET\",\"POST\"]:\n raise ValueError(\"method must be GET or POST\")\n self.url=url\n self.method=method\n \n def mapLogRecord(self,record):\n ''\n\n\n\n \n return record.__dict__\n \n def emit(self,record):\n ''\n\n\n\n \n try:\n req=ajax.open(self.method,self.url,sync=False)\n req.send(self.mapLogRecord(record))\n except:\n self.handleError(record)\n", ["browser.ajax", "logging"]], "logging.config": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\"\nConfiguration functions for the logging package for Python. The core package\nis based on PEP 282 and comments thereto in comp.lang.python, and influenced\nby Apache's log4j system.\n\nCopyright (C) 2001-2022 Vinay Sajip. All Rights Reserved.\n\nTo use, simply 'import logging' and log away!\n\"\"\"\n\nimport errno\nimport functools\nimport io\nimport logging\nimport logging.handlers\nimport os\nimport queue\nimport re\nimport struct\nimport threading\nimport traceback\n\nfrom socketserver import ThreadingTCPServer,StreamRequestHandler\n\n\nDEFAULT_LOGGING_CONFIG_PORT=9030\n\nRESET_ERROR=errno.ECONNRESET\n\n\n\n\n\n\n_listener=None\n\ndef fileConfig(fname,defaults=None,disable_existing_loggers=True,encoding=None):\n ''\n\n\n\n\n\n\n \n import configparser\n \n if isinstance(fname,str):\n if not os.path.exists(fname):\n raise FileNotFoundError(f\"{fname} doesn't exist\")\n elif not os.path.getsize(fname):\n raise RuntimeError(f'{fname} is an empty file')\n \n if isinstance(fname,configparser.RawConfigParser):\n cp=fname\n else:\n try:\n cp=configparser.ConfigParser(defaults)\n if hasattr(fname,'readline'):\n cp.read_file(fname)\n else:\n encoding=io.text_encoding(encoding)\n cp.read(fname,encoding=encoding)\n except configparser.ParsingError as e:\n raise RuntimeError(f'{fname} is invalid: {e}')\n \n formatters=_create_formatters(cp)\n \n \n with logging._lock:\n _clearExistingHandlers()\n \n \n handlers=_install_handlers(cp,formatters)\n _install_loggers(cp,handlers,disable_existing_loggers)\n \n \ndef _resolve(name):\n ''\n name=name.split('.')\n used=name.pop(0)\n found=__import__(used)\n for n in name:\n used=used+'.'+n\n try:\n found=getattr(found,n)\n except AttributeError:\n __import__(used)\n found=getattr(found,n)\n return found\n \ndef _strip_spaces(alist):\n return map(str.strip,alist)\n \ndef _create_formatters(cp):\n ''\n flist=cp[\"formatters\"][\"keys\"]\n if not len(flist):\n return{}\n flist=flist.split(\",\")\n flist=_strip_spaces(flist)\n formatters={}\n for form in flist:\n sectname=\"formatter_%s\"%form\n fs=cp.get(sectname,\"format\",raw=True,fallback=None)\n dfs=cp.get(sectname,\"datefmt\",raw=True,fallback=None)\n stl=cp.get(sectname,\"style\",raw=True,fallback='%')\n defaults=cp.get(sectname,\"defaults\",raw=True,fallback=None)\n \n c=logging.Formatter\n class_name=cp[sectname].get(\"class\")\n if class_name:\n c=_resolve(class_name)\n \n if defaults is not None:\n defaults=eval(defaults,vars(logging))\n f=c(fs,dfs,stl,defaults=defaults)\n else:\n f=c(fs,dfs,stl)\n formatters[form]=f\n return formatters\n \n \ndef _install_handlers(cp,formatters):\n ''\n hlist=cp[\"handlers\"][\"keys\"]\n if not len(hlist):\n return{}\n hlist=hlist.split(\",\")\n hlist=_strip_spaces(hlist)\n handlers={}\n fixups=[]\n for hand in hlist:\n section=cp[\"handler_%s\"%hand]\n klass=section[\"class\"]\n fmt=section.get(\"formatter\",\"\")\n try:\n klass=eval(klass,vars(logging))\n except(AttributeError,NameError):\n klass=_resolve(klass)\n args=section.get(\"args\",'()')\n args=eval(args,vars(logging))\n kwargs=section.get(\"kwargs\",'{}')\n kwargs=eval(kwargs,vars(logging))\n h=klass(*args,**kwargs)\n h.name=hand\n if \"level\"in section:\n level=section[\"level\"]\n h.setLevel(level)\n if len(fmt):\n h.setFormatter(formatters[fmt])\n if issubclass(klass,logging.handlers.MemoryHandler):\n target=section.get(\"target\",\"\")\n if len(target):\n fixups.append((h,target))\n handlers[hand]=h\n \n for h,t in fixups:\n h.setTarget(handlers[t])\n return handlers\n \ndef _handle_existing_loggers(existing,child_loggers,disable_existing):\n ''\n\n\n\n\n\n\n\n\n \n root=logging.root\n for log in existing:\n logger=root.manager.loggerDict[log]\n if log in child_loggers:\n if not isinstance(logger,logging.PlaceHolder):\n logger.setLevel(logging.NOTSET)\n logger.handlers=[]\n logger.propagate=True\n else:\n logger.disabled=disable_existing\n \ndef _install_loggers(cp,handlers,disable_existing):\n ''\n \n \n llist=cp[\"loggers\"][\"keys\"]\n llist=llist.split(\",\")\n llist=list(_strip_spaces(llist))\n llist.remove(\"root\")\n section=cp[\"logger_root\"]\n root=logging.root\n log=root\n if \"level\"in section:\n level=section[\"level\"]\n log.setLevel(level)\n for h in root.handlers[:]:\n root.removeHandler(h)\n hlist=section[\"handlers\"]\n if len(hlist):\n hlist=hlist.split(\",\")\n hlist=_strip_spaces(hlist)\n for hand in hlist:\n log.addHandler(handlers[hand])\n \n \n \n \n \n \n \n \n \n \n existing=list(root.manager.loggerDict.keys())\n \n \n \n \n existing.sort()\n \n \n child_loggers=[]\n \n for log in llist:\n section=cp[\"logger_%s\"%log]\n qn=section[\"qualname\"]\n propagate=section.getint(\"propagate\",fallback=1)\n logger=logging.getLogger(qn)\n if qn in existing:\n i=existing.index(qn)+1\n prefixed=qn+\".\"\n pflen=len(prefixed)\n num_existing=len(existing)\n while i [a-z]+)://(?P.*)$')\n \n WORD_PATTERN=re.compile(r'^\\s*(\\w+)\\s*')\n DOT_PATTERN=re.compile(r'^\\.\\s*(\\w+)\\s*')\n INDEX_PATTERN=re.compile(r'^\\[([^\\[\\]]*)\\]\\s*')\n DIGIT_PATTERN=re.compile(r'^\\d+$')\n \n value_converters={\n 'ext':'ext_convert',\n 'cfg':'cfg_convert',\n }\n \n \n importer=staticmethod(__import__)\n \n def __init__(self,config):\n self.config=ConvertingDict(config)\n self.config.configurator=self\n \n def resolve(self,s):\n ''\n\n\n \n name=s.split('.')\n used=name.pop(0)\n try:\n found=self.importer(used)\n for frag in name:\n used +='.'+frag\n try:\n found=getattr(found,frag)\n except AttributeError:\n self.importer(used)\n found=getattr(found,frag)\n return found\n except ImportError as e:\n v=ValueError('Cannot resolve %r: %s'%(s,e))\n raise v from e\n \n def ext_convert(self,value):\n ''\n return self.resolve(value)\n \n def cfg_convert(self,value):\n ''\n rest=value\n m=self.WORD_PATTERN.match(rest)\n if m is None:\n raise ValueError(\"Unable to convert %r\"%value)\n else:\n rest=rest[m.end():]\n d=self.config[m.groups()[0]]\n \n while rest:\n m=self.DOT_PATTERN.match(rest)\n if m:\n d=d[m.groups()[0]]\n else:\n m=self.INDEX_PATTERN.match(rest)\n if m:\n idx=m.groups()[0]\n if not self.DIGIT_PATTERN.match(idx):\n d=d[idx]\n else:\n try:\n n=int(idx)\n d=d[n]\n except TypeError:\n d=d[idx]\n if m:\n rest=rest[m.end():]\n else:\n raise ValueError('Unable to convert '\n '%r at %r'%(value,rest))\n \n return d\n \n def convert(self,value):\n ''\n\n\n\n \n if not isinstance(value,ConvertingDict)and isinstance(value,dict):\n value=ConvertingDict(value)\n value.configurator=self\n elif not isinstance(value,ConvertingList)and isinstance(value,list):\n value=ConvertingList(value)\n value.configurator=self\n elif not isinstance(value,ConvertingTuple)and\\\n isinstance(value,tuple)and not hasattr(value,'_fields'):\n value=ConvertingTuple(value)\n value.configurator=self\n elif isinstance(value,str):\n m=self.CONVERT_PATTERN.match(value)\n if m:\n d=m.groupdict()\n prefix=d['prefix']\n converter=self.value_converters.get(prefix,None)\n if converter:\n suffix=d['suffix']\n converter=getattr(self,converter)\n value=converter(suffix)\n return value\n \n def configure_custom(self,config):\n ''\n c=config.pop('()')\n if not callable(c):\n c=self.resolve(c)\n \n kwargs={k:config[k]for k in config if(k !='.'and valid_ident(k))}\n result=c(**kwargs)\n props=config.pop('.',None)\n if props:\n for name,value in props.items():\n setattr(result,name,value)\n return result\n \n def as_tuple(self,value):\n ''\n if isinstance(value,list):\n value=tuple(value)\n return value\n \nclass DictConfigurator(BaseConfigurator):\n ''\n\n\n \n \n def configure(self):\n ''\n \n config=self.config\n if 'version'not in config:\n raise ValueError(\"dictionary doesn't specify a version\")\n if config['version']!=1:\n raise ValueError(\"Unsupported version: %s\"%config['version'])\n incremental=config.pop('incremental',False)\n EMPTY_DICT={}\n with logging._lock:\n if incremental:\n handlers=config.get('handlers',EMPTY_DICT)\n for name in handlers:\n if name not in logging._handlers:\n raise ValueError('No handler found with '\n 'name %r'%name)\n else:\n try:\n handler=logging._handlers[name]\n handler_config=handlers[name]\n level=handler_config.get('level',None)\n if level:\n handler.setLevel(logging._checkLevel(level))\n except Exception as e:\n raise ValueError('Unable to configure handler '\n '%r'%name)from e\n loggers=config.get('loggers',EMPTY_DICT)\n for name in loggers:\n try:\n self.configure_logger(name,loggers[name],True)\n except Exception as e:\n raise ValueError('Unable to configure logger '\n '%r'%name)from e\n root=config.get('root',None)\n if root:\n try:\n self.configure_root(root,True)\n except Exception as e:\n raise ValueError('Unable to configure root '\n 'logger')from e\n else:\n disable_existing=config.pop('disable_existing_loggers',True)\n \n _clearExistingHandlers()\n \n \n formatters=config.get('formatters',EMPTY_DICT)\n for name in formatters:\n try:\n formatters[name]=self.configure_formatter(\n formatters[name])\n except Exception as e:\n raise ValueError('Unable to configure '\n 'formatter %r'%name)from e\n \n filters=config.get('filters',EMPTY_DICT)\n for name in filters:\n try:\n filters[name]=self.configure_filter(filters[name])\n except Exception as e:\n raise ValueError('Unable to configure '\n 'filter %r'%name)from e\n \n \n \n \n handlers=config.get('handlers',EMPTY_DICT)\n deferred=[]\n for name in sorted(handlers):\n try:\n handler=self.configure_handler(handlers[name])\n handler.name=name\n handlers[name]=handler\n except Exception as e:\n if ' not configured yet'in str(e.__cause__):\n deferred.append(name)\n else:\n raise ValueError('Unable to configure handler '\n '%r'%name)from e\n \n \n for name in deferred:\n try:\n handler=self.configure_handler(handlers[name])\n handler.name=name\n handlers[name]=handler\n except Exception as e:\n raise ValueError('Unable to configure handler '\n '%r'%name)from e\n \n \n \n \n \n \n \n \n \n \n \n root=logging.root\n existing=list(root.manager.loggerDict.keys())\n \n \n \n \n existing.sort()\n \n \n child_loggers=[]\n \n loggers=config.get('loggers',EMPTY_DICT)\n for name in loggers:\n if name in existing:\n i=existing.index(name)+1\n prefixed=name+\".\"\n pflen=len(prefixed)\n num_existing=len(existing)\n while i L\",chunk)[0]\n chunk=self.connection.recv(slen)\n while len(chunk)0:\n mode='a'\n if \"b\"not in mode:\n encoding=io.text_encoding(encoding)\n BaseRotatingHandler.__init__(self,filename,mode,encoding=encoding,\n delay=delay,errors=errors)\n self.maxBytes=maxBytes\n self.backupCount=backupCount\n \n def doRollover(self):\n ''\n\n \n if self.stream:\n self.stream.close()\n self.stream=None\n if self.backupCount >0:\n for i in range(self.backupCount -1,0,-1):\n sfn=self.rotation_filename(\"%s.%d\"%(self.baseFilename,i))\n dfn=self.rotation_filename(\"%s.%d\"%(self.baseFilename,\n i+1))\n if os.path.exists(sfn):\n if os.path.exists(dfn):\n os.remove(dfn)\n os.rename(sfn,dfn)\n dfn=self.rotation_filename(self.baseFilename+\".1\")\n if os.path.exists(dfn):\n os.remove(dfn)\n self.rotate(self.baseFilename,dfn)\n if not self.delay:\n self.stream=self._open()\n \n def shouldRollover(self,record):\n ''\n\n\n\n\n \n \n if os.path.exists(self.baseFilename)and not os.path.isfile(self.baseFilename):\n return False\n if self.stream is None:\n self.stream=self._open()\n if self.maxBytes >0:\n msg=\"%s\\n\"%self.format(record)\n self.stream.seek(0,2)\n if self.stream.tell()+len(msg)>=self.maxBytes:\n return True\n return False\n \nclass TimedRotatingFileHandler(BaseRotatingHandler):\n ''\n\n\n\n\n\n \n def __init__(self,filename,when='h',interval=1,backupCount=0,\n encoding=None,delay=False,utc=False,atTime=None,\n errors=None):\n encoding=io.text_encoding(encoding)\n BaseRotatingHandler.__init__(self,filename,'a',encoding=encoding,\n delay=delay,errors=errors)\n self.when=when.upper()\n self.backupCount=backupCount\n self.utc=utc\n self.atTime=atTime\n \n \n \n \n \n \n \n \n \n \n \n \n if self.when =='S':\n self.interval=1\n self.suffix=\"%Y-%m-%d_%H-%M-%S\"\n extMatch=r\"(?'6':\n raise ValueError(\"Invalid day specified for weekly rollover: %s\"%self.when)\n self.dayOfWeek=int(self.when[1])\n self.suffix=\"%Y-%m-%d\"\n extMatch=r\"(?=self.rolloverAt:\n \n if os.path.exists(self.baseFilename)and not os.path.isfile(self.baseFilename):\n \n \n self.rolloverAt=self.computeRollover(t)\n return False\n \n return True\n return False\n \n def getFilesToDelete(self):\n ''\n\n\n\n \n dirName,baseName=os.path.split(self.baseFilename)\n fileNames=os.listdir(dirName)\n result=[]\n if self.namer is None:\n prefix=baseName+'.'\n plen=len(prefix)\n for fileName in fileNames:\n if fileName[:plen]==prefix:\n suffix=fileName[plen:]\n if self.extMatch.fullmatch(suffix):\n result.append(os.path.join(dirName,fileName))\n else:\n for fileName in fileNames:\n \n \n \n \n m=self.extMatch.search(fileName)\n while m:\n dfn=self.namer(self.baseFilename+\".\"+m[0])\n if os.path.basename(dfn)==fileName:\n result.append(os.path.join(dirName,fileName))\n break\n m=self.extMatch.search(fileName,m.start()+1)\n \n if len(result)0:\n for s in self.getFilesToDelete():\n os.remove(s)\n if not self.delay:\n self.stream=self._open()\n self.rolloverAt=self.computeRollover(currentTime)\n \nclass WatchedFileHandler(logging.FileHandler):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,filename,mode='a',encoding=None,delay=False,\n errors=None):\n if \"b\"not in mode:\n encoding=io.text_encoding(encoding)\n logging.FileHandler.__init__(self,filename,mode=mode,\n encoding=encoding,delay=delay,\n errors=errors)\n self.dev,self.ino=-1,-1\n self._statstream()\n \n def _statstream(self):\n if self.stream is None:\n return\n sres=os.fstat(self.stream.fileno())\n self.dev=sres.st_dev\n self.ino=sres.st_ino\n \n def reopenIfNeeded(self):\n ''\n\n\n\n\n\n \n if self.stream is None:\n return\n \n \n \n \n \n try:\n \n sres=os.stat(self.baseFilename)\n \n \n reopen=(sres.st_dev !=self.dev or sres.st_ino !=self.ino)\n except FileNotFoundError:\n reopen=True\n \n if not reopen:\n return\n \n \n self.stream.flush()\n self.stream.close()\n self.stream=None\n \n \n self.stream=self._open()\n self._statstream()\n \n def emit(self,record):\n ''\n\n\n\n\n \n self.reopenIfNeeded()\n logging.FileHandler.emit(self,record)\n \n \nclass SocketHandler(logging.Handler):\n ''\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,host,port):\n ''\n\n\n\n\n\n \n logging.Handler.__init__(self)\n self.host=host\n self.port=port\n if port is None:\n self.address=host\n else:\n self.address=(host,port)\n self.sock=None\n self.closeOnError=False\n self.retryTime=None\n \n \n \n self.retryStart=1.0\n self.retryMax=30.0\n self.retryFactor=2.0\n \n def makeSocket(self,timeout=1):\n ''\n\n\n \n if self.port is not None:\n result=socket.create_connection(self.address,timeout=timeout)\n else:\n result=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)\n result.settimeout(timeout)\n try:\n result.connect(self.address)\n except OSError:\n result.close()\n raise\n return result\n \n def createSocket(self):\n ''\n\n\n\n \n now=time.time()\n \n \n \n if self.retryTime is None:\n attempt=True\n else:\n attempt=(now >=self.retryTime)\n if attempt:\n try:\n self.sock=self.makeSocket()\n self.retryTime=None\n except OSError:\n \n if self.retryTime is None:\n self.retryPeriod=self.retryStart\n else:\n self.retryPeriod=self.retryPeriod *self.retryFactor\n if self.retryPeriod >self.retryMax:\n self.retryPeriod=self.retryMax\n self.retryTime=now+self.retryPeriod\n \n def send(self,s):\n ''\n\n\n\n\n \n if self.sock is None:\n self.createSocket()\n \n \n \n if self.sock:\n try:\n self.sock.sendall(s)\n except OSError:\n self.sock.close()\n self.sock=None\n \n def makePickle(self,record):\n ''\n\n\n \n ei=record.exc_info\n if ei:\n \n dummy=self.format(record)\n \n \n \n d=dict(record.__dict__)\n d['msg']=record.getMessage()\n d['args']=None\n d['exc_info']=None\n \n d.pop('message',None)\n s=pickle.dumps(d,1)\n slen=struct.pack(\">L\",len(s))\n return slen+s\n \n def handleError(self,record):\n ''\n\n\n\n\n\n \n if self.closeOnError and self.sock:\n self.sock.close()\n self.sock=None\n else:\n logging.Handler.handleError(self,record)\n \n def emit(self,record):\n ''\n\n\n\n\n\n\n \n try:\n s=self.makePickle(record)\n self.send(s)\n except Exception:\n self.handleError(record)\n \n def close(self):\n ''\n\n \n with self.lock:\n sock=self.sock\n if sock:\n self.sock=None\n sock.close()\n logging.Handler.close(self)\n \nclass DatagramHandler(SocketHandler):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,host,port):\n ''\n\n \n SocketHandler.__init__(self,host,port)\n self.closeOnError=False\n \n def makeSocket(self):\n ''\n\n\n \n if self.port is None:\n family=socket.AF_UNIX\n else:\n family=socket.AF_INET\n s=socket.socket(family,socket.SOCK_DGRAM)\n return s\n \n def send(self,s):\n ''\n\n\n\n\n\n \n if self.sock is None:\n self.createSocket()\n self.sock.sendto(s,self.address)\n \nclass SysLogHandler(logging.Handler):\n ''\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n LOG_EMERG=0\n LOG_ALERT=1\n LOG_CRIT=2\n LOG_ERR=3\n LOG_WARNING=4\n LOG_NOTICE=5\n LOG_INFO=6\n LOG_DEBUG=7\n \n \n LOG_KERN=0\n LOG_USER=1\n LOG_MAIL=2\n LOG_DAEMON=3\n LOG_AUTH=4\n LOG_SYSLOG=5\n LOG_LPR=6\n LOG_NEWS=7\n LOG_UUCP=8\n LOG_CRON=9\n LOG_AUTHPRIV=10\n LOG_FTP=11\n LOG_NTP=12\n LOG_SECURITY=13\n LOG_CONSOLE=14\n LOG_SOLCRON=15\n \n \n LOG_LOCAL0=16\n LOG_LOCAL1=17\n LOG_LOCAL2=18\n LOG_LOCAL3=19\n LOG_LOCAL4=20\n LOG_LOCAL5=21\n LOG_LOCAL6=22\n LOG_LOCAL7=23\n \n priority_names={\n \"alert\":LOG_ALERT,\n \"crit\":LOG_CRIT,\n \"critical\":LOG_CRIT,\n \"debug\":LOG_DEBUG,\n \"emerg\":LOG_EMERG,\n \"err\":LOG_ERR,\n \"error\":LOG_ERR,\n \"info\":LOG_INFO,\n \"notice\":LOG_NOTICE,\n \"panic\":LOG_EMERG,\n \"warn\":LOG_WARNING,\n \"warning\":LOG_WARNING,\n }\n \n facility_names={\n \"auth\":LOG_AUTH,\n \"authpriv\":LOG_AUTHPRIV,\n \"console\":LOG_CONSOLE,\n \"cron\":LOG_CRON,\n \"daemon\":LOG_DAEMON,\n \"ftp\":LOG_FTP,\n \"kern\":LOG_KERN,\n \"lpr\":LOG_LPR,\n \"mail\":LOG_MAIL,\n \"news\":LOG_NEWS,\n \"ntp\":LOG_NTP,\n \"security\":LOG_SECURITY,\n \"solaris-cron\":LOG_SOLCRON,\n \"syslog\":LOG_SYSLOG,\n \"user\":LOG_USER,\n \"uucp\":LOG_UUCP,\n \"local0\":LOG_LOCAL0,\n \"local1\":LOG_LOCAL1,\n \"local2\":LOG_LOCAL2,\n \"local3\":LOG_LOCAL3,\n \"local4\":LOG_LOCAL4,\n \"local5\":LOG_LOCAL5,\n \"local6\":LOG_LOCAL6,\n \"local7\":LOG_LOCAL7,\n }\n \n \n \n priority_map={\n \"DEBUG\":\"debug\",\n \"INFO\":\"info\",\n \"WARNING\":\"warning\",\n \"ERROR\":\"error\",\n \"CRITICAL\":\"critical\"\n }\n \n def __init__(self,address=('localhost',SYSLOG_UDP_PORT),\n facility=LOG_USER,socktype=None):\n ''\n\n\n\n\n\n\n\n\n\n \n logging.Handler.__init__(self)\n \n self.address=address\n self.facility=facility\n self.socktype=socktype\n self.socket=None\n self.createSocket()\n \n def _connect_unixsocket(self,address):\n use_socktype=self.socktype\n if use_socktype is None:\n use_socktype=socket.SOCK_DGRAM\n self.socket=socket.socket(socket.AF_UNIX,use_socktype)\n try:\n self.socket.connect(address)\n \n self.socktype=use_socktype\n except OSError:\n self.socket.close()\n if self.socktype is not None:\n \n raise\n use_socktype=socket.SOCK_STREAM\n self.socket=socket.socket(socket.AF_UNIX,use_socktype)\n try:\n self.socket.connect(address)\n \n self.socktype=use_socktype\n except OSError:\n self.socket.close()\n raise\n \n def createSocket(self):\n ''\n\n\n\n\n\n \n address=self.address\n socktype=self.socktype\n \n if isinstance(address,str):\n self.unixsocket=True\n \n \n \n \n try:\n self._connect_unixsocket(address)\n except OSError:\n pass\n else:\n self.unixsocket=False\n if socktype is None:\n socktype=socket.SOCK_DGRAM\n host,port=address\n ress=socket.getaddrinfo(host,port,0,socktype)\n if not ress:\n raise OSError(\"getaddrinfo returns an empty list\")\n for res in ress:\n af,socktype,proto,_,sa=res\n err=sock=None\n try:\n sock=socket.socket(af,socktype,proto)\n if socktype ==socket.SOCK_STREAM:\n sock.connect(sa)\n break\n except OSError as exc:\n err=exc\n if sock is not None:\n sock.close()\n if err is not None:\n raise err\n self.socket=sock\n self.socktype=socktype\n \n def encodePriority(self,facility,priority):\n ''\n\n\n\n\n \n if isinstance(facility,str):\n facility=self.facility_names[facility]\n if isinstance(priority,str):\n priority=self.priority_names[priority]\n return(facility <<3)|priority\n \n def close(self):\n ''\n\n \n with self.lock:\n sock=self.socket\n if sock:\n self.socket=None\n sock.close()\n logging.Handler.close(self)\n \n def mapPriority(self,levelName):\n ''\n\n\n\n\n\n \n return self.priority_map.get(levelName,\"warning\")\n \n ident=''\n append_nul=True\n \n def emit(self,record):\n ''\n\n\n\n\n \n try:\n msg=self.format(record)\n if self.ident:\n msg=self.ident+msg\n if self.append_nul:\n msg +='\\000'\n \n \n \n prio='<%d>'%self.encodePriority(self.facility,\n self.mapPriority(record.levelname))\n prio=prio.encode('utf-8')\n \n msg=msg.encode('utf-8')\n msg=prio+msg\n \n if not self.socket:\n self.createSocket()\n \n if self.unixsocket:\n try:\n self.socket.send(msg)\n except OSError:\n self.socket.close()\n self._connect_unixsocket(self.address)\n self.socket.send(msg)\n elif self.socktype ==socket.SOCK_DGRAM:\n self.socket.sendto(msg,self.address)\n else:\n self.socket.sendall(msg)\n except Exception:\n self.handleError(record)\n \nclass SMTPHandler(logging.Handler):\n ''\n\n \n def __init__(self,mailhost,fromaddr,toaddrs,subject,\n credentials=None,secure=None,timeout=5.0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n logging.Handler.__init__(self)\n if isinstance(mailhost,(list,tuple)):\n self.mailhost,self.mailport=mailhost\n else:\n self.mailhost,self.mailport=mailhost,None\n if isinstance(credentials,(list,tuple)):\n self.username,self.password=credentials\n else:\n self.username=None\n self.fromaddr=fromaddr\n if isinstance(toaddrs,str):\n toaddrs=[toaddrs]\n self.toaddrs=toaddrs\n self.subject=subject\n self.secure=secure\n self.timeout=timeout\n \n def getSubject(self,record):\n ''\n\n\n\n\n \n return self.subject\n \n def emit(self,record):\n ''\n\n\n\n \n try:\n import smtplib\n from email.message import EmailMessage\n import email.utils\n \n port=self.mailport\n if not port:\n port=smtplib.SMTP_PORT\n smtp=smtplib.SMTP(self.mailhost,port,timeout=self.timeout)\n msg=EmailMessage()\n msg['From']=self.fromaddr\n msg['To']=','.join(self.toaddrs)\n msg['Subject']=self.getSubject(record)\n msg['Date']=email.utils.localtime()\n msg.set_content(self.format(record))\n if self.username:\n if self.secure is not None:\n smtp.ehlo()\n smtp.starttls(*self.secure)\n smtp.ehlo()\n smtp.login(self.username,self.password)\n smtp.send_message(msg)\n smtp.quit()\n except Exception:\n self.handleError(record)\n \nclass NTEventLogHandler(logging.Handler):\n ''\n\n\n\n\n\n\n\n \n def __init__(self,appname,dllname=None,logtype=\"Application\"):\n logging.Handler.__init__(self)\n try:\n import win32evtlogutil,win32evtlog\n self.appname=appname\n self._welu=win32evtlogutil\n if not dllname:\n dllname=os.path.split(self._welu.__file__)\n dllname=os.path.split(dllname[0])\n dllname=os.path.join(dllname[0],r'win32service.pyd')\n self.dllname=dllname\n self.logtype=logtype\n \n \n \n try:\n self._welu.AddSourceToRegistry(appname,dllname,logtype)\n except Exception as e:\n \n \n if getattr(e,'winerror',None)!=5:\n raise\n self.deftype=win32evtlog.EVENTLOG_ERROR_TYPE\n self.typemap={\n logging.DEBUG:win32evtlog.EVENTLOG_INFORMATION_TYPE,\n logging.INFO:win32evtlog.EVENTLOG_INFORMATION_TYPE,\n logging.WARNING:win32evtlog.EVENTLOG_WARNING_TYPE,\n logging.ERROR:win32evtlog.EVENTLOG_ERROR_TYPE,\n logging.CRITICAL:win32evtlog.EVENTLOG_ERROR_TYPE,\n }\n except ImportError:\n print(\"The Python Win32 extensions for NT (service, event \"\\\n \"logging) appear not to be available.\")\n self._welu=None\n \n def getMessageID(self,record):\n ''\n\n\n\n\n\n \n return 1\n \n def getEventCategory(self,record):\n ''\n\n\n\n\n \n return 0\n \n def getEventType(self,record):\n ''\n\n\n\n\n\n\n\n\n \n return self.typemap.get(record.levelno,self.deftype)\n \n def emit(self,record):\n ''\n\n\n\n\n \n if self._welu:\n try:\n id=self.getMessageID(record)\n cat=self.getEventCategory(record)\n type=self.getEventType(record)\n msg=self.format(record)\n self._welu.ReportEvent(self.appname,id,cat,type,[msg])\n except Exception:\n self.handleError(record)\n \n def close(self):\n ''\n\n\n\n\n\n\n\n \n \n logging.Handler.close(self)\n \nclass HTTPHandler(logging.Handler):\n ''\n\n\n \n def __init__(self,host,url,method=\"GET\",secure=False,credentials=None,\n context=None):\n ''\n\n\n \n logging.Handler.__init__(self)\n method=method.upper()\n if method not in[\"GET\",\"POST\"]:\n raise ValueError(\"method must be GET or POST\")\n if not secure and context is not None:\n raise ValueError(\"context parameter only makes sense \"\n \"with secure=True\")\n self.host=host\n self.url=url\n self.method=method\n self.secure=secure\n self.credentials=credentials\n self.context=context\n \n def mapLogRecord(self,record):\n ''\n\n\n\n \n return record.__dict__\n \n def getConnection(self,host,secure):\n ''\n\n\n\n\n \n import http.client\n if secure:\n connection=http.client.HTTPSConnection(host,context=self.context)\n else:\n connection=http.client.HTTPConnection(host)\n return connection\n \n def emit(self,record):\n ''\n\n\n\n \n try:\n import urllib.parse\n host=self.host\n h=self.getConnection(host,self.secure)\n url=self.url\n data=urllib.parse.urlencode(self.mapLogRecord(record))\n if self.method ==\"GET\":\n if(url.find('?')>=0):\n sep='&'\n else:\n sep='?'\n url=url+\"%c%s\"%(sep,data)\n h.putrequest(self.method,url)\n \n \n i=host.find(\":\")\n if i >=0:\n host=host[:i]\n \n \n \n if self.method ==\"POST\":\n h.putheader(\"Content-type\",\n \"application/x-www-form-urlencoded\")\n h.putheader(\"Content-length\",str(len(data)))\n if self.credentials:\n import base64\n s=('%s:%s'%self.credentials).encode('utf-8')\n s='Basic '+base64.b64encode(s).strip().decode('ascii')\n h.putheader('Authorization',s)\n h.endheaders()\n if self.method ==\"POST\":\n h.send(data.encode('utf-8'))\n h.getresponse()\n except Exception:\n self.handleError(record)\n \nclass BufferingHandler(logging.Handler):\n ''\n\n\n\n \n def __init__(self,capacity):\n ''\n\n \n logging.Handler.__init__(self)\n self.capacity=capacity\n self.buffer=[]\n \n def shouldFlush(self,record):\n ''\n\n\n\n\n \n return(len(self.buffer)>=self.capacity)\n \n def emit(self,record):\n ''\n\n\n\n\n \n self.buffer.append(record)\n if self.shouldFlush(record):\n self.flush()\n \n def flush(self):\n ''\n\n\n\n \n with self.lock:\n self.buffer.clear()\n \n def close(self):\n ''\n\n\n\n \n try:\n self.flush()\n finally:\n logging.Handler.close(self)\n \nclass MemoryHandler(BufferingHandler):\n ''\n\n\n\n \n def __init__(self,capacity,flushLevel=logging.ERROR,target=None,\n flushOnClose=True):\n ''\n\n\n\n\n\n\n\n\n\n\n \n BufferingHandler.__init__(self,capacity)\n self.flushLevel=flushLevel\n self.target=target\n \n self.flushOnClose=flushOnClose\n \n def shouldFlush(self,record):\n ''\n\n \n return(len(self.buffer)>=self.capacity)or\\\n (record.levelno >=self.flushLevel)\n \n def setTarget(self,target):\n ''\n\n \n with self.lock:\n self.target=target\n \n def flush(self):\n ''\n\n\n\n\n\n \n with self.lock:\n if self.target:\n for record in self.buffer:\n self.target.handle(record)\n self.buffer.clear()\n \n def close(self):\n ''\n\n\n \n try:\n if self.flushOnClose:\n self.flush()\n finally:\n with self.lock:\n self.target=None\n BufferingHandler.close(self)\n \n \nclass QueueHandler(logging.Handler):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,queue):\n ''\n\n \n logging.Handler.__init__(self)\n self.queue=queue\n self.listener=None\n \n def enqueue(self,record):\n ''\n\n\n\n\n\n \n self.queue.put_nowait(record)\n \n def prepare(self,record):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n msg=self.format(record)\n \n record=copy.copy(record)\n record.message=msg\n record.msg=msg\n record.args=None\n record.exc_info=None\n record.exc_text=None\n record.stack_info=None\n return record\n \n def emit(self,record):\n ''\n\n\n\n \n try:\n self.enqueue(self.prepare(record))\n except Exception:\n self.handleError(record)\n \n \nclass QueueListener(object):\n ''\n\n\n\n \n _sentinel=None\n \n def __init__(self,queue,*handlers,respect_handler_level=False):\n ''\n\n\n \n self.queue=queue\n self.handlers=handlers\n self._thread=None\n self.respect_handler_level=respect_handler_level\n \n def dequeue(self,block):\n ''\n\n\n\n\n \n return self.queue.get(block)\n \n def start(self):\n ''\n\n\n\n\n \n self._thread=t=threading.Thread(target=self._monitor)\n t.daemon=True\n t.start()\n \n def prepare(self,record):\n ''\n\n\n\n\n\n \n return record\n \n def handle(self,record):\n ''\n\n\n\n\n \n record=self.prepare(record)\n for handler in self.handlers:\n if not self.respect_handler_level:\n process=True\n else:\n process=record.levelno >=handler.level\n if process:\n handler.handle(record)\n \n def _monitor(self):\n ''\n\n\n\n\n\n \n q=self.queue\n has_task_done=hasattr(q,'task_done')\n while True:\n try:\n record=self.dequeue(True)\n if record is self._sentinel:\n if has_task_done:\n q.task_done()\n break\n self.handle(record)\n if has_task_done:\n q.task_done()\n except queue.Empty:\n break\n \n def enqueue_sentinel(self):\n ''\n\n\n\n\n\n \n self.queue.put_nowait(self._sentinel)\n \n def stop(self):\n ''\n\n\n\n\n\n \n if self._thread:\n self.enqueue_sentinel()\n self._thread.join()\n self._thread=None\n", ["base64", "copy", "email.message", "email.utils", "http.client", "io", "logging", "os", "pickle", "queue", "re", "smtplib", "socket", "struct", "threading", "time", "urllib.parse", "win32evtlog", "win32evtlogutil"]], "logging": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\"\nLogging package for Python. Based on PEP 282 and comments thereto in\ncomp.lang.python.\n\nCopyright (C) 2001-2022 Vinay Sajip. All Rights Reserved.\n\nTo use, simply 'import logging' and log away!\n\"\"\"\n\nimport sys,os,time,io,re,traceback,warnings,weakref,collections.abc\n\nfrom types import GenericAlias\nfrom string import Template\nfrom string import Formatter as StrFormatter\n\n\n__all__=['BASIC_FORMAT','BufferingFormatter','CRITICAL','DEBUG','ERROR',\n'FATAL','FileHandler','Filter','Formatter','Handler','INFO',\n'LogRecord','Logger','LoggerAdapter','NOTSET','NullHandler',\n'StreamHandler','WARN','WARNING','addLevelName','basicConfig',\n'captureWarnings','critical','debug','disable','error',\n'exception','fatal','getLevelName','getLogger','getLoggerClass',\n'info','log','makeLogRecord','setLoggerClass','shutdown',\n'warning','getLogRecordFactory','setLogRecordFactory',\n'lastResort','raiseExceptions','getLevelNamesMapping',\n'getHandlerByName','getHandlerNames']\n\nimport threading\n\n__author__=\"Vinay Sajip \"\n__status__=\"production\"\n\n__version__=\"0.5.1.2\"\n__date__=\"07 February 2010\"\n\n\n\n\n\n\n\n\n_startTime=time.time_ns()\n\n\n\n\n\nraiseExceptions=True\n\n\n\n\nlogThreads=True\n\n\n\n\nlogMultiprocessing=True\n\n\n\n\nlogProcesses=True\n\n\n\n\nlogAsyncioTasks=True\n\n\n\n\n\n\n\n\n\n\n\n\nCRITICAL=50\nFATAL=CRITICAL\nERROR=40\nWARNING=30\nWARN=WARNING\nINFO=20\nDEBUG=10\nNOTSET=0\n\n_levelToName={\nCRITICAL:'CRITICAL',\nERROR:'ERROR',\nWARNING:'WARNING',\nINFO:'INFO',\nDEBUG:'DEBUG',\nNOTSET:'NOTSET',\n}\n_nameToLevel={\n'CRITICAL':CRITICAL,\n'FATAL':FATAL,\n'ERROR':ERROR,\n'WARN':WARNING,\n'WARNING':WARNING,\n'INFO':INFO,\n'DEBUG':DEBUG,\n'NOTSET':NOTSET,\n}\n\ndef getLevelNamesMapping():\n return _nameToLevel.copy()\n \ndef getLevelName(level):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n result=_levelToName.get(level)\n if result is not None:\n return result\n result=_nameToLevel.get(level)\n if result is not None:\n return result\n return \"Level %s\"%level\n \ndef addLevelName(level,levelName):\n ''\n\n\n\n \n with _lock:\n _levelToName[level]=levelName\n _nameToLevel[levelName]=level\n \nif hasattr(sys,\"_getframe\"):\n currentframe=lambda:sys._getframe(1)\nelse:\n def currentframe():\n ''\n try:\n raise Exception\n except Exception as exc:\n return exc.__traceback__.tb_frame.f_back\n \n \n \n \n \n \n \n \n \n \n \n \n \n_srcfile=os.path.normcase(addLevelName.__code__.co_filename)\n\n\n\n\n\n\n\n\ndef _is_internal_frame(frame):\n ''\n filename=os.path.normcase(frame.f_code.co_filename)\n return filename ==_srcfile or(\n \"importlib\"in filename and \"_bootstrap\"in filename\n )\n \n \ndef _checkLevel(level):\n if isinstance(level,int):\n rv=level\n elif str(level)==level:\n if level not in _nameToLevel:\n raise ValueError(\"Unknown level: %r\"%level)\n rv=_nameToLevel[level]\n else:\n raise TypeError(\"Level not an integer or a valid string: %r\"\n %(level,))\n return rv\n \n \n \n \n \n \n \n \n \n \n \n \n \n_lock=threading.RLock()\n\ndef _prepareFork():\n ''\n\n\n\n \n \n \n try:\n _lock.acquire()\n except BaseException:\n _lock.release()\n raise\n \ndef _afterFork():\n ''\n\n\n\n \n _lock.release()\n \n \n \n \nif not hasattr(os,'register_at_fork'):\n def _register_at_fork_reinit_lock(instance):\n pass\nelse:\n\n\n\n _at_fork_reinit_lock_weakset=weakref.WeakSet()\n \n def _register_at_fork_reinit_lock(instance):\n with _lock:\n _at_fork_reinit_lock_weakset.add(instance)\n \n def _after_at_fork_child_reinit_locks():\n for handler in _at_fork_reinit_lock_weakset:\n handler._at_fork_reinit()\n \n \n \n _lock._at_fork_reinit()\n \n os.register_at_fork(before=_prepareFork,\n after_in_child=_after_at_fork_child_reinit_locks,\n after_in_parent=_afterFork)\n \n \n \n \n \n \nclass LogRecord(object):\n ''\n\n\n\n\n\n\n\n\n\n \n def __init__(self,name,level,pathname,lineno,\n msg,args,exc_info,func=None,sinfo=None,**kwargs):\n ''\n\n \n ct=time.time_ns()\n self.name=name\n self.msg=msg\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if(args and len(args)==1 and isinstance(args[0],collections.abc.Mapping)\n and args[0]):\n args=args[0]\n self.args=args\n self.levelname=getLevelName(level)\n self.levelno=level\n self.pathname=pathname\n try:\n self.filename=os.path.basename(pathname)\n self.module=os.path.splitext(self.filename)[0]\n except(TypeError,ValueError,AttributeError):\n self.filename=pathname\n self.module=\"Unknown module\"\n self.exc_info=exc_info\n self.exc_text=None\n self.stack_info=sinfo\n self.lineno=lineno\n self.funcName=func\n self.created=ct /1e9\n \n \n \n \n self.msecs=(ct %1_000_000_000)//1_000_000+0.0\n \n self.relativeCreated=(ct -_startTime)/1e6\n if logThreads:\n self.thread=threading.get_ident()\n self.threadName=threading.current_thread().name\n else:\n self.thread=None\n self.threadName=None\n if not logMultiprocessing:\n self.processName=None\n else:\n self.processName='MainProcess'\n mp=sys.modules.get('multiprocessing')\n if mp is not None:\n \n \n \n \n try:\n self.processName=mp.current_process().name\n except Exception:\n pass\n if logProcesses and hasattr(os,'getpid'):\n self.process=os.getpid()\n else:\n self.process=None\n \n self.taskName=None\n if logAsyncioTasks:\n asyncio=sys.modules.get('asyncio')\n if asyncio:\n try:\n self.taskName=asyncio.current_task().get_name()\n except Exception:\n pass\n \n def __repr__(self):\n return ''%(self.name,self.levelno,\n self.pathname,self.lineno,self.msg)\n \n def getMessage(self):\n ''\n\n\n\n\n \n msg=str(self.msg)\n if self.args:\n msg=msg %self.args\n return msg\n \n \n \n \n_logRecordFactory=LogRecord\n\ndef setLogRecordFactory(factory):\n ''\n\n\n\n\n \n global _logRecordFactory\n _logRecordFactory=factory\n \ndef getLogRecordFactory():\n ''\n\n \n \n return _logRecordFactory\n \ndef makeLogRecord(dict):\n ''\n\n\n\n\n \n rv=_logRecordFactory(None,None,\"\",0,\"\",(),None,None)\n rv.__dict__.update(dict)\n return rv\n \n \n \n \n \n_str_formatter=StrFormatter()\ndel StrFormatter\n\n\nclass PercentStyle(object):\n\n default_format='%(message)s'\n asctime_format='%(asctime)s'\n asctime_search='%(asctime)'\n validation_pattern=re.compile(r'%\\(\\w+\\)[#0+ -]*(\\*|\\d+)?(\\.(\\*|\\d+))?[diouxefgcrsa%]',re.I)\n \n def __init__(self,fmt,*,defaults=None):\n self._fmt=fmt or self.default_format\n self._defaults=defaults\n \n def usesTime(self):\n return self._fmt.find(self.asctime_search)>=0\n \n def validate(self):\n ''\n if not self.validation_pattern.search(self._fmt):\n raise ValueError(\"Invalid format '%s' for '%s' style\"%(self._fmt,self.default_format[0]))\n \n def _format(self,record):\n if defaults :=self._defaults:\n values=defaults |record.__dict__\n else:\n values=record.__dict__\n return self._fmt %values\n \n def format(self,record):\n try:\n return self._format(record)\n except KeyError as e:\n raise ValueError('Formatting field not found in record: %s'%e)\n \n \nclass StrFormatStyle(PercentStyle):\n default_format='{message}'\n asctime_format='{asctime}'\n asctime_search='{asctime'\n \n fmt_spec=re.compile(r'^(.?[<>=^])?[+ -]?#?0?(\\d+|{\\w+})?[,_]?(\\.(\\d+|{\\w+}))?[bcdefgnosx%]?$',re.I)\n field_spec=re.compile(r'^(\\d+|\\w+)(\\.\\w+|\\[[^]]+\\])*$')\n \n def _format(self,record):\n if defaults :=self._defaults:\n values=defaults |record.__dict__\n else:\n values=record.__dict__\n return self._fmt.format(**values)\n \n def validate(self):\n ''\n fields=set()\n try:\n for _,fieldname,spec,conversion in _str_formatter.parse(self._fmt):\n if fieldname:\n if not self.field_spec.match(fieldname):\n raise ValueError('invalid field name/expression: %r'%fieldname)\n fields.add(fieldname)\n if conversion and conversion not in 'rsa':\n raise ValueError('invalid conversion: %r'%conversion)\n if spec and not self.fmt_spec.match(spec):\n raise ValueError('bad specifier: %r'%spec)\n except ValueError as e:\n raise ValueError('invalid format: %s'%e)\n if not fields:\n raise ValueError('invalid format: no fields')\n \n \nclass StringTemplateStyle(PercentStyle):\n default_format='${message}'\n asctime_format='${asctime}'\n asctime_search='${asctime}'\n \n def __init__(self,*args,**kwargs):\n super().__init__(*args,**kwargs)\n self._tpl=Template(self._fmt)\n \n def usesTime(self):\n fmt=self._fmt\n return fmt.find('$asctime')>=0 or fmt.find(self.asctime_search)>=0\n \n def validate(self):\n pattern=Template.pattern\n fields=set()\n for m in pattern.finditer(self._fmt):\n d=m.groupdict()\n if d['named']:\n fields.add(d['named'])\n elif d['braced']:\n fields.add(d['braced'])\n elif m.group(0)=='$':\n raise ValueError('invalid format: bare \\'$\\' not allowed')\n if not fields:\n raise ValueError('invalid format: no fields')\n \n def _format(self,record):\n if defaults :=self._defaults:\n values=defaults |record.__dict__\n else:\n values=record.__dict__\n return self._tpl.substitute(**values)\n \n \nBASIC_FORMAT=\"%(levelname)s:%(name)s:%(message)s\"\n\n_STYLES={\n'%':(PercentStyle,BASIC_FORMAT),\n'{':(StrFormatStyle,'{levelname}:{name}:{message}'),\n'$':(StringTemplateStyle,'${levelname}:${name}:${message}'),\n}\n\nclass Formatter(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n converter=time.localtime\n \n def __init__(self,fmt=None,datefmt=None,style='%',validate=True,*,\n defaults=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if style not in _STYLES:\n raise ValueError('Style must be one of: %s'%','.join(\n _STYLES.keys()))\n self._style=_STYLES[style][0](fmt,defaults=defaults)\n if validate:\n self._style.validate()\n \n self._fmt=self._style._fmt\n self.datefmt=datefmt\n \n default_time_format='%Y-%m-%d %H:%M:%S'\n default_msec_format='%s,%03d'\n \n def formatTime(self,record,datefmt=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n ct=self.converter(record.created)\n if datefmt:\n s=time.strftime(datefmt,ct)\n else:\n s=time.strftime(self.default_time_format,ct)\n if self.default_msec_format:\n s=self.default_msec_format %(s,record.msecs)\n return s\n \n def formatException(self,ei):\n ''\n\n\n\n\n \n sio=io.StringIO()\n tb=ei[2]\n \n \n \n traceback.print_exception(ei[0],ei[1],tb,limit=None,file=sio)\n s=sio.getvalue()\n sio.close()\n if s[-1:]==\"\\n\":\n s=s[:-1]\n return s\n \n def usesTime(self):\n ''\n\n \n return self._style.usesTime()\n \n def formatMessage(self,record):\n return self._style.format(record)\n \n def formatStack(self,stack_info):\n ''\n\n\n\n\n\n\n\n\n \n return stack_info\n \n def format(self,record):\n ''\n\n\n\n\n\n\n\n\n\n\n \n record.message=record.getMessage()\n if self.usesTime():\n record.asctime=self.formatTime(record,self.datefmt)\n s=self.formatMessage(record)\n if record.exc_info:\n \n \n if not record.exc_text:\n record.exc_text=self.formatException(record.exc_info)\n if record.exc_text:\n if s[-1:]!=\"\\n\":\n s=s+\"\\n\"\n s=s+record.exc_text\n if record.stack_info:\n if s[-1:]!=\"\\n\":\n s=s+\"\\n\"\n s=s+self.formatStack(record.stack_info)\n return s\n \n \n \n \n_defaultFormatter=Formatter()\n\nclass BufferingFormatter(object):\n ''\n\n \n def __init__(self,linefmt=None):\n ''\n\n\n \n if linefmt:\n self.linefmt=linefmt\n else:\n self.linefmt=_defaultFormatter\n \n def formatHeader(self,records):\n ''\n\n \n return \"\"\n \n def formatFooter(self,records):\n ''\n\n \n return \"\"\n \n def format(self,records):\n ''\n\n \n rv=\"\"\n if len(records)>0:\n rv=rv+self.formatHeader(records)\n for record in records:\n rv=rv+self.linefmt.format(record)\n rv=rv+self.formatFooter(records)\n return rv\n \n \n \n \n \nclass Filter(object):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,name=''):\n ''\n\n\n\n\n\n \n self.name=name\n self.nlen=len(name)\n \n def filter(self,record):\n ''\n\n\n\n\n \n if self.nlen ==0:\n return True\n elif self.name ==record.name:\n return True\n elif record.name.find(self.name,0,self.nlen)!=0:\n return False\n return(record.name[self.nlen]==\".\")\n \nclass Filterer(object):\n ''\n\n\n \n def __init__(self):\n ''\n\n \n self.filters=[]\n \n def addFilter(self,filter):\n ''\n\n \n if not(filter in self.filters):\n self.filters.append(filter)\n \n def removeFilter(self,filter):\n ''\n\n \n if filter in self.filters:\n self.filters.remove(filter)\n \n def filter(self,record):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n for f in self.filters:\n if hasattr(f,'filter'):\n result=f.filter(record)\n else:\n result=f(record)\n if not result:\n return False\n if isinstance(result,LogRecord):\n record=result\n return record\n \n \n \n \n \n_handlers=weakref.WeakValueDictionary()\n_handlerList=[]\n\ndef _removeHandlerRef(wr):\n ''\n\n \n \n \n \n \n handlers,lock=_handlerList,_lock\n if lock and handlers:\n with lock:\n try:\n handlers.remove(wr)\n except ValueError:\n pass\n \ndef _addHandlerRef(handler):\n ''\n\n \n with _lock:\n _handlerList.append(weakref.ref(handler,_removeHandlerRef))\n \n \ndef getHandlerByName(name):\n ''\n\n\n \n return _handlers.get(name)\n \n \ndef getHandlerNames():\n ''\n\n \n return frozenset(_handlers)\n \n \nclass Handler(Filterer):\n ''\n\n\n\n\n\n\n \n def __init__(self,level=NOTSET):\n ''\n\n\n \n Filterer.__init__(self)\n self._name=None\n self.level=_checkLevel(level)\n self.formatter=None\n self._closed=False\n \n _addHandlerRef(self)\n self.createLock()\n \n def get_name(self):\n return self._name\n \n def set_name(self,name):\n with _lock:\n if self._name in _handlers:\n del _handlers[self._name]\n self._name=name\n if name:\n _handlers[name]=self\n \n name=property(get_name,set_name)\n \n def createLock(self):\n ''\n\n \n self.lock=threading.RLock()\n _register_at_fork_reinit_lock(self)\n \n def _at_fork_reinit(self):\n self.lock._at_fork_reinit()\n \n def acquire(self):\n ''\n\n \n if self.lock:\n self.lock.acquire()\n \n def release(self):\n ''\n\n \n if self.lock:\n self.lock.release()\n \n def setLevel(self,level):\n ''\n\n \n self.level=_checkLevel(level)\n \n def format(self,record):\n ''\n\n\n\n\n \n if self.formatter:\n fmt=self.formatter\n else:\n fmt=_defaultFormatter\n return fmt.format(record)\n \n def emit(self,record):\n ''\n\n\n\n\n \n raise NotImplementedError('emit must be implemented '\n 'by Handler subclasses')\n \n def handle(self,record):\n ''\n\n\n\n\n\n\n\n\n \n rv=self.filter(record)\n if isinstance(rv,LogRecord):\n record=rv\n if rv:\n with self.lock:\n self.emit(record)\n return rv\n \n def setFormatter(self,fmt):\n ''\n\n \n self.formatter=fmt\n \n def flush(self):\n ''\n\n\n\n\n \n pass\n \n def close(self):\n ''\n\n\n\n\n\n\n \n \n with _lock:\n self._closed=True\n if self._name and self._name in _handlers:\n del _handlers[self._name]\n \n def handleError(self,record):\n ''\n\n\n\n\n\n\n\n\n\n \n if raiseExceptions and sys.stderr:\n exc=sys.exception()\n try:\n sys.stderr.write('--- Logging error ---\\n')\n traceback.print_exception(exc,limit=None,file=sys.stderr)\n sys.stderr.write('Call stack:\\n')\n \n \n frame=exc.__traceback__.tb_frame\n while(frame and os.path.dirname(frame.f_code.co_filename)==\n __path__[0]):\n frame=frame.f_back\n if frame:\n traceback.print_stack(frame,file=sys.stderr)\n else:\n \n sys.stderr.write('Logged from file %s, line %s\\n'%(\n record.filename,record.lineno))\n \n try:\n sys.stderr.write('Message: %r\\n'\n 'Arguments: %s\\n'%(record.msg,\n record.args))\n except RecursionError:\n raise\n except Exception:\n sys.stderr.write('Unable to print the message and arguments'\n ' - possible formatting error.\\nUse the'\n ' traceback above to help find the error.\\n'\n )\n except OSError:\n pass\n finally:\n del exc\n \n def __repr__(self):\n level=getLevelName(self.level)\n return '<%s (%s)>'%(self.__class__.__name__,level)\n \nclass StreamHandler(Handler):\n ''\n\n\n\n \n \n terminator='\\n'\n \n def __init__(self,stream=None):\n ''\n\n\n\n \n Handler.__init__(self)\n if stream is None:\n stream=sys.stderr\n self.stream=stream\n \n def flush(self):\n ''\n\n \n with self.lock:\n if self.stream and hasattr(self.stream,\"flush\"):\n self.stream.flush()\n \n def emit(self,record):\n ''\n\n\n\n\n\n\n\n\n \n try:\n msg=self.format(record)\n stream=self.stream\n \n stream.write(msg+self.terminator)\n self.flush()\n except RecursionError:\n raise\n except Exception:\n self.handleError(record)\n \n def setStream(self,stream):\n ''\n\n\n\n\n\n \n if stream is self.stream:\n result=None\n else:\n result=self.stream\n with self.lock:\n self.flush()\n self.stream=stream\n return result\n \n def __repr__(self):\n level=getLevelName(self.level)\n name=getattr(self.stream,'name','')\n \n name=str(name)\n if name:\n name +=' '\n return '<%s %s(%s)>'%(self.__class__.__name__,name,level)\n \n __class_getitem__=classmethod(GenericAlias)\n \n \nclass FileHandler(StreamHandler):\n ''\n\n \n def __init__(self,filename,mode='a',encoding=None,delay=False,errors=None):\n ''\n\n \n \n filename=os.fspath(filename)\n \n \n self.baseFilename=os.path.abspath(filename)\n self.mode=mode\n self.encoding=encoding\n if \"b\"not in mode:\n self.encoding=io.text_encoding(encoding)\n self.errors=errors\n self.delay=delay\n \n \n \n self._builtin_open=open\n if delay:\n \n \n Handler.__init__(self)\n self.stream=None\n else:\n StreamHandler.__init__(self,self._open())\n \n def close(self):\n ''\n\n \n with self.lock:\n try:\n if self.stream:\n try:\n self.flush()\n finally:\n stream=self.stream\n self.stream=None\n if hasattr(stream,\"close\"):\n stream.close()\n finally:\n \n \n \n \n StreamHandler.close(self)\n \n def _open(self):\n ''\n\n\n \n open_func=self._builtin_open\n return open_func(self.baseFilename,self.mode,\n encoding=self.encoding,errors=self.errors)\n \n def emit(self,record):\n ''\n\n\n\n\n\n\n\n \n if self.stream is None:\n if self.mode !='w'or not self._closed:\n self.stream=self._open()\n if self.stream:\n StreamHandler.emit(self,record)\n \n def __repr__(self):\n level=getLevelName(self.level)\n return '<%s %s (%s)>'%(self.__class__.__name__,self.baseFilename,level)\n \n \nclass _StderrHandler(StreamHandler):\n ''\n\n\n\n \n def __init__(self,level=NOTSET):\n ''\n\n \n Handler.__init__(self,level)\n \n @property\n def stream(self):\n return sys.stderr\n \n \n_defaultLastResort=_StderrHandler(WARNING)\nlastResort=_defaultLastResort\n\n\n\n\n\nclass PlaceHolder(object):\n ''\n\n\n\n \n def __init__(self,alogger):\n ''\n\n \n self.loggerMap={alogger:None}\n \n def append(self,alogger):\n ''\n\n \n if alogger not in self.loggerMap:\n self.loggerMap[alogger]=None\n \n \n \n \n \ndef setLoggerClass(klass):\n ''\n\n\n\n \n if klass !=Logger:\n if not issubclass(klass,Logger):\n raise TypeError(\"logger not derived from logging.Logger: \"\n +klass.__name__)\n global _loggerClass\n _loggerClass=klass\n \ndef getLoggerClass():\n ''\n\n \n return _loggerClass\n \nclass Manager(object):\n ''\n\n\n \n def __init__(self,rootnode):\n ''\n\n \n self.root=rootnode\n self.disable=0\n self.emittedNoHandlerWarning=False\n self.loggerDict={}\n self.loggerClass=None\n self.logRecordFactory=None\n \n @property\n def disable(self):\n return self._disable\n \n @disable.setter\n def disable(self,value):\n self._disable=_checkLevel(value)\n \n def getLogger(self,name):\n ''\n\n\n\n\n\n\n\n\n \n rv=None\n if not isinstance(name,str):\n raise TypeError('A logger name must be a string')\n with _lock:\n if name in self.loggerDict:\n rv=self.loggerDict[name]\n if isinstance(rv,PlaceHolder):\n ph=rv\n rv=(self.loggerClass or _loggerClass)(name)\n rv.manager=self\n self.loggerDict[name]=rv\n self._fixupChildren(ph,rv)\n self._fixupParents(rv)\n else:\n rv=(self.loggerClass or _loggerClass)(name)\n rv.manager=self\n self.loggerDict[name]=rv\n self._fixupParents(rv)\n return rv\n \n def setLoggerClass(self,klass):\n ''\n\n \n if klass !=Logger:\n if not issubclass(klass,Logger):\n raise TypeError(\"logger not derived from logging.Logger: \"\n +klass.__name__)\n self.loggerClass=klass\n \n def setLogRecordFactory(self,factory):\n ''\n\n\n \n self.logRecordFactory=factory\n \n def _fixupParents(self,alogger):\n ''\n\n\n \n name=alogger.name\n i=name.rfind(\".\")\n rv=None\n while(i >0)and not rv:\n substr=name[:i]\n if substr not in self.loggerDict:\n self.loggerDict[substr]=PlaceHolder(alogger)\n else:\n obj=self.loggerDict[substr]\n if isinstance(obj,Logger):\n rv=obj\n else:\n assert isinstance(obj,PlaceHolder)\n obj.append(alogger)\n i=name.rfind(\".\",0,i -1)\n if not rv:\n rv=self.root\n alogger.parent=rv\n \n def _fixupChildren(self,ph,alogger):\n ''\n\n\n \n name=alogger.name\n namelen=len(name)\n for c in ph.loggerMap.keys():\n \n if c.parent.name[:namelen]!=name:\n alogger.parent=c.parent\n c.parent=alogger\n \n def _clear_cache(self):\n ''\n\n\n \n \n with _lock:\n for logger in self.loggerDict.values():\n if isinstance(logger,Logger):\n logger._cache.clear()\n self.root._cache.clear()\n \n \n \n \n \nclass Logger(Filterer):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,name,level=NOTSET):\n ''\n\n \n Filterer.__init__(self)\n self.name=name\n self.level=_checkLevel(level)\n self.parent=None\n self.propagate=True\n self.handlers=[]\n self.disabled=False\n self._cache={}\n \n def setLevel(self,level):\n ''\n\n \n self.level=_checkLevel(level)\n self.manager._clear_cache()\n \n def debug(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(DEBUG):\n self._log(DEBUG,msg,args,**kwargs)\n \n def info(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(INFO):\n self._log(INFO,msg,args,**kwargs)\n \n def warning(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(WARNING):\n self._log(WARNING,msg,args,**kwargs)\n \n def error(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(ERROR):\n self._log(ERROR,msg,args,**kwargs)\n \n def exception(self,msg,*args,exc_info=True,**kwargs):\n ''\n\n \n self.error(msg,*args,exc_info=exc_info,**kwargs)\n \n def critical(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(CRITICAL):\n self._log(CRITICAL,msg,args,**kwargs)\n \n def fatal(self,msg,*args,**kwargs):\n ''\n\n \n self.critical(msg,*args,**kwargs)\n \n def log(self,level,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if not isinstance(level,int):\n if raiseExceptions:\n raise TypeError(\"level must be an integer\")\n else:\n return\n if self.isEnabledFor(level):\n self._log(level,msg,args,**kwargs)\n \n def findCaller(self,stack_info=False,stacklevel=1):\n ''\n\n\n \n f=currentframe()\n \n \n if f is None:\n return \"(unknown file)\",0,\"(unknown function)\",None\n while stacklevel >0:\n next_f=f.f_back\n if next_f is None:\n \n \n break\n \n \n \n \n f=next_f\n if not _is_internal_frame(f):\n stacklevel -=1\n co=f.f_code\n sinfo=None\n if stack_info:\n with io.StringIO()as sio:\n sio.write(\"Stack (most recent call last):\\n\")\n traceback.print_stack(f,file=sio)\n sinfo=sio.getvalue()\n if sinfo[-1]=='\\n':\n sinfo=sinfo[:-1]\n return co.co_filename,f.f_lineno,co.co_name,sinfo\n \n def makeRecord(self,name,level,fn,lno,msg,args,exc_info,\n func=None,extra=None,sinfo=None):\n ''\n\n\n \n rv=_logRecordFactory(name,level,fn,lno,msg,args,exc_info,func,\n sinfo)\n if extra is not None:\n for key in extra:\n if(key in[\"message\",\"asctime\"])or(key in rv.__dict__):\n raise KeyError(\"Attempt to overwrite %r in LogRecord\"%key)\n rv.__dict__[key]=extra[key]\n return rv\n \n def _log(self,level,msg,args,exc_info=None,extra=None,stack_info=False,\n stacklevel=1):\n ''\n\n\n \n sinfo=None\n if _srcfile:\n \n \n \n try:\n fn,lno,func,sinfo=self.findCaller(stack_info,stacklevel)\n except ValueError:\n fn,lno,func=\"(unknown file)\",0,\"(unknown function)\"\n else:\n fn,lno,func=\"(unknown file)\",0,\"(unknown function)\"\n if exc_info:\n if isinstance(exc_info,BaseException):\n exc_info=(type(exc_info),exc_info,exc_info.__traceback__)\n elif not isinstance(exc_info,tuple):\n exc_info=sys.exc_info()\n record=self.makeRecord(self.name,level,fn,lno,msg,args,\n exc_info,func,extra,sinfo)\n self.handle(record)\n \n def handle(self,record):\n ''\n\n\n\n\n \n if self.disabled:\n return\n maybe_record=self.filter(record)\n if not maybe_record:\n return\n if isinstance(maybe_record,LogRecord):\n record=maybe_record\n self.callHandlers(record)\n \n def addHandler(self,hdlr):\n ''\n\n \n with _lock:\n if not(hdlr in self.handlers):\n self.handlers.append(hdlr)\n \n def removeHandler(self,hdlr):\n ''\n\n \n with _lock:\n if hdlr in self.handlers:\n self.handlers.remove(hdlr)\n \n def hasHandlers(self):\n ''\n\n\n\n\n\n\n\n \n c=self\n rv=False\n while c:\n if c.handlers:\n rv=True\n break\n if not c.propagate:\n break\n else:\n c=c.parent\n return rv\n \n def callHandlers(self,record):\n ''\n\n\n\n\n\n\n\n \n c=self\n found=0\n while c:\n for hdlr in c.handlers:\n found=found+1\n if record.levelno >=hdlr.level:\n hdlr.handle(record)\n if not c.propagate:\n c=None\n else:\n c=c.parent\n if(found ==0):\n if lastResort:\n if record.levelno >=lastResort.level:\n lastResort.handle(record)\n elif raiseExceptions and not self.manager.emittedNoHandlerWarning:\n sys.stderr.write(\"No handlers could be found for logger\"\n \" \\\"%s\\\"\\n\"%self.name)\n self.manager.emittedNoHandlerWarning=True\n \n def getEffectiveLevel(self):\n ''\n\n\n\n\n \n logger=self\n while logger:\n if logger.level:\n return logger.level\n logger=logger.parent\n return NOTSET\n \n def isEnabledFor(self,level):\n ''\n\n \n if self.disabled:\n return False\n \n try:\n return self._cache[level]\n except KeyError:\n with _lock:\n if self.manager.disable >=level:\n is_enabled=self._cache[level]=False\n else:\n is_enabled=self._cache[level]=(\n level >=self.getEffectiveLevel()\n )\n return is_enabled\n \n def getChild(self,suffix):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self.root is not self:\n suffix='.'.join((self.name,suffix))\n return self.manager.getLogger(suffix)\n \n def getChildren(self):\n \n def _hierlevel(logger):\n if logger is logger.manager.root:\n return 0\n return 1+logger.name.count('.')\n \n d=self.manager.loggerDict\n with _lock:\n \n \n \n return set(item for item in d.values()\n if isinstance(item,Logger)and item.parent is self and\n _hierlevel(item)==1+_hierlevel(item.parent))\n \n def __repr__(self):\n level=getLevelName(self.getEffectiveLevel())\n return '<%s %s (%s)>'%(self.__class__.__name__,self.name,level)\n \n def __reduce__(self):\n if getLogger(self.name)is not self:\n import pickle\n raise pickle.PicklingError('logger cannot be pickled')\n return getLogger,(self.name,)\n \n \nclass RootLogger(Logger):\n ''\n\n\n\n \n def __init__(self,level):\n ''\n\n \n Logger.__init__(self,\"root\",level)\n \n def __reduce__(self):\n return getLogger,()\n \n_loggerClass=Logger\n\nclass LoggerAdapter(object):\n ''\n\n\n \n \n def __init__(self,logger,extra=None,merge_extra=False):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.logger=logger\n self.extra=extra\n self.merge_extra=merge_extra\n \n def process(self,msg,kwargs):\n ''\n\n\n\n\n\n\n\n \n if self.merge_extra and \"extra\"in kwargs:\n kwargs[\"extra\"]={**self.extra,**kwargs[\"extra\"]}\n else:\n kwargs[\"extra\"]=self.extra\n return msg,kwargs\n \n \n \n \n def debug(self,msg,*args,**kwargs):\n ''\n\n \n self.log(DEBUG,msg,*args,**kwargs)\n \n def info(self,msg,*args,**kwargs):\n ''\n\n \n self.log(INFO,msg,*args,**kwargs)\n \n def warning(self,msg,*args,**kwargs):\n ''\n\n \n self.log(WARNING,msg,*args,**kwargs)\n \n def error(self,msg,*args,**kwargs):\n ''\n\n \n self.log(ERROR,msg,*args,**kwargs)\n \n def exception(self,msg,*args,exc_info=True,**kwargs):\n ''\n\n \n self.log(ERROR,msg,*args,exc_info=exc_info,**kwargs)\n \n def critical(self,msg,*args,**kwargs):\n ''\n\n \n self.log(CRITICAL,msg,*args,**kwargs)\n \n def log(self,level,msg,*args,**kwargs):\n ''\n\n\n \n if self.isEnabledFor(level):\n msg,kwargs=self.process(msg,kwargs)\n self.logger.log(level,msg,*args,**kwargs)\n \n def isEnabledFor(self,level):\n ''\n\n \n return self.logger.isEnabledFor(level)\n \n def setLevel(self,level):\n ''\n\n \n self.logger.setLevel(level)\n \n def getEffectiveLevel(self):\n ''\n\n \n return self.logger.getEffectiveLevel()\n \n def hasHandlers(self):\n ''\n\n \n return self.logger.hasHandlers()\n \n def _log(self,level,msg,args,**kwargs):\n ''\n\n \n return self.logger._log(level,msg,args,**kwargs)\n \n @property\n def manager(self):\n return self.logger.manager\n \n @manager.setter\n def manager(self,value):\n self.logger.manager=value\n \n @property\n def name(self):\n return self.logger.name\n \n def __repr__(self):\n logger=self.logger\n level=getLevelName(logger.getEffectiveLevel())\n return '<%s %s (%s)>'%(self.__class__.__name__,logger.name,level)\n \n __class_getitem__=classmethod(GenericAlias)\n \nroot=RootLogger(WARNING)\nLogger.root=root\nLogger.manager=Manager(Logger.root)\n\n\n\n\n\ndef basicConfig(**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n with _lock:\n force=kwargs.pop('force',False)\n encoding=kwargs.pop('encoding',None)\n errors=kwargs.pop('errors','backslashreplace')\n if force:\n for h in root.handlers[:]:\n root.removeHandler(h)\n h.close()\n if len(root.handlers)==0:\n handlers=kwargs.pop(\"handlers\",None)\n if handlers is None:\n if \"stream\"in kwargs and \"filename\"in kwargs:\n raise ValueError(\"'stream' and 'filename' should not be \"\n \"specified together\")\n else:\n if \"stream\"in kwargs or \"filename\"in kwargs:\n raise ValueError(\"'stream' or 'filename' should not be \"\n \"specified together with 'handlers'\")\n if handlers is None:\n filename=kwargs.pop(\"filename\",None)\n mode=kwargs.pop(\"filemode\",'a')\n if filename:\n if 'b'in mode:\n errors=None\n else:\n encoding=io.text_encoding(encoding)\n h=FileHandler(filename,mode,\n encoding=encoding,errors=errors)\n else:\n stream=kwargs.pop(\"stream\",None)\n h=StreamHandler(stream)\n handlers=[h]\n dfs=kwargs.pop(\"datefmt\",None)\n style=kwargs.pop(\"style\",'%')\n if style not in _STYLES:\n raise ValueError('Style must be one of: %s'%','.join(\n _STYLES.keys()))\n fs=kwargs.pop(\"format\",_STYLES[style][1])\n fmt=Formatter(fs,dfs,style)\n for h in handlers:\n if h.formatter is None:\n h.setFormatter(fmt)\n root.addHandler(h)\n level=kwargs.pop(\"level\",None)\n if level is not None:\n root.setLevel(level)\n if kwargs:\n keys=', '.join(kwargs.keys())\n raise ValueError('Unrecognised argument(s): %s'%keys)\n \n \n \n \n \n \ndef getLogger(name=None):\n ''\n\n\n\n \n if not name or isinstance(name,str)and name ==root.name:\n return root\n return Logger.manager.getLogger(name)\n \ndef critical(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.critical(msg,*args,**kwargs)\n \ndef fatal(msg,*args,**kwargs):\n ''\n\n \n critical(msg,*args,**kwargs)\n \ndef error(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.error(msg,*args,**kwargs)\n \ndef exception(msg,*args,exc_info=True,**kwargs):\n ''\n\n\n\n \n error(msg,*args,exc_info=exc_info,**kwargs)\n \ndef warning(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.warning(msg,*args,**kwargs)\n \ndef info(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.info(msg,*args,**kwargs)\n \ndef debug(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.debug(msg,*args,**kwargs)\n \ndef log(level,msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.log(level,msg,*args,**kwargs)\n \ndef disable(level=CRITICAL):\n ''\n\n \n root.manager.disable=level\n root.manager._clear_cache()\n \ndef shutdown(handlerList=_handlerList):\n ''\n\n\n\n\n \n for wr in reversed(handlerList[:]):\n \n \n try:\n h=wr()\n if h:\n try:\n h.acquire()\n \n \n \n if getattr(h,'flushOnClose',True):\n h.flush()\n h.close()\n except(OSError,ValueError):\n \n \n \n \n pass\n finally:\n h.release()\n except:\n if raiseExceptions:\n raise\n \n \n \nimport atexit\natexit.register(shutdown)\n\n\n\nclass NullHandler(Handler):\n ''\n\n\n\n\n\n\n\n \n def handle(self,record):\n ''\n \n def emit(self,record):\n ''\n \n def createLock(self):\n self.lock=None\n \n def _at_fork_reinit(self):\n pass\n \n \n \n_warnings_showwarning=None\n\ndef _showwarning(message,category,filename,lineno,file=None,line=None):\n ''\n\n\n\n\n\n \n if file is not None:\n if _warnings_showwarning is not None:\n _warnings_showwarning(message,category,filename,lineno,file,line)\n else:\n s=warnings.formatwarning(message,category,filename,lineno,line)\n logger=getLogger(\"py.warnings\")\n if not logger.handlers:\n logger.addHandler(NullHandler())\n \n \n logger.warning(str(s))\n \ndef captureWarnings(capture):\n ''\n\n\n\n \n global _warnings_showwarning\n if capture:\n if _warnings_showwarning is None:\n _warnings_showwarning=warnings.showwarning\n warnings.showwarning=_showwarning\n else:\n if _warnings_showwarning is not None:\n warnings.showwarning=_warnings_showwarning\n _warnings_showwarning=None\n", ["atexit", "collections.abc", "io", "os", "pickle", "re", "string", "sys", "threading", "time", "traceback", "types", "warnings", "weakref"], 1], "multiprocessing.connection": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['Client','Listener','Pipe']\n\nfrom queue import Queue\n\n\nfamilies=[None]\n\n\nclass Listener(object):\n\n def __init__(self,address=None,family=None,backlog=1):\n self._backlog_queue=Queue(backlog)\n \n def accept(self):\n return Connection(*self._backlog_queue.get())\n \n def close(self):\n self._backlog_queue=None\n \n address=property(lambda self:self._backlog_queue)\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,exc_tb):\n self.close()\n \n \ndef Client(address):\n _in,_out=Queue(),Queue()\n address.put((_out,_in))\n return Connection(_in,_out)\n \n \ndef Pipe(duplex=True):\n a,b=Queue(),Queue()\n return Connection(a,b),Connection(b,a)\n \n \nclass Connection(object):\n\n def __init__(self,_in,_out):\n self._out=_out\n self._in=_in\n self.send=self.send_bytes=_out.put\n self.recv=self.recv_bytes=_in.get\n \n def poll(self,timeout=0.0):\n if self._in.qsize()>0:\n return True\n if timeout <=0.0:\n return False\n self._in.not_empty.acquire()\n self._in.not_empty.wait(timeout)\n self._in.not_empty.release()\n return self._in.qsize()>0\n \n def close(self):\n pass\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,exc_tb):\n self.close()\n", ["queue"]], "multiprocessing.pool": [".py", "\n\n\n\n\n\n\n\n\n__all__=['Pool']\n\n\n\n\n\nimport threading\nimport queue\nimport itertools\nimport collections\nimport time\n\nfrom multiprocessing import Process,cpu_count,TimeoutError\nfrom multiprocessing.util import Finalize,debug\n\n\n\n\n\nRUN=0\nCLOSE=1\nTERMINATE=2\n\n\n\n\n\njob_counter=itertools.count()\n\ndef mapstar(args):\n return list(map(*args))\n \ndef starmapstar(args):\n return list(itertools.starmap(args[0],args[1]))\n \n \n \n \n \nclass MaybeEncodingError(Exception):\n ''\n \n \n def __init__(self,exc,value):\n self.exc=repr(exc)\n self.value=repr(value)\n super(MaybeEncodingError,self).__init__(self.exc,self.value)\n \n def __str__(self):\n return \"Error sending result: '%s'. Reason: '%s'\"%(self.value,\n self.exc)\n \n def __repr__(self):\n return \"\"%str(self)\n \n \ndef worker(inqueue,outqueue,initializer=None,initargs=(),maxtasks=None):\n assert maxtasks is None or(type(maxtasks)==int and maxtasks >0)\n put=outqueue.put\n get=inqueue.get\n if hasattr(inqueue,'_writer'):\n inqueue._writer.close()\n outqueue._reader.close()\n \n if initializer is not None:\n initializer(*initargs)\n \n completed=0\n while maxtasks is None or(maxtasks and completed 1\n task_batches=Pool._get_tasks(func,iterable,chunksize)\n result=IMapIterator(self._cache)\n self._taskqueue.put((((result._job,i,mapstar,(x,),{})\n for i,x in enumerate(task_batches)),result._set_length))\n return(item for chunk in result for item in chunk)\n \n def imap_unordered(self,func,iterable,chunksize=1):\n ''\n\n \n if self._state !=RUN:\n raise ValueError(\"Pool not running\")\n if chunksize ==1:\n result=IMapUnorderedIterator(self._cache)\n self._taskqueue.put((((result._job,i,func,(x,),{})\n for i,x in enumerate(iterable)),result._set_length))\n return result\n else:\n assert chunksize >1\n task_batches=Pool._get_tasks(func,iterable,chunksize)\n result=IMapUnorderedIterator(self._cache)\n self._taskqueue.put((((result._job,i,mapstar,(x,),{})\n for i,x in enumerate(task_batches)),result._set_length))\n return(item for chunk in result for item in chunk)\n \n def apply_async(self,func,args=(),kwds={},callback=None,\n error_callback=None):\n ''\n\n \n if self._state !=RUN:\n raise ValueError(\"Pool not running\")\n result=ApplyResult(self._cache,callback,error_callback)\n self._taskqueue.put(([(result._job,None,func,args,kwds)],None))\n return result\n \n def map_async(self,func,iterable,chunksize=None,callback=None,\n error_callback=None):\n ''\n\n \n return self._map_async(func,iterable,mapstar,chunksize,callback,\n error_callback)\n \n def _map_async(self,func,iterable,mapper,chunksize=None,callback=None,\n error_callback=None):\n ''\n\n \n if self._state !=RUN:\n raise ValueError(\"Pool not running\")\n if not hasattr(iterable,'__len__'):\n iterable=list(iterable)\n \n if chunksize is None:\n chunksize,extra=divmod(len(iterable),len(self._pool)*4)\n if extra:\n chunksize +=1\n if len(iterable)==0:\n chunksize=0\n \n task_batches=Pool._get_tasks(func,iterable,chunksize)\n result=MapResult(self._cache,chunksize,len(iterable),callback,\n error_callback=error_callback)\n self._taskqueue.put((((result._job,i,mapper,(x,),{})\n for i,x in enumerate(task_batches)),None))\n return result\n \n @staticmethod\n def _handle_workers(pool):\n thread=threading.current_thread()\n \n \n \n while thread._state ==RUN or(pool._cache and thread._state !=TERMINATE):\n pool._maintain_pool()\n time.sleep(0.1)\n \n pool._taskqueue.put(None)\n debug('worker handler exiting')\n \n @staticmethod\n def _handle_tasks(taskqueue,put,outqueue,pool):\n thread=threading.current_thread()\n \n for taskseq,set_length in iter(taskqueue.get,None):\n i=-1\n for i,task in enumerate(taskseq):\n if thread._state:\n debug('task handler found thread._state != RUN')\n break\n try:\n put(task)\n except IOError:\n debug('could not put task on queue')\n break\n else:\n if set_length:\n debug('doing set_length()')\n set_length(i+1)\n continue\n break\n else:\n debug('task handler got sentinel')\n \n \n try:\n \n debug('task handler sending sentinel to result handler')\n outqueue.put(None)\n \n \n debug('task handler sending sentinel to workers')\n for p in pool:\n put(None)\n except IOError:\n debug('task handler got IOError when sending sentinels')\n \n debug('task handler exiting')\n \n @staticmethod\n def _handle_results(outqueue,get,cache):\n thread=threading.current_thread()\n \n while 1:\n try:\n task=get()\n except(IOError,EOFError):\n debug('result handler got EOFError/IOError -- exiting')\n return\n \n if thread._state:\n assert thread._state ==TERMINATE\n debug('result handler found thread._state=TERMINATE')\n break\n \n if task is None:\n debug('result handler got sentinel')\n break\n \n job,i,obj=task\n try:\n cache[job]._set(i,obj)\n except KeyError:\n pass\n \n while cache and thread._state !=TERMINATE:\n try:\n task=get()\n except(IOError,EOFError):\n debug('result handler got EOFError/IOError -- exiting')\n return\n \n if task is None:\n debug('result handler ignoring extra sentinel')\n continue\n job,i,obj=task\n try:\n cache[job]._set(i,obj)\n except KeyError:\n pass\n \n if hasattr(outqueue,'_reader'):\n debug('ensuring that outqueue is not full')\n \n \n \n try:\n for i in range(10):\n if not outqueue._reader.poll():\n break\n get()\n except(IOError,EOFError):\n pass\n \n debug('result handler exiting: len(cache)=%s, thread._state=%s',\n len(cache),thread._state)\n \n @staticmethod\n def _get_tasks(func,it,size):\n it=iter(it)\n while 1:\n x=tuple(itertools.islice(it,size))\n if not x:\n return\n yield(func,x)\n \n def __reduce__(self):\n raise NotImplementedError(\n 'pool objects cannot be passed between processes or pickled'\n )\n \n def close(self):\n debug('closing pool')\n if self._state ==RUN:\n self._state=CLOSE\n self._worker_handler._state=CLOSE\n \n def terminate(self):\n debug('terminating pool')\n self._state=TERMINATE\n self._worker_handler._state=TERMINATE\n self._terminate()\n \n def join(self):\n debug('joining pool')\n assert self._state in(CLOSE,TERMINATE)\n self._worker_handler.join()\n self._task_handler.join()\n self._result_handler.join()\n for p in self._pool:\n p.join()\n \n @staticmethod\n def _help_stuff_finish(inqueue,task_handler,size):\n \n debug('removing tasks from inqueue until task handler finished')\n inqueue._rlock.acquire()\n while task_handler.is_alive()and inqueue._reader.poll():\n inqueue._reader.recv()\n time.sleep(0)\n \n @classmethod\n def _terminate_pool(cls,taskqueue,inqueue,outqueue,pool,\n worker_handler,task_handler,result_handler,cache):\n \n debug('finalizing pool')\n \n worker_handler._state=TERMINATE\n task_handler._state=TERMINATE\n \n debug('helping task handler/workers to finish')\n cls._help_stuff_finish(inqueue,task_handler,len(pool))\n \n assert result_handler.is_alive()or len(cache)==0\n \n result_handler._state=TERMINATE\n outqueue.put(None)\n \n \n \n debug('joining worker handler')\n if threading.current_thread()is not worker_handler:\n worker_handler.join()\n \n \n if pool and hasattr(pool[0],'terminate'):\n debug('terminating workers')\n for p in pool:\n if p.exitcode is None:\n p.terminate()\n \n debug('joining task handler')\n if threading.current_thread()is not task_handler:\n task_handler.join()\n \n debug('joining result handler')\n if threading.current_thread()is not result_handler:\n result_handler.join()\n \n if pool and hasattr(pool[0],'terminate'):\n debug('joining pool workers')\n for p in pool:\n if p.is_alive():\n \n debug('cleaning up worker %d'%p.pid)\n p.join()\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_val,exc_tb):\n self.terminate()\n \n \n \n \n \nclass ApplyResult(object):\n\n def __init__(self,cache,callback,error_callback):\n self._event=threading.Event()\n self._job=next(job_counter)\n self._cache=cache\n self._callback=callback\n self._error_callback=error_callback\n cache[self._job]=self\n \n def ready(self):\n return self._event.is_set()\n \n def successful(self):\n assert self.ready()\n return self._success\n \n def wait(self,timeout=None):\n self._event.wait(timeout)\n \n def get(self,timeout=None):\n self.wait(timeout)\n if not self.ready():\n raise TimeoutError\n if self._success:\n return self._value\n else:\n raise self._value\n \n def _set(self,i,obj):\n self._success,self._value=obj\n if self._callback and self._success:\n self._callback(self._value)\n if self._error_callback and not self._success:\n self._error_callback(self._value)\n self._event.set()\n del self._cache[self._job]\n \nAsyncResult=ApplyResult\n\n\n\n\n\nclass MapResult(ApplyResult):\n\n def __init__(self,cache,chunksize,length,callback,error_callback):\n ApplyResult.__init__(self,cache,callback,\n error_callback=error_callback)\n self._success=True\n self._value=[None]*length\n self._chunksize=chunksize\n if chunksize <=0:\n self._number_left=0\n self._event.set()\n del cache[self._job]\n else:\n self._number_left=length //chunksize+bool(length %chunksize)\n \n def _set(self,i,success_result):\n success,result=success_result\n if success:\n self._value[i *self._chunksize:(i+1)*self._chunksize]=result\n self._number_left -=1\n if self._number_left ==0:\n if self._callback:\n self._callback(self._value)\n del self._cache[self._job]\n self._event.set()\n else:\n self._success=False\n self._value=result\n if self._error_callback:\n self._error_callback(self._value)\n del self._cache[self._job]\n self._event.set()\n \n \n \n \n \nclass IMapIterator(object):\n\n def __init__(self,cache):\n self._cond=threading.Condition(threading.Lock())\n self._job=next(job_counter)\n self._cache=cache\n self._items=collections.deque()\n self._index=0\n self._length=None\n self._unsorted={}\n cache[self._job]=self\n \n def __iter__(self):\n return self\n \n def next(self,timeout=None):\n self._cond.acquire()\n try:\n try:\n item=self._items.popleft()\n except IndexError:\n if self._index ==self._length:\n raise StopIteration\n self._cond.wait(timeout)\n try:\n item=self._items.popleft()\n except IndexError:\n if self._index ==self._length:\n raise StopIteration\n raise TimeoutError\n finally:\n self._cond.release()\n \n success,value=item\n if success:\n return value\n raise value\n \n __next__=next\n \n def _set(self,i,obj):\n self._cond.acquire()\n try:\n if self._index ==i:\n self._items.append(obj)\n self._index +=1\n while self._index in self._unsorted:\n obj=self._unsorted.pop(self._index)\n self._items.append(obj)\n self._index +=1\n self._cond.notify()\n else:\n self._unsorted[i]=obj\n \n if self._index ==self._length:\n del self._cache[self._job]\n finally:\n self._cond.release()\n \n def _set_length(self,length):\n self._cond.acquire()\n try:\n self._length=length\n if self._index ==self._length:\n self._cond.notify()\n del self._cache[self._job]\n finally:\n self._cond.release()\n \n \n \n \n \nclass IMapUnorderedIterator(IMapIterator):\n\n def _set(self,i,obj):\n self._cond.acquire()\n try:\n self._items.append(obj)\n self._index +=1\n self._cond.notify()\n if self._index ==self._length:\n del self._cache[self._job]\n finally:\n self._cond.release()\n \n \n \n \n \nclass ThreadPool(Pool):\n\n from.dummy import Process\n \n def __init__(self,processes=None,initializer=None,initargs=()):\n Pool.__init__(self,processes,initializer,initargs)\n \n def _setup_queues(self):\n self._inqueue=queue.Queue()\n self._outqueue=queue.Queue()\n self._quick_put=self._inqueue.put\n self._quick_get=self._outqueue.get\n \n @staticmethod\n def _help_stuff_finish(inqueue,task_handler,size):\n \n inqueue.not_empty.acquire()\n try:\n inqueue.queue.clear()\n inqueue.queue.extend([None]*size)\n inqueue.not_empty.notify_all()\n finally:\n inqueue.not_empty.release()\n", ["collections", "itertools", "multiprocessing", "multiprocessing.Process", "multiprocessing.dummy", "multiprocessing.queues", "multiprocessing.util", "queue", "threading", "time"]], "multiprocessing.process": [".py", "\n\n\n\n\n\n\n\n\n__all__=['Process','current_process','active_children']\n\n\n\n\n\nimport os\nimport sys\nimport signal\nimport itertools\nfrom _weakrefset import WeakSet\n\n\nfrom _multiprocessing import Process\n\n\n\n\ntry:\n ORIGINAL_DIR=os.path.abspath(os.getcwd())\nexcept OSError:\n ORIGINAL_DIR=None\n \n \n \n \n \ndef current_process():\n ''\n\n \n return _current_process\n \ndef active_children():\n ''\n\n \n _cleanup()\n return list(_current_process._children)\n \n \n \n \n \ndef _cleanup():\n\n for p in list(_current_process._children):\n if p._popen.poll()is not None:\n _current_process._children.discard(p)\n \n \n \n \n \n \n \n \n \n \n \n \nclass AuthenticationString(bytes):\n def __reduce__(self):\n from.forking import Popen\n if not Popen.thread_is_spawning():\n raise TypeError(\n 'Pickling an AuthenticationString object is '\n 'disallowed for security reasons'\n )\n return AuthenticationString,(bytes(self),)\n \n \n \n \n \nclass _MainProcess(Process):\n\n def __init__(self):\n self._identity=()\n self._daemonic=False\n self._name='MainProcess'\n self._parent_pid=None\n self._popen=None\n self._counter=itertools.count(1)\n self._children=set()\n self._authkey=AuthenticationString(os.urandom(32))\n self._tempdir=None\n \n_current_process=_MainProcess()\ndel _MainProcess\n\n\n\n\n\n_exitcode_to_name={}\n\nfor name,signum in list(signal.__dict__.items()):\n if name[:3]=='SIG'and '_'not in name:\n _exitcode_to_name[-signum]=name\n \n \n_dangling=WeakSet()\n", ["_multiprocessing", "_weakrefset", "itertools", "multiprocessing.forking", "os", "signal", "sys"]], "multiprocessing.util": [".py", "\n\n\n\n\n\n\n\n\nimport sys\nimport functools\nimport os\nimport itertools\nimport weakref\nimport atexit\nimport threading\n\nfrom subprocess import _args_from_interpreter_flags\n\nfrom multiprocessing.process import current_process,active_children\n\n__all__=[\n'sub_debug','debug','info','sub_warning','get_logger',\n'log_to_stderr','get_temp_dir','register_after_fork',\n'is_exiting','Finalize','ForkAwareThreadLock','ForkAwareLocal',\n'SUBDEBUG','SUBWARNING',\n]\n\n\n\n\n\nNOTSET=0\nSUBDEBUG=5\nDEBUG=10\nINFO=20\nSUBWARNING=25\n\nLOGGER_NAME='multiprocessing'\nDEFAULT_LOGGING_FORMAT='[%(levelname)s/%(processName)s] %(message)s'\n\n_logger=None\n_log_to_stderr=False\n\ndef sub_debug(msg,*args):\n if _logger:\n _logger.log(SUBDEBUG,msg,*args)\n \ndef debug(msg,*args):\n if _logger:\n _logger.log(DEBUG,msg,*args)\n \ndef info(msg,*args):\n if _logger:\n _logger.log(INFO,msg,*args)\n \ndef sub_warning(msg,*args):\n if _logger:\n _logger.log(SUBWARNING,msg,*args)\n \ndef get_logger():\n ''\n\n \n global _logger\n import logging\n \n logging._acquireLock()\n try:\n if not _logger:\n \n _logger=logging.getLogger(LOGGER_NAME)\n _logger.propagate=0\n logging.addLevelName(SUBDEBUG,'SUBDEBUG')\n logging.addLevelName(SUBWARNING,'SUBWARNING')\n \n \n if hasattr(atexit,'unregister'):\n atexit.unregister(_exit_function)\n atexit.register(_exit_function)\n else:\n atexit._exithandlers.remove((_exit_function,(),{}))\n atexit._exithandlers.append((_exit_function,(),{}))\n \n finally:\n logging._releaseLock()\n \n return _logger\n \ndef log_to_stderr(level=None):\n ''\n\n \n global _log_to_stderr\n import logging\n \n logger=get_logger()\n formatter=logging.Formatter(DEFAULT_LOGGING_FORMAT)\n handler=logging.StreamHandler()\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n \n if level:\n logger.setLevel(level)\n _log_to_stderr=True\n return _logger\n \n \n \n \n \ndef get_temp_dir():\n\n if current_process()._tempdir is None:\n import shutil,tempfile\n tempdir=tempfile.mkdtemp(prefix='pymp-')\n info('created temp directory %s',tempdir)\n Finalize(None,shutil.rmtree,args=[tempdir],exitpriority=-100)\n current_process()._tempdir=tempdir\n return current_process()._tempdir\n \n \n \n \n \n_afterfork_registry=weakref.WeakValueDictionary()\n_afterfork_counter=itertools.count()\n\ndef _run_after_forkers():\n items=list(_afterfork_registry.items())\n items.sort()\n for(index,ident,func),obj in items:\n try:\n func(obj)\n except Exception as e:\n info('after forker raised exception %s',e)\n \ndef register_after_fork(obj,func):\n _afterfork_registry[(next(_afterfork_counter),id(obj),func)]=obj\n \n \n \n \n \n_finalizer_registry={}\n_finalizer_counter=itertools.count()\n\n\nclass Finalize(object):\n ''\n\n \n def __init__(self,obj,callback,args=(),kwargs=None,exitpriority=None):\n assert exitpriority is None or type(exitpriority)is int\n \n if obj is not None:\n self._weakref=weakref.ref(obj,self)\n else:\n assert exitpriority is not None\n \n self._callback=callback\n self._args=args\n self._kwargs=kwargs or{}\n self._key=(exitpriority,next(_finalizer_counter))\n self._pid=os.getpid()\n \n _finalizer_registry[self._key]=self\n \n def __call__(self,wr=None,\n \n \n _finalizer_registry=_finalizer_registry,\n sub_debug=sub_debug,getpid=os.getpid):\n ''\n\n \n try:\n del _finalizer_registry[self._key]\n except KeyError:\n sub_debug('finalizer no longer registered')\n else:\n if self._pid !=getpid():\n sub_debug('finalizer ignored because different process')\n res=None\n else:\n sub_debug('finalizer calling %s with args %s and kwargs %s',\n self._callback,self._args,self._kwargs)\n res=self._callback(*self._args,**self._kwargs)\n self._weakref=self._callback=self._args=\\\n self._kwargs=self._key=None\n return res\n \n def cancel(self):\n ''\n\n \n try:\n del _finalizer_registry[self._key]\n except KeyError:\n pass\n else:\n self._weakref=self._callback=self._args=\\\n self._kwargs=self._key=None\n \n def still_active(self):\n ''\n\n \n return self._key in _finalizer_registry\n \n def __repr__(self):\n try:\n obj=self._weakref()\n except(AttributeError,TypeError):\n obj=None\n \n if obj is None:\n return ''\n \n x=''\n \n \ndef _run_finalizers(minpriority=None):\n ''\n\n\n\n\n \n if _finalizer_registry is None:\n \n \n \n return\n \n if minpriority is None:\n f=lambda p:p[0][0]is not None\n else:\n f=lambda p:p[0][0]is not None and p[0][0]>=minpriority\n \n items=[x for x in list(_finalizer_registry.items())if f(x)]\n items.sort(reverse=True)\n \n for key,finalizer in items:\n sub_debug('calling %s',finalizer)\n try:\n finalizer()\n except Exception:\n import traceback\n traceback.print_exc()\n \n if minpriority is None:\n _finalizer_registry.clear()\n \n \n \n \n \ndef is_exiting():\n ''\n\n \n return _exiting or _exiting is None\n \n_exiting=False\n\ndef _exit_function(info=info,debug=debug,_run_finalizers=_run_finalizers,\nactive_children=active_children,\ncurrent_process=current_process):\n\n\n\n\n global _exiting\n \n if not _exiting:\n _exiting=True\n \n info('process shutting down')\n debug('running all \"atexit\" finalizers with priority >= 0')\n _run_finalizers(0)\n \n if current_process()is not None:\n \n \n \n \n \n \n \n \n \n \n \n \n \n for p in active_children():\n if p._daemonic:\n info('calling terminate() for daemon %s',p.name)\n p._popen.terminate()\n \n for p in active_children():\n info('calling join() for process %s',p.name)\n p.join()\n \n debug('running the remaining \"atexit\" finalizers')\n _run_finalizers()\n \natexit.register(_exit_function)\n\n\n\n\n\nclass ForkAwareThreadLock(object):\n def __init__(self):\n self._reset()\n register_after_fork(self,ForkAwareThreadLock._reset)\n \n def _reset(self):\n self._lock=threading.Lock()\n self.acquire=self._lock.acquire\n self.release=self._lock.release\n \nclass ForkAwareLocal(threading.local):\n def __init__(self):\n register_after_fork(self,lambda obj:obj.__dict__.clear())\n def __reduce__(self):\n return type(self),()\n", ["atexit", "functools", "itertools", "logging", "multiprocessing.process", "os", "shutil", "subprocess", "sys", "tempfile", "threading", "traceback", "weakref"]], "multiprocessing": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__='0.70a1'\n\n__all__=[\n'Process','current_process','active_children','freeze_support',\n'Manager','Pipe','cpu_count','log_to_stderr','get_logger',\n'allow_connection_pickling','BufferTooShort','TimeoutError',\n'Lock','RLock','Semaphore','BoundedSemaphore','Condition',\n'Event','Barrier','Queue','SimpleQueue','JoinableQueue','Pool',\n'Value','Array','RawValue','RawArray','SUBDEBUG','SUBWARNING',\n]\n\n__author__='R. Oudkerk (r.m.oudkerk@gmail.com)'\n\n\n\n\n\nimport os\nimport sys\n\nfrom multiprocessing.process import Process,current_process,active_children\nfrom multiprocessing.util import SUBDEBUG,SUBWARNING\n\n\n\n\n\nclass ProcessError(Exception):\n pass\n \nclass BufferTooShort(ProcessError):\n pass\n \nclass TimeoutError(ProcessError):\n pass\n \nclass AuthenticationError(ProcessError):\n pass\n \nimport _multiprocessing\n\n\n\n\n\ndef Manager():\n ''\n\n\n\n\n \n from multiprocessing.managers import SyncManager\n m=SyncManager()\n m.start()\n return m\n \n \n \n \n \n \n \n \n \ndef cpu_count():\n ''\n\n \n if sys.platform =='win32':\n try:\n num=int(os.environ['NUMBER_OF_PROCESSORS'])\n except(ValueError,KeyError):\n num=0\n elif 'bsd'in sys.platform or sys.platform =='darwin':\n comm='/sbin/sysctl -n hw.ncpu'\n if sys.platform =='darwin':\n comm='/usr'+comm\n try:\n with os.popen(comm)as p:\n num=int(p.read())\n except ValueError:\n num=0\n else:\n try:\n num=os.sysconf('SC_NPROCESSORS_ONLN')\n except(ValueError,OSError,AttributeError):\n num=0\n \n if num >=1:\n return num\n else:\n raise NotImplementedError('cannot determine number of cpus')\n \ndef freeze_support():\n ''\n\n\n \n if sys.platform =='win32'and getattr(sys,'frozen',False):\n from multiprocessing.forking import freeze_support\n freeze_support()\n \ndef get_logger():\n ''\n\n \n from multiprocessing.util import get_logger\n return get_logger()\n \ndef log_to_stderr(level=None):\n ''\n\n \n from multiprocessing.util import log_to_stderr\n return log_to_stderr(level)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef Lock():\n ''\n\n \n from multiprocessing.synchronize import Lock\n return Lock()\n \ndef RLock():\n ''\n\n \n from multiprocessing.synchronize import RLock\n return RLock()\n \ndef Condition(lock=None):\n ''\n\n \n from multiprocessing.synchronize import Condition\n return Condition(lock)\n \ndef Semaphore(value=1):\n ''\n\n \n from multiprocessing.synchronize import Semaphore\n return Semaphore(value)\n \ndef BoundedSemaphore(value=1):\n ''\n\n \n from multiprocessing.synchronize import BoundedSemaphore\n return BoundedSemaphore(value)\n \ndef Event():\n ''\n\n \n from multiprocessing.synchronize import Event\n return Event()\n \ndef Barrier(parties,action=None,timeout=None):\n ''\n\n \n from multiprocessing.synchronize import Barrier\n return Barrier(parties,action,timeout)\n \ndef Queue(maxsize=0):\n ''\n\n \n from multiprocessing.queues import Queue\n return Queue(maxsize)\n \ndef JoinableQueue(maxsize=0):\n ''\n\n \n from multiprocessing.queues import JoinableQueue\n return JoinableQueue(maxsize)\n \ndef SimpleQueue():\n ''\n\n \n from multiprocessing.queues import SimpleQueue\n return SimpleQueue()\n \ndef Pool(processes=None,initializer=None,initargs=(),maxtasksperchild=None):\n ''\n\n \n from multiprocessing.pool import Pool\n return Pool(processes,initializer,initargs,maxtasksperchild)\n \ndef RawValue(typecode_or_type,*args):\n ''\n\n \n from multiprocessing.sharedctypes import RawValue\n return RawValue(typecode_or_type,*args)\n \ndef RawArray(typecode_or_type,size_or_initializer):\n ''\n\n \n from multiprocessing.sharedctypes import RawArray\n return RawArray(typecode_or_type,size_or_initializer)\n \ndef Value(typecode_or_type,*args,lock=True):\n ''\n\n \n from multiprocessing.sharedctypes import Value\n return Value(typecode_or_type,*args,lock=lock)\n \ndef Array(typecode_or_type,size_or_initializer,*,lock=True):\n ''\n\n \n from multiprocessing.sharedctypes import Array\n return Array(typecode_or_type,size_or_initializer,lock=lock)\n \n \n \n \n \nif sys.platform =='win32':\n\n def set_executable(executable):\n ''\n\n\n\n \n from multiprocessing.forking import set_executable\n set_executable(executable)\n \n __all__ +=['set_executable']\n", ["_multiprocessing", "multiprocessing.forking", "multiprocessing.managers", "multiprocessing.pool", "multiprocessing.process", "multiprocessing.queues", "multiprocessing.sharedctypes", "multiprocessing.synchronize", "multiprocessing.util", "os", "sys"], 1], "multiprocessing.dummy.connection": [".py", "\n\n\n\n\n\n\n\n\n__all__=['Client','Listener','Pipe']\n\nfrom queue import Queue\n\n\nfamilies=[None]\n\n\nclass Listener(object):\n\n def __init__(self,address=None,family=None,backlog=1):\n self._backlog_queue=Queue(backlog)\n \n def accept(self):\n return Connection(*self._backlog_queue.get())\n \n def close(self):\n self._backlog_queue=None\n \n @property\n def address(self):\n return self._backlog_queue\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,exc_tb):\n self.close()\n \n \ndef Client(address):\n _in,_out=Queue(),Queue()\n address.put((_out,_in))\n return Connection(_in,_out)\n \n \ndef Pipe(duplex=True):\n a,b=Queue(),Queue()\n return Connection(a,b),Connection(b,a)\n \n \nclass Connection(object):\n\n def __init__(self,_in,_out):\n self._out=_out\n self._in=_in\n self.send=self.send_bytes=_out.put\n self.recv=self.recv_bytes=_in.get\n \n def poll(self,timeout=0.0):\n if self._in.qsize()>0:\n return True\n if timeout <=0.0:\n return False\n with self._in.not_empty:\n self._in.not_empty.wait(timeout)\n return self._in.qsize()>0\n \n def close(self):\n pass\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,exc_tb):\n self.close()\n", ["queue"]], "multiprocessing.dummy": [".py", "\n\n\n\n\n\n\n\n\n__all__=[\n'Process','current_process','active_children','freeze_support',\n'Lock','RLock','Semaphore','BoundedSemaphore','Condition',\n'Event','Barrier','Queue','Manager','Pipe','Pool','JoinableQueue'\n]\n\n\n\n\n\nimport threading\nimport sys\nimport weakref\nimport array\n\nfrom.connection import Pipe\nfrom threading import Lock,RLock,Semaphore,BoundedSemaphore\nfrom threading import Event,Condition,Barrier\nfrom queue import Queue\n\n\n\n\n\nclass DummyProcess(threading.Thread):\n\n def __init__(self,group=None,target=None,name=None,args=(),kwargs={}):\n threading.Thread.__init__(self,group,target,name,args,kwargs)\n self._pid=None\n self._children=weakref.WeakKeyDictionary()\n self._start_called=False\n self._parent=current_process()\n \n def start(self):\n if self._parent is not current_process():\n raise RuntimeError(\n \"Parent is {0!r} but current_process is {1!r}\".format(\n self._parent,current_process()))\n self._start_called=True\n if hasattr(self._parent,'_children'):\n self._parent._children[self]=None\n threading.Thread.start(self)\n \n @property\n def exitcode(self):\n if self._start_called and not self.is_alive():\n return 0\n else:\n return None\n \n \n \n \n \nProcess=DummyProcess\ncurrent_process=threading.current_thread\ncurrent_process()._children=weakref.WeakKeyDictionary()\n\ndef active_children():\n children=current_process()._children\n for p in list(children):\n if not p.is_alive():\n children.pop(p,None)\n return list(children)\n \ndef freeze_support():\n pass\n \n \n \n \n \nclass Namespace(object):\n def __init__(self,/,**kwds):\n self.__dict__.update(kwds)\n def __repr__(self):\n items=list(self.__dict__.items())\n temp=[]\n for name,value in items:\n if not name.startswith('_'):\n temp.append('%s=%r'%(name,value))\n temp.sort()\n return '%s(%s)'%(self.__class__.__name__,', '.join(temp))\n \ndict=dict\nlist=list\n\ndef Array(typecode,sequence,lock=True):\n return array.array(typecode,sequence)\n \nclass Value(object):\n def __init__(self,typecode,value,lock=True):\n self._typecode=typecode\n self._value=value\n \n @property\n def value(self):\n return self._value\n \n @value.setter\n def value(self,value):\n self._value=value\n \n def __repr__(self):\n return '<%s(%r, %r)>'%(type(self).__name__,self._typecode,self._value)\n \ndef Manager():\n return sys.modules[__name__]\n \ndef shutdown():\n pass\n \ndef Pool(processes=None,initializer=None,initargs=()):\n from..pool import ThreadPool\n return ThreadPool(processes,initializer,initargs)\n \nJoinableQueue=Queue\n", ["array", "multiprocessing.dummy.connection", "multiprocessing.pool", "queue", "sys", "threading", "weakref"], 1], "pyexpat_utils.errors": [".py", "\nXML_ERROR_ABORTED=\"\"\"parsing aborted\"\"\"\n\nXML_ERROR_AMPLIFICATION_LIMIT_BREACH=\"\"\"limit on input amplification factor (from DTD and entities) breached\"\"\"\n\nXML_ERROR_ASYNC_ENTITY=\"\"\"asynchronous entity\"\"\"\n\nXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF=\"\"\"reference to external entity in attribute\"\"\"\n\nXML_ERROR_BAD_CHAR_REF=\"\"\"reference to invalid character number\"\"\"\n\nXML_ERROR_BINARY_ENTITY_REF=\"\"\"reference to binary entity\"\"\"\n\nXML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING=\"\"\"cannot change setting once parsing has begun\"\"\"\n\nXML_ERROR_DUPLICATE_ATTRIBUTE=\"\"\"duplicate attribute\"\"\"\n\nXML_ERROR_ENTITY_DECLARED_IN_PE=\"\"\"entity declared in parameter entity\"\"\"\n\nXML_ERROR_EXTERNAL_ENTITY_HANDLING=\"\"\"error in processing external entity reference\"\"\"\n\nXML_ERROR_FEATURE_REQUIRES_XML_DTD=\"\"\"requested feature requires XML_DTD support in Expat\"\"\"\n\nXML_ERROR_FINISHED=\"\"\"parsing finished\"\"\"\n\nXML_ERROR_INCOMPLETE_PE=\"\"\"incomplete markup in parameter entity\"\"\"\n\nXML_ERROR_INCORRECT_ENCODING=\"\"\"encoding specified in XML declaration is incorrect\"\"\"\n\nXML_ERROR_INVALID_ARGUMENT=\"\"\"invalid argument\"\"\"\n\nXML_ERROR_INVALID_TOKEN=\"\"\"not well-formed (invalid token)\"\"\"\n\nXML_ERROR_JUNK_AFTER_DOC_ELEMENT=\"\"\"junk after document element\"\"\"\n\nXML_ERROR_MISPLACED_XML_PI=\"\"\"XML or text declaration not at start of entity\"\"\"\n\nXML_ERROR_NOT_STANDALONE=\"\"\"document is not standalone\"\"\"\n\nXML_ERROR_NOT_SUSPENDED=\"\"\"parser not suspended\"\"\"\n\nXML_ERROR_NO_BUFFER=\"\"\"a successful prior call to function XML_GetBuffer is required\"\"\"\n\nXML_ERROR_NO_ELEMENTS=\"\"\"no element found\"\"\"\n\nXML_ERROR_NO_MEMORY=\"\"\"out of memory\"\"\"\n\nXML_ERROR_PARAM_ENTITY_REF=\"\"\"illegal parameter entity reference\"\"\"\n\nXML_ERROR_PARTIAL_CHAR=\"\"\"partial character\"\"\"\n\nXML_ERROR_PUBLICID=\"\"\"illegal character(s) in public id\"\"\"\n\nXML_ERROR_RECURSIVE_ENTITY_REF=\"\"\"recursive entity reference\"\"\"\n\nXML_ERROR_RESERVED_NAMESPACE_URI=\"\"\"prefix must not be bound to one of the reserved namespace names\"\"\"\n\nXML_ERROR_RESERVED_PREFIX_XML=\"\"\"reserved prefix (xml) must not be undeclared or bound to another namespace name\"\"\"\n\nXML_ERROR_RESERVED_PREFIX_XMLNS=\"\"\"reserved prefix (xmlns) must not be declared or undeclared\"\"\"\n\nXML_ERROR_SUSPENDED=\"\"\"parser suspended\"\"\"\n\nXML_ERROR_SUSPEND_PE=\"\"\"cannot suspend in external parameter entity\"\"\"\n\nXML_ERROR_SYNTAX=\"\"\"syntax error\"\"\"\n\nXML_ERROR_TAG_MISMATCH=\"\"\"mismatched tag\"\"\"\n\nXML_ERROR_TEXT_DECL=\"\"\"text declaration not well-formed\"\"\"\n\nXML_ERROR_UNBOUND_PREFIX=\"\"\"unbound prefix\"\"\"\n\nXML_ERROR_UNCLOSED_CDATA_SECTION=\"\"\"unclosed CDATA section\"\"\"\n\nXML_ERROR_UNCLOSED_TOKEN=\"\"\"unclosed token\"\"\"\n\nXML_ERROR_UNDECLARING_PREFIX=\"\"\"must not undeclare prefix\"\"\"\n\nXML_ERROR_UNDEFINED_ENTITY=\"\"\"undefined entity\"\"\"\n\nXML_ERROR_UNEXPECTED_STATE=\"\"\"unexpected parser state - please send a bug report\"\"\"\n\nXML_ERROR_UNKNOWN_ENCODING=\"\"\"unknown encoding\"\"\"\n\nXML_ERROR_XML_DECL=\"\"\"XML declaration not well-formed\"\"\"\n\n__name__=\"\"\"pyexpat.errors\"\"\"\n\ncodes={'out of memory':1,'syntax error':2,'no element found':3,'not well-formed (invalid token)':4,'unclosed token':5,'partial character':6,'mismatched tag':7,'duplicate attribute':8,'junk after document element':9,'illegal parameter entity reference':10,'undefined entity':11,'recursive entity reference':12,'asynchronous entity':13,'reference to invalid character number':14,'reference to binary entity':15,'reference to external entity in attribute':16,'XML or text declaration not at start of entity':17,'unknown encoding':18,'encoding specified in XML declaration is incorrect':19,'unclosed CDATA section':20,'error in processing external entity reference':21,'document is not standalone':22,'unexpected parser state - please send a bug report':23,'entity declared in parameter entity':24,'requested feature requires XML_DTD support in Expat':25,'cannot change setting once parsing has begun':26,'unbound prefix':27,'must not undeclare prefix':28,'incomplete markup in parameter entity':29,'XML declaration not well-formed':30,'text declaration not well-formed':31,'illegal character(s) in public id':32,'parser suspended':33,'parser not suspended':34,'parsing aborted':35,'parsing finished':36,'cannot suspend in external parameter entity':37,'reserved prefix (xml) must not be undeclared or bound to another namespace name':38,'reserved prefix (xmlns) must not be declared or undeclared':39,'prefix must not be bound to one of the reserved namespace names':40,'invalid argument':41,'a successful prior call to function XML_GetBuffer is required':42,'limit on input amplification factor (from DTD and entities) breached':43}\n\nmessages={1:'out of memory',2:'syntax error',3:'no element found',4:'not well-formed (invalid token)',5:'unclosed token',6:'partial character',7:'mismatched tag',8:'duplicate attribute',9:'junk after document element',10:'illegal parameter entity reference',11:'undefined entity',12:'recursive entity reference',13:'asynchronous entity',14:'reference to invalid character number',15:'reference to binary entity',16:'reference to external entity in attribute',17:'XML or text declaration not at start of entity',18:'unknown encoding',19:'encoding specified in XML declaration is incorrect',20:'unclosed CDATA section',21:'error in processing external entity reference',22:'document is not standalone',23:'unexpected parser state - please send a bug report',24:'entity declared in parameter entity',25:'requested feature requires XML_DTD support in Expat',26:'cannot change setting once parsing has begun',27:'unbound prefix',28:'must not undeclare prefix',29:'incomplete markup in parameter entity',30:'XML declaration not well-formed',31:'text declaration not well-formed',32:'illegal character(s) in public id',33:'parser suspended',34:'parser not suspended',35:'parsing aborted',36:'parsing finished',37:'cannot suspend in external parameter entity',38:'reserved prefix (xml) must not be undeclared or bound to another namespace name',39:'reserved prefix (xmlns) must not be declared or undeclared',40:'prefix must not be bound to one of the reserved namespace names',41:'invalid argument',42:'a successful prior call to function XML_GetBuffer is required',43:'limit on input amplification factor (from DTD and entities) breached'}\n", []], "pyexpat_utils": [".py", "", [], 1], "unittest.async_case": [".py", "import asyncio\nimport contextvars\nimport inspect\nimport warnings\n\nfrom.case import TestCase\n\n\nclass IsolatedAsyncioTestCase(TestCase):\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n loop_factory=None\n \n def __init__(self,methodName='runTest'):\n super().__init__(methodName)\n self._asyncioRunner=None\n self._asyncioTestContext=contextvars.copy_context()\n \n async def asyncSetUp(self):\n pass\n \n async def asyncTearDown(self):\n pass\n \n def addAsyncCleanup(self,func,/,*args,**kwargs):\n \n \n \n \n \n \n \n \n \n \n \n \n self.addCleanup(*(func,*args),**kwargs)\n \n async def enterAsyncContext(self,cm):\n ''\n\n\n\n \n \n \n cls=type(cm)\n try:\n enter=cls.__aenter__\n exit=cls.__aexit__\n except AttributeError:\n raise TypeError(f\"'{cls.__module__}.{cls.__qualname__}' object does \"\n f\"not support the asynchronous context manager protocol\"\n )from None\n result=await enter(cm)\n self.addAsyncCleanup(exit,cm,None,None,None)\n return result\n \n def _callSetUp(self):\n \n \n \n self._asyncioRunner.get_loop()\n self._asyncioTestContext.run(self.setUp)\n self._callAsync(self.asyncSetUp)\n \n def _callTestMethod(self,method):\n if self._callMaybeAsync(method)is not None:\n warnings.warn(f'It is deprecated to return a value that is not None from a '\n f'test case ({method})',DeprecationWarning,stacklevel=4)\n \n def _callTearDown(self):\n self._callAsync(self.asyncTearDown)\n self._asyncioTestContext.run(self.tearDown)\n \n def _callCleanup(self,function,*args,**kwargs):\n self._callMaybeAsync(function,*args,**kwargs)\n \n def _callAsync(self,func,/,*args,**kwargs):\n assert self._asyncioRunner is not None,'asyncio runner is not initialized'\n assert inspect.iscoroutinefunction(func),f'{func !r} is not an async function'\n return self._asyncioRunner.run(\n func(*args,**kwargs),\n context=self._asyncioTestContext\n )\n \n def _callMaybeAsync(self,func,/,*args,**kwargs):\n assert self._asyncioRunner is not None,'asyncio runner is not initialized'\n if inspect.iscoroutinefunction(func):\n return self._asyncioRunner.run(\n func(*args,**kwargs),\n context=self._asyncioTestContext,\n )\n else:\n return self._asyncioTestContext.run(func,*args,**kwargs)\n \n def _setupAsyncioRunner(self):\n assert self._asyncioRunner is None,'asyncio runner is already initialized'\n runner=asyncio.Runner(debug=True,loop_factory=self.loop_factory)\n self._asyncioRunner=runner\n \n def _tearDownAsyncioRunner(self):\n runner=self._asyncioRunner\n runner.close()\n \n def run(self,result=None):\n self._setupAsyncioRunner()\n try:\n return super().run(result)\n finally:\n self._tearDownAsyncioRunner()\n \n def debug(self):\n self._setupAsyncioRunner()\n super().debug()\n self._tearDownAsyncioRunner()\n \n def __del__(self):\n if self._asyncioRunner is not None:\n self._tearDownAsyncioRunner()\n", ["asyncio", "contextvars", "inspect", "unittest.case", "warnings"]], "unittest.case": [".py", "''\n\nimport sys\nimport functools\nimport difflib\nimport pprint\nimport re\nimport warnings\nimport collections\nimport contextlib\nimport traceback\nimport time\nimport types\n\nfrom. import result\nfrom.util import(strclass,safe_repr,_count_diff_all_purpose,\n_count_diff_hashable,_common_shorten_repr)\n\n__unittest=True\n\n_subtest_msg_sentinel=object()\n\nDIFF_OMITTED=('\\nDiff is %s characters long. '\n'Set self.maxDiff to None to see it.')\n\nclass SkipTest(Exception):\n ''\n\n\n\n\n \n \nclass _ShouldStop(Exception):\n ''\n\n \n \nclass _UnexpectedSuccess(Exception):\n ''\n\n \n \n \nclass _Outcome(object):\n def __init__(self,result=None):\n self.expecting_failure=False\n self.result=result\n self.result_supports_subtests=hasattr(result,\"addSubTest\")\n self.success=True\n self.expectedFailure=None\n \n @contextlib.contextmanager\n def testPartExecutor(self,test_case,subTest=False):\n old_success=self.success\n self.success=True\n try:\n yield\n except KeyboardInterrupt:\n raise\n except SkipTest as e:\n self.success=False\n _addSkip(self.result,test_case,str(e))\n except _ShouldStop:\n pass\n except:\n exc_info=sys.exc_info()\n if self.expecting_failure:\n self.expectedFailure=exc_info\n else:\n self.success=False\n if subTest:\n self.result.addSubTest(test_case.test_case,test_case,exc_info)\n else:\n _addError(self.result,test_case,exc_info)\n \n \n exc_info=None\n else:\n if subTest and self.success:\n self.result.addSubTest(test_case.test_case,test_case,None)\n finally:\n self.success=self.success and old_success\n \n \ndef _addSkip(result,test_case,reason):\n addSkip=getattr(result,'addSkip',None)\n if addSkip is not None:\n addSkip(test_case,reason)\n else:\n warnings.warn(\"TestResult has no addSkip method, skips not reported\",\n RuntimeWarning,2)\n result.addSuccess(test_case)\n \ndef _addError(result,test,exc_info):\n if result is not None and exc_info is not None:\n if issubclass(exc_info[0],test.failureException):\n result.addFailure(test,exc_info)\n else:\n result.addError(test,exc_info)\n \ndef _id(obj):\n return obj\n \n \ndef _enter_context(cm,addcleanup):\n\n\n cls=type(cm)\n try:\n enter=cls.__enter__\n exit=cls.__exit__\n except AttributeError:\n raise TypeError(f\"'{cls.__module__}.{cls.__qualname__}' object does \"\n f\"not support the context manager protocol\")from None\n result=enter(cm)\n addcleanup(exit,cm,None,None,None)\n return result\n \n \n_module_cleanups=[]\ndef addModuleCleanup(function,/,*args,**kwargs):\n ''\n \n _module_cleanups.append((function,args,kwargs))\n \ndef enterModuleContext(cm):\n ''\n return _enter_context(cm,addModuleCleanup)\n \n \ndef doModuleCleanups():\n ''\n \n exceptions=[]\n while _module_cleanups:\n function,args,kwargs=_module_cleanups.pop()\n try:\n function(*args,**kwargs)\n except Exception as exc:\n exceptions.append(exc)\n if exceptions:\n \n \n raise exceptions[0]\n \n \ndef skip(reason):\n ''\n\n \n def decorator(test_item):\n if not isinstance(test_item,type):\n @functools.wraps(test_item)\n def skip_wrapper(*args,**kwargs):\n raise SkipTest(reason)\n test_item=skip_wrapper\n \n test_item.__unittest_skip__=True\n test_item.__unittest_skip_why__=reason\n return test_item\n if isinstance(reason,types.FunctionType):\n test_item=reason\n reason=''\n return decorator(test_item)\n return decorator\n \ndef skipIf(condition,reason):\n ''\n\n \n if condition:\n return skip(reason)\n return _id\n \ndef skipUnless(condition,reason):\n ''\n\n \n if not condition:\n return skip(reason)\n return _id\n \ndef expectedFailure(test_item):\n test_item.__unittest_expecting_failure__=True\n return test_item\n \ndef _is_subtype(expected,basetype):\n if isinstance(expected,tuple):\n return all(_is_subtype(e,basetype)for e in expected)\n return isinstance(expected,type)and issubclass(expected,basetype)\n \nclass _BaseTestCaseContext:\n\n def __init__(self,test_case):\n self.test_case=test_case\n \n def _raiseFailure(self,standardMsg):\n msg=self.test_case._formatMessage(self.msg,standardMsg)\n raise self.test_case.failureException(msg)\n \nclass _AssertRaisesBaseContext(_BaseTestCaseContext):\n\n def __init__(self,expected,test_case,expected_regex=None):\n _BaseTestCaseContext.__init__(self,test_case)\n self.expected=expected\n self.test_case=test_case\n if expected_regex is not None:\n expected_regex=re.compile(expected_regex)\n self.expected_regex=expected_regex\n self.obj_name=None\n self.msg=None\n \n def handle(self,name,args,kwargs):\n ''\n\n\n\n\n \n try:\n if not _is_subtype(self.expected,self._base_type):\n raise TypeError('%s() arg 1 must be %s'%\n (name,self._base_type_str))\n if not args:\n self.msg=kwargs.pop('msg',None)\n if kwargs:\n raise TypeError('%r is an invalid keyword argument for '\n 'this function'%(next(iter(kwargs)),))\n return self\n \n callable_obj,*args=args\n try:\n self.obj_name=callable_obj.__name__\n except AttributeError:\n self.obj_name=str(callable_obj)\n with self:\n callable_obj(*args,**kwargs)\n finally:\n \n self=None\n \n \nclass _AssertRaisesContext(_AssertRaisesBaseContext):\n ''\n \n _base_type=BaseException\n _base_type_str='an exception type or tuple of exception types'\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,tb):\n if exc_type is None:\n try:\n exc_name=self.expected.__name__\n except AttributeError:\n exc_name=str(self.expected)\n if self.obj_name:\n self._raiseFailure(\"{} not raised by {}\".format(exc_name,\n self.obj_name))\n else:\n self._raiseFailure(\"{} not raised\".format(exc_name))\n else:\n traceback.clear_frames(tb)\n if not issubclass(exc_type,self.expected):\n \n return False\n \n self.exception=exc_value.with_traceback(None)\n if self.expected_regex is None:\n return True\n \n expected_regex=self.expected_regex\n if not expected_regex.search(str(exc_value)):\n self._raiseFailure('\"{}\" does not match \"{}\"'.format(\n expected_regex.pattern,str(exc_value)))\n return True\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \nclass _AssertWarnsContext(_AssertRaisesBaseContext):\n ''\n \n _base_type=Warning\n _base_type_str='a warning type or tuple of warning types'\n \n def __enter__(self):\n \n \n for v in list(sys.modules.values()):\n if getattr(v,'__warningregistry__',None):\n v.__warningregistry__={}\n self.warnings_manager=warnings.catch_warnings(record=True)\n self.warnings=self.warnings_manager.__enter__()\n warnings.simplefilter(\"always\",self.expected)\n return self\n \n def __exit__(self,exc_type,exc_value,tb):\n self.warnings_manager.__exit__(exc_type,exc_value,tb)\n if exc_type is not None:\n \n return\n try:\n exc_name=self.expected.__name__\n except AttributeError:\n exc_name=str(self.expected)\n first_matching=None\n for m in self.warnings:\n w=m.message\n if not isinstance(w,self.expected):\n continue\n if first_matching is None:\n first_matching=w\n if(self.expected_regex is not None and\n not self.expected_regex.search(str(w))):\n continue\n \n self.warning=w\n self.filename=m.filename\n self.lineno=m.lineno\n return\n \n if first_matching is not None:\n self._raiseFailure('\"{}\" does not match \"{}\"'.format(\n self.expected_regex.pattern,str(first_matching)))\n if self.obj_name:\n self._raiseFailure(\"{} not triggered by {}\".format(exc_name,\n self.obj_name))\n else:\n self._raiseFailure(\"{} not triggered\".format(exc_name))\n \n \nclass _AssertNotWarnsContext(_AssertWarnsContext):\n\n def __exit__(self,exc_type,exc_value,tb):\n self.warnings_manager.__exit__(exc_type,exc_value,tb)\n if exc_type is not None:\n \n return\n try:\n exc_name=self.expected.__name__\n except AttributeError:\n exc_name=str(self.expected)\n for m in self.warnings:\n w=m.message\n if isinstance(w,self.expected):\n self._raiseFailure(f\"{exc_name} triggered\")\n \n \nclass _OrderedChainMap(collections.ChainMap):\n def __iter__(self):\n seen=set()\n for mapping in self.maps:\n for k in mapping:\n if k not in seen:\n seen.add(k)\n yield k\n \n \nclass TestCase(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n failureException=AssertionError\n \n longMessage=True\n \n maxDiff=80 *8\n \n \n \n _diffThreshold=2 **16\n \n def __init_subclass__(cls,*args,**kwargs):\n \n cls._classSetupFailed=False\n cls._class_cleanups=[]\n super().__init_subclass__(*args,**kwargs)\n \n def __init__(self,methodName='runTest'):\n ''\n\n\n \n self._testMethodName=methodName\n self._outcome=None\n self._testMethodDoc='No test'\n try:\n testMethod=getattr(self,methodName)\n except AttributeError:\n if methodName !='runTest':\n \n \n raise ValueError(\"no such test method in %s: %s\"%\n (self.__class__,methodName))\n else:\n self._testMethodDoc=testMethod.__doc__\n self._cleanups=[]\n self._subtest=None\n \n \n \n \n self._type_equality_funcs={}\n self.addTypeEqualityFunc(dict,'assertDictEqual')\n self.addTypeEqualityFunc(list,'assertListEqual')\n self.addTypeEqualityFunc(tuple,'assertTupleEqual')\n self.addTypeEqualityFunc(set,'assertSetEqual')\n self.addTypeEqualityFunc(frozenset,'assertSetEqual')\n self.addTypeEqualityFunc(str,'assertMultiLineEqual')\n \n def addTypeEqualityFunc(self,typeobj,function):\n ''\n\n\n\n\n\n\n\n\n\n\n \n self._type_equality_funcs[typeobj]=function\n \n def addCleanup(self,function,/,*args,**kwargs):\n ''\n\n\n\n \n self._cleanups.append((function,args,kwargs))\n \n def enterContext(self,cm):\n ''\n\n\n\n \n return _enter_context(cm,self.addCleanup)\n \n @classmethod\n def addClassCleanup(cls,function,/,*args,**kwargs):\n ''\n \n cls._class_cleanups.append((function,args,kwargs))\n \n @classmethod\n def enterClassContext(cls,cm):\n ''\n return _enter_context(cm,cls.addClassCleanup)\n \n def setUp(self):\n ''\n pass\n \n def tearDown(self):\n ''\n pass\n \n @classmethod\n def setUpClass(cls):\n ''\n \n @classmethod\n def tearDownClass(cls):\n ''\n \n def countTestCases(self):\n return 1\n \n def defaultTestResult(self):\n return result.TestResult()\n \n def shortDescription(self):\n ''\n\n\n\n\n \n doc=self._testMethodDoc\n return doc.strip().split(\"\\n\")[0].strip()if doc else None\n \n \n def id(self):\n return \"%s.%s\"%(strclass(self.__class__),self._testMethodName)\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self._testMethodName ==other._testMethodName\n \n def __hash__(self):\n return hash((type(self),self._testMethodName))\n \n def __str__(self):\n return \"%s (%s.%s)\"%(self._testMethodName,strclass(self.__class__),self._testMethodName)\n \n def __repr__(self):\n return \"<%s testMethod=%s>\"%\\\n (strclass(self.__class__),self._testMethodName)\n \n @contextlib.contextmanager\n def subTest(self,msg=_subtest_msg_sentinel,**params):\n ''\n\n\n\n\n \n if self._outcome is None or not self._outcome.result_supports_subtests:\n yield\n return\n parent=self._subtest\n if parent is None:\n params_map=_OrderedChainMap(params)\n else:\n params_map=parent.params.new_child(params)\n self._subtest=_SubTest(self,msg,params_map)\n try:\n with self._outcome.testPartExecutor(self._subtest,subTest=True):\n yield\n if not self._outcome.success:\n result=self._outcome.result\n if result is not None and result.failfast:\n raise _ShouldStop\n elif self._outcome.expectedFailure:\n \n \n raise _ShouldStop\n finally:\n self._subtest=parent\n \n def _addExpectedFailure(self,result,exc_info):\n try:\n addExpectedFailure=result.addExpectedFailure\n except AttributeError:\n warnings.warn(\"TestResult has no addExpectedFailure method, reporting as passes\",\n RuntimeWarning)\n result.addSuccess(self)\n else:\n addExpectedFailure(self,exc_info)\n \n def _addUnexpectedSuccess(self,result):\n try:\n addUnexpectedSuccess=result.addUnexpectedSuccess\n except AttributeError:\n warnings.warn(\"TestResult has no addUnexpectedSuccess method, reporting as failure\",\n RuntimeWarning)\n \n \n try:\n raise _UnexpectedSuccess from None\n except _UnexpectedSuccess:\n result.addFailure(self,sys.exc_info())\n else:\n addUnexpectedSuccess(self)\n \n def _addDuration(self,result,elapsed):\n try:\n addDuration=result.addDuration\n except AttributeError:\n warnings.warn(\"TestResult has no addDuration method\",\n RuntimeWarning)\n else:\n addDuration(self,elapsed)\n \n def _callSetUp(self):\n self.setUp()\n \n def _callTestMethod(self,method):\n if method()is not None:\n warnings.warn(f'It is deprecated to return a value that is not None from a '\n f'test case ({method})',DeprecationWarning,stacklevel=3)\n \n def _callTearDown(self):\n self.tearDown()\n \n def _callCleanup(self,function,/,*args,**kwargs):\n function(*args,**kwargs)\n \n def run(self,result=None):\n if result is None:\n result=self.defaultTestResult()\n startTestRun=getattr(result,'startTestRun',None)\n stopTestRun=getattr(result,'stopTestRun',None)\n if startTestRun is not None:\n startTestRun()\n else:\n stopTestRun=None\n \n result.startTest(self)\n try:\n testMethod=getattr(self,self._testMethodName)\n if(getattr(self.__class__,\"__unittest_skip__\",False)or\n getattr(testMethod,\"__unittest_skip__\",False)):\n \n skip_why=(getattr(self.__class__,'__unittest_skip_why__','')\n or getattr(testMethod,'__unittest_skip_why__',''))\n _addSkip(result,self,skip_why)\n return result\n \n expecting_failure=(\n getattr(self,\"__unittest_expecting_failure__\",False)or\n getattr(testMethod,\"__unittest_expecting_failure__\",False)\n )\n outcome=_Outcome(result)\n start_time=time.perf_counter()\n try:\n self._outcome=outcome\n \n with outcome.testPartExecutor(self):\n self._callSetUp()\n if outcome.success:\n outcome.expecting_failure=expecting_failure\n with outcome.testPartExecutor(self):\n self._callTestMethod(testMethod)\n outcome.expecting_failure=False\n with outcome.testPartExecutor(self):\n self._callTearDown()\n self.doCleanups()\n self._addDuration(result,(time.perf_counter()-start_time))\n \n if outcome.success:\n if expecting_failure:\n if outcome.expectedFailure:\n self._addExpectedFailure(result,outcome.expectedFailure)\n else:\n self._addUnexpectedSuccess(result)\n else:\n result.addSuccess(self)\n return result\n finally:\n \n \n outcome.expectedFailure=None\n outcome=None\n \n \n self._outcome=None\n \n finally:\n result.stopTest(self)\n if stopTestRun is not None:\n stopTestRun()\n \n def doCleanups(self):\n ''\n \n outcome=self._outcome or _Outcome()\n while self._cleanups:\n function,args,kwargs=self._cleanups.pop()\n with outcome.testPartExecutor(self):\n self._callCleanup(function,*args,**kwargs)\n \n \n \n return outcome.success\n \n @classmethod\n def doClassCleanups(cls):\n ''\n \n cls.tearDown_exceptions=[]\n while cls._class_cleanups:\n function,args,kwargs=cls._class_cleanups.pop()\n try:\n function(*args,**kwargs)\n except Exception:\n cls.tearDown_exceptions.append(sys.exc_info())\n \n def __call__(self,*args,**kwds):\n return self.run(*args,**kwds)\n \n def debug(self):\n ''\n testMethod=getattr(self,self._testMethodName)\n if(getattr(self.__class__,\"__unittest_skip__\",False)or\n getattr(testMethod,\"__unittest_skip__\",False)):\n \n skip_why=(getattr(self.__class__,'__unittest_skip_why__','')\n or getattr(testMethod,'__unittest_skip_why__',''))\n raise SkipTest(skip_why)\n \n self._callSetUp()\n self._callTestMethod(testMethod)\n self._callTearDown()\n while self._cleanups:\n function,args,kwargs=self._cleanups.pop()\n self._callCleanup(function,*args,**kwargs)\n \n def skipTest(self,reason):\n ''\n raise SkipTest(reason)\n \n def fail(self,msg=None):\n ''\n raise self.failureException(msg)\n \n def assertFalse(self,expr,msg=None):\n ''\n if expr:\n msg=self._formatMessage(msg,\"%s is not false\"%safe_repr(expr))\n raise self.failureException(msg)\n \n def assertTrue(self,expr,msg=None):\n ''\n if not expr:\n msg=self._formatMessage(msg,\"%s is not true\"%safe_repr(expr))\n raise self.failureException(msg)\n \n def _formatMessage(self,msg,standardMsg):\n ''\n\n\n\n\n\n\n\n \n if not self.longMessage:\n return msg or standardMsg\n if msg is None:\n return standardMsg\n try:\n \n \n return '%s : %s'%(standardMsg,msg)\n except UnicodeDecodeError:\n return '%s : %s'%(safe_repr(standardMsg),safe_repr(msg))\n \n def assertRaises(self,expected_exception,*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertRaisesContext(expected_exception,self)\n try:\n return context.handle('assertRaises',args,kwargs)\n finally:\n \n context=None\n \n def assertWarns(self,expected_warning,*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertWarnsContext(expected_warning,self)\n return context.handle('assertWarns',args,kwargs)\n \n def _assertNotWarns(self,expected_warning,*args,**kwargs):\n ''\n context=_AssertNotWarnsContext(expected_warning,self)\n return context.handle('_assertNotWarns',args,kwargs)\n \n def assertLogs(self,logger=None,level=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n from._log import _AssertLogsContext\n return _AssertLogsContext(self,logger,level,no_logs=False)\n \n def assertNoLogs(self,logger=None,level=None):\n ''\n\n\n\n \n from._log import _AssertLogsContext\n return _AssertLogsContext(self,logger,level,no_logs=True)\n \n def _getAssertEqualityFunc(self,first,second):\n ''\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n if type(first)is type(second):\n asserter=self._type_equality_funcs.get(type(first))\n if asserter is not None:\n if isinstance(asserter,str):\n asserter=getattr(self,asserter)\n return asserter\n \n return self._baseAssertEqual\n \n def _baseAssertEqual(self,first,second,msg=None):\n ''\n if not first ==second:\n standardMsg='%s != %s'%_common_shorten_repr(first,second)\n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertEqual(self,first,second,msg=None):\n ''\n\n \n assertion_func=self._getAssertEqualityFunc(first,second)\n assertion_func(first,second,msg=msg)\n \n def assertNotEqual(self,first,second,msg=None):\n ''\n\n \n if not first !=second:\n msg=self._formatMessage(msg,'%s == %s'%(safe_repr(first),\n safe_repr(second)))\n raise self.failureException(msg)\n \n def assertAlmostEqual(self,first,second,places=None,msg=None,\n delta=None):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if first ==second:\n \n return\n if delta is not None and places is not None:\n raise TypeError(\"specify delta or places not both\")\n \n diff=abs(first -second)\n if delta is not None:\n if diff <=delta:\n return\n \n standardMsg='%s != %s within %s delta (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n safe_repr(delta),\n safe_repr(diff))\n else:\n if places is None:\n places=7\n \n if round(diff,places)==0:\n return\n \n standardMsg='%s != %s within %r places (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n places,\n safe_repr(diff))\n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertNotAlmostEqual(self,first,second,places=None,msg=None,\n delta=None):\n ''\n\n\n\n\n\n\n\n\n \n if delta is not None and places is not None:\n raise TypeError(\"specify delta or places not both\")\n diff=abs(first -second)\n if delta is not None:\n if not(first ==second)and diff >delta:\n return\n standardMsg='%s == %s within %s delta (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n safe_repr(delta),\n safe_repr(diff))\n else:\n if places is None:\n places=7\n if not(first ==second)and round(diff,places)!=0:\n return\n standardMsg='%s == %s within %r places'%(safe_repr(first),\n safe_repr(second),\n places)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertSequenceEqual(self,seq1,seq2,msg=None,seq_type=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if seq_type is not None:\n seq_type_name=seq_type.__name__\n if not isinstance(seq1,seq_type):\n raise self.failureException('First sequence is not a %s: %s'\n %(seq_type_name,safe_repr(seq1)))\n if not isinstance(seq2,seq_type):\n raise self.failureException('Second sequence is not a %s: %s'\n %(seq_type_name,safe_repr(seq2)))\n else:\n seq_type_name=\"sequence\"\n \n differing=None\n try:\n len1=len(seq1)\n except(TypeError,NotImplementedError):\n differing='First %s has no length. Non-sequence?'%(\n seq_type_name)\n \n if differing is None:\n try:\n len2=len(seq2)\n except(TypeError,NotImplementedError):\n differing='Second %s has no length. Non-sequence?'%(\n seq_type_name)\n \n if differing is None:\n if seq1 ==seq2:\n return\n \n differing='%ss differ: %s != %s\\n'%(\n (seq_type_name.capitalize(),)+\n _common_shorten_repr(seq1,seq2))\n \n for i in range(min(len1,len2)):\n try:\n item1=seq1[i]\n except(TypeError,IndexError,NotImplementedError):\n differing +=('\\nUnable to index element %d of first %s\\n'%\n (i,seq_type_name))\n break\n \n try:\n item2=seq2[i]\n except(TypeError,IndexError,NotImplementedError):\n differing +=('\\nUnable to index element %d of second %s\\n'%\n (i,seq_type_name))\n break\n \n if item1 !=item2:\n differing +=('\\nFirst differing element %d:\\n%s\\n%s\\n'%\n ((i,)+_common_shorten_repr(item1,item2)))\n break\n else:\n if(len1 ==len2 and seq_type is None and\n type(seq1)!=type(seq2)):\n \n return\n \n if len1 >len2:\n differing +=('\\nFirst %s contains %d additional '\n 'elements.\\n'%(seq_type_name,len1 -len2))\n try:\n differing +=('First extra element %d:\\n%s\\n'%\n (len2,safe_repr(seq1[len2])))\n except(TypeError,IndexError,NotImplementedError):\n differing +=('Unable to index element %d '\n 'of first %s\\n'%(len2,seq_type_name))\n elif len1 self._diffThreshold or\n len(second)>self._diffThreshold):\n self._baseAssertEqual(first,second,msg)\n \n \n \n \n \n first_presplit=first\n second_presplit=second\n if first and second:\n if first[-1]!='\\n'or second[-1]!='\\n':\n first_presplit +='\\n'\n second_presplit +='\\n'\n elif second and second[-1]!='\\n':\n second_presplit +='\\n'\n elif first and first[-1]!='\\n':\n first_presplit +='\\n'\n \n firstlines=first_presplit.splitlines(keepends=True)\n secondlines=second_presplit.splitlines(keepends=True)\n \n \n standardMsg='%s != %s'%_common_shorten_repr(first,second)\n diff='\\n'+''.join(difflib.ndiff(firstlines,secondlines))\n standardMsg=self._truncateMessage(standardMsg,diff)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertLess(self,a,b,msg=None):\n ''\n if not a b:\n standardMsg='%s not greater than %s'%(safe_repr(a),safe_repr(b))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertGreaterEqual(self,a,b,msg=None):\n ''\n if not a >=b:\n standardMsg='%s not greater than or equal to %s'%(safe_repr(a),safe_repr(b))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsNone(self,obj,msg=None):\n ''\n if obj is not None:\n standardMsg='%s is not None'%(safe_repr(obj),)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsNotNone(self,obj,msg=None):\n ''\n if obj is None:\n standardMsg='unexpectedly None'\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsInstance(self,obj,cls,msg=None):\n ''\n \n if not isinstance(obj,cls):\n standardMsg='%s is not an instance of %r'%(safe_repr(obj),cls)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertNotIsInstance(self,obj,cls,msg=None):\n ''\n if isinstance(obj,cls):\n standardMsg='%s is an instance of %r'%(safe_repr(obj),cls)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertRaisesRegex(self,expected_exception,expected_regex,\n *args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n context=_AssertRaisesContext(expected_exception,self,expected_regex)\n return context.handle('assertRaisesRegex',args,kwargs)\n \n def assertWarnsRegex(self,expected_warning,expected_regex,\n *args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertWarnsContext(expected_warning,self,expected_regex)\n return context.handle('assertWarnsRegex',args,kwargs)\n \n def assertRegex(self,text,expected_regex,msg=None):\n ''\n if isinstance(expected_regex,(str,bytes)):\n assert expected_regex,\"expected_regex must not be empty.\"\n expected_regex=re.compile(expected_regex)\n if not expected_regex.search(text):\n standardMsg=\"Regex didn't match: %r not found in %r\"%(\n expected_regex.pattern,text)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertNotRegex(self,text,unexpected_regex,msg=None):\n ''\n if isinstance(unexpected_regex,(str,bytes)):\n unexpected_regex=re.compile(unexpected_regex)\n match=unexpected_regex.search(text)\n if match:\n standardMsg='Regex matched: %r matches %r in %r'%(\n text[match.start():match.end()],\n unexpected_regex.pattern,\n text)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n \n \nclass FunctionTestCase(TestCase):\n ''\n\n\n\n\n\n \n \n def __init__(self,testFunc,setUp=None,tearDown=None,description=None):\n super(FunctionTestCase,self).__init__()\n self._setUpFunc=setUp\n self._tearDownFunc=tearDown\n self._testFunc=testFunc\n self._description=description\n \n def setUp(self):\n if self._setUpFunc is not None:\n self._setUpFunc()\n \n def tearDown(self):\n if self._tearDownFunc is not None:\n self._tearDownFunc()\n \n def runTest(self):\n self._testFunc()\n \n def id(self):\n return self._testFunc.__name__\n \n def __eq__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n \n return self._setUpFunc ==other._setUpFunc and\\\n self._tearDownFunc ==other._tearDownFunc and\\\n self._testFunc ==other._testFunc and\\\n self._description ==other._description\n \n def __hash__(self):\n return hash((type(self),self._setUpFunc,self._tearDownFunc,\n self._testFunc,self._description))\n \n def __str__(self):\n return \"%s (%s)\"%(strclass(self.__class__),\n self._testFunc.__name__)\n \n def __repr__(self):\n return \"<%s tec=%s>\"%(strclass(self.__class__),\n self._testFunc)\n \n def shortDescription(self):\n if self._description is not None:\n return self._description\n doc=self._testFunc.__doc__\n return doc and doc.split(\"\\n\")[0].strip()or None\n \n \nclass _SubTest(TestCase):\n\n def __init__(self,test_case,message,params):\n super().__init__()\n self._message=message\n self.test_case=test_case\n self.params=params\n self.failureException=test_case.failureException\n \n def runTest(self):\n raise NotImplementedError(\"subtests cannot be run directly\")\n \n def _subDescription(self):\n parts=[]\n if self._message is not _subtest_msg_sentinel:\n parts.append(\"[{}]\".format(self._message))\n if self.params:\n params_desc=', '.join(\n \"{}={!r}\".format(k,v)\n for(k,v)in self.params.items())\n parts.append(\"({})\".format(params_desc))\n return \" \".join(parts)or '()'\n \n def id(self):\n return \"{} {}\".format(self.test_case.id(),self._subDescription())\n \n def shortDescription(self):\n ''\n\n \n return self.test_case.shortDescription()\n \n def __str__(self):\n return \"{} {}\".format(self.test_case,self._subDescription())\n", ["collections", "contextlib", "difflib", "functools", "pprint", "re", "sys", "time", "traceback", "types", "unittest", "unittest._log", "unittest.result", "unittest.util", "warnings"]], "unittest.loader": [".py", "''\n\nimport os\nimport re\nimport sys\nimport traceback\nimport types\nimport functools\n\nfrom fnmatch import fnmatch,fnmatchcase\n\nfrom. import case,suite,util\n\n__unittest=True\n\n\n\n\nVALID_MODULE_NAME=re.compile(r'[_a-z]\\w*\\.py$',re.IGNORECASE)\n\n\nclass _FailedTest(case.TestCase):\n _testMethodName=None\n \n def __init__(self,method_name,exception):\n self._exception=exception\n super(_FailedTest,self).__init__(method_name)\n \n def __getattr__(self,name):\n if name !=self._testMethodName:\n return super(_FailedTest,self).__getattr__(name)\n def testFailure():\n raise self._exception\n return testFailure\n \n \ndef _make_failed_import_test(name,suiteClass):\n message='Failed to import test module: %s\\n%s'%(\n name,traceback.format_exc())\n return _make_failed_test(name,ImportError(message),suiteClass,message)\n \ndef _make_failed_load_tests(name,exception,suiteClass):\n message='Failed to call load_tests:\\n%s'%(traceback.format_exc(),)\n return _make_failed_test(\n name,exception,suiteClass,message)\n \ndef _make_failed_test(methodname,exception,suiteClass,message):\n test=_FailedTest(methodname,exception)\n return suiteClass((test,)),message\n \ndef _make_skipped_test(methodname,exception,suiteClass):\n @case.skip(str(exception))\n def testSkipped(self):\n pass\n attrs={methodname:testSkipped}\n TestClass=type(\"ModuleSkipped\",(case.TestCase,),attrs)\n return suiteClass((TestClass(methodname),))\n \ndef _splitext(path):\n return os.path.splitext(path)[0]\n \n \nclass TestLoader(object):\n ''\n\n\n \n testMethodPrefix='test'\n sortTestMethodsUsing=staticmethod(util.three_way_cmp)\n testNamePatterns=None\n suiteClass=suite.TestSuite\n _top_level_dir=None\n \n def __init__(self):\n super(TestLoader,self).__init__()\n self.errors=[]\n \n \n self._loading_packages=set()\n \n def loadTestsFromTestCase(self,testCaseClass):\n ''\n if issubclass(testCaseClass,suite.TestSuite):\n raise TypeError(\"Test cases should not be derived from \"\n \"TestSuite. Maybe you meant to derive from \"\n \"TestCase?\")\n if testCaseClass in(case.TestCase,case.FunctionTestCase):\n \n testCaseNames=[]\n else:\n testCaseNames=self.getTestCaseNames(testCaseClass)\n if not testCaseNames and hasattr(testCaseClass,'runTest'):\n testCaseNames=['runTest']\n loaded_suite=self.suiteClass(map(testCaseClass,testCaseNames))\n return loaded_suite\n \n def loadTestsFromModule(self,module,*,pattern=None):\n ''\n tests=[]\n for name in dir(module):\n obj=getattr(module,name)\n if(\n isinstance(obj,type)\n and issubclass(obj,case.TestCase)\n and obj not in(case.TestCase,case.FunctionTestCase)\n ):\n tests.append(self.loadTestsFromTestCase(obj))\n \n load_tests=getattr(module,'load_tests',None)\n tests=self.suiteClass(tests)\n if load_tests is not None:\n try:\n return load_tests(self,tests,pattern)\n except Exception as e:\n error_case,error_message=_make_failed_load_tests(\n module.__name__,e,self.suiteClass)\n self.errors.append(error_message)\n return error_case\n return tests\n \n def loadTestsFromName(self,name,module=None):\n ''\n\n\n\n\n\n\n \n parts=name.split('.')\n error_case,error_message=None,None\n if module is None:\n parts_copy=parts[:]\n while parts_copy:\n try:\n module_name='.'.join(parts_copy)\n module=__import__(module_name)\n break\n except ImportError:\n next_attribute=parts_copy.pop()\n \n error_case,error_message=_make_failed_import_test(\n next_attribute,self.suiteClass)\n if not parts_copy:\n \n self.errors.append(error_message)\n return error_case\n parts=parts[1:]\n obj=module\n for part in parts:\n try:\n parent,obj=obj,getattr(obj,part)\n except AttributeError as e:\n \n if(getattr(obj,'__path__',None)is not None\n and error_case is not None):\n \n \n \n \n \n self.errors.append(error_message)\n return error_case\n else:\n \n error_case,error_message=_make_failed_test(\n part,e,self.suiteClass,\n 'Failed to access attribute:\\n%s'%(\n traceback.format_exc(),))\n self.errors.append(error_message)\n return error_case\n \n if isinstance(obj,types.ModuleType):\n return self.loadTestsFromModule(obj)\n elif(\n isinstance(obj,type)\n and issubclass(obj,case.TestCase)\n and obj not in(case.TestCase,case.FunctionTestCase)\n ):\n return self.loadTestsFromTestCase(obj)\n elif(isinstance(obj,types.FunctionType)and\n isinstance(parent,type)and\n issubclass(parent,case.TestCase)):\n name=parts[-1]\n inst=parent(name)\n \n if not isinstance(getattr(inst,name),types.FunctionType):\n return self.suiteClass([inst])\n elif isinstance(obj,suite.TestSuite):\n return obj\n if callable(obj):\n test=obj()\n if isinstance(test,suite.TestSuite):\n return test\n elif isinstance(test,case.TestCase):\n return self.suiteClass([test])\n else:\n raise TypeError(\"calling %s returned %s, not a test\"%\n (obj,test))\n else:\n raise TypeError(\"don't know how to make test from: %s\"%obj)\n \n def loadTestsFromNames(self,names,module=None):\n ''\n\n \n suites=[self.loadTestsFromName(name,module)for name in names]\n return self.suiteClass(suites)\n \n def getTestCaseNames(self,testCaseClass):\n ''\n \n def shouldIncludeMethod(attrname):\n if not attrname.startswith(self.testMethodPrefix):\n return False\n testFunc=getattr(testCaseClass,attrname)\n if not callable(testFunc):\n return False\n fullName=f'%s.%s.%s'%(\n testCaseClass.__module__,testCaseClass.__qualname__,attrname\n )\n return self.testNamePatterns is None or\\\n any(fnmatchcase(fullName,pattern)for pattern in self.testNamePatterns)\n testFnNames=list(filter(shouldIncludeMethod,dir(testCaseClass)))\n if self.sortTestMethodsUsing:\n testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))\n return testFnNames\n \n def discover(self,start_dir,pattern='test*.py',top_level_dir=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n original_top_level_dir=self._top_level_dir\n set_implicit_top=False\n if top_level_dir is None and self._top_level_dir is not None:\n \n top_level_dir=self._top_level_dir\n elif top_level_dir is None:\n set_implicit_top=True\n top_level_dir=start_dir\n \n top_level_dir=os.path.abspath(top_level_dir)\n \n if not top_level_dir in sys.path:\n \n \n \n \n sys.path.insert(0,top_level_dir)\n self._top_level_dir=top_level_dir\n \n is_not_importable=False\n if os.path.isdir(os.path.abspath(start_dir)):\n start_dir=os.path.abspath(start_dir)\n if start_dir !=top_level_dir:\n is_not_importable=not os.path.isfile(os.path.join(start_dir,'__init__.py'))\n else:\n \n try:\n __import__(start_dir)\n except ImportError:\n is_not_importable=True\n else:\n the_module=sys.modules[start_dir]\n top_part=start_dir.split('.')[0]\n try:\n start_dir=os.path.abspath(\n os.path.dirname((the_module.__file__)))\n except AttributeError:\n if the_module.__name__ in sys.builtin_module_names:\n \n raise TypeError('Can not use builtin modules '\n 'as dotted module names')from None\n else:\n raise TypeError(\n f\"don't know how to discover from {the_module !r}\"\n )from None\n \n if set_implicit_top:\n self._top_level_dir=self._get_directory_containing_module(top_part)\n sys.path.remove(top_level_dir)\n \n if is_not_importable:\n raise ImportError('Start directory is not importable: %r'%start_dir)\n \n tests=list(self._find_tests(start_dir,pattern))\n self._top_level_dir=original_top_level_dir\n return self.suiteClass(tests)\n \n def _get_directory_containing_module(self,module_name):\n module=sys.modules[module_name]\n full_path=os.path.abspath(module.__file__)\n \n if os.path.basename(full_path).lower().startswith('__init__.py'):\n return os.path.dirname(os.path.dirname(full_path))\n else:\n \n \n \n return os.path.dirname(full_path)\n \n def _get_name_from_path(self,path):\n if path ==self._top_level_dir:\n return '.'\n path=_splitext(os.path.normpath(path))\n \n _relpath=os.path.relpath(path,self._top_level_dir)\n assert not os.path.isabs(_relpath),\"Path must be within the project\"\n assert not _relpath.startswith('..'),\"Path must be within the project\"\n \n name=_relpath.replace(os.path.sep,'.')\n return name\n \n def _get_module_from_name(self,name):\n __import__(name)\n return sys.modules[name]\n \n def _match_path(self,path,full_path,pattern):\n \n return fnmatch(path,pattern)\n \n def _find_tests(self,start_dir,pattern):\n ''\n \n name=self._get_name_from_path(start_dir)\n \n \n if name !='.'and name not in self._loading_packages:\n \n \n tests,should_recurse=self._find_test_path(start_dir,pattern)\n if tests is not None:\n yield tests\n if not should_recurse:\n \n \n return\n \n paths=sorted(os.listdir(start_dir))\n for path in paths:\n full_path=os.path.join(start_dir,path)\n tests,should_recurse=self._find_test_path(full_path,pattern)\n if tests is not None:\n yield tests\n if should_recurse:\n \n name=self._get_name_from_path(full_path)\n self._loading_packages.add(name)\n try:\n yield from self._find_tests(full_path,pattern)\n finally:\n self._loading_packages.discard(name)\n \n def _find_test_path(self,full_path,pattern):\n ''\n\n\n\n\n\n \n basename=os.path.basename(full_path)\n if os.path.isfile(full_path):\n if not VALID_MODULE_NAME.match(basename):\n \n return None,False\n if not self._match_path(basename,full_path,pattern):\n return None,False\n \n name=self._get_name_from_path(full_path)\n try:\n module=self._get_module_from_name(name)\n except case.SkipTest as e:\n return _make_skipped_test(name,e,self.suiteClass),False\n except:\n error_case,error_message=\\\n _make_failed_import_test(name,self.suiteClass)\n self.errors.append(error_message)\n return error_case,False\n else:\n mod_file=os.path.abspath(\n getattr(module,'__file__',full_path))\n realpath=_splitext(\n os.path.realpath(mod_file))\n fullpath_noext=_splitext(\n os.path.realpath(full_path))\n if realpath.lower()!=fullpath_noext.lower():\n module_dir=os.path.dirname(realpath)\n mod_name=_splitext(\n os.path.basename(full_path))\n expected_dir=os.path.dirname(full_path)\n msg=(\"%r module incorrectly imported from %r. Expected \"\n \"%r. Is this module globally installed?\")\n raise ImportError(\n msg %(mod_name,module_dir,expected_dir))\n return self.loadTestsFromModule(module,pattern=pattern),False\n elif os.path.isdir(full_path):\n if not os.path.isfile(os.path.join(full_path,'__init__.py')):\n return None,False\n \n load_tests=None\n tests=None\n name=self._get_name_from_path(full_path)\n try:\n package=self._get_module_from_name(name)\n except case.SkipTest as e:\n return _make_skipped_test(name,e,self.suiteClass),False\n except:\n error_case,error_message=\\\n _make_failed_import_test(name,self.suiteClass)\n self.errors.append(error_message)\n return error_case,False\n else:\n load_tests=getattr(package,'load_tests',None)\n \n self._loading_packages.add(name)\n try:\n tests=self.loadTestsFromModule(package,pattern=pattern)\n if load_tests is not None:\n \n return tests,False\n return tests,True\n finally:\n self._loading_packages.discard(name)\n else:\n return None,False\n \n \ndefaultTestLoader=TestLoader()\n", ["fnmatch", "functools", "os", "re", "sys", "traceback", "types", "unittest", "unittest.case", "unittest.suite", "unittest.util"]], "unittest.main": [".py", "''\n\nimport sys\nimport argparse\nimport os\n\nfrom. import loader,runner\nfrom.signals import installHandler\n\n__unittest=True\n_NO_TESTS_EXITCODE=5\n\nMAIN_EXAMPLES=\"\"\"\\\nExamples:\n %(prog)s test_module - run tests from test_module\n %(prog)s module.TestClass - run tests from module.TestClass\n %(prog)s module.Class.test_method - run specified test method\n %(prog)s path/to/test_file.py - run tests from test_file.py\n\"\"\"\n\nMODULE_EXAMPLES=\"\"\"\\\nExamples:\n %(prog)s - run default set of tests\n %(prog)s MyTestSuite - run suite 'MyTestSuite'\n %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething\n %(prog)s MyTestCase - run all 'test*' test methods\n in MyTestCase\n\"\"\"\n\ndef _convert_name(name):\n\n\n\n\n if os.path.isfile(name)and name.lower().endswith('.py'):\n if os.path.isabs(name):\n rel_path=os.path.relpath(name,os.getcwd())\n if os.path.isabs(rel_path)or rel_path.startswith(os.pardir):\n return name\n name=rel_path\n \n \n return os.path.normpath(name)[:-3].replace('\\\\','.').replace('/','.')\n return name\n \ndef _convert_names(names):\n return[_convert_name(name)for name in names]\n \n \ndef _convert_select_pattern(pattern):\n if not '*'in pattern:\n pattern='*%s*'%pattern\n return pattern\n \n \nclass TestProgram(object):\n ''\n\n \n \n module=None\n verbosity=1\n failfast=catchbreak=buffer=progName=warnings=testNamePatterns=None\n _discovery_parser=None\n \n def __init__(self,module='__main__',defaultTest=None,argv=None,\n testRunner=None,testLoader=loader.defaultTestLoader,\n exit=True,verbosity=1,failfast=None,catchbreak=None,\n buffer=None,warnings=None,*,tb_locals=False,\n durations=None):\n if isinstance(module,str):\n self.module=__import__(module)\n for part in module.split('.')[1:]:\n self.module=getattr(self.module,part)\n else:\n self.module=module\n if argv is None:\n argv=sys.argv\n \n self.exit=exit\n self.failfast=failfast\n self.catchbreak=catchbreak\n self.verbosity=verbosity\n self.buffer=buffer\n self.tb_locals=tb_locals\n self.durations=durations\n if warnings is None and not sys.warnoptions:\n \n \n \n self.warnings='default'\n else:\n \n \n \n \n \n self.warnings=warnings\n self.defaultTest=defaultTest\n self.testRunner=testRunner\n self.testLoader=testLoader\n self.progName=os.path.basename(argv[0])\n self.parseArgs(argv)\n self.runTests()\n \n def _print_help(self,*args,**kwargs):\n if self.module is None:\n print(self._main_parser.format_help())\n print(MAIN_EXAMPLES %{'prog':self.progName})\n self._discovery_parser.print_help()\n else:\n print(self._main_parser.format_help())\n print(MODULE_EXAMPLES %{'prog':self.progName})\n \n def parseArgs(self,argv):\n self._initArgParsers()\n if self.module is None:\n if len(argv)>1 and argv[1].lower()=='discover':\n self._do_discovery(argv[2:])\n return\n self._main_parser.parse_args(argv[1:],self)\n if not self.tests:\n \n \n self._do_discovery([])\n return\n else:\n self._main_parser.parse_args(argv[1:],self)\n \n if self.tests:\n self.testNames=_convert_names(self.tests)\n if __name__ =='__main__':\n \n self.module=None\n elif self.defaultTest is None:\n \n self.testNames=None\n elif isinstance(self.defaultTest,str):\n self.testNames=(self.defaultTest,)\n else:\n self.testNames=list(self.defaultTest)\n self.createTests()\n \n def createTests(self,from_discovery=False,Loader=None):\n if self.testNamePatterns:\n self.testLoader.testNamePatterns=self.testNamePatterns\n if from_discovery:\n loader=self.testLoader if Loader is None else Loader()\n self.test=loader.discover(self.start,self.pattern,self.top)\n elif self.testNames is None:\n self.test=self.testLoader.loadTestsFromModule(self.module)\n else:\n self.test=self.testLoader.loadTestsFromNames(self.testNames,\n self.module)\n \n def _initArgParsers(self):\n parent_parser=self._getParentArgParser()\n self._main_parser=self._getMainArgParser(parent_parser)\n self._discovery_parser=self._getDiscoveryArgParser(parent_parser)\n \n def _getParentArgParser(self):\n parser=argparse.ArgumentParser(add_help=False)\n \n parser.add_argument('-v','--verbose',dest='verbosity',\n action='store_const',const=2,\n help='Verbose output')\n parser.add_argument('-q','--quiet',dest='verbosity',\n action='store_const',const=0,\n help='Quiet output')\n parser.add_argument('--locals',dest='tb_locals',\n action='store_true',\n help='Show local variables in tracebacks')\n parser.add_argument('--durations',dest='durations',type=int,\n default=None,metavar=\"N\",\n help='Show the N slowest test cases (N=0 for all)')\n if self.failfast is None:\n parser.add_argument('-f','--failfast',dest='failfast',\n action='store_true',\n help='Stop on first fail or error')\n self.failfast=False\n if self.catchbreak is None:\n parser.add_argument('-c','--catch',dest='catchbreak',\n action='store_true',\n help='Catch Ctrl-C and display results so far')\n self.catchbreak=False\n if self.buffer is None:\n parser.add_argument('-b','--buffer',dest='buffer',\n action='store_true',\n help='Buffer stdout and stderr during tests')\n self.buffer=False\n if self.testNamePatterns is None:\n parser.add_argument('-k',dest='testNamePatterns',\n action='append',type=_convert_select_pattern,\n help='Only run tests which match the given substring')\n self.testNamePatterns=[]\n \n return parser\n \n def _getMainArgParser(self,parent):\n parser=argparse.ArgumentParser(parents=[parent])\n parser.prog=self.progName\n parser.print_help=self._print_help\n \n parser.add_argument('tests',nargs='*',\n help='a list of any number of test modules, '\n 'classes and test methods.')\n \n return parser\n \n def _getDiscoveryArgParser(self,parent):\n parser=argparse.ArgumentParser(parents=[parent])\n parser.prog='%s discover'%self.progName\n parser.epilog=('For test discovery all test modules must be '\n 'importable from the top level directory of the '\n 'project.')\n \n parser.add_argument('-s','--start-directory',dest='start',\n help=\"Directory to start discovery ('.' default)\")\n parser.add_argument('-p','--pattern',dest='pattern',\n help=\"Pattern to match tests ('test*.py' default)\")\n parser.add_argument('-t','--top-level-directory',dest='top',\n help='Top level directory of project (defaults to '\n 'start directory)')\n for arg in('start','pattern','top'):\n parser.add_argument(arg,nargs='?',\n default=argparse.SUPPRESS,\n help=argparse.SUPPRESS)\n \n return parser\n \n def _do_discovery(self,argv,Loader=None):\n self.start='.'\n self.pattern='test*.py'\n self.top=None\n if argv is not None:\n \n if self._discovery_parser is None:\n \n self._initArgParsers()\n self._discovery_parser.parse_args(argv,self)\n \n self.createTests(from_discovery=True,Loader=Loader)\n \n def runTests(self):\n if self.catchbreak:\n installHandler()\n if self.testRunner is None:\n self.testRunner=runner.TextTestRunner\n if isinstance(self.testRunner,type):\n try:\n try:\n testRunner=self.testRunner(verbosity=self.verbosity,\n failfast=self.failfast,\n buffer=self.buffer,\n warnings=self.warnings,\n tb_locals=self.tb_locals,\n durations=self.durations)\n except TypeError:\n \n testRunner=self.testRunner(verbosity=self.verbosity,\n failfast=self.failfast,\n buffer=self.buffer,\n warnings=self.warnings)\n except TypeError:\n \n testRunner=self.testRunner()\n else:\n \n testRunner=self.testRunner\n self.result=testRunner.run(self.test)\n if self.exit:\n if self.result.testsRun ==0 and len(self.result.skipped)==0:\n sys.exit(_NO_TESTS_EXITCODE)\n elif self.result.wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n \n \nmain=TestProgram\n", ["argparse", "os", "sys", "unittest", "unittest.loader", "unittest.runner", "unittest.signals"]], "unittest.mock": [".py", "\n\n\n\n\n\n__all__=(\n'Mock',\n'MagicMock',\n'patch',\n'sentinel',\n'DEFAULT',\n'ANY',\n'call',\n'create_autospec',\n'AsyncMock',\n'ThreadingMock',\n'FILTER_DIR',\n'NonCallableMock',\n'NonCallableMagicMock',\n'mock_open',\n'PropertyMock',\n'seal',\n)\n\n\nimport asyncio\nimport contextlib\nimport io\nimport inspect\nimport pprint\nimport sys\nimport builtins\nimport pkgutil\nfrom asyncio import iscoroutinefunction\nimport threading\nfrom types import CodeType,ModuleType,MethodType\nfrom unittest.util import safe_repr\nfrom functools import wraps,partial\nfrom threading import RLock\n\n\nclass InvalidSpecError(Exception):\n ''\n \n \n_builtins={name for name in dir(builtins)if not name.startswith('_')}\n\nFILTER_DIR=True\n\n\n\n_safe_super=super\n\ndef _is_async_obj(obj):\n if _is_instance_mock(obj)and not isinstance(obj,AsyncMock):\n return False\n if hasattr(obj,'__func__'):\n obj=getattr(obj,'__func__')\n return iscoroutinefunction(obj)or inspect.isawaitable(obj)\n \n \ndef _is_async_func(func):\n if getattr(func,'__code__',None):\n return iscoroutinefunction(func)\n else:\n return False\n \n \ndef _is_instance_mock(obj):\n\n\n return issubclass(type(obj),NonCallableMock)\n \n \ndef _is_exception(obj):\n return(\n isinstance(obj,BaseException)or\n isinstance(obj,type)and issubclass(obj,BaseException)\n )\n \n \ndef _extract_mock(obj):\n\n\n if isinstance(obj,FunctionTypes)and hasattr(obj,'mock'):\n return obj.mock\n else:\n return obj\n \n \ndef _get_signature_object(func,as_instance,eat_self):\n ''\n\n\n\n \n if isinstance(func,type)and not as_instance:\n \n func=func.__init__\n \n eat_self=True\n elif isinstance(func,(classmethod,staticmethod)):\n if isinstance(func,classmethod):\n \n eat_self=True\n \n func=func.__func__\n elif not isinstance(func,FunctionTypes):\n \n \n try:\n func=func.__call__\n except AttributeError:\n return None\n if eat_self:\n sig_func=partial(func,None)\n else:\n sig_func=func\n try:\n return func,inspect.signature(sig_func)\n except ValueError:\n \n return None\n \n \ndef _check_signature(func,mock,skipfirst,instance=False):\n sig=_get_signature_object(func,instance,skipfirst)\n if sig is None:\n return\n func,sig=sig\n def checksig(self,/,*args,**kwargs):\n sig.bind(*args,**kwargs)\n _copy_func_details(func,checksig)\n type(mock)._mock_check_sig=checksig\n type(mock).__signature__=sig\n \n \ndef _copy_func_details(func,funcopy):\n\n\n for attribute in(\n '__name__','__doc__','__text_signature__',\n '__module__','__defaults__','__kwdefaults__',\n ):\n try:\n setattr(funcopy,attribute,getattr(func,attribute))\n except AttributeError:\n pass\n \n \ndef _callable(obj):\n if isinstance(obj,type):\n return True\n if isinstance(obj,(staticmethod,classmethod,MethodType)):\n return _callable(obj.__func__)\n if getattr(obj,'__call__',None)is not None:\n return True\n return False\n \n \ndef _is_list(obj):\n\n\n return type(obj)in(list,tuple)\n \n \ndef _instance_callable(obj):\n ''\n \n if not isinstance(obj,type):\n \n return getattr(obj,'__call__',None)is not None\n \n \n \n for base in(obj,)+obj.__mro__:\n if base.__dict__.get('__call__')is not None:\n return True\n return False\n \n \ndef _set_signature(mock,original,instance=False):\n\n\n\n\n skipfirst=isinstance(original,type)\n result=_get_signature_object(original,instance,skipfirst)\n if result is None:\n return mock\n func,sig=result\n def checksig(*args,**kwargs):\n sig.bind(*args,**kwargs)\n _copy_func_details(func,checksig)\n \n name=original.__name__\n if not name.isidentifier():\n name='funcopy'\n context={'_checksig_':checksig,'mock':mock}\n src=\"\"\"def %s(*args, **kwargs):\n _checksig_(*args, **kwargs)\n return mock(*args, **kwargs)\"\"\"%name\n exec(src,context)\n funcopy=context[name]\n _setup_func(funcopy,mock,sig)\n return funcopy\n \ndef _set_async_signature(mock,original,instance=False,is_async_mock=False):\n\n\n\n\n skipfirst=isinstance(original,type)\n func,sig=_get_signature_object(original,instance,skipfirst)\n def checksig(*args,**kwargs):\n sig.bind(*args,**kwargs)\n _copy_func_details(func,checksig)\n \n name=original.__name__\n context={'_checksig_':checksig,'mock':mock}\n src=\"\"\"async def %s(*args, **kwargs):\n _checksig_(*args, **kwargs)\n return await mock(*args, **kwargs)\"\"\"%name\n exec(src,context)\n funcopy=context[name]\n _setup_func(funcopy,mock,sig)\n _setup_async_mock(funcopy)\n return funcopy\n \n \ndef _setup_func(funcopy,mock,sig):\n funcopy.mock=mock\n \n def assert_called_with(*args,**kwargs):\n return mock.assert_called_with(*args,**kwargs)\n def assert_called(*args,**kwargs):\n return mock.assert_called(*args,**kwargs)\n def assert_not_called(*args,**kwargs):\n return mock.assert_not_called(*args,**kwargs)\n def assert_called_once(*args,**kwargs):\n return mock.assert_called_once(*args,**kwargs)\n def assert_called_once_with(*args,**kwargs):\n return mock.assert_called_once_with(*args,**kwargs)\n def assert_has_calls(*args,**kwargs):\n return mock.assert_has_calls(*args,**kwargs)\n def assert_any_call(*args,**kwargs):\n return mock.assert_any_call(*args,**kwargs)\n def reset_mock():\n funcopy.method_calls=_CallList()\n funcopy.mock_calls=_CallList()\n mock.reset_mock()\n ret=funcopy.return_value\n if _is_instance_mock(ret)and not ret is mock:\n ret.reset_mock()\n \n funcopy.called=False\n funcopy.call_count=0\n funcopy.call_args=None\n funcopy.call_args_list=_CallList()\n funcopy.method_calls=_CallList()\n funcopy.mock_calls=_CallList()\n \n funcopy.return_value=mock.return_value\n funcopy.side_effect=mock.side_effect\n funcopy._mock_children=mock._mock_children\n \n funcopy.assert_called_with=assert_called_with\n funcopy.assert_called_once_with=assert_called_once_with\n funcopy.assert_has_calls=assert_has_calls\n funcopy.assert_any_call=assert_any_call\n funcopy.reset_mock=reset_mock\n funcopy.assert_called=assert_called\n funcopy.assert_not_called=assert_not_called\n funcopy.assert_called_once=assert_called_once\n funcopy.__signature__=sig\n \n mock._mock_delegate=funcopy\n \n \ndef _setup_async_mock(mock):\n mock._is_coroutine=asyncio.coroutines._is_coroutine\n mock.await_count=0\n mock.await_args=None\n mock.await_args_list=_CallList()\n \n \n \n \n def wrapper(attr,/,*args,**kwargs):\n return getattr(mock.mock,attr)(*args,**kwargs)\n \n for attribute in('assert_awaited',\n 'assert_awaited_once',\n 'assert_awaited_with',\n 'assert_awaited_once_with',\n 'assert_any_await',\n 'assert_has_awaits',\n 'assert_not_awaited'):\n \n \n \n \n \n setattr(mock,attribute,partial(wrapper,attribute))\n \n \ndef _is_magic(name):\n return '__%s__'%name[2:-2]==name\n \n \nclass _SentinelObject(object):\n ''\n def __init__(self,name):\n self.name=name\n \n def __repr__(self):\n return 'sentinel.%s'%self.name\n \n def __reduce__(self):\n return 'sentinel.%s'%self.name\n \n \nclass _Sentinel(object):\n ''\n def __init__(self):\n self._sentinels={}\n \n def __getattr__(self,name):\n if name =='__bases__':\n \n raise AttributeError\n return self._sentinels.setdefault(name,_SentinelObject(name))\n \n def __reduce__(self):\n return 'sentinel'\n \n \nsentinel=_Sentinel()\n\nDEFAULT=sentinel.DEFAULT\n_missing=sentinel.MISSING\n_deleted=sentinel.DELETED\n\n\n_allowed_names={\n'return_value','_mock_return_value','side_effect',\n'_mock_side_effect','_mock_parent','_mock_new_parent',\n'_mock_name','_mock_new_name'\n}\n\n\ndef _delegating_property(name):\n _allowed_names.add(name)\n _the_name='_mock_'+name\n def _get(self,name=name,_the_name=_the_name):\n sig=self._mock_delegate\n if sig is None:\n return getattr(self,_the_name)\n return getattr(sig,name)\n def _set(self,value,name=name,_the_name=_the_name):\n sig=self._mock_delegate\n if sig is None:\n self.__dict__[_the_name]=value\n else:\n setattr(sig,name,value)\n \n return property(_get,_set)\n \n \n \nclass _CallList(list):\n\n def __contains__(self,value):\n if not isinstance(value,list):\n return list.__contains__(self,value)\n len_value=len(value)\n len_self=len(self)\n if len_value >len_self:\n return False\n \n for i in range(0,len_self -len_value+1):\n sub_list=self[i:i+len_value]\n if sub_list ==value:\n return True\n return False\n \n def __repr__(self):\n return pprint.pformat(list(self))\n \n \ndef _check_and_set_parent(parent,value,name,new_name):\n value=_extract_mock(value)\n \n if not _is_instance_mock(value):\n return False\n if((value._mock_name or value._mock_new_name)or\n (value._mock_parent is not None)or\n (value._mock_new_parent is not None)):\n return False\n \n _parent=parent\n while _parent is not None:\n \n \n if _parent is value:\n return False\n _parent=_parent._mock_new_parent\n \n if new_name:\n value._mock_new_parent=parent\n value._mock_new_name=new_name\n if name:\n value._mock_parent=parent\n value._mock_name=name\n return True\n \n \nclass _MockIter(object):\n def __init__(self,obj):\n self.obj=iter(obj)\n def __next__(self):\n return next(self.obj)\n \nclass Base(object):\n _mock_return_value=DEFAULT\n _mock_side_effect=None\n def __init__(self,/,*args,**kwargs):\n pass\n \n \n \nclass NonCallableMock(Base):\n ''\n \n \n \n \n \n \n \n _lock=RLock()\n \n def __new__(\n cls,spec=None,wraps=None,name=None,spec_set=None,\n parent=None,_spec_state=None,_new_name='',_new_parent=None,\n _spec_as_instance=False,_eat_self=None,unsafe=False,**kwargs\n ):\n \n \n \n bases=(cls,)\n if not issubclass(cls,AsyncMockMixin):\n \n spec_arg=spec_set or spec\n if spec_arg is not None and _is_async_obj(spec_arg):\n bases=(AsyncMockMixin,cls)\n new=type(cls.__name__,bases,{'__doc__':cls.__doc__})\n instance=_safe_super(NonCallableMock,cls).__new__(new)\n return instance\n \n \n def __init__(\n self,spec=None,wraps=None,name=None,spec_set=None,\n parent=None,_spec_state=None,_new_name='',_new_parent=None,\n _spec_as_instance=False,_eat_self=None,unsafe=False,**kwargs\n ):\n if _new_parent is None:\n _new_parent=parent\n \n __dict__=self.__dict__\n __dict__['_mock_parent']=parent\n __dict__['_mock_name']=name\n __dict__['_mock_new_name']=_new_name\n __dict__['_mock_new_parent']=_new_parent\n __dict__['_mock_sealed']=False\n \n if spec_set is not None:\n spec=spec_set\n spec_set=True\n if _eat_self is None:\n _eat_self=parent is not None\n \n self._mock_add_spec(spec,spec_set,_spec_as_instance,_eat_self)\n \n __dict__['_mock_children']={}\n __dict__['_mock_wraps']=wraps\n __dict__['_mock_delegate']=None\n \n __dict__['_mock_called']=False\n __dict__['_mock_call_args']=None\n __dict__['_mock_call_count']=0\n __dict__['_mock_call_args_list']=_CallList()\n __dict__['_mock_mock_calls']=_CallList()\n \n __dict__['method_calls']=_CallList()\n __dict__['_mock_unsafe']=unsafe\n \n if kwargs:\n self.configure_mock(**kwargs)\n \n _safe_super(NonCallableMock,self).__init__(\n spec,wraps,name,spec_set,parent,\n _spec_state\n )\n \n \n def attach_mock(self,mock,attribute):\n ''\n\n\n \n inner_mock=_extract_mock(mock)\n \n inner_mock._mock_parent=None\n inner_mock._mock_new_parent=None\n inner_mock._mock_name=''\n inner_mock._mock_new_name=None\n \n setattr(self,attribute,mock)\n \n \n def mock_add_spec(self,spec,spec_set=False):\n ''\n\n\n\n \n self._mock_add_spec(spec,spec_set)\n \n \n def _mock_add_spec(self,spec,spec_set,_spec_as_instance=False,\n _eat_self=False):\n if _is_instance_mock(spec):\n raise InvalidSpecError(f'Cannot spec a Mock object. [object={spec !r}]')\n \n _spec_class=None\n _spec_signature=None\n _spec_asyncs=[]\n \n if spec is not None and not _is_list(spec):\n if isinstance(spec,type):\n _spec_class=spec\n else:\n _spec_class=type(spec)\n res=_get_signature_object(spec,\n _spec_as_instance,_eat_self)\n _spec_signature=res and res[1]\n \n spec_list=dir(spec)\n \n for attr in spec_list:\n static_attr=inspect.getattr_static(spec,attr,None)\n unwrapped_attr=static_attr\n try:\n unwrapped_attr=inspect.unwrap(unwrapped_attr)\n except ValueError:\n pass\n if iscoroutinefunction(unwrapped_attr):\n _spec_asyncs.append(attr)\n \n spec=spec_list\n \n __dict__=self.__dict__\n __dict__['_spec_class']=_spec_class\n __dict__['_spec_set']=spec_set\n __dict__['_spec_signature']=_spec_signature\n __dict__['_mock_methods']=spec\n __dict__['_spec_asyncs']=_spec_asyncs\n \n def __get_return_value(self):\n ret=self._mock_return_value\n if self._mock_delegate is not None:\n ret=self._mock_delegate.return_value\n \n if ret is DEFAULT and self._mock_wraps is None:\n ret=self._get_child_mock(\n _new_parent=self,_new_name='()'\n )\n self.return_value=ret\n return ret\n \n \n def __set_return_value(self,value):\n if self._mock_delegate is not None:\n self._mock_delegate.return_value=value\n else:\n self._mock_return_value=value\n _check_and_set_parent(self,value,None,'()')\n \n __return_value_doc=\"The value to be returned when the mock is called.\"\n return_value=property(__get_return_value,__set_return_value,\n __return_value_doc)\n \n \n @property\n def __class__(self):\n if self._spec_class is None:\n return type(self)\n return self._spec_class\n \n called=_delegating_property('called')\n call_count=_delegating_property('call_count')\n call_args=_delegating_property('call_args')\n call_args_list=_delegating_property('call_args_list')\n mock_calls=_delegating_property('mock_calls')\n \n \n def __get_side_effect(self):\n delegated=self._mock_delegate\n if delegated is None:\n return self._mock_side_effect\n sf=delegated.side_effect\n if(sf is not None and not callable(sf)\n and not isinstance(sf,_MockIter)and not _is_exception(sf)):\n sf=_MockIter(sf)\n delegated.side_effect=sf\n return sf\n \n def __set_side_effect(self,value):\n value=_try_iter(value)\n delegated=self._mock_delegate\n if delegated is None:\n self._mock_side_effect=value\n else:\n delegated.side_effect=value\n \n side_effect=property(__get_side_effect,__set_side_effect)\n \n \n def reset_mock(self,visited=None,*,return_value=False,side_effect=False):\n ''\n if visited is None:\n visited=[]\n if id(self)in visited:\n return\n visited.append(id(self))\n \n self.called=False\n self.call_args=None\n self.call_count=0\n self.mock_calls=_CallList()\n self.call_args_list=_CallList()\n self.method_calls=_CallList()\n \n if return_value:\n self._mock_return_value=DEFAULT\n if side_effect:\n self._mock_side_effect=None\n \n for child in self._mock_children.values():\n if isinstance(child,_SpecState)or child is _deleted:\n continue\n child.reset_mock(visited,return_value=return_value,side_effect=side_effect)\n \n ret=self._mock_return_value\n if _is_instance_mock(ret)and ret is not self:\n ret.reset_mock(visited)\n \n \n def configure_mock(self,/,**kwargs):\n ''\n\n\n\n\n\n\n \n for arg,val in sorted(kwargs.items(),\n \n \n \n key=lambda entry:entry[0].count('.')):\n args=arg.split('.')\n final=args.pop()\n obj=self\n for entry in args:\n obj=getattr(obj,entry)\n setattr(obj,final,val)\n \n \n def __getattr__(self,name):\n if name in{'_mock_methods','_mock_unsafe'}:\n raise AttributeError(name)\n elif self._mock_methods is not None:\n if name not in self._mock_methods or name in _all_magics:\n raise AttributeError(\"Mock object has no attribute %r\"%name)\n elif _is_magic(name):\n raise AttributeError(name)\n if not self._mock_unsafe and(not self._mock_methods or name not in self._mock_methods):\n if name.startswith(('assert','assret','asert','aseert','assrt'))or name in _ATTRIB_DENY_LIST:\n raise AttributeError(\n f\"{name !r} is not a valid assertion. Use a spec \"\n f\"for the mock if {name !r} is meant to be an attribute.\")\n \n with NonCallableMock._lock:\n result=self._mock_children.get(name)\n if result is _deleted:\n raise AttributeError(name)\n elif result is None:\n wraps=None\n if self._mock_wraps is not None:\n \n \n wraps=getattr(self._mock_wraps,name)\n \n result=self._get_child_mock(\n parent=self,name=name,wraps=wraps,_new_name=name,\n _new_parent=self\n )\n self._mock_children[name]=result\n \n elif isinstance(result,_SpecState):\n try:\n result=create_autospec(\n result.spec,result.spec_set,result.instance,\n result.parent,result.name\n )\n except InvalidSpecError:\n target_name=self.__dict__['_mock_name']or self\n raise InvalidSpecError(\n f'Cannot autospec attr {name !r} from target '\n f'{target_name !r} as it has already been mocked out. '\n f'[target={self !r}, attr={result.spec !r}]')\n self._mock_children[name]=result\n \n return result\n \n \n def _extract_mock_name(self):\n _name_list=[self._mock_new_name]\n _parent=self._mock_new_parent\n last=self\n \n dot='.'\n if _name_list ==['()']:\n dot=''\n \n while _parent is not None:\n last=_parent\n \n _name_list.append(_parent._mock_new_name+dot)\n dot='.'\n if _parent._mock_new_name =='()':\n dot=''\n \n _parent=_parent._mock_new_parent\n \n _name_list=list(reversed(_name_list))\n _first=last._mock_name or 'mock'\n if len(_name_list)>1:\n if _name_list[1]not in('()','().'):\n _first +='.'\n _name_list[0]=_first\n return ''.join(_name_list)\n \n def __repr__(self):\n name=self._extract_mock_name()\n \n name_string=''\n if name not in('mock','mock.'):\n name_string=' name=%r'%name\n \n spec_string=''\n if self._spec_class is not None:\n spec_string=' spec=%r'\n if self._spec_set:\n spec_string=' spec_set=%r'\n spec_string=spec_string %self._spec_class.__name__\n return \"<%s%s%s id='%s'>\"%(\n type(self).__name__,\n name_string,\n spec_string,\n id(self)\n )\n \n \n def __dir__(self):\n ''\n if not FILTER_DIR:\n return object.__dir__(self)\n \n extras=self._mock_methods or[]\n from_type=dir(type(self))\n from_dict=list(self.__dict__)\n from_child_mocks=[\n m_name for m_name,m_value in self._mock_children.items()\n if m_value is not _deleted]\n \n from_type=[e for e in from_type if not e.startswith('_')]\n from_dict=[e for e in from_dict if not e.startswith('_')or\n _is_magic(e)]\n return sorted(set(extras+from_type+from_dict+from_child_mocks))\n \n \n def __setattr__(self,name,value):\n if name in _allowed_names:\n \n return object.__setattr__(self,name,value)\n elif(self._spec_set and self._mock_methods is not None and\n name not in self._mock_methods and\n name not in self.__dict__):\n raise AttributeError(\"Mock object has no attribute '%s'\"%name)\n elif name in _unsupported_magics:\n msg='Attempting to set unsupported magic method %r.'%name\n raise AttributeError(msg)\n elif name in _all_magics:\n if self._mock_methods is not None and name not in self._mock_methods:\n raise AttributeError(\"Mock object has no attribute '%s'\"%name)\n \n if not _is_instance_mock(value):\n setattr(type(self),name,_get_method(name,value))\n original=value\n value=lambda *args,**kw:original(self,*args,**kw)\n else:\n \n \n _check_and_set_parent(self,value,None,name)\n setattr(type(self),name,value)\n self._mock_children[name]=value\n elif name =='__class__':\n self._spec_class=value\n return\n else:\n if _check_and_set_parent(self,value,name,name):\n self._mock_children[name]=value\n \n if self._mock_sealed and not hasattr(self,name):\n mock_name=f'{self._extract_mock_name()}.{name}'\n raise AttributeError(f'Cannot set {mock_name}')\n \n return object.__setattr__(self,name,value)\n \n \n def __delattr__(self,name):\n if name in _all_magics and name in type(self).__dict__:\n delattr(type(self),name)\n if name not in self.__dict__:\n \n \n return\n \n obj=self._mock_children.get(name,_missing)\n if name in self.__dict__:\n _safe_super(NonCallableMock,self).__delattr__(name)\n elif obj is _deleted:\n raise AttributeError(name)\n if obj is not _missing:\n del self._mock_children[name]\n self._mock_children[name]=_deleted\n \n \n def _format_mock_call_signature(self,args,kwargs):\n name=self._mock_name or 'mock'\n return _format_call_signature(name,args,kwargs)\n \n \n def _format_mock_failure_message(self,args,kwargs,action='call'):\n message='expected %s not found.\\nExpected: %s\\n Actual: %s'\n expected_string=self._format_mock_call_signature(args,kwargs)\n call_args=self.call_args\n actual_string=self._format_mock_call_signature(*call_args)\n return message %(action,expected_string,actual_string)\n \n \n def _get_call_signature_from_name(self,name):\n ''\n\n\n\n\n\n\n\n\n \n if not name:\n return self._spec_signature\n \n sig=None\n names=name.replace('()','').split('.')\n children=self._mock_children\n \n for name in names:\n child=children.get(name)\n if child is None or isinstance(child,_SpecState):\n break\n else:\n \n \n \n child=_extract_mock(child)\n children=child._mock_children\n sig=child._spec_signature\n \n return sig\n \n \n def _call_matcher(self,_call):\n ''\n\n\n\n\n \n \n if isinstance(_call,tuple)and len(_call)>2:\n sig=self._get_call_signature_from_name(_call[0])\n else:\n sig=self._spec_signature\n \n if sig is not None:\n if len(_call)==2:\n name=''\n args,kwargs=_call\n else:\n name,args,kwargs=_call\n try:\n bound_call=sig.bind(*args,**kwargs)\n return call(name,bound_call.args,bound_call.kwargs)\n except TypeError as e:\n return e.with_traceback(None)\n else:\n return _call\n \n def assert_not_called(self):\n ''\n \n if self.call_count !=0:\n msg=(\"Expected '%s' to not have been called. Called %s times.%s\"\n %(self._mock_name or 'mock',\n self.call_count,\n self._calls_repr()))\n raise AssertionError(msg)\n \n def assert_called(self):\n ''\n \n if self.call_count ==0:\n msg=(\"Expected '%s' to have been called.\"%\n (self._mock_name or 'mock'))\n raise AssertionError(msg)\n \n def assert_called_once(self):\n ''\n \n if not self.call_count ==1:\n msg=(\"Expected '%s' to have been called once. Called %s times.%s\"\n %(self._mock_name or 'mock',\n self.call_count,\n self._calls_repr()))\n raise AssertionError(msg)\n \n def assert_called_with(self,/,*args,**kwargs):\n ''\n\n\n \n if self.call_args is None:\n expected=self._format_mock_call_signature(args,kwargs)\n actual='not called.'\n error_message=('expected call not found.\\nExpected: %s\\n Actual: %s'\n %(expected,actual))\n raise AssertionError(error_message)\n \n def _error_message():\n msg=self._format_mock_failure_message(args,kwargs)\n return msg\n expected=self._call_matcher(_Call((args,kwargs),two=True))\n actual=self._call_matcher(self.call_args)\n if actual !=expected:\n cause=expected if isinstance(expected,Exception)else None\n raise AssertionError(_error_message())from cause\n \n \n def assert_called_once_with(self,/,*args,**kwargs):\n ''\n \n if not self.call_count ==1:\n msg=(\"Expected '%s' to be called once. Called %s times.%s\"\n %(self._mock_name or 'mock',\n self.call_count,\n self._calls_repr()))\n raise AssertionError(msg)\n return self.assert_called_with(*args,**kwargs)\n \n \n def assert_has_calls(self,calls,any_order=False):\n ''\n\n\n\n\n\n\n\n \n expected=[self._call_matcher(c)for c in calls]\n cause=next((e for e in expected if isinstance(e,Exception)),None)\n all_calls=_CallList(self._call_matcher(c)for c in self.mock_calls)\n if not any_order:\n if expected not in all_calls:\n if cause is None:\n problem='Calls not found.'\n else:\n problem=('Error processing expected calls.\\n'\n 'Errors: {}').format(\n [e if isinstance(e,Exception)else None\n for e in expected])\n raise AssertionError(\n f'{problem}\\n'\n f'Expected: {_CallList(calls)}\\n'\n f' Actual: {safe_repr(self.mock_calls)}'\n )from cause\n return\n \n all_calls=list(all_calls)\n \n not_found=[]\n for kall in expected:\n try:\n all_calls.remove(kall)\n except ValueError:\n not_found.append(kall)\n if not_found:\n raise AssertionError(\n '%r does not contain all of %r in its call list, '\n 'found %r instead'%(self._mock_name or 'mock',\n tuple(not_found),all_calls)\n )from cause\n \n \n def assert_any_call(self,/,*args,**kwargs):\n ''\n\n\n\n \n expected=self._call_matcher(_Call((args,kwargs),two=True))\n cause=expected if isinstance(expected,Exception)else None\n actual=[self._call_matcher(c)for c in self.call_args_list]\n if cause or expected not in _AnyComparer(actual):\n expected_string=self._format_mock_call_signature(args,kwargs)\n raise AssertionError(\n '%s call not found'%expected_string\n )from cause\n \n \n def _get_child_mock(self,/,**kw):\n ''\n\n\n\n\n\n \n if self._mock_sealed:\n attribute=f\".{kw['name']}\"if \"name\"in kw else \"()\"\n mock_name=self._extract_mock_name()+attribute\n raise AttributeError(mock_name)\n \n _new_name=kw.get(\"_new_name\")\n if _new_name in self.__dict__['_spec_asyncs']:\n return AsyncMock(**kw)\n \n _type=type(self)\n if issubclass(_type,MagicMock)and _new_name in _async_method_magics:\n \n klass=AsyncMock\n elif issubclass(_type,AsyncMockMixin):\n if(_new_name in _all_sync_magics or\n self._mock_methods and _new_name in self._mock_methods):\n \n klass=MagicMock\n else:\n klass=AsyncMock\n elif not issubclass(_type,CallableMixin):\n if issubclass(_type,NonCallableMagicMock):\n klass=MagicMock\n elif issubclass(_type,NonCallableMock):\n klass=Mock\n else:\n klass=_type.__mro__[1]\n return klass(**kw)\n \n \n def _calls_repr(self):\n ''\n\n\n\n\n\n \n if not self.mock_calls:\n return \"\"\n return f\"\\nCalls: {safe_repr(self.mock_calls)}.\"\n \n \n \n_ATTRIB_DENY_LIST=frozenset({\nname.removeprefix(\"assert_\")\nfor name in dir(NonCallableMock)\nif name.startswith(\"assert_\")\n})\n\n\nclass _AnyComparer(list):\n ''\n\n\n \n def __contains__(self,item):\n for _call in self:\n assert len(item)==len(_call)\n if all([\n expected ==actual\n for expected,actual in zip(item,_call)\n ]):\n return True\n return False\n \n \ndef _try_iter(obj):\n if obj is None:\n return obj\n if _is_exception(obj):\n return obj\n if _callable(obj):\n return obj\n try:\n return iter(obj)\n except TypeError:\n \n \n return obj\n \n \nclass CallableMixin(Base):\n\n def __init__(self,spec=None,side_effect=None,return_value=DEFAULT,\n wraps=None,name=None,spec_set=None,parent=None,\n _spec_state=None,_new_name='',_new_parent=None,**kwargs):\n self.__dict__['_mock_return_value']=return_value\n _safe_super(CallableMixin,self).__init__(\n spec,wraps,name,spec_set,parent,\n _spec_state,_new_name,_new_parent,**kwargs\n )\n \n self.side_effect=side_effect\n \n \n def _mock_check_sig(self,/,*args,**kwargs):\n \n pass\n \n \n def __call__(self,/,*args,**kwargs):\n \n \n self._mock_check_sig(*args,**kwargs)\n self._increment_mock_call(*args,**kwargs)\n return self._mock_call(*args,**kwargs)\n \n \n def _mock_call(self,/,*args,**kwargs):\n return self._execute_mock_call(*args,**kwargs)\n \n def _increment_mock_call(self,/,*args,**kwargs):\n self.called=True\n self.call_count +=1\n \n \n \n \n _call=_Call((args,kwargs),two=True)\n self.call_args=_call\n self.call_args_list.append(_call)\n \n \n do_method_calls=self._mock_parent is not None\n method_call_name=self._mock_name\n \n \n mock_call_name=self._mock_new_name\n is_a_call=mock_call_name =='()'\n self.mock_calls.append(_Call(('',args,kwargs)))\n \n \n _new_parent=self._mock_new_parent\n while _new_parent is not None:\n \n \n if do_method_calls:\n _new_parent.method_calls.append(_Call((method_call_name,args,kwargs)))\n do_method_calls=_new_parent._mock_parent is not None\n if do_method_calls:\n method_call_name=_new_parent._mock_name+'.'+method_call_name\n \n \n this_mock_call=_Call((mock_call_name,args,kwargs))\n _new_parent.mock_calls.append(this_mock_call)\n \n if _new_parent._mock_new_name:\n if is_a_call:\n dot=''\n else:\n dot='.'\n is_a_call=_new_parent._mock_new_name =='()'\n mock_call_name=_new_parent._mock_new_name+dot+mock_call_name\n \n \n _new_parent=_new_parent._mock_new_parent\n \n def _execute_mock_call(self,/,*args,**kwargs):\n \n \n \n effect=self.side_effect\n if effect is not None:\n if _is_exception(effect):\n raise effect\n elif not _callable(effect):\n result=next(effect)\n if _is_exception(result):\n raise result\n else:\n result=effect(*args,**kwargs)\n \n if result is not DEFAULT:\n return result\n \n if self._mock_return_value is not DEFAULT:\n return self.return_value\n \n if self._mock_delegate and self._mock_delegate.return_value is not DEFAULT:\n return self.return_value\n \n if self._mock_wraps is not None:\n return self._mock_wraps(*args,**kwargs)\n \n return self.return_value\n \n \n \nclass Mock(CallableMixin,NonCallableMock):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \ndef _check_spec_arg_typos(kwargs_to_check):\n typos=(\"autospect\",\"auto_spec\",\"set_spec\")\n for typo in typos:\n if typo in kwargs_to_check:\n raise RuntimeError(\n f\"{typo !r} might be a typo; use unsafe=True if this is intended\"\n )\n \n \nclass _patch(object):\n\n attribute_name=None\n _active_patches=[]\n \n def __init__(\n self,getter,attribute,new,spec,create,\n spec_set,autospec,new_callable,kwargs,*,unsafe=False\n ):\n if new_callable is not None:\n if new is not DEFAULT:\n raise ValueError(\n \"Cannot use 'new' and 'new_callable' together\"\n )\n if autospec is not None:\n raise ValueError(\n \"Cannot use 'autospec' and 'new_callable' together\"\n )\n if not unsafe:\n _check_spec_arg_typos(kwargs)\n if _is_instance_mock(spec):\n raise InvalidSpecError(\n f'Cannot spec attr {attribute !r} as the spec '\n f'has already been mocked out. [spec={spec !r}]')\n if _is_instance_mock(spec_set):\n raise InvalidSpecError(\n f'Cannot spec attr {attribute !r} as the spec_set '\n f'target has already been mocked out. [spec_set={spec_set !r}]')\n \n self.getter=getter\n self.attribute=attribute\n self.new=new\n self.new_callable=new_callable\n self.spec=spec\n self.create=create\n self.has_local=False\n self.spec_set=spec_set\n self.autospec=autospec\n self.kwargs=kwargs\n self.additional_patchers=[]\n \n \n def copy(self):\n patcher=_patch(\n self.getter,self.attribute,self.new,self.spec,\n self.create,self.spec_set,\n self.autospec,self.new_callable,self.kwargs\n )\n patcher.attribute_name=self.attribute_name\n patcher.additional_patchers=[\n p.copy()for p in self.additional_patchers\n ]\n return patcher\n \n \n def __call__(self,func):\n if isinstance(func,type):\n return self.decorate_class(func)\n if inspect.iscoroutinefunction(func):\n return self.decorate_async_callable(func)\n return self.decorate_callable(func)\n \n \n def decorate_class(self,klass):\n for attr in dir(klass):\n if not attr.startswith(patch.TEST_PREFIX):\n continue\n \n attr_value=getattr(klass,attr)\n if not hasattr(attr_value,\"__call__\"):\n continue\n \n patcher=self.copy()\n setattr(klass,attr,patcher(attr_value))\n return klass\n \n \n @contextlib.contextmanager\n def decoration_helper(self,patched,args,keywargs):\n extra_args=[]\n with contextlib.ExitStack()as exit_stack:\n for patching in patched.patchings:\n arg=exit_stack.enter_context(patching)\n if patching.attribute_name is not None:\n keywargs.update(arg)\n elif patching.new is DEFAULT:\n extra_args.append(arg)\n \n args +=tuple(extra_args)\n yield(args,keywargs)\n \n \n def decorate_callable(self,func):\n \n if hasattr(func,'patchings'):\n func.patchings.append(self)\n return func\n \n @wraps(func)\n def patched(*args,**keywargs):\n with self.decoration_helper(patched,\n args,\n keywargs)as(newargs,newkeywargs):\n return func(*newargs,**newkeywargs)\n \n patched.patchings=[self]\n return patched\n \n \n def decorate_async_callable(self,func):\n \n if hasattr(func,'patchings'):\n func.patchings.append(self)\n return func\n \n @wraps(func)\n async def patched(*args,**keywargs):\n with self.decoration_helper(patched,\n args,\n keywargs)as(newargs,newkeywargs):\n return await func(*newargs,**newkeywargs)\n \n patched.patchings=[self]\n return patched\n \n \n def get_original(self):\n target=self.getter()\n name=self.attribute\n \n original=DEFAULT\n local=False\n \n try:\n original=target.__dict__[name]\n except(AttributeError,KeyError):\n original=getattr(target,name,DEFAULT)\n else:\n local=True\n \n if name in _builtins and isinstance(target,ModuleType):\n self.create=True\n \n if not self.create and original is DEFAULT:\n raise AttributeError(\n \"%s does not have the attribute %r\"%(target,name)\n )\n return original,local\n \n \n def __enter__(self):\n ''\n new,spec,spec_set=self.new,self.spec,self.spec_set\n autospec,kwargs=self.autospec,self.kwargs\n new_callable=self.new_callable\n self.target=self.getter()\n \n \n if spec is False:\n spec=None\n if spec_set is False:\n spec_set=None\n if autospec is False:\n autospec=None\n \n if spec is not None and autospec is not None:\n raise TypeError(\"Can't specify spec and autospec\")\n if((spec is not None or autospec is not None)and\n spec_set not in(True,None)):\n raise TypeError(\"Can't provide explicit spec_set *and* spec or autospec\")\n \n original,local=self.get_original()\n \n if new is DEFAULT and autospec is None:\n inherit=False\n if spec is True:\n \n spec=original\n if spec_set is True:\n spec_set=original\n spec=None\n elif spec is not None:\n if spec_set is True:\n spec_set=spec\n spec=None\n elif spec_set is True:\n spec_set=original\n \n if spec is not None or spec_set is not None:\n if original is DEFAULT:\n raise TypeError(\"Can't use 'spec' with create=True\")\n if isinstance(original,type):\n \n inherit=True\n if spec is None and _is_async_obj(original):\n Klass=AsyncMock\n else:\n Klass=MagicMock\n _kwargs={}\n if new_callable is not None:\n Klass=new_callable\n elif spec is not None or spec_set is not None:\n this_spec=spec\n if spec_set is not None:\n this_spec=spec_set\n if _is_list(this_spec):\n not_callable='__call__'not in this_spec\n else:\n not_callable=not callable(this_spec)\n if _is_async_obj(this_spec):\n Klass=AsyncMock\n elif not_callable:\n Klass=NonCallableMagicMock\n \n if spec is not None:\n _kwargs['spec']=spec\n if spec_set is not None:\n _kwargs['spec_set']=spec_set\n \n \n if(isinstance(Klass,type)and\n issubclass(Klass,NonCallableMock)and self.attribute):\n _kwargs['name']=self.attribute\n \n _kwargs.update(kwargs)\n new=Klass(**_kwargs)\n \n if inherit and _is_instance_mock(new):\n \n \n this_spec=spec\n if spec_set is not None:\n this_spec=spec_set\n if(not _is_list(this_spec)and not\n _instance_callable(this_spec)):\n Klass=NonCallableMagicMock\n \n _kwargs.pop('name')\n new.return_value=Klass(_new_parent=new,_new_name='()',\n **_kwargs)\n elif autospec is not None:\n \n \n \n if new is not DEFAULT:\n raise TypeError(\n \"autospec creates the mock for you. Can't specify \"\n \"autospec and new.\"\n )\n if original is DEFAULT:\n raise TypeError(\"Can't use 'autospec' with create=True\")\n spec_set=bool(spec_set)\n if autospec is True:\n autospec=original\n \n if _is_instance_mock(self.target):\n raise InvalidSpecError(\n f'Cannot autospec attr {self.attribute !r} as the patch '\n f'target has already been mocked out. '\n f'[target={self.target !r}, attr={autospec !r}]')\n if _is_instance_mock(autospec):\n target_name=getattr(self.target,'__name__',self.target)\n raise InvalidSpecError(\n f'Cannot autospec attr {self.attribute !r} from target '\n f'{target_name !r} as it has already been mocked out. '\n f'[target={self.target !r}, attr={autospec !r}]')\n \n new=create_autospec(autospec,spec_set=spec_set,\n _name=self.attribute,**kwargs)\n elif kwargs:\n \n \n raise TypeError(\"Can't pass kwargs to a mock we aren't creating\")\n \n new_attr=new\n \n self.temp_original=original\n self.is_local=local\n self._exit_stack=contextlib.ExitStack()\n try:\n setattr(self.target,self.attribute,new_attr)\n if self.attribute_name is not None:\n extra_args={}\n if self.new is DEFAULT:\n extra_args[self.attribute_name]=new\n for patching in self.additional_patchers:\n arg=self._exit_stack.enter_context(patching)\n if patching.new is DEFAULT:\n extra_args.update(arg)\n return extra_args\n \n return new\n except:\n if not self.__exit__(*sys.exc_info()):\n raise\n \n def __exit__(self,*exc_info):\n ''\n if self.is_local and self.temp_original is not DEFAULT:\n setattr(self.target,self.attribute,self.temp_original)\n else:\n delattr(self.target,self.attribute)\n if not self.create and(not hasattr(self.target,self.attribute)or\n self.attribute in('__doc__','__module__',\n '__defaults__','__annotations__',\n '__kwdefaults__')):\n \n setattr(self.target,self.attribute,self.temp_original)\n \n del self.temp_original\n del self.is_local\n del self.target\n exit_stack=self._exit_stack\n del self._exit_stack\n return exit_stack.__exit__(*exc_info)\n \n \n def start(self):\n ''\n result=self.__enter__()\n self._active_patches.append(self)\n return result\n \n \n def stop(self):\n ''\n try:\n self._active_patches.remove(self)\n except ValueError:\n \n return None\n \n return self.__exit__(None,None,None)\n \n \n \ndef _get_target(target):\n try:\n target,attribute=target.rsplit('.',1)\n except(TypeError,ValueError,AttributeError):\n raise TypeError(\n f\"Need a valid target to patch. You supplied: {target !r}\")\n return partial(pkgutil.resolve_name,target),attribute\n \n \ndef _patch_object(\ntarget,attribute,new=DEFAULT,spec=None,\ncreate=False,spec_set=None,autospec=None,\nnew_callable=None,*,unsafe=False,**kwargs\n):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if type(target)is str:\n raise TypeError(\n f\"{target !r} must be the actual object to be patched, not a str\"\n )\n getter=lambda:target\n return _patch(\n getter,attribute,new,spec,create,\n spec_set,autospec,new_callable,kwargs,unsafe=unsafe\n )\n \n \ndef _patch_multiple(target,spec=None,create=False,spec_set=None,\nautospec=None,new_callable=None,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if type(target)is str:\n getter=partial(pkgutil.resolve_name,target)\n else:\n getter=lambda:target\n \n if not kwargs:\n raise ValueError(\n 'Must supply at least one keyword argument with patch.multiple'\n )\n \n items=list(kwargs.items())\n attribute,new=items[0]\n patcher=_patch(\n getter,attribute,new,spec,create,spec_set,\n autospec,new_callable,{}\n )\n patcher.attribute_name=attribute\n for attribute,new in items[1:]:\n this_patcher=_patch(\n getter,attribute,new,spec,create,spec_set,\n autospec,new_callable,{}\n )\n this_patcher.attribute_name=attribute\n patcher.additional_patchers.append(this_patcher)\n return patcher\n \n \ndef patch(\ntarget,new=DEFAULT,spec=None,create=False,\nspec_set=None,autospec=None,new_callable=None,*,unsafe=False,**kwargs\n):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n getter,attribute=_get_target(target)\n return _patch(\n getter,attribute,new,spec,create,\n spec_set,autospec,new_callable,kwargs,unsafe=unsafe\n )\n \n \nclass _patch_dict(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,in_dict,values=(),clear=False,**kwargs):\n self.in_dict=in_dict\n \n self.values=dict(values)\n self.values.update(kwargs)\n self.clear=clear\n self._original=None\n \n \n def __call__(self,f):\n if isinstance(f,type):\n return self.decorate_class(f)\n if inspect.iscoroutinefunction(f):\n return self.decorate_async_callable(f)\n return self.decorate_callable(f)\n \n \n def decorate_callable(self,f):\n @wraps(f)\n def _inner(*args,**kw):\n self._patch_dict()\n try:\n return f(*args,**kw)\n finally:\n self._unpatch_dict()\n \n return _inner\n \n \n def decorate_async_callable(self,f):\n @wraps(f)\n async def _inner(*args,**kw):\n self._patch_dict()\n try:\n return await f(*args,**kw)\n finally:\n self._unpatch_dict()\n \n return _inner\n \n \n def decorate_class(self,klass):\n for attr in dir(klass):\n attr_value=getattr(klass,attr)\n if(attr.startswith(patch.TEST_PREFIX)and\n hasattr(attr_value,\"__call__\")):\n decorator=_patch_dict(self.in_dict,self.values,self.clear)\n decorated=decorator(attr_value)\n setattr(klass,attr,decorated)\n return klass\n \n \n def __enter__(self):\n ''\n self._patch_dict()\n return self.in_dict\n \n \n def _patch_dict(self):\n values=self.values\n if isinstance(self.in_dict,str):\n self.in_dict=pkgutil.resolve_name(self.in_dict)\n in_dict=self.in_dict\n clear=self.clear\n \n try:\n original=in_dict.copy()\n except AttributeError:\n \n \n original={}\n for key in in_dict:\n original[key]=in_dict[key]\n self._original=original\n \n if clear:\n _clear_dict(in_dict)\n \n try:\n in_dict.update(values)\n except AttributeError:\n \n for key in values:\n in_dict[key]=values[key]\n \n \n def _unpatch_dict(self):\n in_dict=self.in_dict\n original=self._original\n \n _clear_dict(in_dict)\n \n try:\n in_dict.update(original)\n except AttributeError:\n for key in original:\n in_dict[key]=original[key]\n \n \n def __exit__(self,*args):\n ''\n if self._original is not None:\n self._unpatch_dict()\n return False\n \n \n def start(self):\n ''\n result=self.__enter__()\n _patch._active_patches.append(self)\n return result\n \n \n def stop(self):\n ''\n try:\n _patch._active_patches.remove(self)\n except ValueError:\n \n return None\n \n return self.__exit__(None,None,None)\n \n \ndef _clear_dict(in_dict):\n try:\n in_dict.clear()\n except AttributeError:\n keys=list(in_dict)\n for key in keys:\n del in_dict[key]\n \n \ndef _patch_stopall():\n ''\n for patch in reversed(_patch._active_patches):\n patch.stop()\n \n \npatch.object=_patch_object\npatch.dict=_patch_dict\npatch.multiple=_patch_multiple\npatch.stopall=_patch_stopall\npatch.TEST_PREFIX='test'\n\nmagic_methods=(\n\"lt le gt ge eq ne \"\n\"getitem setitem delitem \"\n\"len contains iter \"\n\"hash str sizeof \"\n\"enter exit \"\n\n\n\"divmod rdivmod neg pos abs invert \"\n\"complex int float index \"\n\"round trunc floor ceil \"\n\"bool next \"\n\"fspath \"\n\"aiter \"\n)\n\nnumerics=(\n\"add sub mul matmul truediv floordiv mod lshift rshift and xor or pow\"\n)\ninplace=' '.join('i%s'%n for n in numerics.split())\nright=' '.join('r%s'%n for n in numerics.split())\n\n\n\n\n\n_non_defaults={\n'__get__','__set__','__delete__','__reversed__','__missing__',\n'__reduce__','__reduce_ex__','__getinitargs__','__getnewargs__',\n'__getstate__','__setstate__','__getformat__',\n'__repr__','__dir__','__subclasses__','__format__',\n'__getnewargs_ex__',\n}\n\n\ndef _get_method(name,func):\n ''\n def method(self,/,*args,**kw):\n return func(self,*args,**kw)\n method.__name__=name\n return method\n \n \n_magics={\n'__%s__'%method for method in\n' '.join([magic_methods,numerics,inplace,right]).split()\n}\n\n\n_async_method_magics={\"__aenter__\",\"__aexit__\",\"__anext__\"}\n\n_sync_async_magics={\"__aiter__\"}\n_async_magics=_async_method_magics |_sync_async_magics\n\n_all_sync_magics=_magics |_non_defaults\n_all_magics=_all_sync_magics |_async_magics\n\n_unsupported_magics={\n'__getattr__','__setattr__',\n'__init__','__new__','__prepare__',\n'__instancecheck__','__subclasscheck__',\n'__del__'\n}\n\n_calculate_return_value={\n'__hash__':lambda self:object.__hash__(self),\n'__str__':lambda self:object.__str__(self),\n'__sizeof__':lambda self:object.__sizeof__(self),\n'__fspath__':lambda self:f\"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}\",\n}\n\n_return_values={\n'__lt__':NotImplemented,\n'__gt__':NotImplemented,\n'__le__':NotImplemented,\n'__ge__':NotImplemented,\n'__int__':1,\n'__contains__':False,\n'__len__':0,\n'__exit__':False,\n'__complex__':1j,\n'__float__':1.0,\n'__bool__':True,\n'__index__':1,\n'__aexit__':False,\n}\n\n\ndef _get_eq(self):\n def __eq__(other):\n ret_val=self.__eq__._mock_return_value\n if ret_val is not DEFAULT:\n return ret_val\n if self is other:\n return True\n return NotImplemented\n return __eq__\n \ndef _get_ne(self):\n def __ne__(other):\n if self.__ne__._mock_return_value is not DEFAULT:\n return DEFAULT\n if self is other:\n return False\n return NotImplemented\n return __ne__\n \ndef _get_iter(self):\n def __iter__():\n ret_val=self.__iter__._mock_return_value\n if ret_val is DEFAULT:\n return iter([])\n \n \n return iter(ret_val)\n return __iter__\n \ndef _get_async_iter(self):\n def __aiter__():\n ret_val=self.__aiter__._mock_return_value\n if ret_val is DEFAULT:\n return _AsyncIterator(iter([]))\n return _AsyncIterator(iter(ret_val))\n return __aiter__\n \n_side_effect_methods={\n'__eq__':_get_eq,\n'__ne__':_get_ne,\n'__iter__':_get_iter,\n'__aiter__':_get_async_iter\n}\n\n\n\ndef _set_return_value(mock,method,name):\n fixed=_return_values.get(name,DEFAULT)\n if fixed is not DEFAULT:\n method.return_value=fixed\n return\n \n return_calculator=_calculate_return_value.get(name)\n if return_calculator is not None:\n return_value=return_calculator(mock)\n method.return_value=return_value\n return\n \n side_effector=_side_effect_methods.get(name)\n if side_effector is not None:\n method.side_effect=side_effector(mock)\n \n \n \nclass MagicMixin(Base):\n def __init__(self,/,*args,**kw):\n self._mock_set_magics()\n _safe_super(MagicMixin,self).__init__(*args,**kw)\n self._mock_set_magics()\n \n \n def _mock_set_magics(self):\n orig_magics=_magics |_async_method_magics\n these_magics=orig_magics\n \n if getattr(self,\"_mock_methods\",None)is not None:\n these_magics=orig_magics.intersection(self._mock_methods)\n \n remove_magics=set()\n remove_magics=orig_magics -these_magics\n \n for entry in remove_magics:\n if entry in type(self).__dict__:\n \n delattr(self,entry)\n \n \n these_magics=these_magics -set(type(self).__dict__)\n \n _type=type(self)\n for entry in these_magics:\n setattr(_type,entry,MagicProxy(entry,self))\n \n \n \nclass NonCallableMagicMock(MagicMixin,NonCallableMock):\n ''\n def mock_add_spec(self,spec,spec_set=False):\n ''\n\n\n\n \n self._mock_add_spec(spec,spec_set)\n self._mock_set_magics()\n \n \nclass AsyncMagicMixin(MagicMixin):\n pass\n \n \nclass MagicMock(MagicMixin,Mock):\n ''\n\n\n\n\n\n\n\n\n \n def mock_add_spec(self,spec,spec_set=False):\n ''\n\n\n\n \n self._mock_add_spec(spec,spec_set)\n self._mock_set_magics()\n \n \n \nclass MagicProxy(Base):\n def __init__(self,name,parent):\n self.name=name\n self.parent=parent\n \n def create_mock(self):\n entry=self.name\n parent=self.parent\n m=parent._get_child_mock(name=entry,_new_name=entry,\n _new_parent=parent)\n setattr(parent,entry,m)\n _set_return_value(parent,m,entry)\n return m\n \n def __get__(self,obj,_type=None):\n return self.create_mock()\n \n \ntry:\n _CODE_SIG=inspect.signature(partial(CodeType.__init__,None))\n _CODE_ATTRS=dir(CodeType)\nexcept ValueError:\n _CODE_SIG=None\n \n \nclass AsyncMockMixin(Base):\n await_count=_delegating_property('await_count')\n await_args=_delegating_property('await_args')\n await_args_list=_delegating_property('await_args_list')\n \n def __init__(self,/,*args,**kwargs):\n super().__init__(*args,**kwargs)\n \n \n \n \n \n \n self.__dict__['_is_coroutine']=asyncio.coroutines._is_coroutine\n self.__dict__['_mock_await_count']=0\n self.__dict__['_mock_await_args']=None\n self.__dict__['_mock_await_args_list']=_CallList()\n if _CODE_SIG:\n code_mock=NonCallableMock(spec_set=_CODE_ATTRS)\n code_mock.__dict__[\"_spec_class\"]=CodeType\n code_mock.__dict__[\"_spec_signature\"]=_CODE_SIG\n else:\n code_mock=NonCallableMock(spec_set=CodeType)\n code_mock.co_flags=(\n inspect.CO_COROUTINE\n +inspect.CO_VARARGS\n +inspect.CO_VARKEYWORDS\n )\n code_mock.co_argcount=0\n code_mock.co_varnames=('args','kwargs')\n code_mock.co_posonlyargcount=0\n code_mock.co_kwonlyargcount=0\n self.__dict__['__code__']=code_mock\n self.__dict__['__name__']='AsyncMock'\n self.__dict__['__defaults__']=tuple()\n self.__dict__['__kwdefaults__']={}\n self.__dict__['__annotations__']=None\n \n async def _execute_mock_call(self,/,*args,**kwargs):\n \n \n \n _call=_Call((args,kwargs),two=True)\n self.await_count +=1\n self.await_args=_call\n self.await_args_list.append(_call)\n \n effect=self.side_effect\n if effect is not None:\n if _is_exception(effect):\n raise effect\n elif not _callable(effect):\n try:\n result=next(effect)\n except StopIteration:\n \n \n raise StopAsyncIteration\n if _is_exception(result):\n raise result\n elif iscoroutinefunction(effect):\n result=await effect(*args,**kwargs)\n else:\n result=effect(*args,**kwargs)\n \n if result is not DEFAULT:\n return result\n \n if self._mock_return_value is not DEFAULT:\n return self.return_value\n \n if self._mock_wraps is not None:\n if iscoroutinefunction(self._mock_wraps):\n return await self._mock_wraps(*args,**kwargs)\n return self._mock_wraps(*args,**kwargs)\n \n return self.return_value\n \n def assert_awaited(self):\n ''\n\n \n if self.await_count ==0:\n msg=f\"Expected {self._mock_name or 'mock'} to have been awaited.\"\n raise AssertionError(msg)\n \n def assert_awaited_once(self):\n ''\n\n \n if not self.await_count ==1:\n msg=(f\"Expected {self._mock_name or 'mock'} to have been awaited once.\"\n f\" Awaited {self.await_count} times.\")\n raise AssertionError(msg)\n \n def assert_awaited_with(self,/,*args,**kwargs):\n ''\n\n \n if self.await_args is None:\n expected=self._format_mock_call_signature(args,kwargs)\n raise AssertionError(f'Expected await: {expected}\\nNot awaited')\n \n def _error_message():\n msg=self._format_mock_failure_message(args,kwargs,action='await')\n return msg\n \n expected=self._call_matcher(_Call((args,kwargs),two=True))\n actual=self._call_matcher(self.await_args)\n if actual !=expected:\n cause=expected if isinstance(expected,Exception)else None\n raise AssertionError(_error_message())from cause\n \n def assert_awaited_once_with(self,/,*args,**kwargs):\n ''\n\n\n \n if not self.await_count ==1:\n msg=(f\"Expected {self._mock_name or 'mock'} to have been awaited once.\"\n f\" Awaited {self.await_count} times.\")\n raise AssertionError(msg)\n return self.assert_awaited_with(*args,**kwargs)\n \n def assert_any_await(self,/,*args,**kwargs):\n ''\n\n \n expected=self._call_matcher(_Call((args,kwargs),two=True))\n cause=expected if isinstance(expected,Exception)else None\n actual=[self._call_matcher(c)for c in self.await_args_list]\n if cause or expected not in _AnyComparer(actual):\n expected_string=self._format_mock_call_signature(args,kwargs)\n raise AssertionError(\n '%s await not found'%expected_string\n )from cause\n \n def assert_has_awaits(self,calls,any_order=False):\n ''\n\n\n\n\n\n\n\n\n\n \n expected=[self._call_matcher(c)for c in calls]\n cause=next((e for e in expected if isinstance(e,Exception)),None)\n all_awaits=_CallList(self._call_matcher(c)for c in self.await_args_list)\n if not any_order:\n if expected not in all_awaits:\n if cause is None:\n problem='Awaits not found.'\n else:\n problem=('Error processing expected awaits.\\n'\n 'Errors: {}').format(\n [e if isinstance(e,Exception)else None\n for e in expected])\n raise AssertionError(\n f'{problem}\\n'\n f'Expected: {_CallList(calls)}\\n'\n f'Actual: {self.await_args_list}'\n )from cause\n return\n \n all_awaits=list(all_awaits)\n \n not_found=[]\n for kall in expected:\n try:\n all_awaits.remove(kall)\n except ValueError:\n not_found.append(kall)\n if not_found:\n raise AssertionError(\n '%r not all found in await list'%(tuple(not_found),)\n )from cause\n \n def assert_not_awaited(self):\n ''\n\n \n if self.await_count !=0:\n msg=(f\"Expected {self._mock_name or 'mock'} to not have been awaited.\"\n f\" Awaited {self.await_count} times.\")\n raise AssertionError(msg)\n \n def reset_mock(self,/,*args,**kwargs):\n ''\n\n \n super().reset_mock(*args,**kwargs)\n self.await_count=0\n self.await_args=None\n self.await_args_list=_CallList()\n \n \nclass AsyncMock(AsyncMockMixin,AsyncMagicMixin,Mock):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \nclass _ANY(object):\n ''\n \n def __eq__(self,other):\n return True\n \n def __ne__(self,other):\n return False\n \n def __repr__(self):\n return ''\n \nANY=_ANY()\n\n\n\ndef _format_call_signature(name,args,kwargs):\n message='%s(%%s)'%name\n formatted_args=''\n args_string=', '.join([repr(arg)for arg in args])\n kwargs_string=', '.join([\n '%s=%r'%(key,value)for key,value in kwargs.items()\n ])\n if args_string:\n formatted_args=args_string\n if kwargs_string:\n if formatted_args:\n formatted_args +=', '\n formatted_args +=kwargs_string\n \n return message %formatted_args\n \n \n \nclass _Call(tuple):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __new__(cls,value=(),name='',parent=None,two=False,\n from_kall=True):\n args=()\n kwargs={}\n _len=len(value)\n if _len ==3:\n name,args,kwargs=value\n elif _len ==2:\n first,second=value\n if isinstance(first,str):\n name=first\n if isinstance(second,tuple):\n args=second\n else:\n kwargs=second\n else:\n args,kwargs=first,second\n elif _len ==1:\n value,=value\n if isinstance(value,str):\n name=value\n elif isinstance(value,tuple):\n args=value\n else:\n kwargs=value\n \n if two:\n return tuple.__new__(cls,(args,kwargs))\n \n return tuple.__new__(cls,(name,args,kwargs))\n \n \n def __init__(self,value=(),name=None,parent=None,two=False,\n from_kall=True):\n self._mock_name=name\n self._mock_parent=parent\n self._mock_from_kall=from_kall\n \n \n def __eq__(self,other):\n try:\n len_other=len(other)\n except TypeError:\n return NotImplemented\n \n self_name=''\n if len(self)==2:\n self_args,self_kwargs=self\n else:\n self_name,self_args,self_kwargs=self\n \n if(getattr(self,'_mock_parent',None)and getattr(other,'_mock_parent',None)\n and self._mock_parent !=other._mock_parent):\n return False\n \n other_name=''\n if len_other ==0:\n other_args,other_kwargs=(),{}\n elif len_other ==3:\n other_name,other_args,other_kwargs=other\n elif len_other ==1:\n value,=other\n if isinstance(value,tuple):\n other_args=value\n other_kwargs={}\n elif isinstance(value,str):\n other_name=value\n other_args,other_kwargs=(),{}\n else:\n other_args=()\n other_kwargs=value\n elif len_other ==2:\n \n first,second=other\n if isinstance(first,str):\n other_name=first\n if isinstance(second,tuple):\n other_args,other_kwargs=second,{}\n else:\n other_args,other_kwargs=(),second\n else:\n other_args,other_kwargs=first,second\n else:\n return False\n \n if self_name and other_name !=self_name:\n return False\n \n \n return(other_args,other_kwargs)==(self_args,self_kwargs)\n \n \n __ne__=object.__ne__\n \n \n def __call__(self,/,*args,**kwargs):\n if self._mock_name is None:\n return _Call(('',args,kwargs),name='()')\n \n name=self._mock_name+'()'\n return _Call((self._mock_name,args,kwargs),name=name,parent=self)\n \n \n def __getattr__(self,attr):\n if self._mock_name is None:\n return _Call(name=attr,from_kall=False)\n name='%s.%s'%(self._mock_name,attr)\n return _Call(name=name,parent=self,from_kall=False)\n \n \n def __getattribute__(self,attr):\n if attr in tuple.__dict__:\n raise AttributeError\n return tuple.__getattribute__(self,attr)\n \n \n def _get_call_arguments(self):\n if len(self)==2:\n args,kwargs=self\n else:\n name,args,kwargs=self\n \n return args,kwargs\n \n @property\n def args(self):\n return self._get_call_arguments()[0]\n \n @property\n def kwargs(self):\n return self._get_call_arguments()[1]\n \n def __repr__(self):\n if not self._mock_from_kall:\n name=self._mock_name or 'call'\n if name.startswith('()'):\n name='call%s'%name\n return name\n \n if len(self)==2:\n name='call'\n args,kwargs=self\n else:\n name,args,kwargs=self\n if not name:\n name='call'\n elif not name.startswith('()'):\n name='call.%s'%name\n else:\n name='call%s'%name\n return _format_call_signature(name,args,kwargs)\n \n \n def call_list(self):\n ''\n\n \n vals=[]\n thing=self\n while thing is not None:\n if thing._mock_from_kall:\n vals.append(thing)\n thing=thing._mock_parent\n return _CallList(reversed(vals))\n \n \ncall=_Call(from_kall=False)\n\n\ndef create_autospec(spec,spec_set=False,instance=False,_parent=None,\n_name=None,*,unsafe=False,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if _is_list(spec):\n \n \n spec=type(spec)\n \n is_type=isinstance(spec,type)\n if _is_instance_mock(spec):\n raise InvalidSpecError(f'Cannot autospec a Mock object. '\n f'[object={spec !r}]')\n is_async_func=_is_async_func(spec)\n _kwargs={'spec':spec}\n if spec_set:\n _kwargs={'spec_set':spec}\n elif spec is None:\n \n _kwargs={}\n if _kwargs and instance:\n _kwargs['_spec_as_instance']=True\n if not unsafe:\n _check_spec_arg_typos(kwargs)\n \n _kwargs.update(kwargs)\n \n Klass=MagicMock\n if inspect.isdatadescriptor(spec):\n \n \n _kwargs={}\n elif is_async_func:\n if instance:\n raise RuntimeError(\"Instance can not be True when create_autospec \"\n \"is mocking an async function\")\n Klass=AsyncMock\n elif not _callable(spec):\n Klass=NonCallableMagicMock\n elif is_type and instance and not _instance_callable(spec):\n Klass=NonCallableMagicMock\n \n _name=_kwargs.pop('name',_name)\n \n _new_name=_name\n if _parent is None:\n \n _new_name=''\n \n mock=Klass(parent=_parent,_new_parent=_parent,_new_name=_new_name,\n name=_name,**_kwargs)\n \n if isinstance(spec,FunctionTypes):\n \n \n if is_async_func:\n mock=_set_async_signature(mock,spec)\n else:\n mock=_set_signature(mock,spec)\n else:\n _check_signature(spec,mock,is_type,instance)\n \n if _parent is not None and not instance:\n _parent._mock_children[_name]=mock\n \n \n wrapped=kwargs.pop('wraps',None)\n if is_type and not instance and 'return_value'not in kwargs:\n mock.return_value=create_autospec(spec,spec_set,instance=True,\n _name='()',_parent=mock,\n wraps=wrapped)\n \n for entry in dir(spec):\n if _is_magic(entry):\n \n continue\n \n \n \n \n \n \n \n \n \n \n try:\n original=getattr(spec,entry)\n except AttributeError:\n continue\n \n child_kwargs={'spec':original}\n \n if wrapped and hasattr(wrapped,entry):\n child_kwargs.update(wraps=original)\n if spec_set:\n child_kwargs={'spec_set':original}\n \n if not isinstance(original,FunctionTypes):\n new=_SpecState(original,spec_set,mock,entry,instance)\n mock._mock_children[entry]=new\n else:\n parent=mock\n if isinstance(spec,FunctionTypes):\n parent=mock.mock\n \n skipfirst=_must_skip(spec,entry,is_type)\n child_kwargs['_eat_self']=skipfirst\n if iscoroutinefunction(original):\n child_klass=AsyncMock\n else:\n child_klass=MagicMock\n new=child_klass(parent=parent,name=entry,_new_name=entry,\n _new_parent=parent,**child_kwargs)\n mock._mock_children[entry]=new\n new.return_value=child_klass()\n _check_signature(original,new,skipfirst=skipfirst)\n \n \n \n \n \n if isinstance(new,FunctionTypes):\n setattr(mock,entry,new)\n \n \n \n if _is_instance_mock(mock)and kwargs:\n mock.configure_mock(**kwargs)\n \n return mock\n \n \ndef _must_skip(spec,entry,is_type):\n ''\n\n\n \n if not isinstance(spec,type):\n if entry in getattr(spec,'__dict__',{}):\n \n return False\n spec=spec.__class__\n \n for klass in spec.__mro__:\n result=klass.__dict__.get(entry,DEFAULT)\n if result is DEFAULT:\n continue\n if isinstance(result,(staticmethod,classmethod)):\n return False\n elif isinstance(result,FunctionTypes):\n \n \n return is_type\n else:\n return False\n \n \n return is_type\n \n \nclass _SpecState(object):\n\n def __init__(self,spec,spec_set=False,parent=None,\n name=None,ids=None,instance=False):\n self.spec=spec\n self.ids=ids\n self.spec_set=spec_set\n self.parent=parent\n self.instance=instance\n self.name=name\n \n \nFunctionTypes=(\n\ntype(create_autospec),\n\ntype(ANY.__eq__),\n)\n\n\nfile_spec=None\nopen_spec=None\n\n\ndef _to_stream(read_data):\n if isinstance(read_data,bytes):\n return io.BytesIO(read_data)\n else:\n return io.StringIO(read_data)\n \n \ndef mock_open(mock=None,read_data=''):\n ''\n\n\n\n\n\n\n\n\n\n \n _read_data=_to_stream(read_data)\n _state=[_read_data,None]\n \n def _readlines_side_effect(*args,**kwargs):\n if handle.readlines.return_value is not None:\n return handle.readlines.return_value\n return _state[0].readlines(*args,**kwargs)\n \n def _read_side_effect(*args,**kwargs):\n if handle.read.return_value is not None:\n return handle.read.return_value\n return _state[0].read(*args,**kwargs)\n \n def _readline_side_effect(*args,**kwargs):\n yield from _iter_side_effect()\n while True:\n yield _state[0].readline(*args,**kwargs)\n \n def _iter_side_effect():\n if handle.readline.return_value is not None:\n while True:\n yield handle.readline.return_value\n for line in _state[0]:\n yield line\n \n def _next_side_effect():\n if handle.readline.return_value is not None:\n return handle.readline.return_value\n return next(_state[0])\n \n def _exit_side_effect(exctype,excinst,exctb):\n handle.close()\n \n global file_spec\n if file_spec is None:\n import _io\n file_spec=list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))\n \n global open_spec\n if open_spec is None:\n import _io\n open_spec=list(set(dir(_io.open)))\n if mock is None:\n mock=MagicMock(name='open',spec=open_spec)\n \n handle=MagicMock(spec=file_spec)\n handle.__enter__.return_value=handle\n \n handle.write.return_value=None\n handle.read.return_value=None\n handle.readline.return_value=None\n handle.readlines.return_value=None\n \n handle.read.side_effect=_read_side_effect\n _state[1]=_readline_side_effect()\n handle.readline.side_effect=_state[1]\n handle.readlines.side_effect=_readlines_side_effect\n handle.__iter__.side_effect=_iter_side_effect\n handle.__next__.side_effect=_next_side_effect\n handle.__exit__.side_effect=_exit_side_effect\n \n def reset_data(*args,**kwargs):\n _state[0]=_to_stream(read_data)\n if handle.readline.side_effect ==_state[1]:\n \n _state[1]=_readline_side_effect()\n handle.readline.side_effect=_state[1]\n return DEFAULT\n \n mock.side_effect=reset_data\n mock.return_value=handle\n return mock\n \n \nclass PropertyMock(Mock):\n ''\n\n\n\n\n\n\n \n def _get_child_mock(self,/,**kwargs):\n return MagicMock(**kwargs)\n \n def __get__(self,obj,obj_type=None):\n return self()\n def __set__(self,obj,val):\n self(val)\n \n \n_timeout_unset=sentinel.TIMEOUT_UNSET\n\nclass ThreadingMixin(Base):\n\n DEFAULT_TIMEOUT=None\n \n def _get_child_mock(self,/,**kw):\n if isinstance(kw.get(\"parent\"),ThreadingMixin):\n kw[\"timeout\"]=kw[\"parent\"]._mock_wait_timeout\n elif isinstance(kw.get(\"_new_parent\"),ThreadingMixin):\n kw[\"timeout\"]=kw[\"_new_parent\"]._mock_wait_timeout\n return super()._get_child_mock(**kw)\n \n def __init__(self,*args,timeout=_timeout_unset,**kwargs):\n super().__init__(*args,**kwargs)\n if timeout is _timeout_unset:\n timeout=self.DEFAULT_TIMEOUT\n self.__dict__[\"_mock_event\"]=threading.Event()\n self.__dict__[\"_mock_calls_events\"]=[]\n self.__dict__[\"_mock_calls_events_lock\"]=threading.Lock()\n self.__dict__[\"_mock_wait_timeout\"]=timeout\n \n def reset_mock(self,/,*args,**kwargs):\n ''\n\n \n super().reset_mock(*args,**kwargs)\n self.__dict__[\"_mock_event\"]=threading.Event()\n self.__dict__[\"_mock_calls_events\"]=[]\n \n def __get_event(self,expected_args,expected_kwargs):\n with self._mock_calls_events_lock:\n for args,kwargs,event in self._mock_calls_events:\n if(args,kwargs)==(expected_args,expected_kwargs):\n return event\n new_event=threading.Event()\n self._mock_calls_events.append((expected_args,expected_kwargs,new_event))\n return new_event\n \n def _mock_call(self,*args,**kwargs):\n ret_value=super()._mock_call(*args,**kwargs)\n \n call_event=self.__get_event(args,kwargs)\n call_event.set()\n \n self._mock_event.set()\n \n return ret_value\n \n def wait_until_called(self,*,timeout=_timeout_unset):\n ''\n\n\n\n\n \n if timeout is _timeout_unset:\n timeout=self._mock_wait_timeout\n if not self._mock_event.wait(timeout=timeout):\n msg=(f\"{self._mock_name or 'mock'} was not called before\"\n f\" timeout({timeout}).\")\n raise AssertionError(msg)\n \n def wait_until_any_call_with(self,*args,**kwargs):\n ''\n\n\n \n event=self.__get_event(args,kwargs)\n if not event.wait(timeout=self._mock_wait_timeout):\n expected_string=self._format_mock_call_signature(args,kwargs)\n raise AssertionError(f'{expected_string} call not found')\n \n \nclass ThreadingMock(ThreadingMixin,MagicMixin,Mock):\n ''\n\n\n\n\n\n\n\n\n\n\n \n pass\n \n \ndef seal(mock):\n ''\n\n\n\n\n\n\n\n \n mock._mock_sealed=True\n for attr in dir(mock):\n try:\n m=getattr(mock,attr)\n except AttributeError:\n continue\n if not isinstance(m,NonCallableMock):\n continue\n if isinstance(m._mock_children.get(attr),_SpecState):\n continue\n if m._mock_new_parent is mock:\n seal(m)\n \n \nclass _AsyncIterator:\n ''\n\n \n def __init__(self,iterator):\n self.iterator=iterator\n code_mock=NonCallableMock(spec_set=CodeType)\n code_mock.co_flags=inspect.CO_ITERABLE_COROUTINE\n self.__dict__['__code__']=code_mock\n \n async def __anext__(self):\n try:\n return next(self.iterator)\n except StopIteration:\n pass\n raise StopAsyncIteration\n", ["_io", "asyncio", "builtins", "contextlib", "functools", "inspect", "io", "pkgutil", "pprint", "sys", "threading", "types", "unittest.util"]], "unittest.result": [".py", "''\n\nimport io\nimport sys\nimport traceback\n\nfrom. import util\nfrom functools import wraps\n\n__unittest=True\n\ndef failfast(method):\n @wraps(method)\n def inner(self,*args,**kw):\n if getattr(self,'failfast',False):\n self.stop()\n return method(self,*args,**kw)\n return inner\n \nSTDOUT_LINE='\\nStdout:\\n%s'\nSTDERR_LINE='\\nStderr:\\n%s'\n\n\nclass TestResult(object):\n ''\n\n\n\n\n\n\n\n\n \n _previousTestClass=None\n _testRunEntered=False\n _moduleSetUpFailed=False\n def __init__(self,stream=None,descriptions=None,verbosity=None):\n self.failfast=False\n self.failures=[]\n self.errors=[]\n self.testsRun=0\n self.skipped=[]\n self.expectedFailures=[]\n self.unexpectedSuccesses=[]\n self.collectedDurations=[]\n self.shouldStop=False\n self.buffer=False\n self.tb_locals=False\n self._stdout_buffer=None\n self._stderr_buffer=None\n self._original_stdout=sys.stdout\n self._original_stderr=sys.stderr\n self._mirrorOutput=False\n \n def printErrors(self):\n ''\n \n def startTest(self,test):\n ''\n self.testsRun +=1\n self._mirrorOutput=False\n self._setupStdout()\n \n def _setupStdout(self):\n if self.buffer:\n if self._stderr_buffer is None:\n self._stderr_buffer=io.StringIO()\n self._stdout_buffer=io.StringIO()\n sys.stdout=self._stdout_buffer\n sys.stderr=self._stderr_buffer\n \n def startTestRun(self):\n ''\n\n\n \n \n def stopTest(self,test):\n ''\n self._restoreStdout()\n self._mirrorOutput=False\n \n def _restoreStdout(self):\n if self.buffer:\n if self._mirrorOutput:\n output=sys.stdout.getvalue()\n error=sys.stderr.getvalue()\n if output:\n if not output.endswith('\\n'):\n output +='\\n'\n self._original_stdout.write(STDOUT_LINE %output)\n if error:\n if not error.endswith('\\n'):\n error +='\\n'\n self._original_stderr.write(STDERR_LINE %error)\n \n sys.stdout=self._original_stdout\n sys.stderr=self._original_stderr\n self._stdout_buffer.seek(0)\n self._stdout_buffer.truncate()\n self._stderr_buffer.seek(0)\n self._stderr_buffer.truncate()\n \n def stopTestRun(self):\n ''\n\n\n \n \n @failfast\n def addError(self,test,err):\n ''\n\n \n self.errors.append((test,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n @failfast\n def addFailure(self,test,err):\n ''\n \n self.failures.append((test,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n def addSubTest(self,test,subtest,err):\n ''\n\n\n \n \n \n if err is not None:\n if getattr(self,'failfast',False):\n self.stop()\n if issubclass(err[0],test.failureException):\n errors=self.failures\n else:\n errors=self.errors\n errors.append((subtest,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n def addSuccess(self,test):\n ''\n pass\n \n def addSkip(self,test,reason):\n ''\n self.skipped.append((test,reason))\n \n def addExpectedFailure(self,test,err):\n ''\n self.expectedFailures.append(\n (test,self._exc_info_to_string(err,test)))\n \n @failfast\n def addUnexpectedSuccess(self,test):\n ''\n self.unexpectedSuccesses.append(test)\n \n def addDuration(self,test,elapsed):\n ''\n\n\n\n \n \n if hasattr(self,\"collectedDurations\"):\n \n self.collectedDurations.append((str(test),elapsed))\n \n def wasSuccessful(self):\n ''\n \n \n \n return((len(self.failures)==len(self.errors)==0)and\n (not hasattr(self,'unexpectedSuccesses')or\n len(self.unexpectedSuccesses)==0))\n \n def stop(self):\n ''\n self.shouldStop=True\n \n def _exc_info_to_string(self,err,test):\n ''\n exctype,value,tb=err\n tb=self._clean_tracebacks(exctype,value,tb,test)\n tb_e=traceback.TracebackException(\n exctype,value,tb,\n capture_locals=self.tb_locals,compact=True)\n msgLines=list(tb_e.format())\n \n if self.buffer:\n output=sys.stdout.getvalue()\n error=sys.stderr.getvalue()\n if output:\n if not output.endswith('\\n'):\n output +='\\n'\n msgLines.append(STDOUT_LINE %output)\n if error:\n if not error.endswith('\\n'):\n error +='\\n'\n msgLines.append(STDERR_LINE %error)\n return ''.join(msgLines)\n \n def _clean_tracebacks(self,exctype,value,tb,test):\n ret=None\n first=True\n excs=[(exctype,value,tb)]\n seen={id(value)}\n while excs:\n (exctype,value,tb)=excs.pop()\n \n while tb and self._is_relevant_tb_level(tb):\n tb=tb.tb_next\n \n \n if exctype is test.failureException:\n self._remove_unittest_tb_frames(tb)\n \n if first:\n ret=tb\n first=False\n else:\n value.__traceback__=tb\n \n if value is not None:\n for c in(value.__cause__,value.__context__):\n if c is not None and id(c)not in seen:\n excs.append((type(c),c,c.__traceback__))\n seen.add(id(c))\n return ret\n \n def _is_relevant_tb_level(self,tb):\n return '__unittest'in tb.tb_frame.f_globals\n \n def _remove_unittest_tb_frames(self,tb):\n ''\n\n\n\n\n\n \n prev=None\n while tb and not self._is_relevant_tb_level(tb):\n prev=tb\n tb=tb.tb_next\n if prev is not None:\n prev.tb_next=None\n \n def __repr__(self):\n return(\"<%s run=%i errors=%i failures=%i>\"%\n (util.strclass(self.__class__),self.testsRun,len(self.errors),\n len(self.failures)))\n", ["functools", "io", "sys", "traceback", "unittest", "unittest.util"]], "unittest.runner": [".py", "''\n\nimport sys\nimport time\nimport warnings\n\nfrom. import result\nfrom.case import _SubTest\nfrom.signals import registerResult\n\n__unittest=True\n\n\nclass _WritelnDecorator(object):\n ''\n def __init__(self,stream):\n self.stream=stream\n \n def __getattr__(self,attr):\n if attr in('stream','__getstate__'):\n raise AttributeError(attr)\n return getattr(self.stream,attr)\n \n def writeln(self,arg=None):\n if arg:\n self.write(arg)\n self.write('\\n')\n \n \nclass TextTestResult(result.TestResult):\n ''\n\n\n \n separator1='='*70\n separator2='-'*70\n \n def __init__(self,stream,descriptions,verbosity,*,durations=None):\n ''\n \n super(TextTestResult,self).__init__(stream,descriptions,verbosity)\n self.stream=stream\n self.showAll=verbosity >1\n self.dots=verbosity ==1\n self.descriptions=descriptions\n self._newline=True\n self.durations=durations\n \n def getDescription(self,test):\n doc_first_line=test.shortDescription()\n if self.descriptions and doc_first_line:\n return '\\n'.join((str(test),doc_first_line))\n else:\n return str(test)\n \n def startTest(self,test):\n super(TextTestResult,self).startTest(test)\n if self.showAll:\n self.stream.write(self.getDescription(test))\n self.stream.write(\" ... \")\n self.stream.flush()\n self._newline=False\n \n def _write_status(self,test,status):\n is_subtest=isinstance(test,_SubTest)\n if is_subtest or self._newline:\n if not self._newline:\n self.stream.writeln()\n if is_subtest:\n self.stream.write(\" \")\n self.stream.write(self.getDescription(test))\n self.stream.write(\" ... \")\n self.stream.writeln(status)\n self.stream.flush()\n self._newline=True\n \n def addSubTest(self,test,subtest,err):\n if err is not None:\n if self.showAll:\n if issubclass(err[0],subtest.failureException):\n self._write_status(subtest,\"FAIL\")\n else:\n self._write_status(subtest,\"ERROR\")\n elif self.dots:\n if issubclass(err[0],subtest.failureException):\n self.stream.write('F')\n else:\n self.stream.write('E')\n self.stream.flush()\n super(TextTestResult,self).addSubTest(test,subtest,err)\n \n def addSuccess(self,test):\n super(TextTestResult,self).addSuccess(test)\n if self.showAll:\n self._write_status(test,\"ok\")\n elif self.dots:\n self.stream.write('.')\n self.stream.flush()\n \n def addError(self,test,err):\n super(TextTestResult,self).addError(test,err)\n if self.showAll:\n self._write_status(test,\"ERROR\")\n elif self.dots:\n self.stream.write('E')\n self.stream.flush()\n \n def addFailure(self,test,err):\n super(TextTestResult,self).addFailure(test,err)\n if self.showAll:\n self._write_status(test,\"FAIL\")\n elif self.dots:\n self.stream.write('F')\n self.stream.flush()\n \n def addSkip(self,test,reason):\n super(TextTestResult,self).addSkip(test,reason)\n if self.showAll:\n self._write_status(test,\"skipped {0!r}\".format(reason))\n elif self.dots:\n self.stream.write(\"s\")\n self.stream.flush()\n \n def addExpectedFailure(self,test,err):\n super(TextTestResult,self).addExpectedFailure(test,err)\n if self.showAll:\n self.stream.writeln(\"expected failure\")\n self.stream.flush()\n elif self.dots:\n self.stream.write(\"x\")\n self.stream.flush()\n \n def addUnexpectedSuccess(self,test):\n super(TextTestResult,self).addUnexpectedSuccess(test)\n if self.showAll:\n self.stream.writeln(\"unexpected success\")\n self.stream.flush()\n elif self.dots:\n self.stream.write(\"u\")\n self.stream.flush()\n \n def printErrors(self):\n if self.dots or self.showAll:\n self.stream.writeln()\n self.stream.flush()\n self.printErrorList('ERROR',self.errors)\n self.printErrorList('FAIL',self.failures)\n unexpectedSuccesses=getattr(self,'unexpectedSuccesses',())\n if unexpectedSuccesses:\n self.stream.writeln(self.separator1)\n for test in unexpectedSuccesses:\n self.stream.writeln(f\"UNEXPECTED SUCCESS: {self.getDescription(test)}\")\n self.stream.flush()\n \n def printErrorList(self,flavour,errors):\n for test,err in errors:\n self.stream.writeln(self.separator1)\n self.stream.writeln(\"%s: %s\"%(flavour,self.getDescription(test)))\n self.stream.writeln(self.separator2)\n self.stream.writeln(\"%s\"%err)\n self.stream.flush()\n \n \nclass TextTestRunner(object):\n ''\n\n\n\n \n resultclass=TextTestResult\n \n def __init__(self,stream=None,descriptions=True,verbosity=1,\n failfast=False,buffer=False,resultclass=None,warnings=None,\n *,tb_locals=False,durations=None):\n ''\n\n\n\n \n if stream is None:\n stream=sys.stderr\n self.stream=_WritelnDecorator(stream)\n self.descriptions=descriptions\n self.verbosity=verbosity\n self.failfast=failfast\n self.buffer=buffer\n self.tb_locals=tb_locals\n self.durations=durations\n self.warnings=warnings\n if resultclass is not None:\n self.resultclass=resultclass\n \n def _makeResult(self):\n try:\n return self.resultclass(self.stream,self.descriptions,\n self.verbosity,durations=self.durations)\n except TypeError:\n \n return self.resultclass(self.stream,self.descriptions,\n self.verbosity)\n \n def _printDurations(self,result):\n if not result.collectedDurations:\n return\n ls=sorted(result.collectedDurations,key=lambda x:x[1],\n reverse=True)\n if self.durations >0:\n ls=ls[:self.durations]\n self.stream.writeln(\"Slowest test durations\")\n if hasattr(result,'separator2'):\n self.stream.writeln(result.separator2)\n hidden=False\n for test,elapsed in ls:\n if self.verbosity <2 and elapsed <0.001:\n hidden=True\n continue\n self.stream.writeln(\"%-10s %s\"%(\"%.3fs\"%elapsed,test))\n if hidden:\n self.stream.writeln(\"\\n(durations < 0.001s were hidden; \"\n \"use -v to show these durations)\")\n else:\n self.stream.writeln(\"\")\n \n def run(self,test):\n ''\n result=self._makeResult()\n registerResult(result)\n result.failfast=self.failfast\n result.buffer=self.buffer\n result.tb_locals=self.tb_locals\n with warnings.catch_warnings():\n if self.warnings:\n \n warnings.simplefilter(self.warnings)\n startTime=time.perf_counter()\n startTestRun=getattr(result,'startTestRun',None)\n if startTestRun is not None:\n startTestRun()\n try:\n test(result)\n finally:\n stopTestRun=getattr(result,'stopTestRun',None)\n if stopTestRun is not None:\n stopTestRun()\n stopTime=time.perf_counter()\n timeTaken=stopTime -startTime\n result.printErrors()\n if self.durations is not None:\n self._printDurations(result)\n \n if hasattr(result,'separator2'):\n self.stream.writeln(result.separator2)\n \n run=result.testsRun\n self.stream.writeln(\"Ran %d test%s in %.3fs\"%\n (run,run !=1 and \"s\"or \"\",timeTaken))\n self.stream.writeln()\n \n expectedFails=unexpectedSuccesses=skipped=0\n try:\n results=map(len,(result.expectedFailures,\n result.unexpectedSuccesses,\n result.skipped))\n except AttributeError:\n pass\n else:\n expectedFails,unexpectedSuccesses,skipped=results\n \n infos=[]\n if not result.wasSuccessful():\n self.stream.write(\"FAILED\")\n failed,errored=len(result.failures),len(result.errors)\n if failed:\n infos.append(\"failures=%d\"%failed)\n if errored:\n infos.append(\"errors=%d\"%errored)\n elif run ==0 and not skipped:\n self.stream.write(\"NO TESTS RAN\")\n else:\n self.stream.write(\"OK\")\n if skipped:\n infos.append(\"skipped=%d\"%skipped)\n if expectedFails:\n infos.append(\"expected failures=%d\"%expectedFails)\n if unexpectedSuccesses:\n infos.append(\"unexpected successes=%d\"%unexpectedSuccesses)\n if infos:\n self.stream.writeln(\" (%s)\"%(\", \".join(infos),))\n else:\n self.stream.write(\"\\n\")\n self.stream.flush()\n return result\n", ["sys", "time", "unittest", "unittest.case", "unittest.result", "unittest.signals", "warnings"]], "unittest.signals": [".py", "import signal\nimport weakref\n\nfrom functools import wraps\n\n__unittest=True\n\n\nclass _InterruptHandler(object):\n def __init__(self,default_handler):\n self.called=False\n self.original_handler=default_handler\n if isinstance(default_handler,int):\n if default_handler ==signal.SIG_DFL:\n \n default_handler=signal.default_int_handler\n elif default_handler ==signal.SIG_IGN:\n \n \n def default_handler(unused_signum,unused_frame):\n pass\n else:\n raise TypeError(\"expected SIGINT signal handler to be \"\n \"signal.SIG_IGN, signal.SIG_DFL, or a \"\n \"callable object\")\n self.default_handler=default_handler\n \n def __call__(self,signum,frame):\n installed_handler=signal.getsignal(signal.SIGINT)\n if installed_handler is not self:\n \n \n self.default_handler(signum,frame)\n \n if self.called:\n self.default_handler(signum,frame)\n self.called=True\n for result in _results.keys():\n result.stop()\n \n_results=weakref.WeakKeyDictionary()\ndef registerResult(result):\n _results[result]=1\n \ndef removeResult(result):\n return bool(_results.pop(result,None))\n \n_interrupt_handler=None\ndef installHandler():\n global _interrupt_handler\n if _interrupt_handler is None:\n default_handler=signal.getsignal(signal.SIGINT)\n _interrupt_handler=_InterruptHandler(default_handler)\n signal.signal(signal.SIGINT,_interrupt_handler)\n \n \ndef removeHandler(method=None):\n if method is not None:\n @wraps(method)\n def inner(*args,**kwargs):\n initial=signal.getsignal(signal.SIGINT)\n removeHandler()\n try:\n return method(*args,**kwargs)\n finally:\n signal.signal(signal.SIGINT,initial)\n return inner\n \n global _interrupt_handler\n if _interrupt_handler is not None:\n signal.signal(signal.SIGINT,_interrupt_handler.original_handler)\n", ["functools", "signal", "weakref"]], "unittest.suite": [".py", "''\n\nimport sys\n\nfrom. import case\nfrom. import util\n\n__unittest=True\n\n\ndef _call_if_exists(parent,attr):\n func=getattr(parent,attr,lambda:None)\n func()\n \n \nclass BaseTestSuite(object):\n ''\n \n _cleanup=True\n \n def __init__(self,tests=()):\n self._tests=[]\n self._removed_tests=0\n self.addTests(tests)\n \n def __repr__(self):\n return \"<%s tests=%s>\"%(util.strclass(self.__class__),list(self))\n \n def __eq__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n return list(self)==list(other)\n \n def __iter__(self):\n return iter(self._tests)\n \n def countTestCases(self):\n cases=self._removed_tests\n for test in self:\n if test:\n cases +=test.countTestCases()\n return cases\n \n def addTest(self,test):\n \n if not callable(test):\n raise TypeError(\"{} is not callable\".format(repr(test)))\n if isinstance(test,type)and issubclass(test,\n (case.TestCase,TestSuite)):\n raise TypeError(\"TestCases and TestSuites must be instantiated \"\n \"before passing them to addTest()\")\n self._tests.append(test)\n \n def addTests(self,tests):\n if isinstance(tests,str):\n raise TypeError(\"tests must be an iterable of tests, not a string\")\n for test in tests:\n self.addTest(test)\n \n def run(self,result):\n for index,test in enumerate(self):\n if result.shouldStop:\n break\n test(result)\n if self._cleanup:\n self._removeTestAtIndex(index)\n return result\n \n def _removeTestAtIndex(self,index):\n ''\n try:\n test=self._tests[index]\n except TypeError:\n \n pass\n else:\n \n \n if hasattr(test,'countTestCases'):\n self._removed_tests +=test.countTestCases()\n self._tests[index]=None\n \n def __call__(self,*args,**kwds):\n return self.run(*args,**kwds)\n \n def debug(self):\n ''\n for test in self:\n test.debug()\n \n \nclass TestSuite(BaseTestSuite):\n ''\n\n\n\n\n\n\n \n \n def run(self,result,debug=False):\n topLevel=False\n if getattr(result,'_testRunEntered',False)is False:\n result._testRunEntered=topLevel=True\n \n for index,test in enumerate(self):\n if result.shouldStop:\n break\n \n if _isnotsuite(test):\n self._tearDownPreviousClass(test,result)\n self._handleModuleFixture(test,result)\n self._handleClassSetUp(test,result)\n result._previousTestClass=test.__class__\n \n if(getattr(test.__class__,'_classSetupFailed',False)or\n getattr(result,'_moduleSetUpFailed',False)):\n continue\n \n if not debug:\n test(result)\n else:\n test.debug()\n \n if self._cleanup:\n self._removeTestAtIndex(index)\n \n if topLevel:\n self._tearDownPreviousClass(None,result)\n self._handleModuleTearDown(result)\n result._testRunEntered=False\n return result\n \n def debug(self):\n ''\n debug=_DebugResult()\n self.run(debug,True)\n \n \n \n def _handleClassSetUp(self,test,result):\n previousClass=getattr(result,'_previousTestClass',None)\n currentClass=test.__class__\n if currentClass ==previousClass:\n return\n if result._moduleSetUpFailed:\n return\n if getattr(currentClass,\"__unittest_skip__\",False):\n return\n \n failed=False\n try:\n currentClass._classSetupFailed=False\n except TypeError:\n \n \n pass\n \n setUpClass=getattr(currentClass,'setUpClass',None)\n doClassCleanups=getattr(currentClass,'doClassCleanups',None)\n if setUpClass is not None:\n _call_if_exists(result,'_setupStdout')\n try:\n try:\n setUpClass()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n failed=True\n try:\n currentClass._classSetupFailed=True\n except TypeError:\n pass\n className=util.strclass(currentClass)\n self._createClassOrModuleLevelException(result,e,\n 'setUpClass',\n className)\n if failed and doClassCleanups is not None:\n doClassCleanups()\n for exc_info in currentClass.tearDown_exceptions:\n self._createClassOrModuleLevelException(\n result,exc_info[1],'setUpClass',className,\n info=exc_info)\n finally:\n _call_if_exists(result,'_restoreStdout')\n \n def _get_previous_module(self,result):\n previousModule=None\n previousClass=getattr(result,'_previousTestClass',None)\n if previousClass is not None:\n previousModule=previousClass.__module__\n return previousModule\n \n \n def _handleModuleFixture(self,test,result):\n previousModule=self._get_previous_module(result)\n currentModule=test.__class__.__module__\n if currentModule ==previousModule:\n return\n \n self._handleModuleTearDown(result)\n \n \n result._moduleSetUpFailed=False\n try:\n module=sys.modules[currentModule]\n except KeyError:\n return\n setUpModule=getattr(module,'setUpModule',None)\n if setUpModule is not None:\n _call_if_exists(result,'_setupStdout')\n try:\n try:\n setUpModule()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n result._moduleSetUpFailed=True\n self._createClassOrModuleLevelException(result,e,\n 'setUpModule',\n currentModule)\n if result._moduleSetUpFailed:\n try:\n case.doModuleCleanups()\n except Exception as e:\n self._createClassOrModuleLevelException(result,e,\n 'setUpModule',\n currentModule)\n finally:\n _call_if_exists(result,'_restoreStdout')\n \n def _createClassOrModuleLevelException(self,result,exc,method_name,\n parent,info=None):\n errorName=f'{method_name} ({parent})'\n self._addClassOrModuleLevelException(result,exc,errorName,info)\n \n def _addClassOrModuleLevelException(self,result,exception,errorName,\n info=None):\n error=_ErrorHolder(errorName)\n addSkip=getattr(result,'addSkip',None)\n if addSkip is not None and isinstance(exception,case.SkipTest):\n addSkip(error,str(exception))\n else:\n if not info:\n result.addError(error,sys.exc_info())\n else:\n result.addError(error,info)\n \n def _handleModuleTearDown(self,result):\n previousModule=self._get_previous_module(result)\n if previousModule is None:\n return\n if result._moduleSetUpFailed:\n return\n \n try:\n module=sys.modules[previousModule]\n except KeyError:\n return\n \n _call_if_exists(result,'_setupStdout')\n try:\n tearDownModule=getattr(module,'tearDownModule',None)\n if tearDownModule is not None:\n try:\n tearDownModule()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n self._createClassOrModuleLevelException(result,e,\n 'tearDownModule',\n previousModule)\n try:\n case.doModuleCleanups()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n self._createClassOrModuleLevelException(result,e,\n 'tearDownModule',\n previousModule)\n finally:\n _call_if_exists(result,'_restoreStdout')\n \n def _tearDownPreviousClass(self,test,result):\n previousClass=getattr(result,'_previousTestClass',None)\n currentClass=test.__class__\n if currentClass ==previousClass or previousClass is None:\n return\n if getattr(previousClass,'_classSetupFailed',False):\n return\n if getattr(result,'_moduleSetUpFailed',False):\n return\n if getattr(previousClass,\"__unittest_skip__\",False):\n return\n \n tearDownClass=getattr(previousClass,'tearDownClass',None)\n doClassCleanups=getattr(previousClass,'doClassCleanups',None)\n if tearDownClass is None and doClassCleanups is None:\n return\n \n _call_if_exists(result,'_setupStdout')\n try:\n if tearDownClass is not None:\n try:\n tearDownClass()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n className=util.strclass(previousClass)\n self._createClassOrModuleLevelException(result,e,\n 'tearDownClass',\n className)\n if doClassCleanups is not None:\n doClassCleanups()\n for exc_info in previousClass.tearDown_exceptions:\n if isinstance(result,_DebugResult):\n raise exc_info[1]\n className=util.strclass(previousClass)\n self._createClassOrModuleLevelException(result,exc_info[1],\n 'tearDownClass',\n className,\n info=exc_info)\n finally:\n _call_if_exists(result,'_restoreStdout')\n \n \nclass _ErrorHolder(object):\n ''\n\n\n\n \n \n \n \n \n failureException=None\n \n def __init__(self,description):\n self.description=description\n \n def id(self):\n return self.description\n \n def shortDescription(self):\n return None\n \n def __repr__(self):\n return \"\"%(self.description,)\n \n def __str__(self):\n return self.id()\n \n def run(self,result):\n \n \n pass\n \n def __call__(self,result):\n return self.run(result)\n \n def countTestCases(self):\n return 0\n \ndef _isnotsuite(test):\n ''\n try:\n iter(test)\n except TypeError:\n return True\n return False\n \n \nclass _DebugResult(object):\n ''\n _previousTestClass=None\n _moduleSetUpFailed=False\n shouldStop=False\n", ["sys", "unittest", "unittest.case", "unittest.util"]], "unittest.util": [".py", "''\n\nfrom collections import namedtuple,Counter\nfrom os.path import commonprefix\n\n__unittest=True\n\n_MAX_LENGTH=80\n_PLACEHOLDER_LEN=12\n_MIN_BEGIN_LEN=5\n_MIN_END_LEN=5\n_MIN_COMMON_LEN=5\n_MIN_DIFF_LEN=_MAX_LENGTH -\\\n(_MIN_BEGIN_LEN+_PLACEHOLDER_LEN+_MIN_COMMON_LEN+\n_PLACEHOLDER_LEN+_MIN_END_LEN)\nassert _MIN_DIFF_LEN >=0\n\ndef _shorten(s,prefixlen,suffixlen):\n skip=len(s)-prefixlen -suffixlen\n if skip >_PLACEHOLDER_LEN:\n s='%s[%d chars]%s'%(s[:prefixlen],skip,s[len(s)-suffixlen:])\n return s\n \ndef _common_shorten_repr(*args):\n args=tuple(map(safe_repr,args))\n maxlen=max(map(len,args))\n if maxlen <=_MAX_LENGTH:\n return args\n \n prefix=commonprefix(args)\n prefixlen=len(prefix)\n \n common_len=_MAX_LENGTH -\\\n (maxlen -prefixlen+_MIN_BEGIN_LEN+_PLACEHOLDER_LEN)\n if common_len >_MIN_COMMON_LEN:\n assert _MIN_BEGIN_LEN+_PLACEHOLDER_LEN+_MIN_COMMON_LEN+\\\n (maxlen -prefixlen)<_MAX_LENGTH\n prefix=_shorten(prefix,_MIN_BEGIN_LEN,common_len)\n return tuple(prefix+s[prefixlen:]for s in args)\n \n prefix=_shorten(prefix,_MIN_BEGIN_LEN,_MIN_COMMON_LEN)\n return tuple(prefix+_shorten(s[prefixlen:],_MIN_DIFF_LEN,_MIN_END_LEN)\n for s in args)\n \ndef safe_repr(obj,short=False):\n try:\n result=repr(obj)\n except Exception:\n result=object.__repr__(obj)\n if not short or len(result)<_MAX_LENGTH:\n return result\n return result[:_MAX_LENGTH]+' [truncated]...'\n \ndef strclass(cls):\n return \"%s.%s\"%(cls.__module__,cls.__qualname__)\n \ndef sorted_list_difference(expected,actual):\n ''\n\n\n\n\n\n \n i=j=0\n missing=[]\n unexpected=[]\n while True:\n try:\n e=expected[i]\n a=actual[j]\n if e a:\n unexpected.append(a)\n j +=1\n while actual[j]==a:\n j +=1\n else:\n i +=1\n try:\n while expected[i]==e:\n i +=1\n finally:\n j +=1\n while actual[j]==a:\n j +=1\n except IndexError:\n missing.extend(expected[i:])\n unexpected.extend(actual[j:])\n break\n return missing,unexpected\n \n \ndef unorderable_list_difference(expected,actual):\n ''\n\n\n\n \n missing=[]\n while expected:\n item=expected.pop()\n try:\n actual.remove(item)\n except ValueError:\n missing.append(item)\n \n \n return missing,actual\n \ndef three_way_cmp(x,y):\n ''\n return(x >y)-(x 0:\n self._raiseFailure(\n \"Unexpected logs found: {!r}\".format(\n self.watcher.output\n )\n )\n \n else:\n \n if len(self.watcher.records)==0:\n self._raiseFailure(\n \"no logs of level {} or higher triggered on {}\"\n .format(logging.getLevelName(self.level),self.logger.name))\n", ["collections", "logging", "unittest.case"]], "unittest": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['TestResult','TestCase','IsolatedAsyncioTestCase','TestSuite',\n'TextTestRunner','TestLoader','FunctionTestCase','main',\n'defaultTestLoader','SkipTest','skip','skipIf','skipUnless',\n'expectedFailure','TextTestResult','installHandler',\n'registerResult','removeResult','removeHandler',\n'addModuleCleanup','doModuleCleanups','enterModuleContext']\n\n__unittest=True\n\nfrom.result import TestResult\nfrom.case import(addModuleCleanup,TestCase,FunctionTestCase,SkipTest,skip,\nskipIf,skipUnless,expectedFailure,doModuleCleanups,\nenterModuleContext)\nfrom.suite import BaseTestSuite,TestSuite\nfrom.loader import TestLoader,defaultTestLoader\nfrom.main import TestProgram,main\nfrom.runner import TextTestRunner,TextTestResult\nfrom.signals import installHandler,registerResult,removeResult,removeHandler\n\n\n\n\n\n\n\ndef __dir__():\n return globals().keys()|{'IsolatedAsyncioTestCase'}\n \ndef __getattr__(name):\n if name =='IsolatedAsyncioTestCase':\n global IsolatedAsyncioTestCase\n from.async_case import IsolatedAsyncioTestCase\n return IsolatedAsyncioTestCase\n raise AttributeError(f\"module {__name__ !r} has no attribute {name !r}\")\n", ["unittest.async_case", "unittest.case", "unittest.loader", "unittest.main", "unittest.result", "unittest.runner", "unittest.signals", "unittest.suite"], 1], "unittest.__main__": [".py", "''\n\nimport sys\nif sys.argv[0].endswith(\"__main__.py\"):\n import os.path\n \n \n \n \n executable=os.path.basename(sys.executable)\n sys.argv[0]=executable+\" -m unittest\"\n del os\n \n__unittest=True\n\nfrom.main import main\n\nmain(module=None)\n", ["os.path", "sys", "unittest.main"]], "urllib.error": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\nimport io\nimport urllib.response\n\n__all__=['URLError','HTTPError','ContentTooShortError']\n\n\nclass URLError(OSError):\n\n\n\n\n\n def __init__(self,reason,filename=None):\n self.args=reason,\n self.reason=reason\n if filename is not None:\n self.filename=filename\n \n def __str__(self):\n return ''%self.reason\n \n \nclass HTTPError(URLError,urllib.response.addinfourl):\n ''\n __super_init=urllib.response.addinfourl.__init__\n \n def __init__(self,url,code,msg,hdrs,fp):\n self.code=code\n self.msg=msg\n self.hdrs=hdrs\n self.fp=fp\n self.filename=url\n if fp is None:\n fp=io.BytesIO()\n self.__super_init(fp,hdrs,url,code)\n \n def __str__(self):\n return 'HTTP Error %s: %s'%(self.code,self.msg)\n \n def __repr__(self):\n return ''%(self.code,self.msg)\n \n \n \n @property\n def reason(self):\n return self.msg\n \n @property\n def headers(self):\n return self.hdrs\n \n @headers.setter\n def headers(self,headers):\n self.hdrs=headers\n \n \nclass ContentTooShortError(URLError):\n ''\n def __init__(self,message,content):\n URLError.__init__(self,message)\n self.content=content\n", ["io", "urllib.response"]], "urllib.parse": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom collections import namedtuple\nimport functools\nimport math\nimport re\nimport types\nimport warnings\nimport ipaddress\n\n__all__=[\"urlparse\",\"urlunparse\",\"urljoin\",\"urldefrag\",\n\"urlsplit\",\"urlunsplit\",\"urlencode\",\"parse_qs\",\n\"parse_qsl\",\"quote\",\"quote_plus\",\"quote_from_bytes\",\n\"unquote\",\"unquote_plus\",\"unquote_to_bytes\",\n\"DefragResult\",\"ParseResult\",\"SplitResult\",\n\"DefragResultBytes\",\"ParseResultBytes\",\"SplitResultBytes\"]\n\n\n\n\n\nuses_relative=['','ftp','http','gopher','nntp','imap',\n'wais','file','https','shttp','mms',\n'prospero','rtsp','rtsps','rtspu','sftp',\n'svn','svn+ssh','ws','wss']\n\nuses_netloc=['','ftp','http','gopher','nntp','telnet',\n'imap','wais','file','mms','https','shttp',\n'snews','prospero','rtsp','rtsps','rtspu','rsync',\n'svn','svn+ssh','sftp','nfs','git','git+ssh',\n'ws','wss','itms-services']\n\nuses_params=['','ftp','hdl','prospero','http','imap',\n'https','shttp','rtsp','rtsps','rtspu','sip',\n'sips','mms','sftp','tel']\n\n\n\n\nnon_hierarchical=['gopher','hdl','mailto','news',\n'telnet','wais','imap','snews','sip','sips']\n\nuses_query=['','http','wais','imap','https','shttp','mms',\n'gopher','rtsp','rtsps','rtspu','sip','sips']\n\nuses_fragment=['','ftp','hdl','http','gopher','news',\n'nntp','wais','https','shttp','snews',\n'file','prospero']\n\n\nscheme_chars=('abcdefghijklmnopqrstuvwxyz'\n'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n'0123456789'\n'+-.')\n\n\n\n_WHATWG_C0_CONTROL_OR_SPACE='\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f '\n\n\n_UNSAFE_URL_BYTES_TO_REMOVE=['\\t','\\r','\\n']\n\ndef clear_cache():\n ''\n urlsplit.cache_clear()\n _byte_quoter_factory.cache_clear()\n \n \n \n \n \n \n \n_implicit_encoding='ascii'\n_implicit_errors='strict'\n\ndef _noop(obj):\n return obj\n \ndef _encode_result(obj,encoding=_implicit_encoding,\nerrors=_implicit_errors):\n return obj.encode(encoding,errors)\n \ndef _decode_args(args,encoding=_implicit_encoding,\nerrors=_implicit_errors):\n return tuple(x.decode(encoding,errors)if x else ''for x in args)\n \ndef _coerce_args(*args):\n\n\n\n\n\n str_input=isinstance(args[0],str)\n for arg in args[1:]:\n \n \n if arg and isinstance(arg,str)!=str_input:\n raise TypeError(\"Cannot mix str and non-str arguments\")\n if str_input:\n return args+(_noop,)\n return _decode_args(args)+(_encode_result,)\n \n \nclass _ResultMixinStr(object):\n ''\n __slots__=()\n \n def encode(self,encoding='ascii',errors='strict'):\n return self._encoded_counterpart(*(x.encode(encoding,errors)for x in self))\n \n \nclass _ResultMixinBytes(object):\n ''\n __slots__=()\n \n def decode(self,encoding='ascii',errors='strict'):\n return self._decoded_counterpart(*(x.decode(encoding,errors)for x in self))\n \n \nclass _NetlocResultMixinBase(object):\n ''\n __slots__=()\n \n @property\n def username(self):\n return self._userinfo[0]\n \n @property\n def password(self):\n return self._userinfo[1]\n \n @property\n def hostname(self):\n hostname=self._hostinfo[0]\n if not hostname:\n return None\n \n \n separator='%'if isinstance(hostname,str)else b'%'\n hostname,percent,zone=hostname.partition(separator)\n return hostname.lower()+percent+zone\n \n @property\n def port(self):\n port=self._hostinfo[1]\n if port is not None:\n if port.isdigit()and port.isascii():\n port=int(port)\n else:\n raise ValueError(f\"Port could not be cast to integer value as {port !r}\")\n if not(0 <=port <=65535):\n raise ValueError(\"Port out of range 0-65535\")\n return port\n \n __class_getitem__=classmethod(types.GenericAlias)\n \n \nclass _NetlocResultMixinStr(_NetlocResultMixinBase,_ResultMixinStr):\n __slots__=()\n \n @property\n def _userinfo(self):\n netloc=self.netloc\n userinfo,have_info,hostinfo=netloc.rpartition('@')\n if have_info:\n username,have_password,password=userinfo.partition(':')\n if not have_password:\n password=None\n else:\n username=password=None\n return username,password\n \n @property\n def _hostinfo(self):\n netloc=self.netloc\n _,_,hostinfo=netloc.rpartition('@')\n _,have_open_br,bracketed=hostinfo.partition('[')\n if have_open_br:\n hostname,_,port=bracketed.partition(']')\n _,_,port=port.partition(':')\n else:\n hostname,_,port=hostinfo.partition(':')\n if not port:\n port=None\n return hostname,port\n \n \nclass _NetlocResultMixinBytes(_NetlocResultMixinBase,_ResultMixinBytes):\n __slots__=()\n \n @property\n def _userinfo(self):\n netloc=self.netloc\n userinfo,have_info,hostinfo=netloc.rpartition(b'@')\n if have_info:\n username,have_password,password=userinfo.partition(b':')\n if not have_password:\n password=None\n else:\n username=password=None\n return username,password\n \n @property\n def _hostinfo(self):\n netloc=self.netloc\n _,_,hostinfo=netloc.rpartition(b'@')\n _,have_open_br,bracketed=hostinfo.partition(b'[')\n if have_open_br:\n hostname,_,port=bracketed.partition(b']')\n _,_,port=port.partition(b':')\n else:\n hostname,_,port=hostinfo.partition(b':')\n if not port:\n port=None\n return hostname,port\n \n \n_DefragResultBase=namedtuple('DefragResult','url fragment')\n_SplitResultBase=namedtuple(\n'SplitResult','scheme netloc path query fragment')\n_ParseResultBase=namedtuple(\n'ParseResult','scheme netloc path params query fragment')\n\n_DefragResultBase.__doc__=\"\"\"\nDefragResult(url, fragment)\n\nA 2-tuple that contains the url without fragment identifier and the fragment\nidentifier as a separate argument.\n\"\"\"\n\n_DefragResultBase.url.__doc__=\"\"\"The URL with no fragment identifier.\"\"\"\n\n_DefragResultBase.fragment.__doc__=\"\"\"\nFragment identifier separated from URL, that allows indirect identification of a\nsecondary resource by reference to a primary resource and additional identifying\ninformation.\n\"\"\"\n\n_SplitResultBase.__doc__=\"\"\"\nSplitResult(scheme, netloc, path, query, fragment)\n\nA 5-tuple that contains the different components of a URL. Similar to\nParseResult, but does not split params.\n\"\"\"\n\n_SplitResultBase.scheme.__doc__=\"\"\"Specifies URL scheme for the request.\"\"\"\n\n_SplitResultBase.netloc.__doc__=\"\"\"\nNetwork location where the request is made to.\n\"\"\"\n\n_SplitResultBase.path.__doc__=\"\"\"\nThe hierarchical path, such as the path to a file to download.\n\"\"\"\n\n_SplitResultBase.query.__doc__=\"\"\"\nThe query component, that contains non-hierarchical data, that along with data\nin path component, identifies a resource in the scope of URI's scheme and\nnetwork location.\n\"\"\"\n\n_SplitResultBase.fragment.__doc__=\"\"\"\nFragment identifier, that allows indirect identification of a secondary resource\nby reference to a primary resource and additional identifying information.\n\"\"\"\n\n_ParseResultBase.__doc__=\"\"\"\nParseResult(scheme, netloc, path, params, query, fragment)\n\nA 6-tuple that contains components of a parsed URL.\n\"\"\"\n\n_ParseResultBase.scheme.__doc__=_SplitResultBase.scheme.__doc__\n_ParseResultBase.netloc.__doc__=_SplitResultBase.netloc.__doc__\n_ParseResultBase.path.__doc__=_SplitResultBase.path.__doc__\n_ParseResultBase.params.__doc__=\"\"\"\nParameters for last path element used to dereference the URI in order to provide\naccess to perform some operation on the resource.\n\"\"\"\n\n_ParseResultBase.query.__doc__=_SplitResultBase.query.__doc__\n_ParseResultBase.fragment.__doc__=_SplitResultBase.fragment.__doc__\n\n\n\n\n\nResultBase=_NetlocResultMixinStr\n\n\nclass DefragResult(_DefragResultBase,_ResultMixinStr):\n __slots__=()\n def geturl(self):\n if self.fragment:\n return self.url+'#'+self.fragment\n else:\n return self.url\n \nclass SplitResult(_SplitResultBase,_NetlocResultMixinStr):\n __slots__=()\n def geturl(self):\n return urlunsplit(self)\n \nclass ParseResult(_ParseResultBase,_NetlocResultMixinStr):\n __slots__=()\n def geturl(self):\n return urlunparse(self)\n \n \nclass DefragResultBytes(_DefragResultBase,_ResultMixinBytes):\n __slots__=()\n def geturl(self):\n if self.fragment:\n return self.url+b'#'+self.fragment\n else:\n return self.url\n \nclass SplitResultBytes(_SplitResultBase,_NetlocResultMixinBytes):\n __slots__=()\n def geturl(self):\n return urlunsplit(self)\n \nclass ParseResultBytes(_ParseResultBase,_NetlocResultMixinBytes):\n __slots__=()\n def geturl(self):\n return urlunparse(self)\n \n \ndef _fix_result_transcoding():\n _result_pairs=(\n (DefragResult,DefragResultBytes),\n (SplitResult,SplitResultBytes),\n (ParseResult,ParseResultBytes),\n )\n for _decoded,_encoded in _result_pairs:\n _decoded._encoded_counterpart=_encoded\n _encoded._decoded_counterpart=_decoded\n \n_fix_result_transcoding()\ndel _fix_result_transcoding\n\ndef urlparse(url,scheme='',allow_fragments=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n url,scheme,_coerce_result=_coerce_args(url,scheme)\n splitresult=urlsplit(url,scheme,allow_fragments)\n scheme,netloc,url,query,fragment=splitresult\n if scheme in uses_params and ';'in url:\n url,params=_splitparams(url)\n else:\n params=''\n result=ParseResult(scheme,netloc,url,params,query,fragment)\n return _coerce_result(result)\n \ndef _splitparams(url):\n if '/'in url:\n i=url.find(';',url.rfind('/'))\n if i <0:\n return url,''\n else:\n i=url.find(';')\n return url[:i],url[i+1:]\n \ndef _splitnetloc(url,start=0):\n delim=len(url)\n for c in '/?#':\n wdelim=url.find(c,start)\n if wdelim >=0:\n delim=min(delim,wdelim)\n return url[start:delim],url[delim:]\n \ndef _checknetloc(netloc):\n if not netloc or netloc.isascii():\n return\n \n \n import unicodedata\n n=netloc.replace('@','')\n n=n.replace(':','')\n n=n.replace('#','')\n n=n.replace('?','')\n netloc2=unicodedata.normalize('NFKC',n)\n if n ==netloc2:\n return\n for c in '/?#@:':\n if c in netloc2:\n raise ValueError(\"netloc '\"+netloc+\"' contains invalid \"+\n \"characters under NFKC normalization\")\n \n \n \ndef _check_bracketed_host(hostname):\n if hostname.startswith('v'):\n if not re.match(r\"\\Av[a-fA-F0-9]+\\..+\\Z\",hostname):\n raise ValueError(f\"IPvFuture address is invalid\")\n else:\n ip=ipaddress.ip_address(hostname)\n if isinstance(ip,ipaddress.IPv4Address):\n raise ValueError(f\"An IPv4 address cannot be in brackets\")\n \n \n \n@functools.lru_cache(typed=True)\ndef urlsplit(url,scheme='',allow_fragments=True):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n url,scheme,_coerce_result=_coerce_args(url,scheme)\n \n \n url=url.lstrip(_WHATWG_C0_CONTROL_OR_SPACE)\n scheme=scheme.strip(_WHATWG_C0_CONTROL_OR_SPACE)\n \n for b in _UNSAFE_URL_BYTES_TO_REMOVE:\n url=url.replace(b,\"\")\n scheme=scheme.replace(b,\"\")\n \n allow_fragments=bool(allow_fragments)\n netloc=query=fragment=''\n i=url.find(':')\n if i >0 and url[0].isascii()and url[0].isalpha():\n for c in url[:i]:\n if c not in scheme_chars:\n break\n else:\n scheme,url=url[:i].lower(),url[i+1:]\n if url[:2]=='//':\n netloc,url=_splitnetloc(url,2)\n if(('['in netloc and ']'not in netloc)or\n (']'in netloc and '['not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if '['in netloc and ']'in netloc:\n bracketed_host=netloc.partition('[')[2].partition(']')[0]\n _check_bracketed_host(bracketed_host)\n if allow_fragments and '#'in url:\n url,fragment=url.split('#',1)\n if '?'in url:\n url,query=url.split('?',1)\n _checknetloc(netloc)\n v=SplitResult(scheme,netloc,url,query,fragment)\n return _coerce_result(v)\n \ndef urlunparse(components):\n ''\n\n\n \n scheme,netloc,url,params,query,fragment,_coerce_result=(\n _coerce_args(*components))\n if params:\n url=\"%s;%s\"%(url,params)\n return _coerce_result(urlunsplit((scheme,netloc,url,query,fragment)))\n \ndef urlunsplit(components):\n ''\n\n\n\n \n scheme,netloc,url,query,fragment,_coerce_result=(\n _coerce_args(*components))\n if netloc or(scheme and scheme in uses_netloc and url[:2]!='//'):\n if url and url[:1]!='/':url='/'+url\n url='//'+(netloc or '')+url\n if scheme:\n url=scheme+':'+url\n if query:\n url=url+'?'+query\n if fragment:\n url=url+'#'+fragment\n return _coerce_result(url)\n \ndef urljoin(base,url,allow_fragments=True):\n ''\n \n if not base:\n return url\n if not url:\n return base\n \n base,url,_coerce_result=_coerce_args(base,url)\n bscheme,bnetloc,bpath,bparams,bquery,bfragment=\\\n urlparse(base,'',allow_fragments)\n scheme,netloc,path,params,query,fragment=\\\n urlparse(url,bscheme,allow_fragments)\n \n if scheme !=bscheme or scheme not in uses_relative:\n return _coerce_result(url)\n if scheme in uses_netloc:\n if netloc:\n return _coerce_result(urlunparse((scheme,netloc,path,\n params,query,fragment)))\n netloc=bnetloc\n \n if not path and not params:\n path=bpath\n params=bparams\n if not query:\n query=bquery\n return _coerce_result(urlunparse((scheme,netloc,path,\n params,query,fragment)))\n \n base_parts=bpath.split('/')\n if base_parts[-1]!='':\n \n \n del base_parts[-1]\n \n \n if path[:1]=='/':\n segments=path.split('/')\n else:\n segments=base_parts+path.split('/')\n \n \n segments[1:-1]=filter(None,segments[1:-1])\n \n resolved_path=[]\n \n for seg in segments:\n if seg =='..':\n try:\n resolved_path.pop()\n except IndexError:\n \n \n pass\n elif seg =='.':\n continue\n else:\n resolved_path.append(seg)\n \n if segments[-1]in('.','..'):\n \n \n resolved_path.append('')\n \n return _coerce_result(urlunparse((scheme,netloc,'/'.join(\n resolved_path)or '/',params,query,fragment)))\n \n \ndef urldefrag(url):\n ''\n\n\n\n\n \n url,_coerce_result=_coerce_args(url)\n if '#'in url:\n s,n,p,a,q,frag=urlparse(url)\n defrag=urlunparse((s,n,p,a,q,''))\n else:\n frag=''\n defrag=url\n return _coerce_result(DefragResult(defrag,frag))\n \n_hexdig='0123456789ABCDEFabcdef'\n_hextobyte=None\n\ndef unquote_to_bytes(string):\n ''\n return bytes(_unquote_impl(string))\n \ndef _unquote_impl(string:bytes |bytearray |str)->bytes |bytearray:\n\n\n if not string:\n \n string.split\n return b''\n if isinstance(string,str):\n string=string.encode('utf-8')\n bits=string.split(b'%')\n if len(bits)==1:\n return string\n res=bytearray(bits[0])\n append=res.extend\n \n \n global _hextobyte\n if _hextobyte is None:\n _hextobyte={(a+b).encode():bytes.fromhex(a+b)\n for a in _hexdig for b in _hexdig}\n for item in bits[1:]:\n try:\n append(_hextobyte[item[:2]])\n append(item[2:])\n except KeyError:\n append(b'%')\n append(item)\n return res\n \n_asciire=re.compile('([\\x00-\\x7f]+)')\n\ndef _generate_unquoted_parts(string,encoding,errors):\n previous_match_end=0\n for ascii_match in _asciire.finditer(string):\n start,end=ascii_match.span()\n yield string[previous_match_end:start]\n \n yield _unquote_impl(ascii_match[1]).decode(encoding,errors)\n previous_match_end=end\n yield string[previous_match_end:]\n \ndef unquote(string,encoding='utf-8',errors='replace'):\n ''\n\n\n\n\n\n\n\n \n if isinstance(string,bytes):\n return _unquote_impl(string).decode(encoding,errors)\n if '%'not in string:\n \n string.split\n return string\n if encoding is None:\n encoding='utf-8'\n if errors is None:\n errors='replace'\n return ''.join(_generate_unquoted_parts(string,encoding,errors))\n \n \ndef parse_qs(qs,keep_blank_values=False,strict_parsing=False,\nencoding='utf-8',errors='replace',max_num_fields=None,separator='&'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n parsed_result={}\n pairs=parse_qsl(qs,keep_blank_values,strict_parsing,\n encoding=encoding,errors=errors,\n max_num_fields=max_num_fields,separator=separator)\n for name,value in pairs:\n if name in parsed_result:\n parsed_result[name].append(value)\n else:\n parsed_result[name]=[value]\n return parsed_result\n \n \ndef parse_qsl(qs,keep_blank_values=False,strict_parsing=False,\nencoding='utf-8',errors='replace',max_num_fields=None,separator='&'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not separator or not isinstance(separator,(str,bytes)):\n raise ValueError(\"Separator must be of type string or bytes.\")\n if isinstance(qs,str):\n if not isinstance(separator,str):\n separator=str(separator,'ascii')\n eq='='\n def _unquote(s):\n return unquote_plus(s,encoding=encoding,errors=errors)\n else:\n if not qs:\n return[]\n \n \n qs=bytes(memoryview(qs))\n if isinstance(separator,str):\n separator=bytes(separator,'ascii')\n eq=b'='\n def _unquote(s):\n return unquote_to_bytes(s.replace(b'+',b' '))\n \n if not qs:\n return[]\n \n \n \n \n if max_num_fields is not None:\n num_fields=1+qs.count(separator)\n if max_num_fields \"\n \n def __missing__(self,b):\n \n res=chr(b)if b in self.safe else '%{:02X}'.format(b)\n self[b]=res\n return res\n \ndef quote(string,safe='/',encoding=None,errors=None):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(string,str):\n if not string:\n return string\n if encoding is None:\n encoding='utf-8'\n if errors is None:\n errors='strict'\n string=string.encode(encoding,errors)\n else:\n if encoding is not None:\n raise TypeError(\"quote() doesn't support 'encoding' for bytes\")\n if errors is not None:\n raise TypeError(\"quote() doesn't support 'errors' for bytes\")\n return quote_from_bytes(string,safe)\n \ndef quote_plus(string,safe='',encoding=None,errors=None):\n ''\n\n\n \n \n \n if((isinstance(string,str)and ' 'not in string)or\n (isinstance(string,bytes)and b' 'not in string)):\n return quote(string,safe,encoding,errors)\n if isinstance(safe,str):\n space=' '\n else:\n space=b' '\n string=quote(string,safe+space,encoding,errors)\n return string.replace(' ','+')\n \n \n@functools.lru_cache\ndef _byte_quoter_factory(safe):\n return _Quoter(safe).__getitem__\n \ndef quote_from_bytes(bs,safe='/'):\n ''\n\n\n \n if not isinstance(bs,(bytes,bytearray)):\n raise TypeError(\"quote_from_bytes() expected bytes\")\n if not bs:\n return ''\n if isinstance(safe,str):\n \n safe=safe.encode('ascii','ignore')\n else:\n \n safe=bytes([c for c in safe if c <128])\n if not bs.rstrip(_ALWAYS_SAFE_BYTES+safe):\n return bs.decode()\n quoter=_byte_quoter_factory(safe)\n if(bs_len :=len(bs))<200_000:\n return ''.join(map(quoter,bs))\n else:\n \n chunk_size=math.isqrt(bs_len)\n chunks=[''.join(map(quoter,bs[i:i+chunk_size]))\n for i in range(0,bs_len,chunk_size)]\n return ''.join(chunks)\n \ndef urlencode(query,doseq=False,safe='',encoding=None,errors=None,\nquote_via=quote_plus):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if hasattr(query,\"items\"):\n query=query.items()\n else:\n \n \n try:\n \n \n if len(query)and not isinstance(query[0],tuple):\n raise TypeError\n \n \n \n \n except TypeError as err:\n raise TypeError(\"not a valid non-string sequence \"\n \"or mapping object\")from err\n \n l=[]\n if not doseq:\n for k,v in query:\n if isinstance(k,bytes):\n k=quote_via(k,safe)\n else:\n k=quote_via(str(k),safe,encoding,errors)\n \n if isinstance(v,bytes):\n v=quote_via(v,safe)\n else:\n v=quote_via(str(v),safe,encoding,errors)\n l.append(k+'='+v)\n else:\n for k,v in query:\n if isinstance(k,bytes):\n k=quote_via(k,safe)\n else:\n k=quote_via(str(k),safe,encoding,errors)\n \n if isinstance(v,bytes):\n v=quote_via(v,safe)\n l.append(k+'='+v)\n elif isinstance(v,str):\n v=quote_via(v,safe,encoding,errors)\n l.append(k+'='+v)\n else:\n try:\n \n x=len(v)\n except TypeError:\n \n v=quote_via(str(v),safe,encoding,errors)\n l.append(k+'='+v)\n else:\n \n for elt in v:\n if isinstance(elt,bytes):\n elt=quote_via(elt,safe)\n else:\n elt=quote_via(str(elt),safe,encoding,errors)\n l.append(k+'='+elt)\n return '&'.join(l)\n \n \ndef to_bytes(url):\n warnings.warn(\"urllib.parse.to_bytes() is deprecated as of 3.8\",\n DeprecationWarning,stacklevel=2)\n return _to_bytes(url)\n \n \ndef _to_bytes(url):\n ''\n \n \n \n if isinstance(url,str):\n try:\n url=url.encode(\"ASCII\").decode()\n except UnicodeError:\n raise UnicodeError(\"URL \"+repr(url)+\n \" contains non-ASCII characters\")\n return url\n \n \ndef unwrap(url):\n ''\n\n\n \n url=str(url).strip()\n if url[:1]=='<'and url[-1:]=='>':\n url=url[1:-1].strip()\n if url[:4]=='URL:':\n url=url[4:].strip()\n return url\n \n \ndef splittype(url):\n warnings.warn(\"urllib.parse.splittype() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splittype(url)\n \n \n_typeprog=None\ndef _splittype(url):\n ''\n global _typeprog\n if _typeprog is None:\n _typeprog=re.compile('([^/:]+):(.*)',re.DOTALL)\n \n match=_typeprog.match(url)\n if match:\n scheme,data=match.groups()\n return scheme.lower(),data\n return None,url\n \n \ndef splithost(url):\n warnings.warn(\"urllib.parse.splithost() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splithost(url)\n \n \n_hostprog=None\ndef _splithost(url):\n ''\n global _hostprog\n if _hostprog is None:\n _hostprog=re.compile('//([^/#?]*)(.*)',re.DOTALL)\n \n match=_hostprog.match(url)\n if match:\n host_port,path=match.groups()\n if path and path[0]!='/':\n path='/'+path\n return host_port,path\n return None,url\n \n \ndef splituser(host):\n warnings.warn(\"urllib.parse.splituser() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splituser(host)\n \n \ndef _splituser(host):\n ''\n user,delim,host=host.rpartition('@')\n return(user if delim else None),host\n \n \ndef splitpasswd(user):\n warnings.warn(\"urllib.parse.splitpasswd() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitpasswd(user)\n \n \ndef _splitpasswd(user):\n ''\n user,delim,passwd=user.partition(':')\n return user,(passwd if delim else None)\n \n \ndef splitport(host):\n warnings.warn(\"urllib.parse.splitport() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitport(host)\n \n \n \n_portprog=None\ndef _splitport(host):\n ''\n global _portprog\n if _portprog is None:\n _portprog=re.compile('(.*):([0-9]*)',re.DOTALL)\n \n match=_portprog.fullmatch(host)\n if match:\n host,port=match.groups()\n if port:\n return host,port\n return host,None\n \n \ndef splitnport(host,defport=-1):\n warnings.warn(\"urllib.parse.splitnport() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitnport(host,defport)\n \n \ndef _splitnport(host,defport=-1):\n ''\n\n\n \n host,delim,port=host.rpartition(':')\n if not delim:\n host=port\n elif port:\n if port.isdigit()and port.isascii():\n nport=int(port)\n else:\n nport=None\n return host,nport\n return host,defport\n \n \ndef splitquery(url):\n warnings.warn(\"urllib.parse.splitquery() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitquery(url)\n \n \ndef _splitquery(url):\n ''\n path,delim,query=url.rpartition('?')\n if delim:\n return path,query\n return url,None\n \n \ndef splittag(url):\n warnings.warn(\"urllib.parse.splittag() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splittag(url)\n \n \ndef _splittag(url):\n ''\n path,delim,tag=url.rpartition('#')\n if delim:\n return path,tag\n return url,None\n \n \ndef splitattr(url):\n warnings.warn(\"urllib.parse.splitattr() is deprecated as of 3.8, \"\n \"use urllib.parse.urlparse() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitattr(url)\n \n \ndef _splitattr(url):\n ''\n \n words=url.split(';')\n return words[0],words[1:]\n \n \ndef splitvalue(attr):\n warnings.warn(\"urllib.parse.splitvalue() is deprecated as of 3.8, \"\n \"use urllib.parse.parse_qsl() instead\",\n DeprecationWarning,stacklevel=2)\n return _splitvalue(attr)\n \n \ndef _splitvalue(attr):\n ''\n attr,delim,value=attr.partition('=')\n return attr,(value if delim else None)\n", ["collections", "functools", "ipaddress", "math", "re", "types", "unicodedata", "warnings"]], "urllib.request": [".py", "from browser import ajax\nfrom. import error\n\nclass FileIO:\n\n def __init__(self,data):\n self._data=data\n \n def __enter__(self):\n return self\n \n def __exit__(self,*args):\n pass\n \n def read(self):\n return self._data\n \ndef urlopen(url,data=None,timeout=None):\n global result\n result=None\n \n def on_complete(req):\n global result\n if req.status ==200:\n result=req\n \n _ajax=ajax.ajax()\n _ajax.bind('complete',on_complete)\n if timeout is not None:\n _ajax.set_timeout(timeout)\n \n if data is None:\n _ajax.open('GET',url,False)\n _ajax.send()\n else:\n _ajax.open('POST',url,False)\n _ajax.send(data)\n \n if result is not None:\n if isinstance(result.text,str):\n return FileIO(result.text)\n \n return FileIO(result.text())\n raise error.HTTPError('file not found')\n", ["browser", "browser.ajax", "urllib", "urllib.error"]], "urllib.response": [".py", "''\n\n\n\n\n\n\n\nimport tempfile\n\n__all__=['addbase','addclosehook','addinfo','addinfourl']\n\n\nclass addbase(tempfile._TemporaryFileWrapper):\n ''\n \n \n \n def __init__(self,fp):\n super(addbase,self).__init__(fp,'',delete=False)\n \n self.fp=fp\n \n def __repr__(self):\n return '<%s at %r whose fp = %r>'%(self.__class__.__name__,\n id(self),self.file)\n \n def __enter__(self):\n if self.fp.closed:\n raise ValueError(\"I/O operation on closed file\")\n return self\n \n def __exit__(self,type,value,traceback):\n self.close()\n \n \nclass addclosehook(addbase):\n ''\n \n def __init__(self,fp,closehook,*hookargs):\n super(addclosehook,self).__init__(fp)\n self.closehook=closehook\n self.hookargs=hookargs\n \n def close(self):\n try:\n closehook=self.closehook\n hookargs=self.hookargs\n if closehook:\n self.closehook=None\n self.hookargs=None\n closehook(*hookargs)\n finally:\n super(addclosehook,self).close()\n \n \nclass addinfo(addbase):\n ''\n \n def __init__(self,fp,headers):\n super(addinfo,self).__init__(fp)\n self.headers=headers\n \n def info(self):\n return self.headers\n \n \nclass addinfourl(addinfo):\n ''\n \n def __init__(self,fp,headers,url,code=None):\n super(addinfourl,self).__init__(fp,headers)\n self.url=url\n self.code=code\n \n @property\n def status(self):\n return self.code\n \n def getcode(self):\n return self.code\n \n def geturl(self):\n return self.url\n", ["tempfile"]], "urllib": [".py", "", [], 1]} __BRYTHON__.update_VFS(scripts) diff --git a/www/src/py_flags.js b/www/src/py_flags.js index 3784a9f12..e54e6e60e 100644 --- a/www/src/py_flags.js +++ b/www/src/py_flags.js @@ -2,13 +2,13 @@ (function($B){ $B.builtin_class_flags = { builtins: { - 1073763586: ['ImportError', 'StopIteration', 'ArithmeticError', 'PythonFinalizationError', 'EnvironmentError', 'GeneratorExit', 'RuntimeError', 'IOError', 'NotImplementedError', 'FileNotFoundError', 'KeyError', 'UnboundLocalError', 'WindowsError', 'TimeoutError', 'NotADirectoryError', 'OverflowError', 'IndexError', 'AttributeError', 'ResourceWarning', 'BaseException', 'ConnectionResetError', 'ChildProcessError', 'Warning', 'UnicodeDecodeError', 'UnicodeTranslateError', 'RuntimeWarning', 'FutureWarning', 'BytesWarning', 'InterruptedError', 'BaseExceptionGroup', 'TabError', 'AssertionError', 'ImportWarning', 'ConnectionError', 'OSError', 'ConnectionAbortedError', 'ConnectionRefusedError', 'EncodingWarning', 'EOFError', 'TypeError', 'UserWarning', 'Exception', 'PermissionError', 'UnicodeEncodeError', 'FloatingPointError', 'ModuleNotFoundError', 'SyntaxWarning', 'MemoryError', 'SystemExit', 'ReferenceError', 'SyntaxError', '_IncompleteInputError', 'PendingDeprecationWarning', 'SystemError', 'DeprecationWarning', 'IsADirectoryError', 'ValueError', 'FileExistsError', 'BufferError', 'RecursionError', 'ProcessLookupError', 'LookupError', 'BlockingIOError', 'BrokenPipeError', 'IndentationError', 'StopAsyncIteration', 'NameError', 'UnicodeError', 'UnicodeWarning', 'KeyboardInterrupt', 'ZeroDivisionError'], + 1073763586: ['ReferenceError', 'BaseExceptionGroup', 'InterruptedError', 'ConnectionRefusedError', 'RecursionError', 'KeyError', 'ImportError', 'UserWarning', 'BufferError', 'AttributeError', 'OverflowError', 'Exception', 'ChildProcessError', 'SystemError', 'ConnectionError', 'FutureWarning', 'TypeError', 'FileNotFoundError', 'IsADirectoryError', 'NotImplementedError', 'IndentationError', 'PythonFinalizationError', 'FloatingPointError', 'EOFError', 'TabError', 'ValueError', 'ConnectionResetError', 'ImportWarning', 'ConnectionAbortedError', 'PermissionError', 'FileExistsError', 'EnvironmentError', 'NameError', '_IncompleteInputError', 'NotADirectoryError', 'WindowsError', 'SyntaxError', 'ArithmeticError', 'RuntimeWarning', 'BaseException', 'MemoryError', 'StopIteration', 'ZeroDivisionError', 'UnboundLocalError', 'UnicodeWarning', 'UnicodeEncodeError', 'ModuleNotFoundError', 'StopAsyncIteration', 'UnicodeTranslateError', 'GeneratorExit', 'LookupError', 'BlockingIOError', 'IOError', 'AssertionError', 'IndexError', 'ProcessLookupError', 'UnicodeError', 'KeyboardInterrupt', 'BytesWarning', 'ResourceWarning', 'TimeoutError', 'PendingDeprecationWarning', 'Warning', 'BrokenPipeError', 'OSError', 'SyntaxWarning', 'RuntimeError', 'UnicodeDecodeError', 'SystemExit', 'EncodingWarning', 'DeprecationWarning'], 1073763848: ['ExceptionGroup'], 20975874: ['bool'], 4199682: ['float', 'bytearray'], 138417410: ['bytes'], - 21762: ['super', 'enumerate', 'staticmethod', 'classmethod', 'property', 'zip', 'map', 'reversed', 'filter'], - 5378: ['object', 'complex'], + 21762: ['filter', 'zip', 'property', 'reversed', 'staticmethod', 'super', 'classmethod', 'map', 'enumerate'], + 5378: ['complex', 'object'], 541087042: ['dict'], 4216066: ['frozenset', 'set'], 20976898: ['int'], @@ -21,10 +21,10 @@ $B.builtin_class_flags = { 2155896066: ['type'], }, types: { - 20866: ['generator', 'member_descriptor', 'method-wrapper', 'classmethod_descriptor', 'async_generator', 'coroutine', 'frame', 'getset_descriptor'], + 20866: ['getset_descriptor', 'member_descriptor', 'classmethod_descriptor', 'generator', 'coroutine', 'method-wrapper', 'async_generator', 'frame'], 22914: ['builtin_function_or_method'], 20738: ['cell', 'traceback'], - 4354: ['ellipsis', 'NoneType', 'code', 'NotImplementedType'], + 4354: ['code', 'ellipsis', 'NoneType', 'NotImplementedType'], 153858: ['function'], 20802: ['mappingproxy'], 153986: ['method_descriptor'], diff --git a/www/src/version_info.js b/www/src/version_info.js index 830a55da3..cc814e0b6 100644 --- a/www/src/version_info.js +++ b/www/src/version_info.js @@ -1,7 +1,7 @@ __BRYTHON__.implementation = [3, 13, 0, 'dev', 0] __BRYTHON__.version_info = [3, 13, 0, 'final', 0] -__BRYTHON__.compiled_date = "2024-10-10 09:35:26.141461" -__BRYTHON__.timestamp = 1728545726141 +__BRYTHON__.compiled_date = "2024-10-10 09:45:40.204033" +__BRYTHON__.timestamp = 1728546340203 __BRYTHON__.builtin_module_names = ["_ajax", "_ast", "_base64", diff --git a/www/tests/test_unicodedata.py b/www/tests/test_unicodedata.py index 557257072..f89cc5af9 100644 --- a/www/tests/test_unicodedata.py +++ b/www/tests/test_unicodedata.py @@ -244,1796 +244,1752 @@ "9": "0039" }, "names": { - "PERCENT SIGN": "0025", - "LATIN CAPITAL LETTER N": "004E", - "LATIN SMALL LETTER S": "0073", - "": "009A", - "SECTION SIGN": "00A7", - "PLUS-MINUS SIGN": "00B1", - "VULGAR FRACTION ONE QUARTER": "00BC", - "LATIN CAPITAL LETTER U WITH GRAVE": "00D9", - "LATIN SMALL LETTER A WITH GRAVE": "00E0", - "LATIN SMALL LETTER I WITH DIAERESIS": "00EF", - "LATIN SMALL LETTER U WITH GRAVE": "00F9", - "LATIN SMALL LETTER E WITH CARON": "011B", - "LATIN CAPITAL LETTER G WITH DOT ABOVE": "0120", - "LATIN CAPITAL LETTER I WITH TILDE": "0128", - "LATIN SMALL LETTER N PRECEDED BY APOSTROPHE": "0149", - "LATIN SMALL LETTER R WITH ACUTE": "0155", - "LATIN CAPITAL LETTER N WITH LEFT HOOK": "019D", - "LATIN CAPITAL LETTER O WITH HORN": "01A0", - "LATIN CAPITAL LETTER TONE TWO": "01A7", - "LATIN SMALL LETTER U WITH HORN": "01B0", - "LATIN CAPITAL LETTER Z WITH STROKE": "01B5", - "LATIN SMALL LETTER O WITH CARON": "01D2", - "LATIN SMALL LETTER R WITH INVERTED BREVE": "0213", - "LATIN SMALL LETTER Z WITH SWASH TAIL": "0240", - "LATIN CAPITAL LETTER R WITH STROKE": "024C", - "LATIN SMALL LETTER TURNED A": "0250", - "LATIN LETTER SMALL CAPITAL I": "026A", - "LATIN SMALL LETTER N WITH RETROFLEX HOOK": "0273", - "LATIN SMALL LETTER R WITH LONG LEG": "027C", - "LATIN SMALL LETTER CLOSED OPEN E": "029A", - "LATIN LETTER SMALL CAPITAL G WITH HOOK": "029B", - "LATIN SMALL LETTER J WITH CROSSED-TAIL": "029D", - "MODIFIER LETTER RIGHT HALF RING": "02BE", - "MODIFIER LETTER REVERSED GLOTTAL STOP": "02C1", - "MODIFIER LETTER LOW VERTICAL LINE": "02CC", - "DOT ABOVE": "02D9", - "MODIFIER LETTER LOW RING": "02F3", - "MODIFIER LETTER LOW TILDE": "02F7", - "MODIFIER LETTER END LOW TONE": "02FC", - "COMBINING DOUBLE ACUTE ACCENT": "030B", - "COMBINING COMMA ABOVE RIGHT": "0315", - "COMBINING LATIN SMALL LETTER R": "036C", - "GREEK TONOS": "0384", + "COLON": "003A", + "LATIN CAPITAL LETTER P": "0050", + "LATIN CAPITAL LETTER Z": "005A", + "LATIN SMALL LETTER G": "0067", + "": "0085", + "LATIN CAPITAL LETTER O WITH STROKE": "00D8", + "LATIN SMALL LETTER A WITH CIRCUMFLEX": "00E2", + "LATIN CAPITAL LETTER E WITH CARON": "011A", + "LATIN CAPITAL LETTER I WITH MACRON": "012A", + "LATIN CAPITAL LETTER W WITH CIRCUMFLEX": "0174", + "LATIN CAPITAL LETTER OPEN E": "0190", + "LATIN LETTER TWO WITH STROKE": "01BB", + "LATIN LETTER WYNN": "01BF", + "LATIN SMALL LETTER J WITH CARON": "01F0", + "LATIN CAPITAL LETTER B WITH STROKE": "0243", + "LATIN SMALL LETTER T WITH RETROFLEX HOOK": "0288", + "LATIN SMALL LETTER TURNED K": "029E", + "MODIFIER LETTER SMALL W": "02B7", + "MODIFIER LETTER HIGH TONE BAR": "02E6", + "COMBINING MACRON": "0304", + "COMBINING BRIDGE BELOW": "032A", + "COMBINING INVERTED BRIDGE BELOW": "033A", + "COMBINING GRAVE TONE MARK": "0340", + "COMBINING BRIDGE ABOVE": "0346", + "COMBINING EQUALS SIGN BELOW": "0347", + "COMBINING GRAPHEME JOINER": "034F", + "COMBINING RIGHT HALF RING ABOVE": "0357", + "COMBINING ZIGZAG ABOVE": "035B", + "COMBINING DOUBLE BREVE": "035D", + "GREEK CAPITAL LETTER OMICRON WITH TONOS": "038C", "GREEK CAPITAL LETTER DELTA": "0394", - "GREEK CAPITAL LETTER ZETA": "0396", - "GREEK CAPITAL LETTER UPSILON": "03A5", - "GREEK SMALL LETTER ALPHA": "03B1", - "GREEK SMALL LETTER ZETA": "03B6", - "GREEK SMALL LETTER PHI": "03C6", - "GREEK PI SYMBOL": "03D6", - "GREEK LUNATE SIGMA SYMBOL": "03F2", - "GREEK LETTER YOT": "03F3", - "CYRILLIC CAPITAL LETTER LJE": "0409", + "GREEK SMALL LETTER PSI": "03C8", + "GREEK SMALL LETTER OMICRON WITH TONOS": "03CC", + "COPTIC CAPITAL LETTER HORI": "03E8", + "GREEK CAPITAL LETTER SAN": "03FA", + "CYRILLIC CAPITAL LETTER IE WITH GRAVE": "0400", "CYRILLIC CAPITAL LETTER SHORT U": "040E", - "CYRILLIC CAPITAL LETTER IE": "0415", - "CYRILLIC CAPITAL LETTER TE": "0422", - "CYRILLIC CAPITAL LETTER CHE": "0427", - "CYRILLIC CAPITAL LETTER FITA": "0472", - "COMBINING CYRILLIC TITLO": "0483", - "CYRILLIC SMALL LETTER BASHKIR KA": "04A1", - "CYRILLIC CAPITAL LETTER HA WITH DESCENDER": "04B2", - "CYRILLIC CAPITAL LETTER ABKHASIAN CHE": "04BC", - "CYRILLIC CAPITAL LETTER ZHE WITH BREVE": "04C1", - "CYRILLIC SMALL LETTER SCHWA WITH DIAERESIS": "04DB", - "CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS": "04EA", - "CYRILLIC SMALL LETTER GHE WITH DESCENDER": "04F7", - "CYRILLIC CAPITAL LETTER ALEUT KA": "051E", - "CYRILLIC SMALL LETTER DCHE": "052D", - "ARMENIAN CAPITAL LETTER INI": "053B", - "ARMENIAN CAPITAL LETTER REH": "0550", - "ARMENIAN SMALL LETTER BEN": "0562", - "ARMENIAN SMALL LETTER CO": "0581", - "ARMENIAN DRAM SIGN": "058F", - "HEBREW ACCENT ZAQEF QATAN": "0594", - "HEBREW ACCENT YERAH BEN YOMO": "05AA", - "HEBREW POINT HOLAM": "05B9", - "HEBREW POINT METEG": "05BD", - "ARABIC RAY": "0608", - "ARABIC SIGN ALAYHE ASSALLAM": "0611", + "CYRILLIC SMALL LETTER KA": "043A", + "CYRILLIC SMALL LETTER O": "043E", + "CYRILLIC SMALL LETTER DZHE": "045F", + "CYRILLIC CAPITAL LETTER LITTLE YUS": "0466", + "CYRILLIC SMALL LETTER UK": "0479", + "CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK": "0494", + "CYRILLIC SMALL LETTER PE WITH MIDDLE HOOK": "04A7", + "CYRILLIC CAPITAL LETTER ES WITH DESCENDER": "04AA", + "CYRILLIC CAPITAL LETTER EL WITH TAIL": "04C5", + "CYRILLIC CAPITAL LETTER A WITH BREVE": "04D0", + "CYRILLIC SMALL LIGATURE A IE": "04D5", + "CYRILLIC CAPITAL LETTER I WITH MACRON": "04E2", + "CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS": "04F8", + "CYRILLIC SMALL LETTER EL WITH HOOK": "0513", + "CYRILLIC SMALL LETTER EL WITH DESCENDER": "052F", + "ARMENIAN CAPITAL LETTER CO": "0551", + "ARMENIAN CAPITAL LETTER KEH": "0554", + "HEBREW MARK LOWER DOT": "05C5", + "HEBREW LETTER FINAL TSADI": "05E5", + "HEBREW LETTER TSADI": "05E6", + "ARABIC SIGN TAKHALLUS": "0614", + "ARABIC SMALL HIGH TAH": "0615", + "ARABIC TATWEEL": "0640", "ARABIC INVERTED DAMMA": "0657", - "ARABIC-INDIC DIGIT EIGHT": "0668", - "ARABIC LETTER ALEF WITH WAVY HAMZA BELOW": "0673", - "ARABIC LETTER HAH WITH HAMZA ABOVE": "0681", - "ARABIC LETTER SEEN WITH THREE DOTS BELOW AND THREE DOTS ABOVE": "069C", - "ARABIC LETTER SAD WITH THREE DOTS ABOVE": "069E", - "ARABIC LETTER TEH MARBUTA GOAL": "06C3", - "ARABIC LETTER YU": "06C8", + "ARABIC-INDIC DIGIT ONE": "0661", + "ARABIC LETTER TEH WITH RING": "067C", + "ARABIC LETTER BEHEH": "0680", + "ARABIC LETTER FEH WITH DOT BELOW": "06A3", + "ARABIC LETTER HEH GOAL": "06C1", "ARABIC SMALL HIGH JEEM": "06DA", - "ARABIC ROUNDED HIGH STOP WITH FILLED CENTRE": "06EC", - "ARABIC LETTER HEH WITH INVERTED V": "06FF", - "SYRIAC SUBLINEAR COLON SKEWED RIGHT": "0709", - "SYRIAC LETTER TETH": "071B", - "SYRIAC LETTER QAPH": "0729", - "SYRIAC PTHAHA ABOVE": "0730", - "SYRIAC OBLIQUE LINE BELOW": "0748", - "ARABIC LETTER BEH WITH THREE DOTS POINTING UPWARDS BELOW AND TWO DOTS ABOVE": "0753", - "ARABIC LETTER FARSI YEH WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE": "0776", - "ARABIC LETTER YEH BARREE WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE": "077A", - "THAANA LETTER LHAVIYANI": "0785", - "THAANA AABAAFILI": "07A7", - "NKO DIGIT SEVEN": "07C7", - "NKO LETTER A": "07CA", - "NKO LETTER FA": "07DD", - "NKO LETTER WA": "07E5", - "NKO COMBINING LONG HIGH TONE": "07EF", - "NKO LOW TONE APOSTROPHE": "07F5", - "SAMARITAN LETTER IY": "0804", - "SAMARITAN MARK DAGESH": "0819", - "SAMARITAN VOWEL SIGN AA": "0820", - "SAMARITAN VOWEL SIGN OVERLONG A": "0821", - "SAMARITAN VOWEL SIGN SHORT A": "0825", - "MANDAIC LETTER AL": "084B", - "MANDAIC LETTER AN": "084D", - "MANDAIC LETTER AR": "0853", - "MANDAIC LETTER DUSHENNA": "0856", - "ARABIC LETTER ALEF WITH ATTACHED RIGHT HAMZA": "0881", - "ARABIC LETTER LOW ALEF": "08AD", - "ARABIC LETTER DAL WITH THREE DOTS BELOW": "08AE", - "ARABIC LETTER ZAIN WITH INVERTED V ABOVE": "08B2", - "ARABIC LETTER TCHEH WITH SMALL V": "08C1", - "ARABIC LETTER KEHEH WITH SMALL V": "08C2", - "ARABIC CURLY FATHATAN": "08E7", - "ARABIC OPEN KASRATAN": "08F2", - "ARABIC LEFT ARROWHEAD BELOW": "08F9", - "DEVANAGARI LETTER GHA": "0918", - "DEVANAGARI LETTER DA": "0926", - "DEVANAGARI LETTER BHA": "092D", - "DEVANAGARI VOWEL SIGN E": "0947", - "DEVANAGARI VOWEL SIGN UUE": "0957", + "ARABIC EMPTY CENTRE HIGH STOP": "06EB", + "SYRIAC SUBLINEAR FULL STOP": "0702", + "SYRIAC COLON SKEWED LEFT": "0706", + "SYRIAC LETTER ZAIN": "0719", + "THAANA LETTER GAAFU": "078E", + "THAANA LETTER AINU": "07A2", + "NKO LETTER E": "07CD", + "NKO LETTER NYA": "07E2", + "NKO COMBINING SHORT RISING TONE": "07ED", + "NKO DOROME SIGN": "07FE", + "NKO TAMAN SIGN": "07FF", + "SAMARITAN VOWEL SIGN LONG AA": "081F", + "SAMARITAN PUNCTUATION SHIYYAALAA": "0835", + "MANDAIC PUNCTUATION": "085E", + "ARABIC BASELINE ROUND DOT": "0887", + "ARABIC LETTER WAW WITH DOT WITHIN": "08AB", + "ARABIC TURNED DAMMA BELOW": "08E3", + "ARABIC TONE ONE DOT ABOVE": "08EA", + "ARABIC FATHA WITH RING": "08F4", + "DEVANAGARI LETTER UU": "090A", + "DEVANAGARI LETTER E": "090F", + "DEVANAGARI LETTER DDA": "0921", + "DEVANAGARI VOWEL SIGN SHORT E": "0946", "DEVANAGARI LETTER VOCALIC LL": "0961", + "DEVANAGARI DIGIT SIX": "096C", "DEVANAGARI DIGIT NINE": "096F", - "BENGALI LETTER VOCALIC L": "098C", - "BENGALI LETTER KA": "0995", - "BENGALI LETTER SA": "09B8", - "BENGALI SIGN AVAGRAHA": "09BD", - "BENGALI DIGIT EIGHT": "09EE", - "BENGALI DIGIT NINE": "09EF", - "BENGALI ABBREVIATION SIGN": "09FD", - "GURMUKHI LETTER TA": "0A24", - "GURMUKHI VOWEL SIGN EE": "0A47", - "GURMUKHI VOWEL SIGN OO": "0A4B", + "DEVANAGARI LETTER OE": "0973", + "DEVANAGARI LETTER AW": "0975", + "BENGALI LETTER TA": "09A4", + "BENGALI LETTER BHA": "09AD", + "BENGALI VOWEL SIGN II": "09C0", + "BENGALI VOWEL SIGN VOCALIC LL": "09E3", + "BENGALI DIGIT ONE": "09E7", + "BENGALI DIGIT SEVEN": "09ED", + "BENGALI CURRENCY NUMERATOR TWO": "09F5", + "GURMUKHI VOWEL SIGN AA": "0A3E", "GURMUKHI DIGIT ZERO": "0A66", - "GUJARATI VOWEL CANDRA E": "0A8D", - "GUJARATI VOWEL CANDRA O": "0A91", - "GUJARATI LETTER GHA": "0A98", - "GUJARATI LETTER NNA": "0AA3", - "GUJARATI LETTER BHA": "0AAD", + "GURMUKHI DIGIT SEVEN": "0A6D", + "GURMUKHI TIPPI": "0A70", + "GUJARATI LETTER AU": "0A94", "GUJARATI VOWEL SIGN VOCALIC R": "0AC3", - "GUJARATI VOWEL SIGN AI": "0AC8", - "GUJARATI DIGIT ONE": "0AE7", - "ORIYA VOWEL SIGN AA": "0B3E", - "ORIYA VOWEL SIGN VOCALIC RR": "0B44", - "ORIYA VOWEL SIGN E": "0B47", - "ORIYA VOWEL SIGN AI": "0B48", - "ORIYA DIGIT SIX": "0B6C", - "ORIYA DIGIT EIGHT": "0B6E", - "ORIYA FRACTION THREE QUARTERS": "0B74", - "TAMIL OM": "0BD0", - "TAMIL DIGIT ZERO": "0BE6", - "TAMIL DIGIT NINE": "0BEF", + "GUJARATI VOWEL SIGN AU": "0ACC", + "ORIYA LETTER U": "0B09", + "ORIYA LETTER AI": "0B10", + "ORIYA LETTER GHA": "0B18", + "ORIYA AU LENGTH MARK": "0B57", + "ORIYA DIGIT SEVEN": "0B6D", + "ORIYA FRACTION ONE QUARTER": "0B72", "TAMIL NUMBER ONE HUNDRED": "0BF1", - "TAMIL YEAR SIGN": "0BF5", - "TELUGU LETTER I": "0C07", - "TELUGU LETTER OO": "0C13", - "TELUGU LETTER DDA": "0C21", - "TELUGU LETTER DHA": "0C27", - "TELUGU FRACTION DIGIT ONE FOR ODD POWERS OF FOUR": "0C79", - "KANNADA LETTER OO": "0C93", - "KANNADA LETTER DA": "0CA6", - "KANNADA LETTER MA": "0CAE", - "KANNADA DIGIT ONE": "0CE7", - "MALAYALAM LETTER GA": "0D17", - "MALAYALAM LETTER HA": "0D39", - "MALAYALAM LETTER TTTA": "0D3A", - "MALAYALAM SIGN VIRAMA": "0D4D", - "MALAYALAM VOWEL SIGN VOCALIC LL": "0D63", - "MALAYALAM DATE MARK": "0D79", - "SINHALA LETTER IRUYANNA": "0D8D", - "SINHALA LETTER SANYAKA DDAYANNA": "0DAC", - "SINHALA VOWEL SIGN KETTI AEDA-PILLA": "0DD0", - "THAI CHARACTER KHO KHUAT": "0E03", - "THAI CHARACTER THO THUNG": "0E16", - "THAI CHARACTER SARA AI MAIMUAN": "0E43", - "THAI DIGIT SIX": "0E56", - "LAO LETTER PO": "0E9B", - "LAO LETTER PHO TAM": "0E9E", - "LAO LETTER HO SUNG": "0EAB", - "LAO DIGIT NINE": "0ED9", - "TIBETAN SIGN RDEL NAG GNYIS": "0F1E", - "TIBETAN DIGIT ONE": "0F21", - "TIBETAN DIGIT SEVEN": "0F27", - "TIBETAN LETTER KA": "0F40", - "TIBETAN LETTER TTA": "0F4A", - "TIBETAN LETTER SA": "0F66", - "TIBETAN VOWEL SIGN REVERSED I": "0F80", - "TIBETAN SUBJOINED LETTER TSA": "0FA9", - "TIBETAN SUBJOINED LETTER SA": "0FB6", - "TIBETAN CANTILLATION SIGN SBUB -CHAL": "0FC3", - "TIBETAN SYMBOL NOR BU NYIS -KHYIL": "0FCA", - "RIGHT-FACING SVASTI SIGN": "0FD5", - "TIBETAN MARK LEADING MCHAN RTAGS": "0FD9", - "MYANMAR LETTER GREAT SA": "103F", - "MYANMAR DIGIT TWO": "1042", - "MYANMAR DIGIT FIVE": "1045", - "MYANMAR LETTER MON JHA": "105B", - "MYANMAR LETTER WESTERN PWO KAREN THA": "1065", - "MYANMAR LETTER WESTERN PWO KAREN PWA": "1066", - "MYANMAR LETTER SHAN GA": "1077", - "MYANMAR VOWEL SIGN SHAN AA": "1083", - "MYANMAR SHAN DIGIT SIX": "1096", - "MYANMAR VOWEL SIGN AITON A": "109C", - "GEORGIAN CAPITAL LETTER SHIN": "10B8", - "GEORGIAN CAPITAL LETTER HIE": "10C2", - "GEORGIAN LETTER SHIN": "10E8", - "GEORGIAN LETTER HAR": "10F4", - "HANGUL CHOSEONG MIEUM": "1106", - "HANGUL CHOSEONG SIOS-MIEUM": "1131", - "HANGUL JONGSEONG IEUNG": "11BC", + "TAMIL NUMBER ONE THOUSAND": "0BF2", + "TELUGU SIGN COMBINING ANUSVARA ABOVE": "0C04", + "TELUGU LETTER GA": "0C17", + "KANNADA SIGN ANUSVARA": "0C82", + "KANNADA LETTER U": "0C89", + "KANNADA LETTER VOCALIC R": "0C8B", + "KANNADA LETTER YA": "0CAF", + "KANNADA LETTER SA": "0CB8", + "KANNADA LETTER HA": "0CB9", + "MALAYALAM LETTER EE": "0D0F", + "MALAYALAM LETTER RA": "0D30", + "MALAYALAM VOWEL SIGN U": "0D41", + "MALAYALAM VOWEL SIGN OO": "0D4B", + "MALAYALAM LETTER CHILLU LLL": "0D56", + "SINHALA LETTER IIYANNA": "0D8A", + "SINHALA LETTER EEYANNA": "0D92", + "SINHALA LETTER OOYANNA": "0D95", + "SINHALA VOWEL SIGN KOMBUVA": "0DD9", + "THAI CHARACTER NGO NGU": "0E07", + "THAI CHARACTER MO MA": "0E21", + "THAI CHARACTER YO YAK": "0E22", + "THAI CHARACTER NIKHAHIT": "0E4D", + "THAI CHARACTER YAMAKKAN": "0E4E", + "THAI CHARACTER ANGKHANKHU": "0E5A", + "LAO DIGIT FOUR": "0ED4", + "TIBETAN MARK GTER YIG MGO -UM GTER TSHEG MA": "0F03", + "TIBETAN SIGN YAR TSHES": "0F3E", + "TIBETAN LETTER CHA": "0F46", + "TIBETAN LETTER DHA": "0F52", + "TIBETAN SUBJOINED LETTER DDHA": "0F9D", + "TIBETAN SUBJOINED LETTER NNA": "0F9E", + "TIBETAN SUBJOINED LETTER PA": "0FA4", + "TIBETAN SUBJOINED LETTER FIXED-FORM YA": "0FBB", + "MYANMAR LETTER BHA": "1018", + "MYANMAR SYMBOL GENITIVE": "104F", + "MYANMAR LETTER MON NGA": "105A", + "MYANMAR LETTER MON BBE": "105D", + "MYANMAR LETTER SHAN NA": "107C", + "MYANMAR SHAN DIGIT ZERO": "1090", + "GEORGIAN CAPITAL LETTER BAN": "10A1", + "GEORGIAN LETTER LAS": "10DA", + "GEORGIAN LETTER JIL": "10EB", + "HANGUL CHOSEONG SSANGNIEUN": "1114", + "HANGUL CHOSEONG SIOS-KIYEOK": "112D", + "HANGUL CHOSEONG IEUNG-CHIEUCH": "1149", + "HANGUL JUNGSEONG YO": "116D", + "HANGUL JUNGSEONG YEO-U": "117E", + "HANGUL JUNGSEONG U-A": "1189", + "HANGUL JUNGSEONG U-AE": "118A", + "HANGUL JUNGSEONG U-U": "118D", + "HANGUL JUNGSEONG YU-A": "118E", + "HANGUL JUNGSEONG ARAEA-EO": "119F", + "HANGUL JONGSEONG PIEUP-SIOS": "11B9", "HANGUL JONGSEONG HIEUH": "11C2", - "HANGUL JONGSEONG MIEUM-SIOS": "11DD", - "ETHIOPIC SYLLABLE MI": "121A", - "ETHIOPIC SYLLABLE CAA": "127B", - "ETHIOPIC SYLLABLE NI": "1292", - "ETHIOPIC SYLLABLE NYO": "129E", - "ETHIOPIC SYLLABLE WEE": "12CC", - "ETHIOPIC SYLLABLE DE": "12F5", + "HANGUL JONGSEONG KIYEOK-RIEUL": "11C3", + "HANGUL JONGSEONG NIEUN-KIYEOK": "11C5", + "HANGUL JONGSEONG RIEUL-KAPYEOUNPIEUP": "11D5", + "HANGUL JONGSEONG MIEUM-PIEUP": "11DC", + "HANGUL JONGSEONG HIEUH-PIEUP": "11F8", + "HANGUL JONGSEONG YEORINHIEUH": "11F9", + "ETHIOPIC SYLLABLE SZE": "1225", + "ETHIOPIC SYLLABLE VEE": "126C", + "ETHIOPIC SYLLABLE XO": "1286", + "ETHIOPIC SYLLABLE NYAA": "129B", + "ETHIOPIC SYLLABLE KXO": "12BE", + "ETHIOPIC SYLLABLE WA": "12C8", + "ETHIOPIC SYLLABLE YE": "12ED", "ETHIOPIC SYLLABLE JO": "1306", + "ETHIOPIC SYLLABLE GE": "130D", + "ETHIOPIC SYLLABLE GWEE": "1314", "ETHIOPIC SYLLABLE GGU": "1319", - "ETHIOPIC SYLLABLE GGO": "131E", - "ETHIOPIC SYLLABLE THE": "1325", - "ETHIOPIC COMMA": "1363", + "ETHIOPIC SYLLABLE CHE": "132D", + "ETHIOPIC SYLLABLE FEE": "134C", + "ETHIOPIC SYLLABLE FWA": "134F", + "ETHIOPIC SYLLABLE FYA": "135A", + "CHEROKEE LETTER LU": "13B7", "CHEROKEE LETTER NU": "13C4", - "CHEROKEE LETTER SU": "13D1", "CHEROKEE LETTER SV": "13D2", - "CHEROKEE LETTER DI": "13D7", - "CANADIAN SYLLABICS E": "1401", - "CANADIAN SYLLABICS WA": "1417", - "CANADIAN SYLLABICS Y-CREE W": "141D", - "CANADIAN SYLLABICS CARRIER HI": "1437", - "CANADIAN SYLLABICS Y-CREE TOO": "1452", - "CANADIAN SYLLABICS TWI": "1459", - "CANADIAN SYLLABICS KAA": "1473", - "CANADIAN SYLLABICS SOUTH-SLAVEY KAH": "1488", - "CANADIAN SYLLABICS CWOO": "149A", - "CANADIAN SYLLABICS WEST-CREE CWOO": "149B", - "CANADIAN SYLLABICS WEST-CREE CWAA": "149F", - "CANADIAN SYLLABICS WEST-CREE MWO": "14B3", - "CANADIAN SYLLABICS NWE": "14C9", - "CANADIAN SYLLABICS CARRIER NG": "14D1", - "CANADIAN SYLLABICS Y-CREE LOO": "14D9", - "CANADIAN SYLLABICS LWI": "14DE", - "CANADIAN SYLLABICS WEST-CREE LWAA": "14E9", - "CANADIAN SYLLABICS SO": "14F1", - "CANADIAN SYLLABICS S": "1505", - "CANADIAN SYLLABICS YE": "1526", - "CANADIAN SYLLABICS YII": "1529", - "CANADIAN SYLLABICS YWAA": "153B", - "CANADIAN SYLLABICS RI": "1546", - "CANADIAN SYLLABICS FE": "1553", - "CANADIAN SYLLABICS TTHA": "156E", - "CANADIAN SYLLABICS TYA": "1573", - "CANADIAN SYLLABICS TLHI": "1587", - "CANADIAN SYLLABICS NG": "1595", - "CANADIAN SYLLABICS SAYISI SHE": "1597", + "CHEROKEE LETTER TSA": "13E3", + "CANADIAN SYLLABICS WEST-CREE WII": "1411", + "CANADIAN SYLLABICS WEST-CREE WO": "1413", + "CANADIAN SYLLABICS FINAL GRAVE": "1420", + "CANADIAN SYLLABICS TII": "144F", + "CANADIAN SYLLABICS WEST-CREE TWII": "145C", + "CANADIAN SYLLABICS WEST-CREE KWE": "1475", + "CANADIAN SYLLABICS C": "14A1", + "CANADIAN SYLLABICS ME": "14A3", + "CANADIAN SYLLABICS LWE": "14DC", + "CANADIAN SYLLABICS WEST-CREE SWOO": "14FF", + "CANADIAN SYLLABICS NASKAPI SKWA": "150E", + "CANADIAN SYLLABICS SHWII": "151B", + "CANADIAN SYLLABICS YA": "152D", + "CANADIAN SYLLABICS YWO": "1535", + "CANADIAN SYLLABICS RO": "1548", + "CANADIAN SYLLABICS R": "1550", + "CANADIAN SYLLABICS FAAI": "1554", + "CANADIAN SYLLABICS FI": "1555", + "CANADIAN SYLLABICS N-CREE THI": "1561", + "CANADIAN SYLLABICS THWAA": "1568", + "CANADIAN SYLLABICS NUNAVUT H": "157C", + "CANADIAN SYLLABICS QII": "1580", + "CANADIAN SYLLABICS QOO": "1582", + "CANADIAN SYLLABICS LHA": "15A4", + "CANADIAN SYLLABICS LHAA": "15A5", "CANADIAN SYLLABICS TH-CREE THII": "15A9", - "CANADIAN SYLLABICS TH-CREE THOO": "15AB", - "CANADIAN SYLLABICS BLACKFOOT NA": "15BB", - "CANADIAN SYLLABICS BLACKFOOT KO": "15BE", - "CANADIAN SYLLABICS BLACKFOOT KA": "15BF", - "CANADIAN SYLLABICS CARRIER KKA": "1600", - "CANADIAN SYLLABICS CARRIER JEE": "1618", - "CANADIAN SYLLABICS CARRIER JA": "161B", - "CANADIAN SYLLABICS CARRIER LU": "1622", - "CANADIAN SYLLABICS CARRIER Z": "1646", - "CANADIAN SYLLABICS CARRIER SO": "164F", - "CANADIAN SYLLABICS CARRIER SHEE": "1657", - "CANADIAN SYLLABICS CARRIER CHE": "1663", - "CANADIAN SYLLABICS NNGOO": "1674", - "OGHAM LETTER BEITH": "1681", - "OGHAM LETTER FEARN": "1683", - "OGHAM LETTER NGEADAL": "168D", - "RUNIC LETTER AESC": "16AB", - "RUNIC LETTER HAEGL H": "16BB", - "RUNIC LETTER Z": "16CE", - "RUNIC LETTER LONG-BRANCH-MADR M": "16D8", - "BUHID LETTER I": "1741", - "BUHID LETTER NA": "1748", - "TAGBANWA LETTER U": "1762", - "TAGBANWA VOWEL SIGN I": "1772", - "KHMER LETTER SHA": "179D", - "KHMER SIGN KAKABAT": "17CE", - "KHMER SYMBOL LEK ATTAK PRAM-BUON": "17F9", - "MONGOLIAN FOUR DOTS": "1805", + "CANADIAN SYLLABICS TH-CREE TH": "15AE", + "CANADIAN SYLLABICS CARRIER HWO": "15D7", + "CANADIAN SYLLABICS CARRIER THE": "15DE", + "CANADIAN SYLLABICS CARRIER THEE": "15DF", + "CANADIAN SYLLABICS CARRIER NA": "1607", + "CANADIAN SYLLABICS CARRIER MEE": "160B", + "CANADIAN SYLLABICS CARRIER JJI": "1620", + "CANADIAN SYLLABICS CARRIER SE": "1650", + "CANADIAN SYLLABICS CARRIER SHU": "1654", + "CANADIAN SYLLABICS CARRIER SHA": "1659", + "CANADIAN SYLLABICS CARRIER TSA": "1660", + "CANADIAN SYLLABICS WOODS-CREE THWOO": "167B", + "CANADIAN SYLLABICS WOODS-CREE THWAA": "167D", + "OGHAM LETTER UILLEANN": "1697", + "RUNIC LETTER ANSUZ A": "16A8", + "RUNIC LETTER SHORT-TWIG-TYR T": "16D0", + "RUNIC CROSS PUNCTUATION": "16ED", + "TAGALOG LETTER TA": "1706", + "TAGALOG LETTER RA": "170D", + "TAGALOG LETTER SA": "1710", + "TAGALOG LETTER HA": "1711", + "HANUNOO LETTER YA": "172C", + "BUHID LETTER YA": "174C", + "BUHID VOWEL SIGN U": "1753", + "KHMER LETTER NYO": "1789", + "KHMER LETTER VO": "179C", + "KHMER INDEPENDENT VOWEL QAA": "17A4", + "KHMER SIGN KHAN": "17D4", + "KHMER SIGN ATTHACAN": "17DD", + "KHMER SYMBOL LEK ATTAK MUOY": "17F1", + "KHMER SYMBOL LEK ATTAK PII": "17F2", + "MONGOLIAN DIGIT TWO": "1812", "MONGOLIAN DIGIT FOUR": "1814", - "MONGOLIAN DIGIT EIGHT": "1818", - "MONGOLIAN LETTER O": "1823", - "MONGOLIAN LETTER TODO JIA": "185A", - "MONGOLIAN LETTER SIBE JA": "186A", - "MONGOLIAN LETTER MANCHU ALI GALI ZHA": "18A4", - "CANADIAN SYLLABICS YAY": "18C4", - "CANADIAN SYLLABICS RWOO": "18D2", - "CANADIAN SYLLABICS OJIBWAY M": "18D8", - "CANADIAN SYLLABICS WESTERN W": "18DD", - "LIMBU LETTER GA": "1903", - "LIMBU LETTER YAN": "190A", - "LIMBU LETTER DHA": "190E", - "LIMBU LETTER GYAN": "191D", - "LIMBU VOWEL SIGN U": "1922", - "LIMBU EXCLAMATION MARK": "1944", - "TAI LE LETTER NA": "1962", - "NEW TAI LUE LETTER LOW XA": "1986", - "NEW TAI LUE LETTER LOW DA": "19A4", - "KHMER SYMBOL BEI ROC": "19F3", - "BUGINESE LETTER NGA": "1A02", + "MONGOLIAN LETTER I": "1822", + "MONGOLIAN LETTER ZA": "183D", + "MONGOLIAN LETTER CHI": "1842", + "MONGOLIAN LETTER SIBE CHA": "1871", + "MONGOLIAN LETTER ALI GALI UBADAMA": "1883", + "CANADIAN SYLLABICS PAY": "18B5", + "CANADIAN SYLLABICS TAY": "18B7", + "CANADIAN SYLLABICS SHAY": "18C1", + "CANADIAN SYLLABICS SHWOY": "18C2", + "CANADIAN SYLLABICS R-CREE RWE": "18E0", + "LIMBU LETTER BA": "1912", + "LIMBU SMALL LETTER KA": "1930", + "TAI LE LETTER AI": "196D", + "NEW TAI LUE LETTER HIGH QA": "1980", + "NEW TAI LUE LETTER LOW LA": "199F", + "KHMER SYMBOL BUON ROC": "19F4", + "KHMER SYMBOL PRAM ROC": "19F5", + "KHMER SYMBOL DAP-BUON ROC": "19FE", "BUGINESE LETTER DA": "1A09", + "BUGINESE LETTER SA": "1A14", + "BUGINESE LETTER A": "1A15", + "TAI THAM LETTER HIGH KXA": "1A22", "TAI THAM LETTER LOW CA": "1A29", - "TAI THAM LETTER HIGH SA": "1A48", - "TAI THAM CONSONANT SIGN LA TANG LAI": "1A57", - "TAI THAM VOWEL SIGN UU": "1A6A", - "TAI THAM SIGN KHUEN TONE-5": "1A79", - "COMBINING DOUBLE OPEN MARK BELOW": "1AB8", - "BALINESE LETTER AKARA": "1B05", - "BALINESE LETTER RA REPA TEDUNG": "1B0C", - "BALINESE LETTER NGA": "1B17", - "BALINESE LETTER TZIR SASAK": "1B47", - "BALINESE LETTER VE SASAK": "1B49", - "BALINESE LETTER ARCHAIC JNYA": "1B4C", - "BALINESE MUSICAL SYMBOL DANG GEDE": "1B6A", - "BALINESE MUSICAL SYMBOL COMBINING KEMPUL WITH JEGOGAN": "1B70", - "BALINESE MUSICAL SYMBOL RIGHT-HAND OPEN DAG": "1B75", - "BALINESE PAMADA LANTANG": "1B7E", - "SUNDANESE DIGIT NINE": "1BB9", - "BATAK LETTER PAKPAK WA": "1BCD", - "BATAK LETTER NGA": "1BDD", - "BATAK VOWEL SIGN E": "1BE7", - "LEPCHA LETTER KLA": "1C01", - "LEPCHA LETTER THA": "1C0B", - "LEPCHA LETTER A": "1C23", - "OL CHIKI DIGIT EIGHT": "1C58", - "OL CHIKI LETTER AT": "1C5B", - "OL CHIKI LETTER ANG": "1C5D", - "OL CHIKI MU-GAAHLAA TTUDDAAG": "1C7A", - "GEORGIAN MTAVRULI CAPITAL LETTER GHAN": "1CA6", - "GEORGIAN MTAVRULI CAPITAL LETTER HAE": "1CB0", - "VEDIC TONE TRIPLE SVARITA": "1CDB", - "VEDIC TONE CANDRA ABOVE": "1CF4", - "LATIN SMALL LETTER SIDEWAYS O WITH STROKE": "1D13", - "LATIN SMALL LETTER SIDEWAYS U": "1D1D", - "MODIFIER LETTER CAPITAL O": "1D3C", - "MODIFIER LETTER SMALL U": "1D58", - "MODIFIER LETTER SMALL AIN": "1D5C", - "GREEK SUBSCRIPT SMALL LETTER BETA": "1D66", - "LATIN SMALL LETTER Z WITH MIDDLE TILDE": "1D76", - "LATIN SMALL LETTER F WITH PALATAL HOOK": "1D82", - "LATIN SMALL LETTER A WITH RETROFLEX HOOK": "1D8F", - "LATIN SMALL LETTER OPEN E WITH RETROFLEX HOOK": "1D93", - "MODIFIER LETTER SMALL REVERSED OPEN E": "1D9F", - "MODIFIER LETTER SMALL CAPITAL N": "1DB0", - "COMBINING MACRON-GRAVE": "1DC6", - "COMBINING DOUBLE CIRCUMFLEX ABOVE": "1DCD", + "TAI THAM LETTER LOW CHA": "1A2B", + "TAI THAM LETTER MA": "1A3E", + "TAI THAM LETTER RA": "1A41", + "TAI THAM LETTER HIGH SSA": "1A47", + "TAI THAM LETTER LOW HA": "1A4C", + "TAI THAM HORA DIGIT TWO": "1A82", + "TAI THAM SIGN SAWAN": "1AA2", + "TAI THAM SIGN KEOW": "1AA3", + "COMBINING WIGGLY LINE BELOW": "1AB6", + "COMBINING LIGHT CENTRALIZATION STROKE BELOW": "1AB9", + "BALINESE LETTER IKARA TEDUNG": "1B08", + "BALINESE LETTER OKARA TEDUNG": "1B12", + "BALINESE SIGN REREKAN": "1B34", + "BALINESE VOWEL SIGN PEPET TEDUNG": "1B43", + "BALINESE DIGIT SIX": "1B56", + "SUNDANESE SIGN PAMAAEH": "1BAA", + "BATAK SYMBOL BINDU PINARBORAS": "1BFD", + "LEPCHA LETTER TA": "1C0A", + "LEPCHA LETTER NA": "1C0D", + "LEPCHA LETTER FA": "1C11", + "LEPCHA DIGIT ZERO": "1C40", + "LEPCHA DIGIT FIVE": "1C45", + "LEPCHA DIGIT SIX": "1C46", + "OL CHIKI LETTER IR": "1C68", + "OL CHIKI PHAARKAA": "1C7C", + "GEORGIAN MTAVRULI CAPITAL LETTER HIE": "1CB2", + "GEORGIAN MTAVRULI CAPITAL LETTER HAR": "1CB4", + "GEORGIAN MTAVRULI CAPITAL LETTER ELIFI": "1CB8", + "VEDIC SIGN DOUBLE ANUSVARA ANTARGOMUKHA": "1CFA", + "LATIN LETTER SMALL CAPITAL E": "1D07", + "LATIN LETTER SMALL CAPITAL REVERSED N": "1D0E", + "LATIN SMALL LETTER SIDEWAYS O": "1D11", + "MODIFIER LETTER CAPITAL REVERSED E": "1D32", + "MODIFIER LETTER CAPITAL I": "1D35", + "MODIFIER LETTER SMALL ALPHA": "1D45", + "MODIFIER LETTER SMALL D": "1D48", + "MODIFIER LETTER SMALL T": "1D57", + "GREEK SUBSCRIPT SMALL LETTER PHI": "1D69", + "COMBINING ACUTE-GRAVE-ACUTE": "1DC9", "COMBINING LATIN SMALL LETTER B": "1DE8", - "LATIN CAPITAL LETTER E WITH MACRON AND GRAVE": "1E14", - "LATIN CAPITAL LETTER E WITH TILDE BELOW": "1E1A", - "LATIN SMALL LETTER G WITH MACRON": "1E21", - "LATIN SMALL LETTER H WITH BREVE BELOW": "1E2B", - "LATIN SMALL LETTER I WITH DIAERESIS AND ACUTE": "1E2F", - "LATIN CAPITAL LETTER K WITH DOT BELOW": "1E32", - "LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON": "1E5C", - "LATIN SMALL LETTER W WITH GRAVE": "1E81", - "LATIN SMALL LETTER X WITH DOT ABOVE": "1E8B", - "LATIN CAPITAL LETTER X WITH DIAERESIS": "1E8C", - "LATIN CAPITAL LETTER E WITH HOOK ABOVE": "1EBA", - "LATIN CAPITAL LETTER I WITH HOOK ABOVE": "1EC8", - "LATIN SMALL LETTER O WITH DOT BELOW": "1ECD", - "LATIN SMALL LETTER O WITH CIRCUMFLEX AND GRAVE": "1ED3", - "LATIN SMALL LETTER U WITH HORN AND DOT BELOW": "1EF1", - "LATIN SMALL LETTER Y WITH GRAVE": "1EF3", - "GREEK SMALL LETTER ETA WITH DASIA": "1F21", - "GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI": "1F3E", - "GREEK SMALL LETTER UPSILON WITH DASIA AND VARIA": "1F53", - "GREEK SMALL LETTER ALPHA WITH OXIA": "1F71", - "GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA AND YPOGEGRAMMENI": "1F85", - "GREEK PERISPOMENI": "1FC0", - "ZERO WIDTH JOINER": "200D", - "ONE DOT LEADER": "2024", - "REVERSED TRIPLE PRIME": "2037", - "CARET": "2038", - "COMMERCIAL MINUS SIGN": "2052", - "NATIONAL DIGIT SHAPES": "206E", - "SUPERSCRIPT RIGHT PARENTHESIS": "207E", - "INDIAN RUPEE SIGN": "20B9", + "COMBINING LATIN SMALL LETTER SCHWA": "1DEA", + "LATIN CAPITAL LETTER B WITH DOT ABOVE": "1E02", + "LATIN SMALL LETTER B WITH DOT BELOW": "1E05", + "LATIN SMALL LETTER D WITH DOT BELOW": "1E0D", + "LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW": "1E12", + "LATIN SMALL LETTER K WITH LINE BELOW": "1E35", + "LATIN SMALL LETTER L WITH LINE BELOW": "1E3B", + "LATIN SMALL LETTER L WITH CIRCUMFLEX BELOW": "1E3D", + "LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS": "1E4E", + "LATIN SMALL LETTER S WITH ACUTE AND DOT ABOVE": "1E65", + "LATIN CAPITAL LETTER Z WITH DOT BELOW": "1E92", + "LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE": "1EA5", + "LATIN CAPITAL LETTER A WITH BREVE AND GRAVE": "1EB0", + "LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW": "1EB6", + "LATIN SMALL LETTER I WITH HOOK ABOVE": "1EC9", + "LATIN SMALL LETTER O WITH CIRCUMFLEX AND TILDE": "1ED7", + "LATIN CAPITAL LETTER O WITH HORN AND ACUTE": "1EDA", + "LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW": "1EF0", + "LATIN CAPITAL LETTER MIDDLE-WELSH V": "1EFC", + "GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI": "1F27", + "GREEK SMALL LETTER IOTA WITH OXIA": "1F77", + "GREEK SMALL LETTER UPSILON WITH VARIA": "1F7A", + "GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI": "1F88", + "GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI": "1F89", + "GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI": "1FA7", + "GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI": "1FAE", + "GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI": "1FB4", + "GREEK PROSGEGRAMMENI": "1FBE", + "GREEK CAPITAL LETTER EPSILON WITH VARIA": "1FC8", + "GREEK CAPITAL LETTER IOTA WITH VRACHY": "1FD8", + "GREEK DASIA AND VARIA": "1FDD", + "GREEK CAPITAL LETTER OMEGA WITH VARIA": "1FFA", + "THREE-PER-EM SPACE": "2004", + "DAGGER": "2020", + "TWO DOT LEADER": "2025", + "TIRONIAN SIGN ET": "204A", + "SUBSCRIPT ONE": "2081", + "MANAT SIGN": "20BC", + "COMBINING ENCLOSING UPWARD POINTING TRIANGLE": "20E4", "COMBINING ASTERISK ABOVE": "20F0", - "CARE OF": "2105", - "EULER CONSTANT": "2107", - "SCRIPT CAPITAL I": "2110", - "DOUBLE-STRUCK CAPITAL PI": "213F", - "DOUBLE-STRUCK ITALIC SMALL D": "2146", - "VULGAR FRACTION ONE THIRD": "2153", - "VULGAR FRACTION TWO THIRDS": "2154", - "ROMAN NUMERAL FIFTY": "216C", - "SMALL ROMAN NUMERAL FIVE": "2174", - "SMALL ROMAN NUMERAL FIVE HUNDRED": "217E", - "UP DOWN ARROW": "2195", - "LEFTWARDS WAVE ARROW": "219C", - "LEFTWARDS DOUBLE ARROW WITH STROKE": "21CD", - "UPWARDS ARROW WITH DOUBLE STROKE": "21DE", - "DOWNWARDS WHITE ARROW": "21E9", - "LEFT RIGHT ARROW WITH VERTICAL STROKE": "21F9", - "BULLET OPERATOR": "2219", - "PROPORTIONAL TO": "221D", - "INFINITY": "221E", - "EQUIVALENT TO": "224D", - "APPROXIMATELY EQUAL TO OR THE IMAGE OF": "2252", - "ESTIMATES": "2259", - "PRECEDES OR EQUAL TO": "227C", - "SUPERSET OF WITH NOT EQUAL TO": "228B", - "MULTISET UNION": "228E", + "DOUBLE-STRUCK CAPITAL N": "2115", + "SERVICE MARK": "2120", + "TELEPHONE SIGN": "2121", + "VULGAR FRACTION TWO FIFTHS": "2156", + "ROMAN NUMERAL SIX": "2165", + "ROMAN NUMERAL SIX LATE FORM": "2185", + "DOWNWARDS TWO HEADED ARROW": "21A1", + "NORTH WEST ARROW TO LONG BAR": "21B8", + "RIGHTWARDS HARPOON WITH BARB DOWNWARDS": "21C1", + "RIGHTWARDS ARROW OVER LEFTWARDS ARROW": "21C4", + "LEFTWARDS DOUBLE ARROW": "21D0", + "SOUTH WEST DOUBLE ARROW": "21D9", + "UPWARDS WHITE DOUBLE ARROW ON PEDESTAL": "21EF", + "INVERTED LAZY S": "223E", + "MINUS TILDE": "2242", + "APPROXIMATELY EQUAL TO": "2245", + "NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO": "2247", + "NEITHER GREATER-THAN NOR LESS-THAN": "2279", + "PRECEDES OR EQUIVALENT TO": "227E", + "SUPERSET OF": "2283", + "CIRCLED DOT OPERATOR": "2299", "CIRCLED RING OPERATOR": "229A", - "SQUARED MINUS": "229F", - "RIGHT TACK": "22A2", - "EQUAL TO OR PRECEDES": "22DE", - "LESS-THAN BUT NOT EQUIVALENT TO": "22E6", - "ELEMENT OF WITH DOT ABOVE": "22F5", - "LEFT CEILING": "2308", - "TOP LEFT CROP": "230F", - "ARC": "2312", - "TELEPHONE RECORDER": "2315", - "LEFT-POINTING ANGLE BRACKET": "2329", - "DIMENSION ORIGIN": "2331", - "COUNTERSINK": "2335", - "APL FUNCTIONAL SYMBOL IOTA UNDERBAR": "2378", - "CIRCLED HORIZONTAL BAR WITH NOTCH": "2389", - "UNDO SYMBOL": "238C", - "MONOSTABLE SYMBOL": "238D", - "HORIZONTAL LINE EXTENSION": "23AF", - "HORIZONTAL SCAN LINE-3": "23BB", - "DECIMAL EXPONENT SYMBOL": "23E8", - "BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR": "23ED", - "POWER ON SYMBOL": "23FD", - "SYMBOL FOR SHIFT IN": "240F", - "SYMBOL FOR FILE SEPARATOR": "241C", - "OCR FORK": "2442", - "OCR DASH": "2448", - "CIRCLED DIGIT SEVEN": "2466", - "CIRCLED NUMBER TWENTY": "2473", - "NUMBER SIXTEEN FULL STOP": "2497", - "PARENTHESIZED LATIN SMALL LETTER D": "249F", + "UP TACK": "22A5", + "LESS-THAN WITH DOT": "22D6", + "PRECEDES BUT NOT EQUIVALENT TO": "22E8", + "WAVY LINE": "2307", + "BOTTOM HALF INTEGRAL": "2321", + "APL FUNCTIONAL SYMBOL SQUISH QUAD": "2337", + "APL FUNCTIONAL SYMBOL QUAD DIAMOND": "233A", + "APL FUNCTIONAL SYMBOL DEL STILE": "2352", + "APL FUNCTIONAL SYMBOL QUAD COLON": "2360", + "APL FUNCTIONAL SYMBOL OMEGA": "2375", + "BELL SYMBOL": "237E", + "VERTICAL LINE WITH MIDDLE DOT": "237F", + "ALTERNATIVE KEY SYMBOL": "2387", + "DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL": "23CA", + "STRAIGHTNESS": "23E4", + "SYMBOL FOR END OF TEXT": "2403", + "SYMBOL FOR SHIFT OUT": "240E", + "SYMBOL FOR DEVICE CONTROL FOUR": "2414", + "SYMBOL FOR END OF TRANSMISSION BLOCK": "2417", + "SYMBOL FOR GROUP SEPARATOR": "241D", + "DIGIT ONE FULL STOP": "2488", + "DIGIT NINE FULL STOP": "2490", "PARENTHESIZED LATIN SMALL LETTER F": "24A1", - "PARENTHESIZED LATIN SMALL LETTER H": "24A3", - "PARENTHESIZED LATIN SMALL LETTER K": "24A6", - "CIRCLED LATIN CAPITAL LETTER Y": "24CE", - "NEGATIVE CIRCLED NUMBER SEVENTEEN": "24F1", - "NEGATIVE CIRCLED NUMBER EIGHTEEN": "24F2", - "DOUBLE CIRCLED DIGIT THREE": "24F7", + "PARENTHESIZED LATIN SMALL LETTER J": "24A5", + "CIRCLED LATIN SMALL LETTER A": "24D0", + "NEGATIVE CIRCLED NUMBER ELEVEN": "24EB", + "NEGATIVE CIRCLED NUMBER FOURTEEN": "24EE", + "NEGATIVE CIRCLED NUMBER NINETEEN": "24F3", + "NEGATIVE CIRCLED NUMBER TWENTY": "24F4", "DOUBLE CIRCLED DIGIT FOUR": "24F8", - "NEGATIVE CIRCLED DIGIT ZERO": "24FF", - "BOX DRAWINGS RIGHT HEAVY AND LEFT DOWN LIGHT": "252E", - "BOX DRAWINGS VERTICAL LIGHT AND HORIZONTAL HEAVY": "253F", - "BOX DRAWINGS RIGHT UP HEAVY AND LEFT DOWN LIGHT": "2544", - "BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL": "254E", - "LOWER HALF BLOCK": "2584", - "QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER LEFT": "259B", - "WHITE SQUARE WITH ROUNDED CORNERS": "25A2", - "BULLSEYE": "25CE", - "CIRCLE WITH UPPER HALF BLACK": "25D3", - "WHITE SQUARE WITH UPPER RIGHT QUADRANT": "25F3", - "BLACK MEDIUM SQUARE": "25FC", - "BLACK SHOGI PIECE": "2617", - "CADUCEUS": "2624", - "FEMALE SIGN": "2640", - "LIBRA": "264E", - "WHITE CHESS QUEEN": "2655", - "BLACK CHESS KING": "265A", - "WHITE SPADE SUIT": "2664", - "EIGHTH NOTE": "266A", - "SCALES": "2696", - "CERES": "26B3", - "BLACK DRAUGHTS MAN": "26C2", - "UPPER RIGHT PENCIL": "2710", - "FOUR BALLOON-SPOKED ASTERISK": "2723", - "OPEN CENTRE BLACK STAR": "272B", + "BOX DRAWINGS DOWN LIGHT AND LEFT HEAVY": "2511", + "BOX DRAWINGS UP HEAVY AND LEFT LIGHT": "251A", + "BOX DRAWINGS RIGHT HEAVY AND LEFT UP LIGHT": "2536", + "BOX DRAWINGS LEFT DOWN HEAVY AND RIGHT UP LIGHT": "2545", + "BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE": "255E", + "BOX DRAWINGS LIGHT LEFT": "2574", + "WHITE SMALL SQUARE": "25AB", + "LOWER HALF INVERSE WHITE CIRCLE": "25DB", + "BLACK LOWER RIGHT TRIANGLE": "25E2", + "WHITE SQUARE WITH LOWER LEFT QUADRANT": "25F1", + "WHITE LEFT POINTING INDEX": "261C", + "YIN YANG": "262F", + "WHITE SMILING FACE": "263A", + "URANUS": "2645", + "RECYCLING SYMBOL FOR TYPE-1 PLASTICS": "2673", + "RECYCLING SYMBOL FOR TYPE-5 PLASTICS": "2677", + "HIGH VOLTAGE SIGN": "26A1", + "MEDIUM SMALL WHITE CIRCLE": "26AC", + "CIRCLED CROSSING LANES": "26D2", + "GEAR WITH HANDLES": "26EE", + "HEAVY OUTLINED BLACK STAR": "272E", "HEAVY ASTERISK": "2731", - "BLACK QUESTION MARK ORNAMENT": "2753", - "HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT": "275D", - "HEAVY LOW DOUBLE COMMA QUOTATION MARK ORNAMENT": "2760", - "DINGBAT NEGATIVE CIRCLED DIGIT FOUR": "2779", - "DINGBAT CIRCLED SANS-SERIF DIGIT TWO": "2781", - "THREE DIMENSIONAL ANGLE": "27C0", - "SUPERSET PRECEDING SOLIDUS": "27C9", - "LOWER RIGHT CORNER WITH DOT": "27D3", - "LONG LEFT TACK": "27DE", - "WHITE CONCAVE-SIDED DIAMOND WITH RIGHTWARDS TICK": "27E3", - "BRAILLE PATTERN DOTS-2457": "285A", - "BRAILLE PATTERN DOTS-67": "2860", - "BRAILLE PATTERN DOTS-1467": "2869", + "EIGHT SPOKED ASTERISK": "2733", + "SIX PETALLED BLACK AND WHITE FLORETTE": "273E", + "EIGHT PETALLED OUTLINED BLACK FLORETTE": "2741", + "UPPER RIGHT DROP-SHADOWED WHITE SQUARE": "2750", + "DINGBAT NEGATIVE CIRCLED DIGIT EIGHT": "277D", + "DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT THREE": "278C", + "NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW": "27B1", + "MATHEMATICAL LEFT ANGLE BRACKET": "27E8", + "MATHEMATICAL RIGHT WHITE TORTOISE SHELL BRACKET": "27ED", + "LONG LEFT RIGHT ARROW": "27F7", + "LONG RIGHTWARDS DOUBLE ARROW": "27F9", + "BRAILLE PATTERN DOTS-136": "2825", + "BRAILLE PATTERN DOTS-246": "282A", + "BRAILLE PATTERN DOTS-1347": "284D", + "BRAILLE PATTERN DOTS-2467": "286A", "BRAILLE PATTERN DOTS-12467": "286B", - "BRAILLE PATTERN DOTS-358": "2894", - "BRAILLE PATTERN DOTS-12568": "28B3", - "BRAILLE PATTERN DOTS-1234568": "28BF", - "BRAILLE PATTERN DOTS-378": "28C4", - "BRAILLE PATTERN DOTS-12378": "28C7", - "BRAILLE PATTERN DOTS-3578": "28D4", - "RIGHTWARDS ARROW THROUGH X": "2947", - "LEFT BARB DOWN RIGHT BARB DOWN HARPOON": "2950", - "RIGHTWARDS ARROW ABOVE TILDE OPERATOR": "2974", - "Z NOTATION RIGHT BINDING BRACKET": "298A", - "SPHERICAL ANGLE OPENING UP": "29A1", - "REVERSED ANGLE WITH UNDERBAR": "29A5", - "OBLIQUE ANGLE OPENING UP": "29A6", + "BRAILLE PATTERN DOTS-18": "2881", + "BRAILLE PATTERN DOTS-1358": "2895", + "BRAILLE PATTERN DOTS-2458": "289A", + "BRAILLE PATTERN DOTS-23468": "28AE", + "BRAILLE PATTERN DOTS-1568": "28B1", + "BRAILLE PATTERN DOTS-45678": "28F8", + "BRAILLE PATTERN DOTS-2345678": "28FE", + "NORTH EAST ARROW WITH HOOK": "2924", + "SOUTH EAST ARROW AND SOUTH WEST ARROW": "2929", + "TOP ARC ANTICLOCKWISE ARROW": "293A", + "UP BARB LEFT DOWN BARB RIGHT HARPOON": "294D", + "RIGHTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB UP": "2968", + "Z NOTATION TYPE COLON": "2982", + "RIGHT WHITE CURLY BRACKET": "2984", + "MEASURED ANGLE OPENING LEFT": "299B", "TRIANGLE WITH UNDERBAR": "29CB", - "EQUALS SIGN AND SLANTED PARALLEL": "29E3", - "MODULO TWO SUM": "2A0A", - "CIRCULATION FUNCTION": "2A10", - "Z NOTATION SCHEMA PIPING": "2A20", - "SMASH PRODUCT": "2A33", - "DOUBLE LOGICAL AND": "2A53", - "SLOPING LARGE AND": "2A58", - "LOGICAL AND WITH UNDERBAR": "2A5F", - "LESS-THAN AND NOT APPROXIMATE": "2A89", - "EQUALS SIGN WITH BUMPY ABOVE": "2AAE", - "PRECEDES ABOVE NOT EQUAL TO": "2AB5", - "SUPERSET OF OR EQUAL TO WITH DOT ABOVE": "2AC4", - "DOWN TACK WITH CIRCLE BELOW": "2AF1", - "NORTH EAST BLACK ARROW": "2B08", - "BLACK MEDIUM DIAMOND": "2B25", - "WHITE SMALL LOZENGE": "2B2B", - "THREE LEFTWARDS ARROWS": "2B31", - "SLANTED NORTH ARROW WITH HORIZONTAL TAIL": "2B5C", - "UPWARDS TRIANGLE-HEADED ARROW LEFTWARDS OF DOWNWARDS TRIANGLE-HEADED ARROW": "2B81", - "BLACK OCTAGON": "2BC4", - "ADMETOS": "2BE5", - "VULCANUS": "2BE6", - "STAR WITH RIGHT HALF BLACK": "2BEB", - "REVERSED RIGHT ANGLE": "2BFE", - "GLAGOLITIC SMALL LETTER HERU": "2C48", - "COPTIC SMALL LETTER NI": "2C9B", - "COPTIC SMALL LETTER KSI": "2C9D", - "COPTIC CAPITAL LETTER CRYPTOGRAMMIC NI": "2CBC", - "COPTIC SMALL LETTER OLD COPTIC OOU": "2CBF", - "COPTIC CAPITAL LETTER OLD COPTIC HA": "2CCE", - "COPTIC SMALL LETTER OLD NUBIAN NGI": "2CDF", - "COPTIC MORPHOLOGICAL DIVIDER": "2CFF", - "TIFINAGH LETTER YAH": "2D40", - "TIFINAGH LETTER YAZH": "2D4A", - "TIFINAGH LETTER YU": "2D53", - "TIFINAGH LETTER YAR": "2D54", - "TIFINAGH LETTER YACH": "2D5E", - "ETHIOPIC SYLLABLE CCAA": "2DAB", - "ETHIOPIC SYLLABLE CCHO": "2DBE", - "COMBINING CYRILLIC LETTER EN": "2DE9", - "COMBINING CYRILLIC LETTER YAT": "2DFA", + "S IN TRIANGLE": "29CC", + "RIGHT DOUBLE WIGGLY FENCE": "29DB", + "INCREASES AS": "29E1", + "PLUS SIGN WITH CIRCUMFLEX ACCENT ABOVE": "2A23", + "INTERIOR PRODUCT": "2A3C", + "INTERSECTION WITH DOT": "2A40", + "INTERSECTION ABOVE UNION": "2A47", + "UNION ABOVE BAR ABOVE INTERSECTION": "2A48", + "TILDE OPERATOR WITH RISING DOTS": "2A6B", + "EQUALS SIGN ABOVE TILDE OPERATOR": "2A73", + "LESS-THAN OR SLANTED EQUAL TO WITH DOT ABOVE": "2A81", + "LESS-THAN ABOVE SIMILAR ABOVE GREATER-THAN": "2A8F", + "SIMILAR OR GREATER-THAN": "2A9E", + "PRECEDES ABOVE EQUALS SIGN": "2AB3", + "DOUBLE PRECEDES": "2ABB", + "DOUBLE SUCCEEDS": "2ABC", + "SUPERSET OF ABOVE ALMOST EQUAL TO": "2ACA", + "ELEMENT OF OPENING DOWNWARDS": "2AD9", + "SHORT DOWN TACK": "2ADF", + "PARALLEL WITH HORIZONTAL STROKE": "2AF2", + "PARALLEL WITH TILDE OPERATOR": "2AF3", + "WHITE VERTICAL BAR": "2AFE", + "RIGHTWARDS ARROW WITH TIP DOWNWARDS": "2B0E", + "RIGHTWARDS ARROW WITH TIP UPWARDS": "2B0F", + "LEFTWARDS ARROW WITH TIP DOWNWARDS": "2B10", + "RIGHTWARDS ARROW THROUGH GREATER-THAN": "2B43", + "HORIZONTAL TAB KEY": "2B7E", + "WHITE FOUR POINTED CUSP": "2BCE", + "GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL": "2C25", + "GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS": "2C29", + "GLAGOLITIC CAPITAL LETTER TROKUTASTI A": "2C2D", + "GLAGOLITIC SMALL LETTER YESTU": "2C35", + "GLAGOLITIC SMALL LETTER PE": "2C4A", + "LATIN SMALL LETTER L WITH DOUBLE BAR": "2C61", + "LATIN SMALL LETTER TAILLESS PHI": "2C77", + "COPTIC CAPITAL LETTER PSI": "2CAE", + "COPTIC CAPITAL LETTER DIALECT-P ALEF": "2CB2", + "COPTIC SMALL LETTER AKHMIMIC KHEI": "2CC9", + "COPTIC SMALL LETTER L-SHAPED HA": "2CD1", + "COPTIC CAPITAL LETTER CRYPTOGRAMMIC GANGIA": "2CED", + "COPTIC OLD NUBIAN DIRECT QUESTION MARK": "2CFA", + "GEORGIAN SMALL LETTER KAN": "2D09", + "GEORGIAN SMALL LETTER PHAR": "2D14", + "GEORGIAN SMALL LETTER CHIN": "2D19", + "TIFINAGH LETTER YEY": "2D3B", + "TIFINAGH LETTER YAK": "2D3D", + "TIFINAGH LETTER TUAREG YAH": "2D42", + "TIFINAGH LETTER YAZZ": "2D65", + "ETHIOPIC SYLLABLE SSO": "2DA6", + "ETHIOPIC SYLLABLE CCA": "2DA8", + "ETHIOPIC SYLLABLE ZZAA": "2DB3", + "COMBINING CYRILLIC LETTER ZHE": "2DE4", + "COMBINING CYRILLIC LETTER TSE": "2DF0", + "COMBINING CYRILLIC LETTER MONOGRAPH UK": "2DF9", + "DOUBLE OBLIQUE HYPHEN": "2E17", "HYPHEN WITH DIAERESIS": "2E1A", - "TOP RIGHT HALF BRACKET": "2E23", - "RIGHT SIDEWAYS U BRACKET": "2E27", - "LEFT DOUBLE PARENTHESIS": "2E28", - "CAPITULUM": "2E3F", - "RIGHT SQUARE BRACKET WITH DOUBLE STROKE": "2E58", - "CJK RADICAL LAME TWO": "2E8F", - "CJK RADICAL LAME FOUR": "2E91", - "CJK RADICAL THREAD": "2E93", - "CJK RADICAL NET ONE": "2EB1", - "CJK RADICAL FOOT": "2ECA", - "CJK RADICAL EAT THREE": "2EDF", + "LEFT SQUARE BRACKET WITH STROKE": "2E55", + "BOTTOM HALF RIGHT PARENTHESIS": "2E5C", + "CJK RADICAL SECOND THREE": "2E84", + "CJK RADICAL BOX": "2E86", + "CJK RADICAL SHEEP": "2EB6", + "CJK RADICAL BRUSH ONE": "2EBA", + "CJK RADICAL CITY": "2ECF", + "CJK RADICAL C-SIMPLIFIED GATE": "2ED4", "CJK RADICAL SIMPLIFIED WHEAT": "2EE8", - "KANGXI RADICAL HOOK": "2F05", - "KANGXI RADICAL TEN": "2F17", - "KANGXI RADICAL SEAL": "2F19", - "KANGXI RADICAL WORK": "2F2F", - "KANGXI RADICAL SCRIPT": "2F42", - "KANGXI RADICAL NOT": "2F46", - "KANGXI RADICAL JADE": "2F5F", - "KANGXI RADICAL FIELD": "2F65", - "KANGXI RADICAL EYE": "2F6C", - "KANGXI RADICAL STONE": "2F6F", - "KANGXI RADICAL TRACK": "2F71", - "KANGXI RADICAL OLD": "2F7C", - "KANGXI RADICAL PLOW": "2F7E", - "KANGXI RADICAL SELF": "2F83", - "KANGXI RADICAL TANNED LEATHER": "2FB1", - "KANGXI RADICAL DRUM": "2FCE", - "LEFT ANGLE BRACKET": "3008", - "VERTICAL KANA REPEAT WITH VOICED SOUND MARK": "3032", - "HIRAGANA LETTER A": "3042", - "HIRAGANA LETTER I": "3044", - "HIRAGANA LETTER GE": "3052", - "HIRAGANA LETTER TO": "3068", - "HIRAGANA LETTER HE": "3078", - "HIRAGANA LETTER PO": "307D", - "HIRAGANA LETTER SMALL YO": "3087", - "HIRAGANA LETTER SMALL WA": "308E", - "KATAKANA LETTER KU": "30AF", - "KATAKANA LETTER PI": "30D4", - "KATAKANA LETTER MU": "30E0", - "KATAKANA LETTER YU": "30E6", - "KATAKANA LETTER VA": "30F7", - "KATAKANA LETTER VI": "30F8", - "HANGUL LETTER WA": "3158", - "HANGUL LETTER SSANGNIEUN": "3165", - "HANGUL LETTER RIEUL-TIKEUT": "316A", - "IDEOGRAPHIC ANNOTATION FOUR MARK": "3195", - "BOPOMOFO LETTER OO": "31A6", - "BOPOMOFO LETTER AINN": "31AE", - "BOPOMOFO LETTER INNN": "31B3", - "BOPOMOFO FINAL LETTER H": "31B7", - "CJK STROKE S": "31D1", - "CJK STROKE PD": "31DB", - "KATAKANA LETTER SMALL HU": "31F7", - "PARENTHESIZED HANGUL MIEUM A": "3212", - "PARENTHESIZED IDEOGRAPH ONE": "3220", - "CIRCLED NUMBER TWENTY ON BLACK SQUARE": "3249", - "CIRCLED NUMBER THIRTY TWO": "325C", - "CIRCLED IDEOGRAPH HAVE": "3292", - "CIRCLED NUMBER FORTY EIGHT": "32BD", - "SQUARE HG": "32CC", - "CIRCLED KATAKANA NU": "32E6", - "CIRCLED KATAKANA HE": "32EC", - "CIRCLED KATAKANA RA": "32F6", - "CIRCLED KATAKANA WE": "32FD", - "SQUARE KEESU": "331C", - "SQUARE SENTI": "3322", + "KANGXI RADICAL EIGHT": "2F0B", + "KANGXI RADICAL DOWN BOX": "2F0C", + "KANGXI RADICAL HAND": "2F3F", + "KANGXI RADICAL BRANCH": "2F40", + "KANGXI RADICAL SUN": "2F47", + "KANGXI RADICAL PROFOUND": "2F5E", + "KANGXI RADICAL DOTTED TENT": "2F68", + "KANGXI RADICAL GRAIN": "2F72", + "KANGXI RADICAL ARRIVE": "2F84", + "KANGXI RADICAL BEAN": "2F96", + "KANGXI RADICAL LONG": "2FA7", + "IDEOGRAPHIC DESCRIPTION CHARACTER HORIZONTAL REFLECTION": "2FFE", + "DOUBLE PRIME QUOTATION MARK": "301E", + "HIRAGANA LETTER NA": "306A", + "HIRAGANA LETTER BI": "3073", + "KATAKANA LETTER GI": "30AE", + "KATAKANA LETTER TI": "30C1", + "KATAKANA LETTER HO": "30DB", + "KATAKANA LETTER SMALL YA": "30E3", + "KATAKANA LETTER RI": "30EA", + "KATAKANA LETTER VE": "30F9", + "KATAKANA DIGRAPH KOTO": "30FF", + "HANGUL LETTER NIEUN-CIEUC": "3135", + "HANGUL LETTER A": "314F", + "HANGUL LETTER YESIEUNG": "3181", + "BOPOMOFO LETTER EE": "31A4", + "PARENTHESIZED HANGUL CIEUC A": "3216", + "PARENTHESIZED HANGUL CIEUC U": "321C", + "PARENTHESIZED IDEOGRAPH TEN": "3229", + "CIRCLED NUMBER TWENTY TWO": "3252", + "CIRCLED IDEOGRAPH MALE": "329A", + "CIRCLED IDEOGRAPH SUPERVISE": "32AC", + "CIRCLED KATAKANA KO": "32D9", + "CIRCLED KATAKANA SU": "32DC", + "SQUARE APAATO": "3300", + "SQUARE GIRUDAA": "3313", + "SQUARE KOOPO": "331E", + "SQUARE PESO": "3337", "SQUARE HOON": "3342", - "SQUARE RUUBURU": "3354", - "IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIX": "335E", - "SQUARE DM": "3377", - "SQUARE KL": "3398", - "SQUARE M CUBED": "33A5", - "SQUARE KM CUBED": "33A6", - "SQUARE DB": "33C8", - "IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWELVE": "33EB", - "IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIFTEEN": "33EE", - "HEXAGRAM FOR HOLDING TOGETHER": "4DC7", - "HEXAGRAM FOR PEACE": "4DCA", - "HEXAGRAM FOR GREAT POSSESSION": "4DCD", - "HEXAGRAM FOR GRACE": "4DD5", - "HEXAGRAM FOR GREAT TAMING": "4DD9", - "HEXAGRAM FOR PROGRESS": "4DE2", - "HEXAGRAM FOR THE FAMILY": "4DE4", - "YI SYLLABLE AT": "A008", - "YI SYLLABLE BURX": "A030", - "YI SYLLABLE PIEP": "A03E", - "YI SYLLABLE POX": "A047", - "YI SYLLABLE PU": "A04C", - "YI SYLLABLE BBY": "A074", - "YI SYLLABLE NBAP": "A080", - "YI SYLLABLE HMY": "A0AA", - "YI SYLLABLE HMYP": "A0AB", - "YI SYLLABLE MUOP": "A0BC", - "YI SYLLABLE ME": "A0C2", - "YI SYLLABLE MURX": "A0C7", - "YI SYLLABLE FUP": "A0DB", - "YI SYLLABLE VYT": "A0FA", - "YI SYLLABLE DOT": "A10D", - "YI SYLLABLE DDIEX": "A13A", - "YI SYLLABLE DDAX": "A13E", - "YI SYLLABLE DDUP": "A14E", - "YI SYLLABLE NDOX": "A15C", - "YI SYLLABLE NDE": "A160", - "YI SYLLABLE HNIEX": "A16D", - "YI SYLLABLE HNEP": "A17B", - "YI SYLLABLE NUR": "A196", - "YI SYLLABLE HLYP": "A1B4", - "YI SYLLABLE LIP": "A1BA", + "SQUARE MEGATON": "334C", + "SQUARE MEETORU": "334D", + "IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINETEEN": "336B", + "SQUARE GHZ": "3393", + "SQUARE KM SQUARED": "33A2", + "SQUARE KW": "33BE", + "SQUARE CO": "33C7", + "SQUARE V OVER M": "33DE", + "": "4DBF", + "HEXAGRAM FOR DIFFICULTY AT THE BEGINNING": "4DC2", + "HEXAGRAM FOR TREADING": "4DC9", + "HEXAGRAM FOR GREAT PREPONDERANCE": "4DDB", + "HEXAGRAM FOR DURATION": "4DDF", + "HEXAGRAM FOR GREAT POWER": "4DE1", + "HEXAGRAM FOR THE KEEPING STILL MOUNTAIN": "4DF3", + "YI SYLLABLE IEP": "A007", + "YI SYLLABLE BIX": "A017", + "YI SYLLABLE PIEX": "A03C", + "YI SYLLABLE PAT": "A03F", + "YI SYLLABLE PA": "A041", + "YI SYLLABLE BBA": "A060", + "YI SYLLABLE BBO": "A067", + "YI SYLLABLE BBU": "A06E", + "YI SYLLABLE BBURX": "A070", + "YI SYLLABLE NBY": "A08D", + "YI SYLLABLE HMI": "A093", + "YI SYLLABLE HMA": "A09A", + "YI SYLLABLE HMAP": "A09B", + "YI SYLLABLE HMUOX": "A09C", + "YI SYLLABLE HMURX": "A0A7", + "YI SYLLABLE HMYX": "A0A9", + "YI SYLLABLE MIEX": "A0B2", + "YI SYLLABLE MUX": "A0C4", + "YI SYLLABLE VIT": "A0E2", + "YI SYLLABLE VIEX": "A0E7", + "YI SYLLABLE DI": "A102", + "YI SYLLABLE DA": "A109", + "YI SYLLABLE TA": "A123", + "YI SYLLABLE TOP": "A12C", + "YI SYLLABLE DDUOP": "A143", + "YI SYLLABLE DDO": "A146", + "YI SYLLABLE DDURX": "A14F", + "YI SYLLABLE HNIE": "A16E", + "YI SYLLABLE HNUT": "A17C", "YI SYLLABLE LAP": "A1C2", - "YI SYLLABLE KUOX": "A203", - "YI SYLLABLE KET": "A20A", - "YI SYLLABLE HXA": "A250", - "YI SYLLABLE NGOP": "A26A", + "YI SYLLABLE GUO": "A1E8", + "YI SYLLABLE KIT": "A1F8", + "YI SYLLABLE KAT": "A1FF", + "YI SYLLABLE KE": "A20C", + "YI SYLLABLE KUT": "A20E", + "YI SYLLABLE MGUP": "A243", "YI SYLLABLE HUOX": "A276", - "YI SYLLABLE ZA": "A296", - "YI SYLLABLE ZO": "A29D", - "YI SYLLABLE ZZIEP": "A2D7", - "YI SYLLABLE ZZOP": "A2DE", - "YI SYLLABLE NZYP": "A306", - "YI SYLLABLE SIT": "A309", - "YI SYLLABLE SIEP": "A30F", - "YI SYLLABLE SUO": "A315", - "YI SYLLABLE SO": "A319", + "YI SYLLABLE WAP": "A283", + "YI SYLLABLE ZIT": "A28D", + "YI SYLLABLE ZAX": "A295", + "YI SYLLABLE CIX": "A2AF", + "YI SYLLABLE ZZUX": "A2E2", + "YI SYLLABLE NZIX": "A2EE", + "YI SYLLABLE NZUP": "A300", "YI SYLLABLE SUX": "A31F", - "YI SYLLABLE SSI": "A32C", - "YI SYLLABLE SSIE": "A32F", - "YI SYLLABLE SSEP": "A33B", - "YI SYLLABLE ZHUX": "A356", - "YI SYLLABLE CHOT": "A369", - "YI SYLLABLE NRUP": "A3A2", - "YI SYLLABLE NRYX": "A3A6", - "YI SYLLABLE SHAP": "A3AE", + "YI SYLLABLE SSYT": "A340", + "YI SYLLABLE ZHAT": "A346", + "YI SYLLABLE ZHO": "A34F", + "YI SYLLABLE CHYT": "A376", + "YI SYLLABLE RRO": "A382", + "YI SYLLABLE RRE": "A386", + "YI SYLLABLE RRYP": "A391", + "YI SYLLABLE NRAT": "A394", + "YI SYLLABLE NRET": "A39B", + "YI SYLLABLE NRURX": "A3A3", "YI SYLLABLE SHO": "A3B4", - "YI SYLLABLE SHEP": "A3B9", - "YI SYLLABLE SHURX": "A3BE", - "YI SYLLABLE SHUR": "A3BF", - "YI SYLLABLE RUO": "A3CB", - "YI SYLLABLE RUT": "A3D4", - "YI SYLLABLE QIX": "A3FD", - "YI SYLLABLE QUR": "A411", - "YI SYLLABLE JJIET": "A41C", - "YI SYLLABLE JJY": "A42F", - "YI SYLLABLE NJYP": "A447", - "YI SYLLABLE NYUO": "A453", - "YI SYLLABLE XIP": "A460", - "YI SYLLABLE YIE": "A477", - "YI SYLLABLE YIEP": "A478", - "YI SYLLABLE YYR": "A48C", - "YI RADICAL GOT": "A4B6", - "YI RADICAL NBIE": "A4C5", + "YI SYLLABLE JYX": "A3F7", + "YI SYLLABLE JY": "A3F8", + "YI SYLLABLE QOT": "A408", + "YI SYLLABLE QUX": "A40D", + "YI SYLLABLE JJI": "A41A", + "YI SYLLABLE JJO": "A425", + "YI SYLLABLE JJU": "A429", + "YI SYLLABLE NJIT": "A431", + "YI SYLLABLE NJIEP": "A438", + "YI SYLLABLE NJUX": "A43F", + "YI SYLLABLE NYO": "A457", + "YI SYLLABLE NYOP": "A458", + "YI SYLLABLE XIEP": "A464", + "YI SYLLABLE XOX": "A468", + "YI RADICAL GA": "A4A1", + "YI RADICAL OP": "A4A9", + "YI RADICAL JJY": "A4B5", "LISU LETTER TSHA": "A4DE", - "LISU LETTER TONE MYA CYA": "A4FA", - "LISU LETTER TONE MYA NA": "A4FC", - "VAI SYLLABLE EE": "A500", - "VAI SYLLABLE HIN": "A527", - "VAI SYLLABLE DI": "A539", - "VAI SYLLABLE NA": "A56F", - "VAI SYLLABLE ZU": "A5AE", - "VAI SYLLABLE JO": "A5D8", - "VAI SYLLABLE KPE": "A5EC", + "LISU LETTER SHA": "A4EB", + "LISU LETTER UH": "A4F6", + "LISU LETTER TONE NA PO": "A4F9", + "VAI SYLLABLE DHHEE": "A511", + "VAI SYLLABLE DEE": "A514", + "VAI SYLLABLE TI": "A533", + "VAI SYLLABLE THI": "A534", + "VAI SYLLABLE JA": "A567", + "VAI SYLLABLE KPOO": "A57A", + "VAI SYLLABLE GBOO": "A57C", + "VAI SYLLABLE FOO": "A57D", + "VAI SYLLABLE WU": "A599", + "VAI SYLLABLE CU": "A5B0", + "VAI SYLLABLE O": "A5BA", + "VAI SYLLABLE E": "A5E1", "VAI SYLLABLE DHHE": "A5F6", - "VAI SYLLABLE CE": "A5FF", - "VAI SYLLABLE ME": "A608", - "VAI SYLLABLE NDOLE FA": "A610", - "VAI DIGIT FIVE": "A625", - "CYRILLIC SMALL LETTER YERU WITH BACK YER": "A651", - "CYRILLIC SMALL LETTER DOUBLE O": "A699", - "BAMUM LETTER KU": "A6A3", - "BAMUM LETTER NUAE": "A6BC", - "BAMUM LETTER KEUX": "A6C4", - "BAMUM LETTER REUX": "A6D0", - "BAMUM LETTER FOM": "A6D9", - "MODIFIER LETTER EXTRA-LOW LEFT-STEM TONE BAR": "A716", - "LATIN CAPITAL LETTER AY": "A73C", - "LATIN SMALL LETTER K WITH STROKE AND DIAGONAL STROKE": "A745", - "LATIN SMALL LETTER INSULAR D": "A77A", - "LATIN CAPITAL LETTER INSULAR G": "A77D", - "LATIN SMALL LETTER INSULAR T": "A787", - "LATIN SMALL LETTER N WITH OBLIQUE STROKE": "A7A5", - "LATIN CAPITAL LETTER REVERSED OPEN E": "A7AB", - "LATIN CAPITAL LETTER SIGMOID S": "A7D8", - "SYLOTI NAGRI LETTER E": "A804", - "SYLOTI NAGRI LETTER DO": "A816", - "PHAGS-PA LETTER CHA": "A845", - "PHAGS-PA LETTER JA": "A846", - "PHAGS-PA LETTER DA": "A84A", - "PHAGS-PA LETTER LA": "A859", + "VAI SYMBOL KUNG": "A61C", + "CYRILLIC CAPITAL LETTER ZEMLYA": "A640", + "CYRILLIC CAPITAL LETTER NEUTRAL YER": "A64E", + "CYRILLIC SMALL LETTER SOFT EL": "A665", + "BAMUM LETTER NGGA": "A6D4", + "BAMUM LETTER WA": "A6DA", + "BAMUM LETTER MA": "A6E3", + "MODIFIER LETTER LOW LEFT-STEM TONE BAR": "A715", + "LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF": "A722", + "LATIN SMALL LETTER HENG": "A727", + "LATIN CAPITAL LETTER AV": "A738", + "LATIN SMALL LETTER AV": "A739", + "LATIN CAPITAL LETTER CON": "A76E", + "LATIN CAPITAL LETTER S WITH OBLIQUE STROKE": "A7A8", + "LATIN CAPITAL LETTER L WITH BELT": "A7AD", + "LATIN CAPITAL LETTER J WITH CROSSED-TAIL": "A7B2", + "LATIN SMALL LETTER BETA": "A7B5", + "LATIN CAPITAL LETTER C WITH PALATAL HOOK": "A7C4", + "MODIFIER LETTER CAPITAL H WITH STROKE": "A7F8", + "LATIN EPIGRAPHIC LETTER REVERSED P": "A7FC", + "SYLOTI NAGRI LETTER CHO": "A80D", + "SYLOTI NAGRI LETTER BHO": "A81C", + "SYLOTI NAGRI VOWEL SIGN I": "A824", + "PHAGS-PA LETTER NA": "A84B", "PHAGS-PA LETTER TTA": "A869", - "SAURASHTRA LETTER KA": "A892", - "SAURASHTRA LETTER TTA": "A89C", - "SAURASHTRA LETTER THA": "A8A2", - "SAURASHTRA LETTER YA": "A8AB", - "SAURASHTRA DIGIT TWO": "A8D2", - "COMBINING DEVANAGARI DIGIT ZERO": "A8E0", - "COMBINING DEVANAGARI DIGIT THREE": "A8E3", - "COMBINING DEVANAGARI DIGIT SEVEN": "A8E7", - "KAYAH LI DIGIT ONE": "A901", - "KAYAH LI LETTER NYA": "A911", - "KAYAH LI VOWEL EE": "A929", - "REJANG LETTER CA": "A939", - "REJANG LETTER HA": "A941", - "JAVANESE LETTER NGA": "A994", - "JAVANESE LETTER DDA": "A99D", - "JAVANESE VOWEL SIGN TARUNG": "A9B4", - "JAVANESE PADA LINGSA": "A9C8", - "CHAM DIGIT TWO": "AA52", - "MYANMAR LETTER KHAMTI JA": "AA63", - "TAI VIET LETTER LOW KO": "AA80", - "TAI VIET LETTER HIGH SO": "AA8F", - "TAI VIET LETTER LOW FO": "AAA0", - "TAI VIET SYMBOL HO HOI": "AADE", - "MEETEI MAYEK LETTER SSA": "AAEA", - "MEETEI MAYEK VOWEL SIGN VISARGA": "AAF5", - "MODIFIER LETTER SMALL U WITH LEFT HOOK": "AB5F", - "CHEROKEE SMALL LETTER KA": "AB77", - "CHEROKEE SMALL LETTER TLV": "ABB2", - "CHEROKEE SMALL LETTER WV": "ABBE", - "MEETEI MAYEK LETTER CHIL": "ABC6", - "MEETEI MAYEK LUM IYEK": "ABEC", - "MEETEI MAYEK DIGIT ONE": "ABF1", - "HANGUL JUNGSEONG O-O-I": "D7B1", - "HANGUL JONGSEONG RIEUL-PIEUP-TIKEUT": "D7D9", - "HANGUL JONGSEONG PIEUP-CHIEUCH": "D7E9", - "HANGUL JONGSEONG SIOS-THIEUTH": "D7F1", - "HANGUL JONGSEONG SSANGCIEUC": "D7F9", - "CJK COMPATIBILITY IDEOGRAPH-F927": "F927", - "CJK COMPATIBILITY IDEOGRAPH-F942": "F942", - "CJK COMPATIBILITY IDEOGRAPH-F948": "F948", - "CJK COMPATIBILITY IDEOGRAPH-F949": "F949", - "CJK COMPATIBILITY IDEOGRAPH-F96C": "F96C", - "CJK COMPATIBILITY IDEOGRAPH-F978": "F978", - "CJK COMPATIBILITY IDEOGRAPH-F988": "F988", - "CJK COMPATIBILITY IDEOGRAPH-F9AB": "F9AB", - "CJK COMPATIBILITY IDEOGRAPH-F9C0": "F9C0", - "CJK COMPATIBILITY IDEOGRAPH-F9C2": "F9C2", - "CJK COMPATIBILITY IDEOGRAPH-F9C4": "F9C4", - "CJK COMPATIBILITY IDEOGRAPH-F9CF": "F9CF", - "CJK COMPATIBILITY IDEOGRAPH-F9D3": "F9D3", - "CJK COMPATIBILITY IDEOGRAPH-F9F7": "F9F7", - "CJK COMPATIBILITY IDEOGRAPH-FA18": "FA18", - "CJK COMPATIBILITY IDEOGRAPH-FA39": "FA39", - "CJK COMPATIBILITY IDEOGRAPH-FA61": "FA61", - "CJK COMPATIBILITY IDEOGRAPH-FA6C": "FA6C", - "CJK COMPATIBILITY IDEOGRAPH-FA74": "FA74", - "CJK COMPATIBILITY IDEOGRAPH-FA8E": "FA8E", - "CJK COMPATIBILITY IDEOGRAPH-FAB7": "FAB7", - "CJK COMPATIBILITY IDEOGRAPH-FABA": "FABA", - "HEBREW LETTER LAMED WITH DAGESH": "FB3C", - "HEBREW LETTER QOF WITH DAGESH": "FB47", - "ARABIC LETTER DDAHAL ISOLATED FORM": "FB82", - "ARABIC LETTER NGOEH INITIAL FORM": "FB9C", - "ARABIC LETTER YEH BARREE WITH HAMZA ABOVE FINAL FORM": "FBB1", - "ARABIC LETTER UIGHUR KAZAKH KIRGHIZ ALEF MAKSURA INITIAL FORM": "FBE8", - "ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH AE ISOLATED FORM": "FBEC", - "ARABIC LIGATURE HAH WITH JEEM ISOLATED FORM": "FC17", - "ARABIC LIGATURE MEEM WITH KHAH ISOLATED FORM": "FC47", - "ARABIC LIGATURE SHADDA WITH FATHA ISOLATED FORM": "FC60", - "ARABIC LIGATURE TEH WITH ZAIN FINAL FORM": "FC71", - "ARABIC LIGATURE SAD WITH KHAH INITIAL FORM": "FCB2", - "ARABIC LIGATURE HAH WITH ALEF MAKSURA ISOLATED FORM": "FCFF", - "ARABIC LIGATURE SHEEN WITH JEEM FINAL FORM": "FD25", - "ARABIC LIGATURE SEEN WITH HEH INITIAL FORM": "FD31", - "ARABIC LIGATURE TEH WITH MEEM WITH HAH INITIAL FORM": "FD56", - "ARABIC LIGATURE TAH WITH MEEM WITH MEEM INITIAL FORM": "FD73", - "ARABIC LIGATURE AIN WITH JEEM WITH MEEM FINAL FORM": "FD75", - "ARABIC LIGATURE LAM WITH JEEM WITH JEEM FINAL FORM": "FD84", - "ARABIC LIGATURE NOON WITH MEEM WITH YEH FINAL FORM": "FD9A", - "ARABIC LIGATURE YEH WITH HAH WITH YEH FINAL FORM": "FDAE", - "ARABIC LIGATURE LAM WITH HAH WITH MEEM INITIAL FORM": "FDB5", - "ARABIC LIGATURE NOON WITH JEEM WITH HAH FINAL FORM": "FDBD", - "ARABIC LIGATURE BEH WITH HAH WITH YEH FINAL FORM": "FDC2", - "ARABIC LIGATURE SEEN WITH KHAH WITH YEH FINAL FORM": "FDC6", - "ARABIC LIGATURE SALLA USED AS KORANIC STOP SIGN ISOLATED FORM": "FDF0", - "VARIATION SELECTOR-5": "FE04", - "PRESENTATION FORM FOR VERTICAL QUESTION MARK": "FE16", - "COMBINING TILDE RIGHT HALF BELOW": "FE2A", - "COMBINING CYRILLIC TITLO LEFT HALF": "FE2E", - "WHITE SESAME DOT": "FE46", - "CENTRELINE OVERLINE": "FE4A", - "DOUBLE WAVY OVERLINE": "FE4C", - "SMALL RIGHT PARENTHESIS": "FE5A", - "SMALL HYPHEN-MINUS": "FE63", - "SMALL REVERSE SOLIDUS": "FE68", - "ARABIC DAMMA ISOLATED FORM": "FE78", - "ARABIC LETTER TEH MARBUTA FINAL FORM": "FE94", - "ARABIC LETTER ZAIN ISOLATED FORM": "FEAF", - "ARABIC LETTER SHEEN ISOLATED FORM": "FEB5", - "ARABIC LETTER SHEEN FINAL FORM": "FEB6", - "ARABIC LETTER TAH FINAL FORM": "FEC2", - "ARABIC LETTER KAF ISOLATED FORM": "FED9", - "ARABIC LETTER YEH FINAL FORM": "FEF2", - "ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM": "FEFB", - "FULLWIDTH LATIN CAPITAL LETTER C": "FF23", - "FULLWIDTH LATIN CAPITAL LETTER U": "FF35", - "FULLWIDTH LATIN SMALL LETTER B": "FF42", - "FULLWIDTH LATIN SMALL LETTER E": "FF45", - "HALFWIDTH KATAKANA LETTER I": "FF72", - "HALFWIDTH KATAKANA LETTER O": "FF75", - "HALFWIDTH KATAKANA LETTER TA": "FF80", - "HALFWIDTH KATAKANA LETTER NI": "FF86", - "HALFWIDTH KATAKANA LETTER YA": "FF94", - "HALFWIDTH HANGUL LETTER SSANGKIYEOK": "FFA2", - "HALFWIDTH HANGUL LETTER RIEUL": "FFA9", - "HALFWIDTH HANGUL LETTER PIEUP": "FFB2", - "HALFWIDTH HANGUL LETTER EU": "FFDA", - "HALFWIDTH LEFTWARDS ARROW": "FFE9", - "LINEAR B SYLLABLE B038 E": "10001", + "SAURASHTRA LETTER A": "A882", + "SAURASHTRA LETTER U": "A886", + "SAURASHTRA LETTER VOCALIC RR": "A889", + "SAURASHTRA LETTER VOCALIC LL": "A88B", + "SAURASHTRA LETTER CA": "A897", + "KAYAH LI LETTER BA": "A919", + "KAYAH LI LETTER I": "A924", + "KAYAH LI TONE PLOPHU": "A92B", + "REJANG LETTER RA": "A93D", + "REJANG LETTER LA": "A93E", + "HANGUL CHOSEONG TIKEUT-PIEUP": "A961", + "HANGUL CHOSEONG MIEUM-TIKEUT": "A970", + "HANGUL CHOSEONG SSANGSIOS-PIEUP": "A975", + "JAVANESE VOWEL SIGN TALING": "A9BA", + "JAVANESE DIGIT SEVEN": "A9D7", + "CHAM LETTER NGA": "AA0B", + "CHAM LETTER CHA": "AA0C", + "CHAM LETTER DHA": "AA16", + "CHAM LETTER YA": "AA22", + "CHAM LETTER SA": "AA27", + "CHAM CONSONANT SIGN WA": "AA36", + "CHAM LETTER FINAL P": "AA47", + "CHAM DIGIT NINE": "AA59", + "TAI VIET LETTER HIGH GO": "AA87", + "TAI VIET LETTER LOW THO": "AA96", + "TAI VIET VOWEL UA": "AABA", + "LATIN SMALL LETTER L WITH DOUBLE MIDDLE TILDE": "AB38", + "CHEROKEE SMALL LETTER E": "AB71", + "CHEROKEE SMALL LETTER I": "AB72", + "CHEROKEE SMALL LETTER U": "AB74", + "CHEROKEE SMALL LETTER NO": "AB93", + "CHEROKEE SMALL LETTER DLA": "ABAC", + "MEETEI MAYEK DIGIT SIX": "ABF6", + "HANGUL JUNGSEONG I-YEO": "D7BF", + "HANGUL JONGSEONG RIEUL-KIYEOK-HIEUH": "D7D6", + "HANGUL JONGSEONG SIOS-PANSIOS": "D7EE", + "HANGUL JONGSEONG CIEUC-SSANGPIEUP": "D7F8", + "HANGUL JONGSEONG PHIEUPH-SIOS": "D7FA", + "CJK COMPATIBILITY IDEOGRAPH-F90A": "F90A", + "CJK COMPATIBILITY IDEOGRAPH-F91E": "F91E", + "CJK COMPATIBILITY IDEOGRAPH-F940": "F940", + "CJK COMPATIBILITY IDEOGRAPH-F946": "F946", + "CJK COMPATIBILITY IDEOGRAPH-F94F": "F94F", + "CJK COMPATIBILITY IDEOGRAPH-F951": "F951", + "CJK COMPATIBILITY IDEOGRAPH-F979": "F979", + "CJK COMPATIBILITY IDEOGRAPH-F97A": "F97A", + "CJK COMPATIBILITY IDEOGRAPH-F97D": "F97D", + "CJK COMPATIBILITY IDEOGRAPH-F97F": "F97F", + "CJK COMPATIBILITY IDEOGRAPH-F982": "F982", + "CJK COMPATIBILITY IDEOGRAPH-F98A": "F98A", + "CJK COMPATIBILITY IDEOGRAPH-F994": "F994", + "CJK COMPATIBILITY IDEOGRAPH-F997": "F997", + "CJK COMPATIBILITY IDEOGRAPH-F9AE": "F9AE", + "CJK COMPATIBILITY IDEOGRAPH-F9B4": "F9B4", + "CJK COMPATIBILITY IDEOGRAPH-F9D0": "F9D0", + "CJK COMPATIBILITY IDEOGRAPH-F9E5": "F9E5", + "CJK COMPATIBILITY IDEOGRAPH-F9ED": "F9ED", + "CJK COMPATIBILITY IDEOGRAPH-FA0A": "FA0A", + "CJK COMPATIBILITY IDEOGRAPH-FA12": "FA12", + "CJK COMPATIBILITY IDEOGRAPH-FA27": "FA27", + "CJK COMPATIBILITY IDEOGRAPH-FA28": "FA28", + "CJK COMPATIBILITY IDEOGRAPH-FA75": "FA75", + "CJK COMPATIBILITY IDEOGRAPH-FA77": "FA77", + "CJK COMPATIBILITY IDEOGRAPH-FA84": "FA84", + "CJK COMPATIBILITY IDEOGRAPH-FA8D": "FA8D", + "CJK COMPATIBILITY IDEOGRAPH-FAA6": "FAA6", + "CJK COMPATIBILITY IDEOGRAPH-FACD": "FACD", + "HEBREW LETTER VAV WITH DAGESH": "FB35", + "ARABIC LETTER HEH DOACHASHMEE FINAL FORM": "FBAB", + "ARABIC LETTER NG MEDIAL FORM": "FBD6", + "ARABIC LETTER U WITH HAMZA ABOVE ISOLATED FORM": "FBDD", + "ARABIC LETTER KIRGHIZ OE ISOLATED FORM": "FBE0", + "ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM ISOLATED FORM": "FC02", + "ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YEH ISOLATED FORM": "FC04", + "ARABIC LIGATURE FEH WITH MEEM ISOLATED FORM": "FC30", + "ARABIC LIGATURE KAF WITH JEEM ISOLATED FORM": "FC38", + "ARABIC LIGATURE LAM WITH YEH ISOLATED FORM": "FC44", + "ARABIC LIGATURE MEEM WITH ALEF MAKSURA ISOLATED FORM": "FC49", + "ARABIC LIGATURE YEH WITH ALEF MAKSURA ISOLATED FORM": "FC59", + "ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF MAKSURA FINAL FORM": "FC68", + "ARABIC LIGATURE BEH WITH NOON FINAL FORM": "FC6D", + "ARABIC LIGATURE TEH WITH YEH FINAL FORM": "FC75", + "ARABIC LIGATURE KHAH WITH JEEM INITIAL FORM": "FCAB", + "ARABIC LIGATURE ZAH WITH MEEM INITIAL FORM": "FCB9", + "ARABIC LIGATURE LAM WITH MEEM INITIAL FORM": "FCCC", + "ARABIC LIGATURE SEEN WITH HEH MEDIAL FORM": "FCE8", + "ARABIC LIGATURE HAH WITH YEH ISOLATED FORM": "FD00", + "ARABIC LIGATURE DAD WITH ALEF MAKSURA FINAL FORM": "FD23", + "ARABIC LIGATURE SHEEN WITH KHAH INITIAL FORM": "FD2F", + "ARABIC LIGATURE ALEF WITH FATHATAN ISOLATED FORM": "FD3D", + "ARABIC LIGATURE SEEN WITH MEEM WITH JEEM INITIAL FORM": "FD61", + "ARABIC LIGATURE SAD WITH MEEM WITH MEEM FINAL FORM": "FD66", + "ARABIC LIGATURE MEEM WITH HAH WITH YEH FINAL FORM": "FD8B", + "ARABIC LIGATURE AKBAR ISOLATED FORM": "FDF3", + "ARABIC LIGATURE BISMILLAH AR-RAHMAN AR-RAHEEM": "FDFD", + "COMBINING LIGATURE RIGHT HALF": "FE21", + "PRESENTATION FORM FOR VERTICAL LOW LINE": "FE33", + "PRESENTATION FORM FOR VERTICAL RIGHT DOUBLE ANGLE BRACKET": "FE3E", + "SMALL EQUALS SIGN": "FE66", + "ARABIC KASRATAN ISOLATED FORM": "FE74", + "ARABIC LETTER KHAH MEDIAL FORM": "FEA8", + "ARABIC LETTER AIN FINAL FORM": "FECA", + "ARABIC LETTER QAF INITIAL FORM": "FED7", + "ARABIC LETTER NOON FINAL FORM": "FEE6", + "FULLWIDTH RIGHT PARENTHESIS": "FF09", + "FULLWIDTH LATIN CAPITAL LETTER T": "FF34", + "FULLWIDTH REVERSE SOLIDUS": "FF3C", + "FULLWIDTH LATIN SMALL LETTER X": "FF58", + "HALFWIDTH HANGUL LETTER RIEUL-MIEUM": "FFAB", + "HALFWIDTH HANGUL LETTER AE": "FFC3", + "HALFWIDTH HANGUL LETTER U": "FFD3", + "HALFWIDTH HANGUL LETTER WEO": "FFD4", + "HALFWIDTH FORMS LIGHT VERTICAL": "FFE8", + "HALFWIDTH WHITE CIRCLE": "FFEE", + "LINEAR B SYLLABLE B028 I": "10002", + "LINEAR B SYLLABLE B045 DE": "10006", "LINEAR B SYLLABLE B014 DO": "10008", - "LINEAR B SYLLABLE B077 KA": "1000F", - "LINEAR B SYLLABLE B015 MO": "10017", - "LINEAR B SYLLABLE B030 NI": "1001B", - "LINEAR B SYLLABLE B002 RO": "1002B", - "LINEAR B SYLLABLE B068 RO2": "1004A", - "LINEAR B SYLLABLE B066 TA2": "1004B", - "LINEAR B MONOGRAM B127 KAPO": "10093", - "LINEAR B IDEOGRAM B161": "100A9", - "LINEAR B IDEOGRAM B248": "100D3", - "LINEAR B IDEOGRAM VESSEL B212": "100EB", - "AEGEAN WORD SEPARATOR DOT": "10101", - "AEGEAN NUMBER SEVEN HUNDRED": "1011F", - "AEGEAN NUMBER TEN THOUSAND": "1012B", - "GREEK ACROPHONIC ATTIC FIFTY THOUSAND": "10147", + "LINEAR B SYLLABLE B065 JU": "1000E", + "LINEAR B SYLLABLE B005 TO": "10035", + "LINEAR B SYLLABLE B069 TU": "10036", + "LINEAR B IDEOGRAM B106F EWE": "10086", + "LINEAR B IDEOGRAM B121 BARLEY": "1008F", + "LINEAR B IDEOGRAM B163 ARMOUR": "100AB", + "LINEAR B MONOGRAM B247 DIPTE": "100D2", + "LINEAR B IDEOGRAM B257": "100DB", + "LINEAR B IDEOGRAM VESSEL B203": "100E2", + "LINEAR B IDEOGRAM VESSEL B204": "100E3", + "AEGEAN NUMBER ONE THOUSAND": "10122", + "AEGEAN NUMBER NINE THOUSAND": "1012A", + "AEGEAN NUMBER SIXTY THOUSAND": "10130", + "AEGEAN WEIGHT THIRD SUBUNIT": "1013A", "GREEK ACROPHONIC ATTIC FIFTY TALENTS": "1014A", - "GREEK ACROPHONIC ATTIC FIFTY STATERS": "10151", - "GREEK ACROPHONIC ATTIC FIFTY THOUSAND STATERS": "10156", - "GREEK ACROPHONIC THESPIAN FIFTY": "10169", - "ASCIA SYMBOL": "1019C", - "PHAISTOS DISC SIGN PAPYRUS": "101F4", - "LYCIAN LETTER Q": "1028C", - "LYCIAN LETTER L": "1028D", - "LYCIAN LETTER X": "1029C", - "CARIAN LETTER UUU": "102A4", - "CARIAN LETTER SS": "102B8", + "GREEK ACROPHONIC ATTIC FIVE STATERS": "1014F", + "GREEK ACROPHONIC THESPIAN ONE HUNDRED": "1016A", + "GREEK ACROPHONIC THESPIAN THREE HUNDRED": "1016B", + "GREEK GRAMMA SIGN": "10188", + "GREEK SINUSOID SIGN": "1018C", + "ROMAN SEMUNCIA SIGN": "10192", + "PHAISTOS DISC SIGN PLUMED HEAD": "101D1", + "PHAISTOS DISC SIGN SHIP": "101E8", + "PHAISTOS DISC SIGN RAM": "101ED", + "PHAISTOS DISC SIGN FLUTE": "101F8", + "PHAISTOS DISC SIGN STRAINER": "101FA", + "CARIAN LETTER D2": "102AC", + "COPTIC EPACT DIGIT NINE": "102E9", "OLD ITALIC LETTER EM": "1030C", - "OLD ITALIC LETTER U": "10316", - "OLD ITALIC LETTER ESS": "1031F", - "GOTHIC LETTER MANNA": "1033C", - "OLD PERMIC LETTER ZHOI": "10355", - "OLD PERMIC LETTER IA": "10375", - "DESERET CAPITAL LETTER SHORT I": "10406", - "DESERET CAPITAL LETTER OW": "1040D", - "DESERET CAPITAL LETTER TEE": "10413", - "DESERET SMALL LETTER LONG OO": "1042D", + "OLD PERMIC LETTER IE": "10372", + "UGARITIC LETTER SHIN": "1038C", + "OLD PERSIAN SIGN GU": "103A6", + "OLD PERSIAN SIGN FA": "103B3", + "OLD PERSIAN SIGN NU": "103B5", + "OLD PERSIAN SIGN MA": "103B6", + "DESERET SMALL LETTER SHORT A": "10430", + "DESERET SMALL LETTER BEE": "1043A", "DESERET SMALL LETTER GAY": "10440", "DESERET SMALL LETTER ENG": "1044D", - "DESERET SMALL LETTER EW": "1044F", - "SHAVIAN LETTER SURE": "10456", - "SHAVIAN LETTER THEY": "1045E", - "SHAVIAN LETTER EAR": "1047D", - "OSMANYA LETTER KHA": "10485", - "OSMANYA LETTER YA": "10495", - "OSAGE CAPITAL LETTER E": "104B7", + "SHAVIAN LETTER YEA": "10458", + "SHAVIAN LETTER HUNG": "10459", + "SHAVIAN LETTER ADO": "10469", + "SHAVIAN LETTER ON": "1046A", + "OSAGE CAPITAL LETTER A": "104B0", + "OSAGE CAPITAL LETTER BRA": "104B4", + "OSAGE CAPITAL LETTER CHA": "104B5", "OSAGE CAPITAL LETTER HYA": "104BA", - "OSAGE SMALL LETTER BRA": "104DC", - "OSAGE SMALL LETTER HYA": "104E2", - "OSAGE SMALL LETTER DHA": "104F5", - "ELBASAN LETTER E": "10508", - "ELBASAN LETTER HE": "1050C", - "ELBASAN LETTER QE": "10518", - "ELBASAN LETTER VE": "10520", - "ELBASAN LETTER Y": "10522", - "ELBASAN LETTER KHE": "10527", - "CAUCASIAN ALBANIAN LETTER MAQ": "1054C", - "CAUCASIAN ALBANIAN LETTER CHAT": "10556", - "VITHKUQI CAPITAL LETTER HA": "1057C", - "VITHKUQI SMALL LETTER BE": "10599", - "VITHKUQI SMALL LETTER DE": "1059C", - "VITHKUQI SMALL LETTER SE": "105B3", + "OSAGE CAPITAL LETTER O": "104C2", + "OSAGE CAPITAL LETTER EHTA": "104C9", + "OSAGE CAPITAL LETTER U": "104CE", + "OSAGE CAPITAL LETTER WA": "104CF", + "OSAGE SMALL LETTER SHA": "104EF", + "OSAGE SMALL LETTER ZHA": "104FB", + "ELBASAN LETTER CE": "10502", + "ELBASAN LETTER JE": "1050E", + "ELBASAN LETTER TE": "1051D", + "ELBASAN LETTER U": "1051F", + "CAUCASIAN ALBANIAN LETTER QAY": "10547", + "CAUCASIAN ALBANIAN LETTER TYAY": "10553", + "CAUCASIAN ALBANIAN LETTER SEYK": "1055A", + "VITHKUQI CAPITAL LETTER I": "1057E", + "VITHKUQI CAPITAL LETTER TE": "1058E", + "VITHKUQI SMALL LETTER NJE": "105AD", "LINEAR A SIGN AB021M": "10611", - "LINEAR A SIGN AB046": "10627", - "LINEAR A SIGN A330": "10676", - "LINEAR A SIGN A338": "1067E", - "LINEAR A SIGN A405-VAS": "106A5", - "LINEAR A SIGN A502": "106B4", - "LINEAR A SIGN A572": "106EB", - "LINEAR A SIGN A611": "1070C", - "LINEAR A SIGN A613": "1070E", - "LINEAR A SIGN A640": "10721", - "LINEAR A SIGN A652": "1072A", - "LINEAR A SIGN A655": "1072D", - "LINEAR A SIGN A712 Y": "1074F", - "MODIFIER LETTER SMALL CLOSED REVERSED OPEN E": "1078F", - "CYPRIOT SYLLABLE U": "10804", - "CYPRIOT SYLLABLE KI": "1080C", + "LINEAR A SIGN AB022M": "10614", + "LINEAR A SIGN AB077": "1063E", + "LINEAR A SIGN AB171": "10651", + "LINEAR A SIGN A306": "1065A", + "LINEAR A SIGN A326": "10672", + "LINEAR A SIGN A363": "10697", + "LINEAR A SIGN A366": "1069A", + "LINEAR A SIGN A400-VAS": "106A0", + "LINEAR A SIGN A402-VAS": "106A2", + "LINEAR A SIGN A404-VAS": "106A4", + "LINEAR A SIGN A412-VAS": "106AC", + "LINEAR A SIGN A416-VAS": "106B0", + "LINEAR A SIGN A511": "106BC", + "LINEAR A SIGN A575": "106EE", + "LINEAR A SIGN A609": "1070A", + "LINEAR A SIGN A653": "1072B", + "LINEAR A SIGN A658": "10730", + "LINEAR A SIGN A660": "10732", + "LINEAR A SIGN A713 OMEGA": "10750", + "LINEAR A SIGN A714 ABB": "10751", + "MODIFIER LETTER SMALL CAPITAL B": "10784", + "MODIFIER LETTER SMALL TURNED Y": "107A0", + "MODIFIER LETTER SMALL CAPITAL Y": "107B2", + "MODIFIER LETTER RETROFLEX CLICK WITH RETROFLEX HOOK": "107B9", "CYPRIOT SYLLABLE KU": "1080E", - "CYPRIOT SYLLABLE SU": "1082C", - "CYPRIOT SYLLABLE TA": "1082D", - "CYPRIOT SYLLABLE ZA": "1083C", - "IMPERIAL ARAMAIC LETTER ALEPH": "10840", - "IMPERIAL ARAMAIC LETTER HETH": "10847", - "IMPERIAL ARAMAIC LETTER YODH": "10849", - "IMPERIAL ARAMAIC NUMBER ONE THOUSAND": "1085E", - "HATRAN LETTER ZAYN": "108E6", - "HATRAN LETTER NUN": "108ED", - "PHOENICIAN LETTER BET": "10901", - "PHOENICIAN LETTER HE": "10904", - "PHOENICIAN LETTER NUN": "1090D", + "IMPERIAL ARAMAIC LETTER SAMEKH": "1084E", + "IMPERIAL ARAMAIC SECTION SIGN": "10857", + "IMPERIAL ARAMAIC NUMBER TWENTY": "1085C", + "PALMYRENE NUMBER FOUR": "1087C", + "PALMYRENE NUMBER FIVE": "1087D", + "NABATAEAN LETTER DALETH": "10885", + "NABATAEAN LETTER SADHE": "10899", + "NABATAEAN LETTER QOPH": "1089A", + "PHOENICIAN LETTER TET": "10908", + "PHOENICIAN LETTER SADE": "10911", + "LYDIAN LETTER B": "10921", + "LYDIAN LETTER G": "10922", + "LYDIAN LETTER Y": "10927", "LYDIAN LETTER R": "1092D", - "MEROITIC HIEROGLYPHIC LETTER A": "10980", - "MEROITIC HIEROGLYPHIC LETTER HHA": "10992", - "MEROITIC CURSIVE LETTER MA": "109A8", - "MEROITIC CURSIVE LOGOGRAM RMT": "109BE", - "MEROITIC CURSIVE NUMBER ONE": "109C0", - "MEROITIC CURSIVE NUMBER FIVE": "109C4", - "MEROITIC CURSIVE NUMBER SEVENTY THOUSAND": "109EA", - "MEROITIC CURSIVE NUMBER NINE HUNDRED THOUSAND": "109F5", - "MEROITIC CURSIVE FRACTION TEN TWELFTHS": "109FF", - "KHAROSHTHI LETTER CA": "10A15", - "KHAROSHTHI LETTER SSA": "10A2E", - "KHAROSHTHI LETTER HA": "10A31", - "KHAROSHTHI PUNCTUATION MANGALAM": "10A54", - "OLD SOUTH ARABIAN LETTER ALEF": "10A71", - "OLD SOUTH ARABIAN LETTER YODH": "10A7A", - "OLD NORTH ARABIAN LETTER YEH": "10A9A", - "OLD NORTH ARABIAN NUMBER TWENTY": "10A9F", - "MANICHAEAN LETTER WAW": "10AC7", - "MANICHAEAN LETTER ZHAYIN": "10ACA", - "MANICHAEAN LETTER TETH": "10ACE", - "MANICHAEAN LETTER LAMEDH": "10AD3", - "MANICHAEAN LETTER XOPH": "10ADF", - "AVESTAN LETTER AAN": "10B05", - "AVESTAN LETTER AE": "10B06", - "AVESTAN LETTER VE": "10B2C", - "INSCRIPTIONAL PAHLAVI LETTER LAMEDH": "10B6B", - "PSALTER PAHLAVI NUMBER ONE HUNDRED": "10BAF", - "OLD TURKIC LETTER YENISEI I": "10C04", - "OLD TURKIC LETTER ORKHON AY": "10C16", - "OLD TURKIC LETTER ORKHON AN": "10C23", - "OLD TURKIC LETTER YENISEI AQ": "10C35", - "OLD TURKIC LETTER ORKHON OT": "10C47", - "OLD HUNGARIAN CAPITAL LETTER I": "10C90", - "OLD HUNGARIAN CAPITAL LETTER SHORT ER": "10CA3", - "OLD HUNGARIAN CAPITAL LETTER RUDIMENTA UE": "10CAD", - "OLD HUNGARIAN SMALL LETTER EG": "10CCD", - "OLD HUNGARIAN SMALL LETTER I": "10CD0", - "OLD HUNGARIAN SMALL LETTER EL": "10CD6", - "OLD HUNGARIAN SMALL LETTER NIKOLSBURG UE": "10CEC", - "OLD HUNGARIAN NUMBER ONE": "10CFA", - "HANIFI ROHINGYA SIGN TAHALA": "10D25", - "HANIFI ROHINGYA DIGIT SIX": "10D36", - "RUMI DIGIT TWO": "10E61", - "RUMI NUMBER THIRTY": "10E6B", - "YEZIDI LETTER QAF": "10E9C", - "YEZIDI LETTER KAF": "10E9D", - "OLD SOGDIAN LETTER BETH": "10F02", - "SOGDIAN LETTER GIMEL": "10F32", - "SOGDIAN COMBINING DOT ABOVE": "10F48", - "OLD UYGHUR LETTER SADHE": "10F7D", - "OLD UYGHUR LETTER LESH": "10F81", - "OLD UYGHUR COMBINING DOT ABOVE": "10F82", - "OLD UYGHUR COMBINING TWO DOTS ABOVE": "10F84", - "CHORASMIAN LETTER MEM": "10FBD", - "CHORASMIAN LETTER TAW": "10FC4", - "BRAHMI SIGN CANDRABINDU": "11000", - "BRAHMI LETTER GHA": "11016", - "BRAHMI LETTER TTHA": "1101E", - "BRAHMI VOWEL SIGN AA": "11038", - "BRAHMI NUMBER FOUR": "11055", - "BRAHMI NUMBER NINETY": "11063", - "KAITHI SIGN CANDRABINDU": "11080", - "KAITHI LETTER AI": "1108A", - "SORA SOMPENG LETTER BAH": "110D2", - "CHAKMA LETTER DAA": "11118", - "CHAKMA LETTER MAA": "1111F", - "CHAKMA DIGIT NINE": "1113F", - "MAHAJANI LETTER TTHA": "1115F", - "MAHAJANI ABBREVIATION SIGN": "11174", - "SHARADA LETTER II": "11186", - "SHARADA LETTER JA": "11198", - "SHARADA LETTER TTHA": "1119C", - "SHARADA SUTRA MARK": "111CD", - "SHARADA DIGIT ZERO": "111D0", - "SHARADA DIGIT FOUR": "111D4", - "SHARADA DIGIT EIGHT": "111D8", - "SHARADA EKAM": "111DA", - "KHOJKI LETTER O": "11206", - "KHOJKI LETTER CHA": "1120F", - "KHOJKI LETTER TTHA": "11215", - "KHOJKI LETTER LA": "11227", - "KHOJKI LETTER VA": "11228", - "KHOJKI VOWEL SIGN I": "1122D", - "MULTANI LETTER DDA": "11292", - "MULTANI LETTER RA": "112A2", - "KHUDAWADI LETTER DDHA": "112CB", - "KHUDAWADI SIGN ANUSVARA": "112DF", - "KHUDAWADI DIGIT FOUR": "112F4", - "GRANTHA SIGN ANUSVARA": "11302", - "GRANTHA LETTER DDHA": "11322", - "GRANTHA LETTER MA": "1132E", - "GRANTHA LETTER LLA": "11333", - "GRANTHA SIGN NUKTA": "1133C", - "GRANTHA VOWEL SIGN VOCALIC R": "11343", - "GRANTHA SIGN VIRAMA": "1134D", - "NEWA LETTER SHA": "11431", + "MEROITIC HIEROGLYPHIC LETTER TA": "10998", + "MEROITIC HIEROGLYPHIC LETTER TA-2": "10999", + "MEROITIC CURSIVE LETTER BA": "109A6", + "MEROITIC CURSIVE LETTER KHA": "109AD", + "MEROITIC CURSIVE NUMBER ONE HUNDRED": "109D2", + "MEROITIC CURSIVE NUMBER SIX THOUSAND": "109E0", + "MEROITIC CURSIVE NUMBER EIGHTY THOUSAND": "109EB", + "KHAROSHTHI VOWEL SIGN U": "10A02", + "KHAROSHTHI LETTER JA": "10A17", + "KHAROSHTHI LETTER VA": "10A2C", + "KHAROSHTHI LETTER KKA": "10A32", + "KHAROSHTHI SIGN BAR ABOVE": "10A38", + "OLD SOUTH ARABIAN LETTER WAW": "10A65", + "OLD NORTH ARABIAN LETTER LAM": "10A81", + "OLD NORTH ARABIAN NUMBER TEN": "10A9E", + "AVESTAN LETTER EE": "10B09", + "AVESTAN LETTER XVE": "10B13", + "AVESTAN LETTER NGVE": "10B24", + "AVESTAN LETTER YYE": "10B2A", + "AVESTAN LETTER SHE": "10B31", + "AVESTAN LETTER SSHE": "10B34", + "INSCRIPTIONAL PARTHIAN LETTER DALETH": "10B43", + "INSCRIPTIONAL PAHLAVI LETTER KAPH": "10B6A", + "PSALTER PAHLAVI LETTER ALEPH": "10B80", + "PSALTER PAHLAVI FOUR DOTS WITH CROSS": "10B9B", + "OLD TURKIC LETTER YENISEI E": "10C05", + "OLD TURKIC LETTER ORKHON EM": "10C22", + "OLD TURKIC LETTER YENISEI ENC": "10C29", + "OLD TURKIC LETTER YENISEI ENY": "10C2B", + "OLD HUNGARIAN CAPITAL LETTER A": "10C80", + "OLD HUNGARIAN CAPITAL LETTER EJ": "10C92", + "OLD HUNGARIAN CAPITAL LETTER UNK": "10C95", + "HANIFI ROHINGYA LETTER SHA": "10D10", + "HANIFI ROHINGYA LETTER LA": "10D13", + "HANIFI ROHINGYA VOWEL O": "10D21", + "HANIFI ROHINGYA DIGIT SEVEN": "10D37", + "HANIFI ROHINGYA DIGIT EIGHT": "10D38", + "RUMI DIGIT ONE": "10E60", + "RUMI DIGIT THREE": "10E62", + "YEZIDI LETTER ZE": "10E96", + "YEZIDI LETTER MIM": "10EA1", + "YEZIDI LETTER LAM WITH DOT ABOVE": "10EB0", + "OLD SOGDIAN LETTER FINAL HE": "10F06", + "SOGDIAN LETTER AYIN": "10F3D", + "SOGDIAN LETTER FETH": "10F43", + "OLD UYGHUR LETTER GIMEL-HETH": "10F72", + "CHORASMIAN LETTER BETH": "10FB2", + "CHORASMIAN LETTER AYIN": "10FC0", + "ELYMAIC LETTER RESH": "10FF3", + "ELYMAIC LETTER TAW": "10FF5", + "BRAHMI LETTER VOCALIC RR": "1100C", + "BRAHMI LETTER DA": "11024", + "BRAHMI LETTER HA": "11033", + "BRAHMI VOWEL SIGN E": "11042", + "BRAHMI NUMBER TWENTY": "1105C", + "BRAHMI NUMBER FORTY": "1105E", + "BRAHMI DIGIT NINE": "1106F", + "KAITHI LETTER GHA": "11090", + "KAITHI LETTER NYA": "11096", + "KAITHI LETTER DDA": "11099", + "KAITHI LETTER THA": "1109F", + "KAITHI LETTER PHA": "110A4", + "KAITHI VOWEL SIGN AI": "110B6", + "CHAKMA LETTER DDHAA": "11114", + "CHAKMA LETTER PAA": "1111B", + "CHAKMA DIGIT SEVEN": "1113D", + "CHAKMA LETTER LHAA": "11144", + "MAHAJANI LETTER U": "11152", + "MAHAJANI LETTER DA": "11165", + "SHARADA LETTER AU": "11190", + "SHARADA VOWEL SIGN E": "111BC", + "SHARADA SIGN VIRAMA": "111C0", + "SHARADA DOUBLE DANDA": "111C6", + "SHARADA SIGN NUKTA": "111CA", + "SHARADA DIGIT SEVEN": "111D7", + "SINHALA ARCHAIC DIGIT FOUR": "111E4", + "KHOJKI LETTER JJA": "11211", + "KHOJKI VOWEL SIGN II": "1122E", + "KHOJKI SIGN SHADDA": "11237", + "KHOJKI DOUBLE DANDA": "11239", + "MULTANI LETTER I": "11281", + "MULTANI LETTER CA": "1128A", + "MULTANI LETTER NA": "1129A", + "MULTANI LETTER MA": "112A0", + "MULTANI LETTER HA": "112A6", + "KHUDAWADI LETTER JHA": "112C4", + "KHUDAWADI LETTER NA": "112D1", + "KHUDAWADI LETTER RA": "112D9", + "GRANTHA LETTER VOCALIC RR": "11360", + "NEWA LETTER THA": "11420", + "NEWA VOWEL SIGN I": "11436", "NEWA SIGN VISARGA": "11445", - "NEWA OM": "11449", - "NEWA SIGN JIHVAMULIYA": "11460", - "TIRHUTA LETTER U": "11485", - "TIRHUTA LETTER VOCALIC L": "11489", - "TIRHUTA LETTER NNA": "1149D", - "TIRHUTA LETTER SHA": "114AC", - "SIDDHAM LETTER I": "11582", - "SIDDHAM LETTER THA": "1159E", - "SIDDHAM VOWEL SIGN II": "115B1", - "SIDDHAM SIGN CANDRABINDU": "115BC", - "SIDDHAM SECTION MARK WITH RAYS AND DOTTED TRIPLE CRESCENTS": "115CE", - "MODI LETTER A": "11600", - "MODI LETTER VOCALIC LL": "11609", - "MODI LETTER E": "1160A", - "MODI LETTER YA": "11627", - "MODI VOWEL SIGN O": "1163B", - "MODI DIGIT ZERO": "11650", - "MONGOLIAN ROTATED BIRGA": "11661", + "NEWA DIGIT ZERO": "11450", + "TIRHUTA LETTER NA": "114A2", + "TIRHUTA VOWEL SIGN U": "114B3", + "SIDDHAM LETTER II": "11583", + "SIDDHAM LETTER CHA": "11594", + "SIDDHAM VOWEL SIGN AA": "115AF", + "SIDDHAM VOWEL SIGN VOCALIC RR": "115B5", + "SIDDHAM VOWEL SIGN AU": "115BB", + "MODI LETTER VOCALIC RR": "11607", + "MODI SIGN VIRAMA": "1163F", + "MONGOLIAN TRIPLE BIRGA WITH ORNAMENT": "11663", "MONGOLIAN ROTATED BIRGA WITH DOUBLE ORNAMENT": "11666", - "TAKRI LETTER U": "11684", - "TAKRI LETTER UU": "11685", - "TAKRI LETTER AI": "11687", - "TAKRI LETTER GHA": "1168D", - "TAKRI DIGIT SIX": "116C6", - "AHOM CONSONANT SIGN MEDIAL RA": "1171E", + "TAKRI LETTER E": "11686", + "TAKRI LETTER O": "11688", + "TAKRI LETTER TTA": "11694", + "TAKRI VOWEL SIGN AI": "116B3", + "TAKRI DIGIT ONE": "116C1", + "TAKRI DIGIT NINE": "116C9", + "AHOM VOWEL SIGN AI": "11729", "AHOM DIGIT ZERO": "11730", - "DOGRA LETTER I": "11802", - "DOGRA LETTER GHA": "1180D", - "DOGRA LETTER JA": "11811", - "DOGRA LETTER NNA": "11818", - "DOGRA LETTER HA": "1182A", - "DOGRA VOWEL SIGN U": "1182F", - "WARANG CITI CAPITAL LETTER NGAA": "118A0", - "WARANG CITI CAPITAL LETTER SSUU": "118BD", - "WARANG CITI SMALL LETTER YO": "118C5", + "AHOM LETTER TTHA": "11742", + "AHOM LETTER DDHA": "11744", + "DOGRA LETTER TTHA": "11815", + "DOGRA LETTER DDHA": "11817", + "DOGRA VOWEL SIGN O": "11835", + "WARANG CITI CAPITAL LETTER DA": "118B4", + "WARANG CITI CAPITAL LETTER AM": "118B6", + "WARANG CITI CAPITAL LETTER HIYO": "118B9", + "WARANG CITI SMALL LETTER UU": "118C7", "WARANG CITI SMALL LETTER GA": "118CB", - "WARANG CITI SMALL LETTER HAR": "118DC", - "DIVES AKURU LETTER KA": "1190C", - "DIVES AKURU LETTER TTA": "11916", - "DIVES AKURU LETTER PHA": "11921", - "DIVES AKURU LETTER HA": "1192D", - "DIVES AKURU LETTER ZA": "1192F", + "WARANG CITI SMALL LETTER VIYO": "118DF", + "WARANG CITI NUMBER SEVENTY": "118F0", "DIVES AKURU SIGN HALANTA": "1193D", + "DIVES AKURU DIGIT ONE": "11951", + "NANDINAGARI LETTER AA": "119A1", + "NANDINAGARI LETTER II": "119A3", "NANDINAGARI LETTER KHA": "119AF", - "NANDINAGARI VOWEL SIGN II": "119D3", - "NANDINAGARI VOWEL SIGN VOCALIC RR": "119D7", - "ZANABAZAR SQUARE LETTER THA": "11A1A", - "ZANABAZAR SQUARE LETTER BHA": "11A21", - "ZANABAZAR SQUARE CLUSTER-FINAL LETTER LA": "11A3D", - "SOYOMBO VOWEL SIGN UE": "11A52", - "SOYOMBO VOWEL SIGN OE": "11A56", - "SOYOMBO LETTER JHA": "11A64", - "SOYOMBO LETTER PHA": "11A71", - "SOYOMBO TERMINAL MARK-2": "11AA2", - "PAU CIN HAU LETTER A": "11AD5", - "PAU CIN HAU LETTER IA": "11ADB", - "PAU CIN HAU RISING TONE LONG": "11AE5", - "PAU CIN HAU GLOTTAL STOP VARIANT": "11AF0", - "PAU CIN HAU MID-LEVEL TONE LONG FINAL": "11AF1", - "BHAIKSUKI LETTER TA": "11C1D", - "MARCHEN LETTER JA": "11C78", - "MARCHEN LETTER TSHA": "11C83", - "MARCHEN LETTER LA": "11C8B", - "MASARAM GONDI LETTER KA": "11D0C", - "MASARAM GONDI LETTER KHA": "11D0D", - "MASARAM GONDI LETTER NNA": "11D1A", - "MASARAM GONDI LETTER TA": "11D1B", - "MASARAM GONDI LETTER DHA": "11D1E", + "NANDINAGARI VOWEL SIGN UU": "119D5", + "NANDINAGARI VOWEL SIGN PRISHTHAMATRA E": "119E4", + "ZANABAZAR SQUARE LETTER TTHA": "11A15", + "ZANABAZAR SQUARE LETTER YA": "11A2A", + "ZANABAZAR SQUARE LETTER RA": "11A2B", + "SOYOMBO LETTER KHA": "11A5D", + "SOYOMBO LETTER NA": "11A6F", + "SOYOMBO CLUSTER-INITIAL LETTER SHA": "11A88", + "SOYOMBO FINAL CONSONANT SIGN R": "11A91", + "CANADIAN SYLLABICS NATTILIK HII": "11AB1", + "PAU CIN HAU LETTER PHA": "11AD1", + "PAU CIN HAU LETTER FINAL P": "11ADC", + "PAU CIN HAU GLOTTAL STOP FINAL": "11AF8", + "BHAIKSUKI LETTER BA": "11C24", + "BHAIKSUKI LETTER BHA": "11C25", + "BHAIKSUKI DANDA": "11C41", + "BHAIKSUKI DIGIT SIX": "11C56", + "BHAIKSUKI DIGIT NINE": "11C59", + "BHAIKSUKI NUMBER FIVE": "11C5E", + "MARCHEN LETTER RA": "11C8A", + "MARCHEN SUBJOINED LETTER JA": "11C98", + "MARCHEN SUBJOINED LETTER RA": "11CAA", + "MASARAM GONDI LETTER AI": "11D08", "MASARAM GONDI LETTER PHA": "11D21", - "MASARAM GONDI LETTER BHA": "11D23", - "MASARAM GONDI LETTER LA": "11D27", - "MASARAM GONDI VOWEL SIGN U": "11D34", - "GUNJALA GONDI LETTER NA": "11D7A", - "GUNJALA GONDI LETTER TTHA": "11D7E", - "GUNJALA GONDI DIGIT NINE": "11DA9", - "MAKASAR VOWEL SIGN O": "11EF6", - "KAWI PUNCTUATION DOUBLE DOT": "11F4A", - "TAMIL FRACTION THREE QUARTERS": "11FD3", - "TAMIL FRACTION DOWNSCALING FACTOR KIIZH": "11FD4", - "TAMIL SIGN UZHAKKU": "11FD8", - "TAMIL SIGN KAACU": "11FDD", - "TAMIL SIGN PON": "11FDF", - "CUNEIFORM SIGN AB GUNU": "12015", - "CUNEIFORM SIGN AB2 TIMES SHA3": "1201A", + "MASARAM GONDI DIGIT SIX": "11D56", + "GUNJALA GONDI LETTER I": "11D62", + "GUNJALA GONDI LETTER OO": "11D6A", + "GUNJALA GONDI LETTER GHA": "11D77", + "GUNJALA GONDI SIGN ANUSVARA": "11D95", + "KAWI LETTER A": "11F04", + "KAWI LETTER VOCALIC LL": "11F0D", + "KAWI LETTER JHA": "11F1A", + "KAWI LETTER DA": "11F23", + "KAWI DIGIT FOUR": "11F54", + "TAMIL FRACTION ONE SIXTEENTH-1": "11FC9", + "TAMIL FRACTION ONE FIFTH": "11FCF", + "CUNEIFORM SIGN A TIMES SAG": "12008", + "CUNEIFORM SIGN AB": "1200A", + "CUNEIFORM SIGN AB TIMES U PLUS U PLUS U": "12014", + "CUNEIFORM SIGN AD": "1201C", "CUNEIFORM SIGN BULUG OVER BULUG": "12052", - "CUNEIFORM SIGN DAG KISIM5 TIMES LU": "12065", - "CUNEIFORM SIGN DAG KISIM5 TIMES LUM": "12067", - "CUNEIFORM SIGN DIN KASKAL U GUNU DISH": "12078", - "CUNEIFORM SIGN DUN3 GUNU": "12086", - "CUNEIFORM SIGN DUN4": "12088", - "CUNEIFORM SIGN ESH2": "120A0", - "CUNEIFORM SIGN EZEN TIMES DUN3 GUNU": "120A7", - "CUNEIFORM SIGN EZEN TIMES HA GUNU": "120AA", - "CUNEIFORM SIGN GA2 TIMES HAL PLUS LA": "120D3", - "CUNEIFORM SIGN GALAM": "120F4", - "CUNEIFORM SIGN GIR2": "12108", - "CUNEIFORM SIGN GURUSH": "12128", - "CUNEIFORM SIGN HA GUNU": "1212B", - "CUNEIFORM SIGN KA TIMES GUR7": "1216C", - "CUNEIFORM SIGN KA2": "1218D", - "CUNEIFORM SIGN KAL": "12197", - "CUNEIFORM SIGN KIN": "121A5", - "CUNEIFORM SIGN KUR OPPOSING KUR": "121B4", - "CUNEIFORM SIGN KWU318": "121B6", - "CUNEIFORM SIGN LAGAB TIMES U2 PLUS ASH": "121E8", - "CUNEIFORM SIGN LAL": "121F2", - "CUNEIFORM SIGN MUSH TIMES KUR": "12234", - "CUNEIFORM SIGN MUSH OVER MUSH": "12236", - "CUNEIFORM SIGN NAGAR": "12244", - "CUNEIFORM SIGN NE TIMES A": "12249", - "CUNEIFORM SIGN NE TIMES UD": "1224A", - "CUNEIFORM SIGN NIM TIMES GAR PLUS GAN2 TENU": "12251", - "CUNEIFORM SIGN NUNUZ AB2 TIMES IGI GUNU": "12272", - "CUNEIFORM SIGN PI TIMES U2": "12288", - "CUNEIFORM SIGN SHE OVER SHE GAD OVER GAD GAR OVER GAR": "122BC", - "CUNEIFORM SIGN SHIR TENU": "122D4", - "CUNEIFORM SIGN SHUBUR": "122DA", - "CUNEIFORM SIGN SIK2": "122E0", - "CUNEIFORM SIGN SUM": "122E7", - "CUNEIFORM SIGN TAB OVER TAB NI OVER NI DISH OVER DISH": "122F1", - "CUNEIFORM SIGN UD TIMES U PLUS U PLUS U GUNU": "12318", - "CUNEIFORM SIGN UM": "1231D", - "CUNEIFORM SIGN USH TIMES KU": "12353", - "CUNEIFORM SIGN USHUMX": "12358", - "CUNEIFORM SIGN UTUKI": "12359", - "CUNEIFORM SIGN EZEN TIMES GUD": "12377", - "CUNEIFORM NUMERIC SIGN SIX U": "12411", - "CUNEIFORM NUMERIC SIGN EIGHT U": "12413", - "CUNEIFORM NUMERIC SIGN FOUR BURU": "12438", - "CUNEIFORM NUMERIC SIGN FIVE BURU": "12439", + "CUNEIFORM SIGN DISH": "12079", + "CUNEIFORM SIGN DUH": "12083", + "CUNEIFORM SIGN EZEN TIMES HA": "120A9", + "CUNEIFORM SIGN EZEN TIMES IGI GUNU": "120AB", + "CUNEIFORM SIGN EZEN TIMES UD": "120B4", + "CUNEIFORM SIGN GA2 TIMES DI": "120C4", + "CUNEIFORM SIGN GA2 TIMES GIR2 PLUS SU": "120D0", + "CUNEIFORM SIGN GA2 TIMES U": "120EA", + "CUNEIFORM SIGN GAN2 CROSSING GAN2": "120FA", + "CUNEIFORM SIGN GI CROSSING GI": "12103", + "CUNEIFORM SIGN GIR3 TIMES A PLUS IGI": "1210B", + "CUNEIFORM SIGN GISAL": "12110", + "CUNEIFORM SIGN GU2 TIMES SAL PLUS TUG2": "1211C", + "CUNEIFORM SIGN GUL": "12122", + "CUNEIFORM SIGN HAL": "1212C", + "CUNEIFORM SIGN IDIM": "12142", + "CUNEIFORM SIGN IL2": "1214D", + "CUNEIFORM SIGN IM SQUARED": "12152", + "CUNEIFORM SIGN KA TIMES AD PLUS KU3": "1215A", + "CUNEIFORM SIGN KA TIMES GU": "1216B", + "CUNEIFORM SIGN KA TIMES ME PLUS DU": "12175", + "CUNEIFORM SIGN KA TIMES MI": "12178", + "CUNEIFORM SIGN KAK": "12195", + "CUNEIFORM SIGN KU OVER HI TIMES ASH2 KU OVER HI TIMES ASH2": "121AB", + "CUNEIFORM SIGN LAGAB TIMES A PLUS GAR": "121BB", + "CUNEIFORM SIGN LAGAB TIMES BI": "121C1", + "CUNEIFORM SIGN LAGAB TIMES GAR": "121C5", + "CUNEIFORM SIGN LAGAB TIMES IM PLUS LU": "121CE", + "CUNEIFORM SIGN LAM TIMES KUR": "121F5", + "CUNEIFORM SIGN LUL": "1221C", + "CUNEIFORM SIGN NA2": "1223F", + "CUNEIFORM SIGN NIM": "1224F", + "CUNEIFORM SIGN PAN": "1227C", + "CUNEIFORM SIGN PESH2": "1227E", + "CUNEIFORM SIGN PIRIG": "1228A", + "CUNEIFORM SIGN RA": "1228F", + "CUNEIFORM SIGN SAG OVER SAG": "122A7", + "CUNEIFORM SIGN SAG GUNU": "122A8", + "CUNEIFORM SIGN SHA3 TIMES GISH": "122B1", + "CUNEIFORM SIGN SHU OVER INVERTED SHU": "122D8", + "CUNEIFORM SIGN SIG4": "122DE", + "CUNEIFORM SIGN TI": "122FE", + "CUNEIFORM SIGN TIR OVER TIR": "12303", + "CUNEIFORM SIGN TUK": "12307", + "CUNEIFORM SIGN UD TIMES BAD": "12315", + "CUNEIFORM SIGN UD SHESHIG TIMES BAD": "1231B", + "CUNEIFORM SIGN UR2 TIMES HA": "1232F", + "CUNEIFORM SIGN USH2": "12357", + "CUNEIFORM SIGN GE22": "1237B", + "CUNEIFORM SIGN HUSH": "1237D", + "CUNEIFORM SIGN LU2 SHESHIG TIMES BAD": "12389", + "CUNEIFORM NUMERIC SIGN THREE DISH": "12408", + "CUNEIFORM NUMERIC SIGN FIVE DISH": "1240A", + "CUNEIFORM NUMERIC SIGN NINE VARIANT FORM ILIMMU A": "12449", + "CUNEIFORM NUMERIC SIGN FIVE SIXTHS DISH": "1245C", "CUNEIFORM SIGN BAD TIMES DISH TENU": "12483", - "CUNEIFORM SIGN DUG TIMES HI": "12498", - "CUNEIFORM SIGN EZEN SHESHIG TIMES IGI GUNU": "124AF", - "CUNEIFORM SIGN EZEN SHESHIG TIMES SU": "124B4", - "CUNEIFORM SIGN GA2 TIMES LAM": "124C0", - "CUNEIFORM SIGN LAK-050": "124D9", - "CUNEIFORM SIGN LAK-142": "124E1", - "CUNEIFORM SIGN LAK-449 TIMES IGI": "124F3", - "CUNEIFORM SIGN LAK-648 TIMES GA": "1250F", - "CUNEIFORM SIGN LAK-648 TIMES SHESH PLUS KI": "12514", - "CUNEIFORM SIGN LU2 TIMES PAP": "1251C", - "CUNEIFORM SIGN SHA6 TENU": "12531", - "CYPRO-MINOAN SIGN CM063": "12FC2", - "CYPRO-MINOAN SIGN CM068": "12FC6", - "CYPRO-MINOAN SIGN CM110": "12FEE", - "EGYPTIAN HIEROGLYPH A016": "13013", - "EGYPTIAN HIEROGLYPH A020": "13018", - "EGYPTIAN HIEROGLYPH A049": "1303A", - "EGYPTIAN HIEROGLYPH A057": "13042", - "EGYPTIAN HIEROGLYPH B001": "13050", - "EGYPTIAN HIEROGLYPH C003": "1305F", - "EGYPTIAN HIEROGLYPH D010": "13080", - "EGYPTIAN HIEROGLYPH D029": "13094", - "EGYPTIAN HIEROGLYPH D046A": "130A8", - "EGYPTIAN HIEROGLYPH D050C": "130B0", - "EGYPTIAN HIEROGLYPH D063": "130C5", - "EGYPTIAN HIEROGLYPH E016A": "130E4", + "CUNEIFORM SIGN BAHAR2 TIMES ZA": "12486", + "CUNEIFORM SIGN DAG TIMES KUR": "12489", + "CUNEIFORM SIGN DUG TIMES ERIN2": "12492", + "CUNEIFORM SIGN DUG TIMES SI GUNU": "124A8", + "CUNEIFORM SIGN GA2 TIMES BAHAR2": "124B6", + "CUNEIFORM SIGN GA2 TIMES LAM TIMES KUR": "124C1", + "CUNEIFORM SIGN GA2 TIMES NE PLUS E2": "124C5", + "CUNEIFORM SIGN LAK-081 OVER LAK-081": "124DE", + "CUNEIFORM SIGN LAK-130": "124E0", + "CUNEIFORM SIGN LAK-225": "124E5", + "CUNEIFORM SIGN LAK-238": "124E7", + "CUNEIFORM SIGN LAK-648 TIMES PAP PLUS PAP PLUS LU3": "12513", + "CUNEIFORM SIGN NINDA2 TIMES HI": "12525", + "CYPRO-MINOAN SIGN CM040": "12FB0", + "CYPRO-MINOAN SIGN CM089": "12FDB", + "EGYPTIAN HIEROGLYPH A003": "13002", + "EGYPTIAN HIEROGLYPH A025": "1301D", + "EGYPTIAN HIEROGLYPH A056": "13041", + "EGYPTIAN HIEROGLYPH A065": "1304A", + "EGYPTIAN HIEROGLYPH D026": "13090", + "EGYPTIAN HIEROGLYPH D039": "130A0", + "EGYPTIAN HIEROGLYPH D067A": "130CA", + "EGYPTIAN HIEROGLYPH E012": "130DF", + "EGYPTIAN HIEROGLYPH E034A": "130FA", "EGYPTIAN HIEROGLYPH F022": "13116", - "EGYPTIAN HIEROGLYPH F023": "13117", - "EGYPTIAN HIEROGLYPH G010": "1314B", - "EGYPTIAN HIEROGLYPH G049": "13179", - "EGYPTIAN HIEROGLYPH I015": "1319A", - "EGYPTIAN HIEROGLYPH K004": "1319E", - "EGYPTIAN HIEROGLYPH L004": "131A7", - "EGYPTIAN HIEROGLYPH M022A": "131D2", - "EGYPTIAN HIEROGLYPH M035": "131E4", - "EGYPTIAN HIEROGLYPH N019": "13203", - "EGYPTIAN HIEROGLYPH N025A": "1320A", - "EGYPTIAN HIEROGLYPH N040": "1321D", - "EGYPTIAN HIEROGLYPH NL002": "13221", - "EGYPTIAN HIEROGLYPH NL014": "1322E", - "EGYPTIAN HIEROGLYPH O013": "13267", - "EGYPTIAN HIEROGLYPH O017": "1326B", - "EGYPTIAN HIEROGLYPH P009": "132A5", - "EGYPTIAN HIEROGLYPH S016": "132E4", - "EGYPTIAN HIEROGLYPH S017A": "132E6", - "EGYPTIAN HIEROGLYPH S019": "132E8", - "EGYPTIAN HIEROGLYPH S040": "13300", - "EGYPTIAN HIEROGLYPH T004": "1330B", - "EGYPTIAN HIEROGLYPH T027": "13327", - "EGYPTIAN HIEROGLYPH T033": "1332E", - "EGYPTIAN HIEROGLYPH U011": "1333F", - "EGYPTIAN HIEROGLYPH U019": "13347", - "EGYPTIAN HIEROGLYPH U040": "1335F", - "EGYPTIAN HIEROGLYPH V020C": "13389", + "EGYPTIAN HIEROGLYPH F025": "13119", + "EGYPTIAN HIEROGLYPH F051B": "1313B", + "EGYPTIAN HIEROGLYPH G011A": "1314D", + "EGYPTIAN HIEROGLYPH G040": "1316E", + "EGYPTIAN HIEROGLYPH H002": "13180", + "EGYPTIAN HIEROGLYPH H008": "13187", + "EGYPTIAN HIEROGLYPH M001A": "131AE", + "EGYPTIAN HIEROGLYPH M014": "131C6", + "EGYPTIAN HIEROGLYPH M031": "131DD", + "EGYPTIAN HIEROGLYPH M044": "131EE", + "EGYPTIAN HIEROGLYPH N017": "131FF", + "EGYPTIAN HIEROGLYPH N030": "1320F", + "EGYPTIAN HIEROGLYPH NL015": "1322F", + "EGYPTIAN HIEROGLYPH NL017A": "13232", + "EGYPTIAN HIEROGLYPH NU006": "1323B", + "EGYPTIAN HIEROGLYPH NU017": "13248", + "EGYPTIAN HIEROGLYPH NU020": "1324C", + "EGYPTIAN HIEROGLYPH O019A": "1326E", + "EGYPTIAN HIEROGLYPH O023": "13273", + "EGYPTIAN HIEROGLYPH O029": "1327B", + "EGYPTIAN HIEROGLYPH O046": "13293", + "EGYPTIAN HIEROGLYPH O050B": "13299", + "EGYPTIAN HIEROGLYPH P004": "132A0", + "EGYPTIAN HIEROGLYPH R017": "132C4", + "EGYPTIAN HIEROGLYPH S022": "132EB", + "EGYPTIAN HIEROGLYPH S029": "132F4", + "EGYPTIAN HIEROGLYPH U023": "1334B", "EGYPTIAN HIEROGLYPH V028": "1339B", - "EGYPTIAN HIEROGLYPH V039": "133AC", - "EGYPTIAN HIEROGLYPH W003": "133B1", - "EGYPTIAN HIEROGLYPH W012": "133BD", - "EGYPTIAN HIEROGLYPH W018A": "133C6", - "EGYPTIAN HIEROGLYPH Z005": "133EF", - "EGYPTIAN HIEROGLYPH Z009": "133F4", - "EGYPTIAN HIEROGLYPH Z015C": "133FD", - "EGYPTIAN HIEROGLYPH INSERT AT MIDDLE": "13439", - "EGYPTIAN HIEROGLYPH INSERT AT TOP": "1343A", - "EGYPTIAN HIEROGLYPH LOST SIGN": "13443", - "EGYPTIAN HIEROGLYPH MODIFIER DAMAGED": "13455", - "ANATOLIAN HIEROGLYPH A020": "14414", - "ANATOLIAN HIEROGLYPH A021": "14415", - "ANATOLIAN HIEROGLYPH A070": "1444F", - "ANATOLIAN HIEROGLYPH A080": "14459", - "ANATOLIAN HIEROGLYPH A095": "14468", - "ANATOLIAN HIEROGLYPH A102A": "14474", - "ANATOLIAN HIEROGLYPH A140": "144A7", - "ANATOLIAN HIEROGLYPH A153": "144B4", - "ANATOLIAN HIEROGLYPH A174": "144C9", - "ANATOLIAN HIEROGLYPH A176": "144CB", - "ANATOLIAN HIEROGLYPH A235": "1450D", - "ANATOLIAN HIEROGLYPH A244": "14516", - "ANATOLIAN HIEROGLYPH A256": "14522", - "ANATOLIAN HIEROGLYPH A283": "1453E", - "ANATOLIAN HIEROGLYPH A288": "14543", - "ANATOLIAN HIEROGLYPH A291": "14547", - "ANATOLIAN HIEROGLYPH A298": "1454F", - "ANATOLIAN HIEROGLYPH A317": "14564", - "ANATOLIAN HIEROGLYPH A325": "1456C", - "ANATOLIAN HIEROGLYPH A357": "14592", - "ANATOLIAN HIEROGLYPH A360": "14596", - "ANATOLIAN HIEROGLYPH A364": "1459A", - "ANATOLIAN HIEROGLYPH A390": "145BA", - "ANATOLIAN HIEROGLYPH A401": "145C5", - "ANATOLIAN HIEROGLYPH A417": "145D6", - "ANATOLIAN HIEROGLYPH A457": "145FF", - "ANATOLIAN HIEROGLYPH A477": "14614", - "ANATOLIAN HIEROGLYPH A483": "1461A", - "ANATOLIAN HIEROGLYPH A524": "14640", - "BAMUM LETTER PHASE-A SHINDA PA NJI": "16808", - "BAMUM LETTER PHASE-A NTAP NTAA": "16822", - "BAMUM LETTER PHASE-A MEUNJOMNDEUQ": "16825", - "BAMUM LETTER PHASE-A MOOMPUQ": "16826", - "BAMUM LETTER PHASE-A TEUTEUWEN": "16831", - "BAMUM LETTER PHASE-A PAAM": "1684C", - "BAMUM LETTER PHASE-A NSHA": "16851", - "BAMUM LETTER PHASE-C NDOMBU": "1689D", - "BAMUM LETTER PHASE-C BUNG": "168C0", - "BAMUM LETTER PHASE-C VEUAEPEN": "168C1", - "BAMUM LETTER PHASE-C MAESI": "168CB", - "BAMUM LETTER PHASE-C NSUN": "168D6", - "BAMUM LETTER PHASE-C NDAP": "168DA", - "BAMUM LETTER PHASE-C MIEE": "168E6", + "EGYPTIAN HIEROGLYPH V031A": "133A2", + "EGYPTIAN HIEROGLYPH W001": "133AF", + "EGYPTIAN HIEROGLYPH W020": "133C8", + "EGYPTIAN HIEROGLYPH X008": "133D9", + "EGYPTIAN HIEROGLYPH Z011": "133F6", + "EGYPTIAN HIEROGLYPH AA019": "13421", + "EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT TOP START": "13447", + "ANATOLIAN HIEROGLYPH A004": "14403", + "ANATOLIAN HIEROGLYPH A016": "14410", + "ANATOLIAN HIEROGLYPH A019": "14413", + "ANATOLIAN HIEROGLYPH A026A": "1441B", + "ANATOLIAN HIEROGLYPH A049": "14437", + "ANATOLIAN HIEROGLYPH A071": "14450", + "ANATOLIAN HIEROGLYPH A097A": "1446B", + "ANATOLIAN HIEROGLYPH A110A": "14485", + "ANATOLIAN HIEROGLYPH A116": "1448D", + "ANATOLIAN HIEROGLYPH A126": "14498", + "ANATOLIAN HIEROGLYPH A181": "144D0", + "ANATOLIAN HIEROGLYPH A191": "144DA", + "ANATOLIAN HIEROGLYPH A201": "144E4", + "ANATOLIAN HIEROGLYPH A230": "14508", + "ANATOLIAN HIEROGLYPH A246": "14518", + "ANATOLIAN HIEROGLYPH A253": "1451F", + "ANATOLIAN HIEROGLYPH A261": "14527", + "ANATOLIAN HIEROGLYPH A269": "14530", + "ANATOLIAN HIEROGLYPH A289": "14544", + "ANATOLIAN HIEROGLYPH A296": "1454D", + "ANATOLIAN HIEROGLYPH A299A": "14551", + "ANATOLIAN HIEROGLYPH A329": "14570", + "ANATOLIAN HIEROGLYPH A339": "14580", + "ANATOLIAN HIEROGLYPH A355": "14590", + "ANATOLIAN HIEROGLYPH A384": "145B3", + "ANATOLIAN HIEROGLYPH A386": "145B5", + "ANATOLIAN HIEROGLYPH A400": "145C4", + "ANATOLIAN HIEROGLYPH A419": "145D8", + "ANATOLIAN HIEROGLYPH A442": "145EF", + "BAMUM LETTER PHASE-A PON PA NJI PIPAEMGBIEE": "16809", + "BAMUM LETTER PHASE-A MVEUAENGAM": "16810", + "BAMUM LETTER PHASE-A MAEMKPEN": "1682B", + "BAMUM LETTER PHASE-A TUAEP": "1682E", + "BAMUM LETTER PHASE-A NJAM": "16847", + "BAMUM LETTER PHASE-B FEE": "16885", + "BAMUM LETTER PHASE-C NANSANAQ": "168B2", + "BAMUM LETTER PHASE-D MBUO": "168F1", + "BAMUM LETTER PHASE-D MFEUT": "16908", "BAMUM LETTER PHASE-D YUWOQ": "16925", - "BAMUM LETTER PHASE-D TEEEE": "16928", - "BAMUM LETTER PHASE-D PAP": "16935", - "BAMUM LETTER PHASE-D GHEUAE": "16948", - "BAMUM LETTER PHASE-D TAE": "1694B", - "BAMUM LETTER PHASE-D SHOQ": "1695C", - "BAMUM LETTER PHASE-E KPEUX": "16974", - "BAMUM LETTER PHASE-E TOO": "16979", - "BAMUM LETTER PHASE-E KUOP": "1697A", - "BAMUM LETTER PHASE-E NSHIEE": "1697C", - "BAMUM LETTER PHASE-E KEUAE": "1699A", - "BAMUM LETTER PHASE-E YIT": "169AE", - "BAMUM LETTER PHASE-E MAE": "169B8", - "BAMUM LETTER PHASE-E FA": "169BB", - "BAMUM LETTER PHASE-E PUAQ": "169CA", - "BAMUM LETTER PHASE-E NTAP": "169CE", - "BAMUM LETTER PHASE-E I": "169D8", - "BAMUM LETTER PHASE-E YOQ SWIMMING": "169E2", - "BAMUM LETTER PHASE-E KO": "169F9", - "BAMUM LETTER PHASE-E MAQ": "169FC", - "BAMUM LETTER PHASE-E TEU": "169FD", - "BAMUM LETTER PHASE-F NJAEM": "16A10", - "BAMUM LETTER PHASE-F NUAE": "16A18", - "TANGSA LETTER UIC": "16A8D", - "TANGSA LETTER UEQ": "16A96", - "TANGSA LETTER MC": "16A9D", + "BAMUM LETTER PHASE-D NGGEUX": "1693B", + "BAMUM LETTER PHASE-D SHII": "16954", + "BAMUM LETTER PHASE-E NGOQ": "16980", + "BAMUM LETTER PHASE-E SET": "16990", + "BAMUM LETTER PHASE-E NGGUAESHAE NYAM": "16993", + "BAMUM LETTER PHASE-E VEUAE": "1699D", + "BAMUM LETTER PHASE-E PIEEQ": "169B1", + "BAMUM LETTER PHASE-E NGKUM": "169CB", + "BAMUM LETTER PHASE-E NJEE EPOCH": "169E8", + "BAMUM LETTER PHASE-F SHU": "16A1C", + "MRO LETTER BA": "16A44", + "MRO LETTER DA": "16A45", + "MRO LETTER NIN": "16A4F", + "MRO LETTER RO": "16A53", + "TANGSA LETTER AQ": "16A76", + "TANGSA LETTER AWZ": "16A88", + "TANGSA LETTER UEX": "16A97", + "TANGSA LETTER UIUZ": "16A98", + "TANGSA LETTER NGA": "16AA3", + "TANGSA LETTER GHA": "16AB7", "TANGSA DIGIT FIVE": "16AC5", - "BASSA VAH LETTER FA": "16AD3", - "BASSA VAH LETTER DO": "16ADE", - "PAHAWH HMONG VOWEL KOOV": "16B0D", - "PAHAWH HMONG VOWEL KAB": "16B16", - "PAHAWH HMONG CONSONANT NCHAU": "16B28", - "PAHAWH HMONG CONSONANT AU": "16B2D", - "PAHAWH HMONG MARK CIM KES": "16B32", - "PAHAWH HMONG SIGN IB YAM": "16B43", - "PAHAWH HMONG SIGN AV": "16B6C", - "MEDEFAIDRIN CAPITAL LETTER NY": "16E57", - "MEDEFAIDRIN SMALL LETTER KP": "16E66", - "MEDEFAIDRIN DIGIT SIX": "16E86", - "MIAO LETTER VA": "16F08", - "MIAO LETTER LHYA": "16F19", - "MIAO LETTER TLHYA": "16F1C", - "MIAO LETTER DZZA": "16F2B", - "MIAO LETTER HHA": "16F44", - "MIAO LETTER SYI": "16F46", - "MIAO VOWEL SIGN AN": "16F57", - "MIAO VOWEL SIGN IE": "16F66", - "MIAO VOWEL SIGN UAN": "16F6C", - "MIAO VOWEL SIGN N": "16F7D", - "MIAO VOWEL SIGN IONG": "16F86", - "MIAO LETTER TONE-4": "16F95", - "MIAO LETTER TONE-6": "16F97", - "TANGUT COMPONENT-001": "18800", + "BASSA VAH LETTER HWAH": "16ADA", + "BASSA VAH LETTER VU": "16AE3", + "BASSA VAH COMBINING LOW TONE": "16AF1", + "PAHAWH HMONG VOWEL KAUV": "16B05", + "PAHAWH HMONG VOWEL KAIV": "16B0B", + "PAHAWH HMONG VOWEL KAWB": "16B0E", + "PAHAWH HMONG CONSONANT NTHAU": "16B2B", + "PAHAWH HMONG MARK CIM SO": "16B31", + "PAHAWH HMONG DIGIT ZERO": "16B50", + "PAHAWH HMONG CLAN SIGN LIS": "16B7F", + "MEDEFAIDRIN SMALL LETTER S": "16E61", + "MEDEFAIDRIN DIGIT SEVEN": "16E87", + "MIAO LETTER PA": "16F00", + "MIAO LETTER MA": "16F04", + "MIAO LETTER FA": "16F07", + "MIAO LETTER TLHA": "16F1A", + "MIAO LETTER DLHYA": "16F1D", + "MIAO VOWEL SIGN EI": "16F7A", + "MIAO VOWEL SIGN VW": "16F83", + "": "17000", + "TANGUT COMPONENT-017": "18810", + "TANGUT COMPONENT-043": "1882A", + "TANGUT COMPONENT-044": "1882B", + "TANGUT COMPONENT-055": "18836", + "TANGUT COMPONENT-085": "18854", "TANGUT COMPONENT-095": "1885E", - "TANGUT COMPONENT-164": "188A3", - "TANGUT COMPONENT-190": "188BD", - "TANGUT COMPONENT-217": "188D8", - "TANGUT COMPONENT-230": "188E5", - "TANGUT COMPONENT-297": "18928", - "TANGUT COMPONENT-308": "18933", + "TANGUT COMPONENT-098": "18861", + "TANGUT COMPONENT-174": "188AD", + "TANGUT COMPONENT-184": "188B7", + "TANGUT COMPONENT-201": "188C8", + "TANGUT COMPONENT-207": "188CE", + "TANGUT COMPONENT-220": "188DB", + "TANGUT COMPONENT-223": "188DE", + "TANGUT COMPONENT-260": "18903", + "TANGUT COMPONENT-310": "18935", "TANGUT COMPONENT-313": "18938", - "TANGUT COMPONENT-326": "18945", - "TANGUT COMPONENT-337": "18950", - "TANGUT COMPONENT-343": "18956", - "TANGUT COMPONENT-345": "18958", - "TANGUT COMPONENT-372": "18973", - "TANGUT COMPONENT-390": "18985", - "TANGUT COMPONENT-391": "18986", - "TANGUT COMPONENT-440": "189B7", - "TANGUT COMPONENT-441": "189B8", - "TANGUT COMPONENT-548": "18A23", - "TANGUT COMPONENT-551": "18A26", - "TANGUT COMPONENT-565": "18A34", - "TANGUT COMPONENT-571": "18A3A", - "TANGUT COMPONENT-585": "18A48", - "TANGUT COMPONENT-603": "18A5A", - "TANGUT COMPONENT-612": "18A63", - "TANGUT COMPONENT-632": "18A77", - "TANGUT COMPONENT-663": "18A96", - "TANGUT COMPONENT-673": "18AA0", - "TANGUT COMPONENT-691": "18AB2", - "TANGUT COMPONENT-744": "18AE7", - "TANGUT COMPONENT-745": "18AE8", - "TANGUT COMPONENT-747": "18AEA", - "KHITAN SMALL SCRIPT CHARACTER-18B02": "18B02", - "KHITAN SMALL SCRIPT CHARACTER-18B04": "18B04", - "KHITAN SMALL SCRIPT CHARACTER-18B07": "18B07", - "KHITAN SMALL SCRIPT CHARACTER-18B0E": "18B0E", - "KHITAN SMALL SCRIPT CHARACTER-18B20": "18B20", - "KHITAN SMALL SCRIPT CHARACTER-18B48": "18B48", - "KHITAN SMALL SCRIPT CHARACTER-18B4F": "18B4F", - "KHITAN SMALL SCRIPT CHARACTER-18B50": "18B50", - "KHITAN SMALL SCRIPT CHARACTER-18B58": "18B58", - "KHITAN SMALL SCRIPT CHARACTER-18B7B": "18B7B", - "KHITAN SMALL SCRIPT CHARACTER-18B7C": "18B7C", - "KHITAN SMALL SCRIPT CHARACTER-18B8C": "18B8C", - "KHITAN SMALL SCRIPT CHARACTER-18B9D": "18B9D", - "KHITAN SMALL SCRIPT CHARACTER-18BB6": "18BB6", - "KHITAN SMALL SCRIPT CHARACTER-18BD0": "18BD0", - "KHITAN SMALL SCRIPT CHARACTER-18BD5": "18BD5", - "KHITAN SMALL SCRIPT CHARACTER-18BD7": "18BD7", - "KHITAN SMALL SCRIPT CHARACTER-18BE1": "18BE1", - "KHITAN SMALL SCRIPT CHARACTER-18C06": "18C06", - "KHITAN SMALL SCRIPT CHARACTER-18C10": "18C10", - "KHITAN SMALL SCRIPT CHARACTER-18C11": "18C11", - "KHITAN SMALL SCRIPT CHARACTER-18C18": "18C18", - "KHITAN SMALL SCRIPT CHARACTER-18C22": "18C22", - "KHITAN SMALL SCRIPT CHARACTER-18C35": "18C35", - "KHITAN SMALL SCRIPT CHARACTER-18C47": "18C47", - "KHITAN SMALL SCRIPT CHARACTER-18C4C": "18C4C", - "KHITAN SMALL SCRIPT CHARACTER-18C5D": "18C5D", - "KHITAN SMALL SCRIPT CHARACTER-18C68": "18C68", - "KHITAN SMALL SCRIPT CHARACTER-18C78": "18C78", - "KHITAN SMALL SCRIPT CHARACTER-18C7E": "18C7E", - "KHITAN SMALL SCRIPT CHARACTER-18CBE": "18CBE", - "KHITAN SMALL SCRIPT CHARACTER-18CD1": "18CD1", - "KATAKANA LETTER MINNAN NASALIZED TONE-2": "1AFF8", - "HENTAIGANA LETTER A-2": "1B003", - "HENTAIGANA LETTER E-2": "1B00F", - "HENTAIGANA LETTER KA-11": "1B021", - "HENTAIGANA LETTER KU-6": "1B030", - "HENTAIGANA LETTER KE-2": "1B033", - "HENTAIGANA LETTER SU-5": "1B04E", - "HENTAIGANA LETTER NA-1": "1B07E", + "TANGUT COMPONENT-321": "18940", + "TANGUT COMPONENT-340": "18953", + "TANGUT COMPONENT-374": "18975", + "TANGUT COMPONENT-439": "189B6", + "TANGUT COMPONENT-458": "189C9", + "TANGUT COMPONENT-476": "189DB", + "TANGUT COMPONENT-503": "189F6", + "TANGUT COMPONENT-530": "18A11", + "TANGUT COMPONENT-567": "18A36", + "TANGUT COMPONENT-597": "18A54", + "TANGUT COMPONENT-599": "18A56", + "TANGUT COMPONENT-617": "18A68", + "TANGUT COMPONENT-634": "18A79", + "TANGUT COMPONENT-643": "18A82", + "TANGUT COMPONENT-653": "18A8C", + "TANGUT COMPONENT-674": "18AA1", + "TANGUT COMPONENT-746": "18AE9", + "TANGUT COMPONENT-748": "18AEB", + "TANGUT COMPONENT-755": "18AF2", + "TANGUT COMPONENT-756": "18AF3", + "TANGUT COMPONENT-759": "18AF6", + "TANGUT COMPONENT-760": "18AF7", + "TANGUT COMPONENT-766": "18AFD", + "KHITAN SMALL SCRIPT CHARACTER-18B15": "18B15", + "KHITAN SMALL SCRIPT CHARACTER-18B18": "18B18", + "KHITAN SMALL SCRIPT CHARACTER-18B4D": "18B4D", + "KHITAN SMALL SCRIPT CHARACTER-18B5A": "18B5A", + "KHITAN SMALL SCRIPT CHARACTER-18B6C": "18B6C", + "KHITAN SMALL SCRIPT CHARACTER-18B6D": "18B6D", + "KHITAN SMALL SCRIPT CHARACTER-18B78": "18B78", + "KHITAN SMALL SCRIPT CHARACTER-18B7A": "18B7A", + "KHITAN SMALL SCRIPT CHARACTER-18BB1": "18BB1", + "KHITAN SMALL SCRIPT CHARACTER-18BCF": "18BCF", + "KHITAN SMALL SCRIPT CHARACTER-18BE7": "18BE7", + "KHITAN SMALL SCRIPT CHARACTER-18C02": "18C02", + "KHITAN SMALL SCRIPT CHARACTER-18C25": "18C25", + "KHITAN SMALL SCRIPT CHARACTER-18C34": "18C34", + "KHITAN SMALL SCRIPT CHARACTER-18C45": "18C45", + "KHITAN SMALL SCRIPT CHARACTER-18C67": "18C67", + "KHITAN SMALL SCRIPT CHARACTER-18C94": "18C94", + "KHITAN SMALL SCRIPT CHARACTER-18CBA": "18CBA", + "KHITAN SMALL SCRIPT CHARACTER-18CCA": "18CCA", + "KHITAN SMALL SCRIPT CHARACTER-18CCD": "18CCD", + "HENTAIGANA LETTER U-2": "1B00B", + "HENTAIGANA LETTER SO-5": "1B05B", + "HENTAIGANA LETTER SO-7": "1B05D", + "HENTAIGANA LETTER TI-6": "1B067", + "HENTAIGANA LETTER NA-6": "1B083", "HENTAIGANA LETTER HA-1": "1B09E", - "HENTAIGANA LETTER MA-1": "1B0C2", - "HENTAIGANA LETTER ME-2": "1B0D5", - "HENTAIGANA LETTER YU-3": "1B0E5", - "HENTAIGANA LETTER RI-2": "1B0F2", + "HENTAIGANA LETTER HA-4": "1B0A1", + "HENTAIGANA LETTER HA-11": "1B0A8", + "HENTAIGANA LETTER HE-5": "1B0B7", + "HENTAIGANA LETTER ME-1": "1B0D4", "HENTAIGANA LETTER RU-5": "1B0FC", - "HENTAIGANA LETTER WA-3": "1B10A", - "NUSHU CHARACTER-1B17D": "1B17D", - "NUSHU CHARACTER-1B17F": "1B17F", - "NUSHU CHARACTER-1B191": "1B191", - "NUSHU CHARACTER-1B1B4": "1B1B4", - "NUSHU CHARACTER-1B1BC": "1B1BC", + "HENTAIGANA LETTER RO-2": "1B103", + "HENTAIGANA LETTER RO-4": "1B105", + "HENTAIGANA LETTER WI-5": "1B111", + "HENTAIGANA LETTER WE-1": "1B112", + "KATAKANA LETTER SMALL KO": "1B155", + "NUSHU CHARACTER-1B174": "1B174", + "NUSHU CHARACTER-1B176": "1B176", + "NUSHU CHARACTER-1B17C": "1B17C", + "NUSHU CHARACTER-1B183": "1B183", + "NUSHU CHARACTER-1B1A9": "1B1A9", "NUSHU CHARACTER-1B1C7": "1B1C7", - "NUSHU CHARACTER-1B1D4": "1B1D4", - "NUSHU CHARACTER-1B1F1": "1B1F1", - "NUSHU CHARACTER-1B204": "1B204", - "NUSHU CHARACTER-1B214": "1B214", - "NUSHU CHARACTER-1B251": "1B251", - "NUSHU CHARACTER-1B256": "1B256", - "NUSHU CHARACTER-1B257": "1B257", - "NUSHU CHARACTER-1B25B": "1B25B", - "NUSHU CHARACTER-1B269": "1B269", - "NUSHU CHARACTER-1B28D": "1B28D", - "NUSHU CHARACTER-1B2A5": "1B2A5", - "NUSHU CHARACTER-1B2C4": "1B2C4", - "NUSHU CHARACTER-1B2E0": "1B2E0", - "NUSHU CHARACTER-1B2E4": "1B2E4", - "NUSHU CHARACTER-1B2E8": "1B2E8", - "NUSHU CHARACTER-1B2EB": "1B2EB", - "DUPLOYAN LETTER S WITH DOT": "1BC25", - "DUPLOYAN LETTER J N": "1BC30", - "DUPLOYAN LETTER J N S": "1BC31", - "DUPLOYAN LETTER S N": "1BC3B", - "DUPLOYAN LETTER LONG I": "1BC4F", - "DUPLOYAN LETTER OOH": "1BC59", - "DUPLOYAN LETTER WOW": "1BC60", - "DUPLOYAN AFFIX LOW DOT": "1BC94", - "DUPLOYAN AFFIX LOW LINE": "1BC96", + "NUSHU CHARACTER-1B1D6": "1B1D6", + "NUSHU CHARACTER-1B1E0": "1B1E0", + "NUSHU CHARACTER-1B23E": "1B23E", + "NUSHU CHARACTER-1B245": "1B245", + "NUSHU CHARACTER-1B25D": "1B25D", + "NUSHU CHARACTER-1B26A": "1B26A", + "NUSHU CHARACTER-1B286": "1B286", + "NUSHU CHARACTER-1B287": "1B287", + "NUSHU CHARACTER-1B28A": "1B28A", + "NUSHU CHARACTER-1B2A3": "1B2A3", + "NUSHU CHARACTER-1B2CE": "1B2CE", + "NUSHU CHARACTER-1B2DC": "1B2DC", + "NUSHU CHARACTER-1B2EA": "1B2EA", + "DUPLOYAN LETTER DH": "1BC13", + "DUPLOYAN LETTER N WITH DOT": "1BC22", + "DUPLOYAN LETTER N M S": "1BC2C", + "DUPLOYAN LETTER G R S": "1BC3E", + "DUPLOYAN LETTER PERNIN AN": "1BC65", + "DUPLOYAN AFFIX HIGH ACUTE": "1BC80", + "DUPLOYAN AFFIX HIGH WAVE": "1BC87", + "DUPLOYAN AFFIX LOW GRAVE": "1BC92", + "DUPLOYAN AFFIX LOW LONG GRAVE": "1BC93", "ZNAMENNY COMBINING MARK NIZKO S KRYZHEM ON LEFT": "1CF01", - "ZNAMENNY COMBINING MARK TSATA ON RIGHT": "1CF0E", - "ZNAMENNY COMBINING MARK RAVNO": "1CF22", - "ZNAMENNY COMBINING MARK KACHKA": "1CF29", - "ZNAMENNY PRIZNAK MODIFIER KRYZH": "1CF45", - "ZNAMENNY NEUME STOPITSA": "1CF56", - "ZNAMENNY NEUME VRAKHIYA SVETLAYA": "1CF65", - "ZNAMENNY NEUME VRAKHIYA TRESVETLAYA": "1CF66", + "ZNAMENNY NEUME SLOZHITIE S KRYZHEM": "1CF80", + "ZNAMENNY NEUME STATYA": "1CF86", + "ZNAMENNY NEUME STATYA S ZAPYATOY I PODCHASHIEM": "1CF8F", "ZNAMENNY NEUME STRELA PROSTAYA": "1CF92", - "ZNAMENNY NEUME STRELA GROMNAYA": "1CFA2", - "ZNAMENNY NEUME MECHIK POVODNY": "1CFA8", - "ZNAMENNY NEUME OSOKA SVETLAYA": "1CFB0", - "ZNAMENNY NEUME STRELA KRYUKOVAYA GROMOPOVODNAYA WITH SINGLE ZAPYATAYA": "1CFB8", - "ZNAMENNY NEUME STRELA KRYUKOVAYA TRYASKA": "1CFBE", - "BYZANTINE MUSICAL SYMBOL DASEIA": "1D001", - "BYZANTINE MUSICAL SYMBOL ANATRICHISMA": "1D028", - "BYZANTINE MUSICAL SYMBOL FTHORA ARCHAION": "1D034", + "ZNAMENNY NEUME OSOKA": "1CFAF", + "ZNAMENNY NEUME STRELA KRYUKOVAYA GROMOKRYZHEVAYA POVODNAYA": "1CFBD", + "BYZANTINE MUSICAL SYMBOL SYNAGMA ARCHAION": "1D02A", + "BYZANTINE MUSICAL SYMBOL OYRANISMA ARCHAION": "1D02C", + "BYZANTINE MUSICAL SYMBOL KRATIMATA": "1D032", + "BYZANTINE MUSICAL SYMBOL PETASMA": "1D041", + "BYZANTINE MUSICAL SYMBOL OLIGON NEO": "1D047", + "BYZANTINE MUSICAL SYMBOL PSIFISTON NEO": "1D05A", + "BYZANTINE MUSICAL SYMBOL PSIFISTOPARAKALESMA": "1D06F", + "BYZANTINE MUSICAL SYMBOL AGOGI METRIA": "1D09D", + "BYZANTINE MUSICAL SYMBOL MARTYRIA PROTOS ICHOS": "1D0A2", + "BYZANTINE MUSICAL SYMBOL MARTYRIA TETARTOS ICHOS": "1D0A8", + "BYZANTINE MUSICAL SYMBOL MARTYRIA TETARTOS LEGETOS ICHOS": "1D0A9", + "BYZANTINE MUSICAL SYMBOL APOSTROFOI TELOUS ICHIMATOS": "1D0AD", "BYZANTINE MUSICAL SYMBOL MARTYRIA PROTOVARYS ICHOS": "1D0B2", - "BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI KE": "1D0BF", - "BYZANTINE MUSICAL SYMBOL FTHORA SKLIRON CHROMA SYNAFI": "1D0C6", - "BYZANTINE MUSICAL SYMBOL KLASMA KATO": "1D0F4", - "MUSICAL SYMBOL SHORT BARLINE": "1D105", - "MUSICAL SYMBOL END BEAM": "1D174", - "MUSICAL SYMBOL COMBINING STACCATISSIMO": "1D17E", - "MUSICAL SYMBOL COMBINING ACCENT-STACCATO": "1D181", - "MUSICAL SYMBOL SUBITO": "1D18D", - "MUSICAL SYMBOL COMBINING SNAP PIZZICATO": "1D1AD", - "MUSICAL SYMBOL SEMIBREVIS BLACK": "1D1BA", - "MUSICAL SYMBOL SCANDICUS FLEXUS": "1D1DB", - "MUSICAL SYMBOL TORCULUS RESUPINUS": "1D1DC", - "GREEK VOCAL NOTATION SYMBOL-2": "1D201", - "GREEK VOCAL NOTATION SYMBOL-17": "1D210", - "GREEK INSTRUMENTAL NOTATION SYMBOL-24": "1D22B", - "GREEK INSTRUMENTAL NOTATION SYMBOL-27": "1D22E", - "GREEK MUSICAL LEIMMA": "1D245", - "MAYAN NUMERAL ONE": "1D2E1", - "MAYAN NUMERAL THIRTEEN": "1D2ED", - "TETRAGRAM FOR BARRIER": "1D309", - "TETRAGRAM FOR CONTRARIETY": "1D30B", - "TETRAGRAM FOR GATHERING": "1D328", - "TETRAGRAM FOR SEVERANCE": "1D34B", - "MATHEMATICAL BOLD SMALL N": "1D427", - "MATHEMATICAL BOLD SMALL Y": "1D432", - "MATHEMATICAL ITALIC CAPITAL O": "1D442", - "MATHEMATICAL ITALIC SMALL S": "1D460", + "BYZANTINE MUSICAL SYMBOL IMIFTHORON": "1D0B8", + "MUSICAL SYMBOL G CLEF OTTAVA BASSA": "1D120", + "MUSICAL SYMBOL TRIANGLE NOTEHEAD UP WHITE": "1D148", + "MUSICAL SYMBOL ORNAMENT STROKE-7": "1D1A1", + "MUSICAL SYMBOL DAMP ALL": "1D1B5", + "MUSICAL SYMBOL TEMPUS PERFECTUM CUM PROLATIONE PERFECTA": "1D1C7", + "MUSICAL SYMBOL TORCULUS": "1D1D8", + "GREEK VOCAL NOTATION SYMBOL-3": "1D202", + "GREEK VOCAL NOTATION SYMBOL-10": "1D209", + "GREEK VOCAL NOTATION SYMBOL-11": "1D20A", + "GREEK INSTRUMENTAL NOTATION SYMBOL-18": "1D228", + "GREEK INSTRUMENTAL NOTATION SYMBOL-49": "1D23C", + "MAYAN NUMERAL FIVE": "1D2E5", + "MAYAN NUMERAL FIFTEEN": "1D2EF", + "MONOGRAM FOR EARTH": "1D300", + "TETRAGRAM FOR RELEASE": "1D31A", + "TETRAGRAM FOR ENCOUNTERS": "1D330", + "TETRAGRAM FOR VASTNESS OR WASTING": "1D337", + "TETRAGRAM FOR MEASURE": "1D339", + "COUNTING ROD TENS DIGIT FOUR": "1D36C", + "COUNTING ROD TENS DIGIT EIGHT": "1D370", + "MATHEMATICAL BOLD SMALL G": "1D420", + "MATHEMATICAL ITALIC CAPITAL S": "1D446", + "MATHEMATICAL ITALIC CAPITAL T": "1D447", + "MATHEMATICAL ITALIC SMALL C": "1D450", + "MATHEMATICAL ITALIC SMALL E": "1D452", + "MATHEMATICAL ITALIC SMALL T": "1D461", "MATHEMATICAL ITALIC SMALL V": "1D463", "MATHEMATICAL BOLD ITALIC CAPITAL B": "1D469", - "MATHEMATICAL BOLD ITALIC SMALL H": "1D489", - "MATHEMATICAL SCRIPT CAPITAL D": "1D49F", - "MATHEMATICAL SCRIPT CAPITAL T": "1D4AF", - "MATHEMATICAL BOLD SCRIPT CAPITAL A": "1D4D0", - "MATHEMATICAL BOLD SCRIPT CAPITAL N": "1D4DD", - "MATHEMATICAL BOLD SCRIPT SMALL K": "1D4F4", - "MATHEMATICAL FRAKTUR SMALL U": "1D532", - "MATHEMATICAL FRAKTUR SMALL X": "1D535", - "MATHEMATICAL DOUBLE-STRUCK SMALL G": "1D558", - "MATHEMATICAL BOLD FRAKTUR CAPITAL S": "1D57E", - "MATHEMATICAL SANS-SERIF CAPITAL X": "1D5B7", - "MATHEMATICAL SANS-SERIF CAPITAL Y": "1D5B8", - "MATHEMATICAL SANS-SERIF SMALL Q": "1D5CA", - "MATHEMATICAL SANS-SERIF BOLD CAPITAL D": "1D5D7", - "MATHEMATICAL SANS-SERIF BOLD CAPITAL Z": "1D5ED", - "MATHEMATICAL SANS-SERIF BOLD SMALL T": "1D601", - "MATHEMATICAL SANS-SERIF ITALIC CAPITAL I": "1D610", - "MATHEMATICAL SANS-SERIF ITALIC CAPITAL P": "1D617", - "MATHEMATICAL SANS-SERIF ITALIC SMALL A": "1D622", - "MATHEMATICAL SANS-SERIF ITALIC SMALL G": "1D628", - "MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL E": "1D640", - "MATHEMATICAL MONOSPACE CAPITAL Y": "1D688", - "MATHEMATICAL MONOSPACE SMALL E": "1D68E", - "MATHEMATICAL MONOSPACE SMALL T": "1D69D", - "MATHEMATICAL BOLD SMALL OMEGA": "1D6DA", - "MATHEMATICAL ITALIC SMALL ZETA": "1D701", - "MATHEMATICAL BOLD ITALIC CAPITAL IOTA": "1D724", - "MATHEMATICAL SANS-SERIF BOLD SMALL LAMDA": "1D77A", - "MATHEMATICAL SANS-SERIF BOLD SMALL XI": "1D77D", - "MATHEMATICAL SANS-SERIF BOLD SMALL RHO": "1D780", - "MATHEMATICAL SANS-SERIF BOLD SMALL PHI": "1D785", - "MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL IOTA": "1D798", + "MATHEMATICAL BOLD ITALIC CAPITAL I": "1D470", + "MATHEMATICAL BOLD ITALIC SMALL G": "1D488", + "MATHEMATICAL BOLD ITALIC SMALL L": "1D48D", + "MATHEMATICAL BOLD ITALIC SMALL R": "1D493", + "MATHEMATICAL BOLD ITALIC SMALL T": "1D495", + "MATHEMATICAL SCRIPT SMALL B": "1D4B7", + "MATHEMATICAL BOLD SCRIPT CAPITAL B": "1D4D1", + "MATHEMATICAL BOLD SCRIPT CAPITAL D": "1D4D3", + "MATHEMATICAL BOLD SCRIPT CAPITAL O": "1D4DE", + "MATHEMATICAL BOLD SCRIPT CAPITAL Z": "1D4E9", + "MATHEMATICAL BOLD SCRIPT SMALL V": "1D4FF", + "MATHEMATICAL FRAKTUR CAPITAL Y": "1D51C", + "MATHEMATICAL FRAKTUR SMALL J": "1D527", + "MATHEMATICAL FRAKTUR SMALL V": "1D533", + "MATHEMATICAL DOUBLE-STRUCK SMALL D": "1D555", + "MATHEMATICAL DOUBLE-STRUCK SMALL L": "1D55D", + "MATHEMATICAL DOUBLE-STRUCK SMALL N": "1D55F", + "MATHEMATICAL BOLD FRAKTUR SMALL F": "1D58B", + "MATHEMATICAL BOLD FRAKTUR SMALL G": "1D58C", + "MATHEMATICAL SANS-SERIF CAPITAL T": "1D5B3", + "MATHEMATICAL SANS-SERIF BOLD CAPITAL A": "1D5D4", + "MATHEMATICAL SANS-SERIF BOLD CAPITAL T": "1D5E7", + "MATHEMATICAL SANS-SERIF BOLD SMALL G": "1D5F4", + "MATHEMATICAL SANS-SERIF BOLD SMALL P": "1D5FD", + "MATHEMATICAL SANS-SERIF ITALIC SMALL I": "1D62A", + "MATHEMATICAL SANS-SERIF ITALIC SMALL N": "1D62F", + "MATHEMATICAL SANS-SERIF ITALIC SMALL S": "1D634", + "MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL D": "1D63F", + "MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL J": "1D645", + "MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL K": "1D646", + "MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL C": "1D658", + "MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL G": "1D65C", + "MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL R": "1D667", + "MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL U": "1D66A", + "MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL X": "1D66D", + "MATHEMATICAL MONOSPACE CAPITAL V": "1D685", + "MATHEMATICAL MONOSPACE CAPITAL W": "1D686", + "MATHEMATICAL MONOSPACE SMALL I": "1D692", + "MATHEMATICAL MONOSPACE SMALL J": "1D693", + "MATHEMATICAL MONOSPACE SMALL K": "1D694", + "MATHEMATICAL BOLD CAPITAL SIGMA": "1D6BA", + "MATHEMATICAL BOLD SMALL ALPHA": "1D6C2", + "MATHEMATICAL BOLD SMALL PI": "1D6D1", + "MATHEMATICAL BOLD PI SYMBOL": "1D6E1", + "MATHEMATICAL ITALIC CAPITAL KAPPA": "1D6EB", + "MATHEMATICAL ITALIC CAPITAL LAMDA": "1D6EC", + "MATHEMATICAL ITALIC CAPITAL NU": "1D6EE", + "MATHEMATICAL ITALIC SMALL NU": "1D708", + "MATHEMATICAL ITALIC KAPPA SYMBOL": "1D718", + "MATHEMATICAL BOLD ITALIC CAPITAL NU": "1D728", + "MATHEMATICAL BOLD ITALIC CAPITAL XI": "1D729", + "MATHEMATICAL SANS-SERIF BOLD CAPITAL LAMDA": "1D760", + "MATHEMATICAL SANS-SERIF BOLD SMALL PI": "1D77F", + "MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL DELTA": "1D793", "MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL KAPPA": "1D799", - "MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ETA": "1D7B0", - "MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL FINAL SIGMA": "1D7BB", - "MATHEMATICAL BOLD DIGIT SEVEN": "1D7D5", - "MATHEMATICAL BOLD DIGIT EIGHT": "1D7D6", - "MATHEMATICAL SANS-SERIF BOLD DIGIT EIGHT": "1D7F4", - "SIGNWRITING HAND-FIST INDEX UP MIDDLE HINGED": "1D813", - "SIGNWRITING HAND-CIRCLE INDEX MIDDLE CROSSED": "1D81B", - "SIGNWRITING HAND-FIST INDEX THUMB HOOKED MIDDLE UP": "1D831", - "SIGNWRITING HAND-FIST INDEX MIDDLE CONJOINED CUPPED THUMB FORWARD": "1D835", - "SIGNWRITING HAND-FIST MIDDLE THUMB ANGLED OUT INDEX UP": "1D840", - "SIGNWRITING HAND-FIST MIDDLE THUMB ANGLED OUT INDEX CROSSED": "1D841", - "SIGNWRITING HAND-FLAT": "1D85A", - "SIGNWRITING HAND-FLAT HEEL THUMB SIDE": "1D85E", - "SIGNWRITING HAND-FLAT THUMB BENT": "1D85F", - "SIGNWRITING HAND-FLAT SPLIT CENTRE THUMB SIDE BENT": "1D864", - "SIGNWRITING HAND-OVAL": "1D877", - "SIGNWRITING HAND-FIST LITTLE THUMB": "1D89A", - "SIGNWRITING HAND-CIRCLE MIDDLE RING LITTLE": "1D8CE", - "SIGNWRITING HAND-CURLICUE MIDDLE RING LITTLE ON": "1D8CF", - "SIGNWRITING HAND-HINGE MIDDLE RING LITTLE": "1D8D1", - "SIGNWRITING HAND-HINGE INDEX HINGED": "1D8DB", - "SIGNWRITING HAND-FIST INDEX THUMB SIDE INDEX HINGE": "1D8E3", + "MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMICRON": "1D7B8", + "MATHEMATICAL SANS-SERIF BOLD ITALIC THETA SYMBOL": "1D7C5", + "MATHEMATICAL BOLD DIGIT ONE": "1D7CF", + "MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO": "1D7D8", + "MATHEMATICAL SANS-SERIF DIGIT FOUR": "1D7E6", + "MATHEMATICAL SANS-SERIF DIGIT EIGHT": "1D7EA", + "MATHEMATICAL SANS-SERIF DIGIT NINE": "1D7EB", + "MATHEMATICAL SANS-SERIF BOLD DIGIT SIX": "1D7F2", + "SIGNWRITING HAND-FIST INDEX MIDDLE CONJOINED THUMB SIDE CONJOINED": "1D82E", + "SIGNWRITING HAND-FIST INDEX MIDDLE CROSSED THUMB SIDE": "1D833", + "SIGNWRITING HAND-FLAT HEEL FIVE FINGERS SPREAD BENT": "1D851", + "SIGNWRITING HAND-FLAT THUMB SIDE": "1D85D", + "SIGNWRITING HAND-CLAW": "1D866", + "SIGNWRITING HAND-CUP OPEN THUMB FORWARD": "1D872", + "SIGNWRITING HAND-HINGE SMALL": "1D87E", + "SIGNWRITING HAND-FIST LITTLE UP": "1D892", + "SIGNWRITING HAND-CIRCLE LITTLE INDEX": "1D8A1", + "SIGNWRITING HAND-ANGLE MIDDLE RING LITTLE OUT": "1D8D2", + "SIGNWRITING HAND-ANGLE INDEX THUMB IN": "1D8F3", "SIGNWRITING BRUSH MULTIPLE": "1D90F", - "SIGNWRITING MOVEMENT-HINGE DOWN SEQUENTIAL": "1D924", - "SIGNWRITING MOVEMENT-WALLPLANE CROSS": "1D933", - "SIGNWRITING MOVEMENT-WALLPLANE CORNER SMALL": "1D93B", - "SIGNWRITING MOVEMENT-DIAGONAL TOWARDS MEDIUM": "1D95A", - "SIGNWRITING MOVEMENT-FLOORPLANE ZIGZAG MEDIUM": "1D97C", - "SIGNWRITING MOVEMENT-FLOORPLANE PEAKS MEDIUM": "1D97F", - "SIGNWRITING TRAVEL-FLOORPLANE ROTATION-FLOORPLANE SINGLE": "1D981", - "SIGNWRITING MOVEMENT-WALLPLANE CURVE QUARTER LARGEST": "1D98B", - "SIGNWRITING MOVEMENT-WALLPLANE CURVE HALF-CIRCLE SMALL": "1D98C", - "SIGNWRITING MOVEMENT-WALLPLANE CURVE THREE-QUARTER CIRCLE MEDIUM": "1D991", - "SIGNWRITING MOVEMENT-FLOORPLANE LOOP HITTING CEILING LARGE SINGLE": "1D9BE", - "SIGNWRITING MOVEMENT-FLOORPLANE HUMP HITTING FLOOR TRIPLE SMALL TRIPLE": "1D9CA", - "SIGNWRITING MOVEMENT-FLOORPLANE LOOP HITTING FLOOR SMALL DOUBLE": "1D9CE", - "SIGNWRITING MOVEMENT-WALLPLANE WRIST CIRCLE FRONT DOUBLE": "1D9EE", - "SIGNWRITING DYNAMIC EVERY OTHER TIME": "1D9FD", - "SIGNWRITING EYEGAZE-WALLPLANE CIRCLING": "1DA29", - "SIGNWRITING BREATH INHALE": "1DA39", - "SIGNWRITING FILL MODIFIER-2": "1DA9B", - "SIGNWRITING ROTATION MODIFIER-11": "1DAAA", - "LATIN SMALL LETTER C WITH RETROFLEX HOOK": "1DF1D", - "COMBINING GLAGOLITIC LETTER GLAGOLI": "1E003", - "CYRILLIC SUBSCRIPT SMALL LETTER HARD SIGN": "1E065", - "NYIAKENG PUACHUE HMONG LETTER MA": "1E100", - "NYIAKENG PUACHUE HMONG LETTER PA": "1E11A", - "TOTO LETTER BA": "1E291", - "TOTO LETTER JA": "1E29D", - "TOTO LETTER E": "1E2A6", - "WANCHO LETTER NYA": "1E2E9", - "NAG MUNDARI LETTER ONG": "1E4D4", - "NAG MUNDARI DIGIT EIGHT": "1E4F8", - "MENDE KIKAKUI SYLLABLE M004 WI": "1E808", - "MENDE KIKAKUI SYLLABLE M059 MEN": "1E817", - "MENDE KIKAKUI SYLLABLE M013 I": "1E822", - "MENDE KIKAKUI SYLLABLE M089 DEE": "1E841", - "MENDE KIKAKUI SYLLABLE M063 JO": "1E851", - "MENDE KIKAKUI SYLLABLE M039 NUN": "1E865", - "MENDE KIKAKUI SYLLABLE M040 HEE": "1E86B", - "MENDE KIKAKUI SYLLABLE M111 GA": "1E884", - "MENDE KIKAKUI SYLLABLE M145 MBI": "1E893", - "MENDE KIKAKUI SYLLABLE M056 GBA": "1E8A7", - "MENDE KIKAKUI SYLLABLE M107 GBE": "1E8AA", - "ADLAM CAPITAL LETTER KPO": "1E920", - "ADLAM SMALL LETTER PE": "1E928", - "ADLAM SMALL LETTER QAAF": "1E939", - "ADLAM DIGIT SEVEN": "1E957", - "INDIC SIYAQ NUMBER FORTY": "1EC7D", - "INDIC SIYAQ NUMBER SEVENTY": "1EC80", - "INDIC SIYAQ NUMBER SEVEN HUNDRED": "1EC89", - "INDIC SIYAQ NUMBER SIX THOUSAND": "1EC91", - "INDIC SIYAQ NUMBER KAROR": "1ECA1", - "OTTOMAN SIYAQ NUMBER TWO": "1ED02", - "OTTOMAN SIYAQ NUMBER ONE THOUSAND": "1ED1C", - "ARABIC MATHEMATICAL JEEM": "1EE02", - "ARABIC MATHEMATICAL YEH": "1EE09", - "ARABIC MATHEMATICAL KAF": "1EE0A", - "ARABIC MATHEMATICAL AIN": "1EE0F", - "ARABIC MATHEMATICAL TAILED DOTLESS NOON": "1EE5D", + "SIGNWRITING BRUSH BETWEEN": "1D910", + "SIGNWRITING SURFACE SYMBOLS": "1D914", + "SIGNWRITING MOVEMENT-WALLPLANE SINGLE STRAIGHT MEDIUM": "1D92B", + "SIGNWRITING MOVEMENT-WALLPLANE DOUBLE WRIST FLEX": "1D930", + "SIGNWRITING TRAVEL-WALLPLANE SHAKING": "1D951", + "SIGNWRITING MOVEMENT-DIAGONAL BETWEEN TOWARDS LARGEST": "1D964", + "SIGNWRITING MOVEMENT-FLOORPLANE DOUBLE ALTERNATING": "1D96C", + "SIGNWRITING MOVEMENT-WALLPLANE LOOP SMALL": "1D995", + "SIGNWRITING MOVEMENT-WALLPLANE LOOP LARGE": "1D997", + "SIGNWRITING ROTATION-WALLPLANE SINGLE HITTING CHEST": "1D9B1", + "SIGNWRITING MOVEMENT-WALLPLANE WAVE DIAGONAL PATH SMALL": "1D9B4", + "SIGNWRITING MOVEMENT-WALLPLANE ARM CIRCLE SMALL DOUBLE": "1D9E5", + "SIGNWRITING MOVEMENT-FLOORPLANE WRIST CIRCLE HITTING WALL SINGLE": "1D9EF", + "SIGNWRITING DYNAMIC SIMULTANEOUS": "1D9FB", + "SIGNWRITING HEAD MOVEMENT-WALLPLANE STRAIGHT": "1DA01", + "SIGNWRITING EYES HALF OPEN": "1DA19", + "SIGNWRITING MOUTH CLOSED CONTACT": "1DA3D", + "SIGNWRITING MOUTH SMILE WRINKLED": "1DA3F", + "SIGNWRITING MOUTH KISS FORWARD": "1DA4E", + "SIGNWRITING UPPER BODY TILTING FROM HIP JOINTS": "1DA75", + "SIGNWRITING ROTATION MODIFIER-6": "1DAA5", + "SIGNWRITING ROTATION MODIFIER-10": "1DAA9", + "LATIN SMALL LETTER TURNED R WITH LONG LEG AND RETROFLEX HOOK": "1DF08", + "LATIN LETTER STRETCHED C WITH CURL": "1DF0F", + "LATIN LETTER SMALL CAPITAL TURNED K": "1DF10", + "COMBINING GLAGOLITIC LETTER ZHIVETE": "1E006", + "COMBINING GLAGOLITIC LETTER ONU": "1E011", + "MODIFIER LETTER CYRILLIC SMALL DE": "1E034", + "MODIFIER LETTER CYRILLIC SMALL I": "1E038", + "MODIFIER LETTER CYRILLIC SMALL TE": "1E040", + "TOTO LETTER PA": "1E290", + "TOTO LETTER AE": "1E2AB", + "WANCHO LETTER AA": "1E2C0", + "WANCHO LETTER LA": "1E2C8", + "WANCHO LETTER THA": "1E2CC", + "WANCHO DIGIT TWO": "1E2F2", + "WANCHO DIGIT THREE": "1E2F3", + "WANCHO DIGIT FIVE": "1E2F5", + "ETHIOPIC SYLLABLE GURAGE QWEE": "1E7F1", + "ETHIOPIC SYLLABLE GURAGE KWI": "1E7F5", + "ETHIOPIC SYLLABLE GURAGE FWI": "1E7FB", + "ETHIOPIC SYLLABLE GURAGE FWEE": "1E7FC", + "MENDE KIKAKUI SYLLABLE M005 WA": "1E809", + "MENDE KIKAKUI SYLLABLE M010 BI": "1E81B", + "MENDE KIKAKUI SYLLABLE M011 BA": "1E81C", + "MENDE KIKAKUI SYLLABLE M150 BEE": "1E81E", + "MENDE KIKAKUI SYLLABLE M137 EI": "1E829", + "MENDE KIKAKUI SYLLABLE M052 HEN": "1E874", + "MENDE KIKAKUI SYLLABLE M123 NDI": "1E8AE", + "MENDE KIKAKUI SYLLABLE M125 NDU": "1E8B0", + "MENDE KIKAKUI SYLLABLE M191 NDEE": "1E8B1", + "MENDE KIKAKUI COMBINING NUMBER TENS": "1E8D1", + "ADLAM CAPITAL LETTER SINNYIIYHE": "1E905", + "ADLAM CAPITAL LETTER BHE": "1E907", + "ADLAM CAPITAL LETTER CHI": "1E915", + "ADLAM SMALL LETTER I": "1E92D", + "ADLAM SMALL LETTER GBE": "1E940", + "INDIC SIYAQ NUMBER ONE": "1EC71", + "INDIC SIYAQ NUMBER SIXTY": "1EC7F", + "INDIC SIYAQ NUMBER THREE HUNDRED": "1EC85", + "INDIC SIYAQ NUMBER FIVE HUNDRED": "1EC87", + "INDIC SIYAQ NUMBER NINE THOUSAND": "1EC94", + "INDIC SIYAQ NUMBER PREFIXED TWO": "1ECA4", + "INDIC SIYAQ NUMBER PREFIXED FIVE": "1ECA7", + "OTTOMAN SIYAQ NUMBER FIVE": "1ED05", + "OTTOMAN SIYAQ NUMBER NINE": "1ED09", + "ARABIC MATHEMATICAL QAF": "1EE12", + "ARABIC MATHEMATICAL THEH": "1EE16", + "ARABIC MATHEMATICAL INITIAL HEH": "1EE24", + "ARABIC MATHEMATICAL INITIAL THEH": "1EE36", + "ARABIC MATHEMATICAL STRETCHED AIN": "1EE6F", "ARABIC MATHEMATICAL STRETCHED QAF": "1EE72", - "ARABIC MATHEMATICAL STRETCHED THEH": "1EE76", - "ARABIC MATHEMATICAL LOOPED ALEF": "1EE80", - "ARABIC MATHEMATICAL LOOPED ZAIN": "1EE86", - "ARABIC MATHEMATICAL LOOPED THEH": "1EE96", - "ARABIC MATHEMATICAL DOUBLE-STRUCK HAH": "1EEA7", - "ARABIC MATHEMATICAL DOUBLE-STRUCK SHEEN": "1EEB4", - "MAHJONG TILE GREEN DRAGON": "1F005", - "MAHJONG TILE WHITE DRAGON": "1F006", - "DOMINO TILE HORIZONTAL-05-05": "1F059", - "DOMINO TILE HORIZONTAL-06-00": "1F05B", - "DOMINO TILE VERTICAL-02-03": "1F074", - "DOMINO TILE VERTICAL-05-02": "1F088", - "PLAYING CARD SEVEN OF DIAMONDS": "1F0C7", + "ARABIC MATHEMATICAL STRETCHED ZAH": "1EE7A", + "ARABIC MATHEMATICAL LOOPED QAF": "1EE92", + "MAHJONG TILE SOUTH WIND": "1F001", + "MAHJONG TILE ONE OF BAMBOOS": "1F010", + "MAHJONG TILE TWO OF BAMBOOS": "1F011", + "MAHJONG TILE NINE OF BAMBOOS": "1F018", + "MAHJONG TILE WINTER": "1F029", + "DOMINO TILE HORIZONTAL-02-05": "1F044", + "DOMINO TILE VERTICAL-02-05": "1F076", + "DOMINO TILE VERTICAL-02-06": "1F077", + "PLAYING CARD FOUR OF SPADES": "1F0A4", + "PLAYING CARD SEVEN OF SPADES": "1F0A7", + "PLAYING CARD FIVE OF HEARTS": "1F0B5", + "PLAYING CARD KNIGHT OF HEARTS": "1F0BC", + "PLAYING CARD KING OF HEARTS": "1F0BE", + "PLAYING CARD TWO OF CLUBS": "1F0D2", "PLAYING CARD THREE OF CLUBS": "1F0D3", - "PLAYING CARD TRUMP-9": "1F0E9", - "SQUARED LATIN CAPITAL LETTER I": "1F138", - "SQUARED LATIN CAPITAL LETTER X": "1F147", - "NEGATIVE CIRCLED LATIN CAPITAL LETTER K": "1F15A", - "SQUARED VOD": "1F1AC", - "REGIONAL INDICATOR SYMBOL LETTER B": "1F1E7", - "REGIONAL INDICATOR SYMBOL LETTER M": "1F1F2", - "REGIONAL INDICATOR SYMBOL LETTER Y": "1F1FE", - "SQUARED CJK UNIFIED IDEOGRAPH-7121": "1F21A", - "SQUARED CJK UNIFIED IDEOGRAPH-518D": "1F21E", + "PLAYING CARD EIGHT OF CLUBS": "1F0D8", + "PARENTHESIZED LATIN CAPITAL LETTER W": "1F126", + "PARENTHESIZED LATIN CAPITAL LETTER X": "1F127", + "CIRCLED ITALIC LATIN CAPITAL LETTER R": "1F12C", + "SQUARED LATIN CAPITAL LETTER L": "1F13B", + "NEGATIVE CIRCLED LATIN CAPITAL LETTER D": "1F153", + "NEGATIVE CIRCLED LATIN CAPITAL LETTER J": "1F159", + "SQUARED FIVE POINT ONE": "1F1A0", + "SQUARED CJK UNIFIED IDEOGRAPH-4E8C": "1F214", "SQUARED CJK UNIFIED IDEOGRAPH-53F3": "1F22E", - "SQUARED CJK UNIFIED IDEOGRAPH-7A7A": "1F233", - "LAST QUARTER MOON WITH FACE": "1F31C", - "TULIP": "1F337", - "CHERRY BLOSSOM": "1F338", - "LEMON": "1F34B", - "FISH CAKE WITH SWIRL DESIGN": "1F365", - "SAKE BOTTLE AND CUP": "1F376", - "STUDIO MICROPHONE": "1F399", - "BEAMED ASCENDING MUSICAL NOTES": "1F39C", - "CIRCUS TENT": "1F3AA", - "SAXOPHONE": "1F3B7", - "NATIONAL PARK": "1F3DE", - "DOG": "1F415", - "ELEPHANT": "1F418", - "EYES": "1F440", - "WHITE DOWN POINTING BACKHAND INDEX": "1F447", - "FISTED HAND SIGN": "1F44A", - "TWO MEN HOLDING HANDS": "1F46C", - "EXTRATERRESTRIAL ALIEN": "1F47D", - "ALIEN MONSTER": "1F47E", - "SKULL": "1F480", - "WEDDING": "1F492", + "ROUNDED SYMBOL FOR CAI": "1F265", + "FULL MOON SYMBOL": "1F315", + "TANGERINE": "1F34A", + "SLICE OF PIZZA": "1F355", + "SPAGHETTI": "1F35D", + "FATHER CHRISTMAS": "1F385", + "PARTY POPPER": "1F389", + "SLOT MACHINE": "1F3B0", + "RUNNING SHIRT WITH SASH": "1F3BD", + "RACING MOTORCYCLE": "1F3CD", + "EUROPEAN POST OFFICE": "1F3E4", + "WAVING WHITE FLAG": "1F3F3", + "WAVING BLACK FLAG": "1F3F4", + "ROOSTER": "1F413", + "WOMANS HAT": "1F452", + "WOMAN WITH BUNNY EARS": "1F46F", + "BRIDE WITH VEIL": "1F470", + "HAIRCUT": "1F487", + "REVOLVING HEARTS": "1F49E", "BANKNOTE WITH EURO SIGN": "1F4B6", - "MONEY WITH WINGS": "1F4B8", - "PAGE WITH CURL": "1F4C3", - "BOOKS": "1F4DA", - "NO MOBILE PHONES": "1F4F5", - "SPEAKER": "1F508", - "KEY": "1F511", - "MICROSCOPE": "1F52C", - "LARGE RED CIRCLE": "1F534", - "LARGE BLUE DIAMOND": "1F537", - "CIRCLED CROSS POMMEE": "1F540", - "JOYSTICK": "1F579", - "TURNED OK HAND SIGN": "1F58F", - "WHITE HARD SHELL FLOPPY DISK": "1F5AB", - "SOFT SHELL FLOPPY DISK": "1F5AC", - "DOCUMENT WITH TEXT": "1F5B9", - "PAGES": "1F5D0", - "WINKING FACE": "1F609", - "TIRED FACE": "1F62B", - "SLIGHTLY SMILING FACE": "1F642", - "HEAVY LIGATURE OPEN ET ORNAMENT": "1F673", - "VERY HEAVY SOLIDUS": "1F67C", - "STATION": "1F689", - "BATHTUB": "1F6C1", - "AIRPLANE ARRIVING": "1F6EC", - "ALCHEMICAL SYMBOL FOR CROCUS OF COPPER-2": "1F724", - "ALCHEMICAL SYMBOL FOR LEAD ORE": "1F72A", - "ALCHEMICAL SYMBOL FOR CRUCIBLE-2": "1F766", - "QUAOAR": "1F77E", - "HEAVY WHITE CIRCLE": "1F787", - "VERY HEAVY FIVE SPOKED ASTERISK": "1F7B3", - "MEDIUM THREE POINTED BLACK STAR": "1F7C1", - "MEDIUM FOUR POINTED PINWHEEL STAR": "1F7C7", - "HEAVY TWELVE POINTED PINWHEEL STAR": "1F7D4", - "UPWARDS HEAVY COMPRESSED ARROW": "1F841", - "LEFTWARDS HEAVY ARROW": "1F844", - "RIGHTWARDS SANS-SERIF ARROW": "1F852", - "NORTH WEST SANS-SERIF ARROW": "1F854", - "WIDE-HEADED RIGHTWARDS MEDIUM BARB ARROW": "1F872", - "WIDE-HEADED DOWNWARDS HEAVY BARB ARROW": "1F87B", - "LEFTWARDS TRIANGLE ARROWHEAD": "1F890", - "DOWNWARDS WHITE ARROW WITHIN TRIANGLE ARROWHEAD": "1F897", - "RIGHTWARDS BOTTOM SHADED WHITE ARROW": "1F8A1", - "LEFTWARDS TOP SHADED WHITE ARROW": "1F8A2", - "RIGHTWARDS TOP SHADED WHITE ARROW": "1F8A3", - "RIGHTWARDS BACK-TILTED SHADOWED WHITE ARROW": "1F8A9", - "LEFT HALF CIRCLE": "1F907", - "SIGN OF THE HORNS": "1F918", + "CALENDAR": "1F4C5", + "MOBILE PHONE": "1F4F1", + "RIGHT-POINTING MAGNIFYING GLASS": "1F50E", + "LARGE ORANGE DIAMOND": "1F536", + "CROSS POMMEE WITH HALF-CIRCLE BELOW": "1F541", + "NOTCHED RIGHT SEMICIRCLE WITH THREE DOTS": "1F544", + "CLOCK FACE FOUR OCLOCK": "1F553", + "SIDEWAYS WHITE DOWN POINTING INDEX": "1F59F", + "TAPE CARTRIDGE": "1F5AD", + "CARD INDEX DIVIDERS": "1F5C2", + "COMPRESSION": "1F5DC", + "LIPS": "1F5E2", + "LEFT SPEECH BUBBLE": "1F5E8", + "BALLOT BOLD SCRIPT X": "1F5F6", + "BALLOT BOX WITH BOLD SCRIPT X": "1F5F7", + "KISSING FACE WITH SMILING EYES": "1F619", + "POUTING FACE": "1F621", + "HUSHED FACE": "1F62F", + "FACE SCREAMING IN FEAR": "1F631", + "FACE WITHOUT MOUTH": "1F636", + "HEAR-NO-EVIL MONKEY": "1F649", + "SOUTH EAST POINTING LEAF": "1F653", + "HEAVY SOUTH WEST POINTING VINE LEAF": "1F65D", + "HEAVY SOUTH EAST POINTING BUD": "1F667", + "HEAVY SCRIPT LIGATURE ET ORNAMENT": "1F671", + "HEAVY INTERROBANG ORNAMENT": "1F679", + "ARTICULATED LORRY": "1F69B", + "SMOKING SYMBOL": "1F6AC", + "POTABLE WATER SYMBOL": "1F6B0", + "SLEEPING ACCOMMODATION": "1F6CC", + "WHEEL": "1F6DE", + "ALCHEMICAL SYMBOL FOR VINEGAR OF ANTIMONY": "1F72F", + "ALCHEMICAL SYMBOL FOR CADUCEUS": "1F750", + "ALCHEMICAL SYMBOL FOR POT ASHES": "1F758", + "ALCHEMICAL SYMBOL FOR STRATUM SUPER STRATUM": "1F75C", + "BLACK UP-POINTING ISOSCELES RIGHT TRIANGLE": "1F781", + "ROUND TARGET": "1F78B", + "HEAVY WHITE SQUARE": "1F791", + "MEDIUM GREEK CROSS": "1F7A3", + "VERY HEAVY EIGHT POINTED BLACK STAR": "1F7D0", + "CIRCLED SQUARE": "1F7D7", + "LARGE GREEN SQUARE": "1F7E9", + "LARGE PURPLE SQUARE": "1F7EA", + "RIGHTWARDS ARROW WITH SMALL TRIANGLE ARROWHEAD": "1F802", + "DOWNWARDS ARROW WITH MEDIUM TRIANGLE ARROWHEAD": "1F807", + "RIGHTWARDS TRIANGLE-HEADED ARROW WITH NARROW SHAFT": "1F822", + "DOWNWARDS TRIANGLE-HEADED ARROW WITH NARROW SHAFT": "1F823", + "DOWNWARDS TRIANGLE-HEADED ARROW WITH MEDIUM SHAFT": "1F827", + "DOWNWARDS HEAVY COMPRESSED ARROW": "1F843", + "DOWNWARDS SANS-SERIF ARROW": "1F853", + "WIDE-HEADED UPWARDS HEAVY BARB ARROW": "1F879", + "WIDE-HEADED SOUTH EAST VERY HEAVY BARB ARROW": "1F886", + "PINCHED FINGERS": "1F90C", "GRINNING FACE WITH ONE LARGE AND ONE SMALL EYE": "1F92A", "JUGGLING": "1F939", - "WILTED FLOWER": "1F940", - "BACON": "1F953", - "KIWIFRUIT": "1F95D", - "SKUNK": "1F9A8", - "EMOJI COMPONENT RED HAIR": "1F9B0", - "BEARDED PERSON": "1F9D4", - "MERPERSON": "1F9DC", - "GENIE": "1F9DE", - "JIGSAW PUZZLE PIECE": "1F9E9", - "ABACUS": "1F9EE", - "WHITE CHESS KING ROTATED NINETY DEGREES": "1FA09", + "FOX FACE": "1F98A", + "HIPPOPOTAMUS": "1F99B", + "MECHANICAL ARM": "1F9BE", + "PERSON CLIMBING": "1F9D7", + "BRAIN": "1F9E0", + "NEUTRAL CHESS BISHOP": "1FA03", "WHITE CHESS TURNED KING": "1FA1E", - "BLACK CHESS TURNED KNIGHT": "1FA28", - "BLACK CHESS PAWN ROTATED TWO HUNDRED SEVENTY DEGREES": "1FA3E", - "NEUTRAL CHESS QUEEN ROTATED TWO HUNDRED SEVENTY DEGREES": "1FA40", - "NEUTRAL CHESS ROOK ROTATED TWO HUNDRED SEVENTY DEGREES": "1FA41", - "WHITE CHESS EQUIHOPPER ROTATED NINETY DEGREES": "1FA4B", - "XIANGQI RED SOLDIER": "1FA66", - "HEADSTONE": "1FAA6", - "ROCK": "1FAA8", - "PREGNANT MAN": "1FAC3", - "DONKEY": "1FACF", + "BLACK CHESS KNIGHT ROTATED TWO HUNDRED TWENTY-FIVE DEGREES": "1FA31", + "NEUTRAL CHESS PAWN ROTATED TWO HUNDRED SEVENTY DEGREES": "1FA44", + "MARACAS": "1FA87", + "FLUTE": "1FA88", + "BEETLE": "1FAB2", "LEFTWARDS PUSHING HAND": "1FAF7", - "RIGHTWARDS PUSHING HAND": "1FAF8", - "BLOCK SEXTANT-134": "1FB0C", - "LOWER LEFT BLOCK DIAGONAL UPPER MIDDLE LEFT TO LOWER MIDDLE RIGHT": "1FB51", - "UPPER RIGHT BLOCK DIAGONAL LOWER MIDDLE LEFT TO LOWER CENTRE": "1FB52", - "UPPER LEFT BLOCK DIAGONAL LOWER CENTRE TO LOWER MIDDLE RIGHT": "1FB5D", - "HORIZONTAL ONE EIGHTH BLOCK-1358": "1FB81", - "RIGHT FIVE EIGHTHS BLOCK": "1FB89", - "BOX DRAWINGS LIGHT DIAGONAL UPPER CENTRE TO MIDDLE LEFT TO LOWER CENTRE TO MIDDLE RIGHT": "1FBAB", - "STICK FIGURE WITH DRESS": "1FBC9", - "": "2B820", + "BLOCK SEXTANT-25": "1FB11", + "BLOCK SEXTANT-1245": "1FB19", + "BLOCK SEXTANT-1346": "1FB2A", + "BLOCK SEXTANT-1456": "1FB36", + "LOWER LEFT BLOCK DIAGONAL UPPER MIDDLE LEFT TO LOWER CENTRE": "1FB3E", + "UPPER RIGHT BLOCK DIAGONAL UPPER MIDDLE LEFT TO LOWER CENTRE": "1FB54", + "RIGHT TRIANGULAR ONE QUARTER BLOCK": "1FB6E", + "HORIZONTAL ONE EIGHTH BLOCK-3": "1FB77", + "UPPER AND LOWER TRIANGULAR HALF BLOCK": "1FB9A", + "": "2A700", "CJK COMPATIBILITY IDEOGRAPH-2F803": "2F803", - "CJK COMPATIBILITY IDEOGRAPH-2F835": "2F835", - "CJK COMPATIBILITY IDEOGRAPH-2F83B": "2F83B", - "CJK COMPATIBILITY IDEOGRAPH-2F84F": "2F84F", - "CJK COMPATIBILITY IDEOGRAPH-2F854": "2F854", - "CJK COMPATIBILITY IDEOGRAPH-2F857": "2F857", - "CJK COMPATIBILITY IDEOGRAPH-2F85C": "2F85C", - "CJK COMPATIBILITY IDEOGRAPH-2F863": "2F863", - "CJK COMPATIBILITY IDEOGRAPH-2F86C": "2F86C", - "CJK COMPATIBILITY IDEOGRAPH-2F872": "2F872", - "CJK COMPATIBILITY IDEOGRAPH-2F874": "2F874", - "CJK COMPATIBILITY IDEOGRAPH-2F8B4": "2F8B4", - "CJK COMPATIBILITY IDEOGRAPH-2F8BE": "2F8BE", - "CJK COMPATIBILITY IDEOGRAPH-2F8CC": "2F8CC", - "CJK COMPATIBILITY IDEOGRAPH-2F8FA": "2F8FA", + "CJK COMPATIBILITY IDEOGRAPH-2F81E": "2F81E", + "CJK COMPATIBILITY IDEOGRAPH-2F828": "2F828", + "CJK COMPATIBILITY IDEOGRAPH-2F83C": "2F83C", + "CJK COMPATIBILITY IDEOGRAPH-2F84E": "2F84E", + "CJK COMPATIBILITY IDEOGRAPH-2F850": "2F850", + "CJK COMPATIBILITY IDEOGRAPH-2F870": "2F870", + "CJK COMPATIBILITY IDEOGRAPH-2F873": "2F873", + "CJK COMPATIBILITY IDEOGRAPH-2F88E": "2F88E", + "CJK COMPATIBILITY IDEOGRAPH-2F8D4": "2F8D4", "CJK COMPATIBILITY IDEOGRAPH-2F90E": "2F90E", - "CJK COMPATIBILITY IDEOGRAPH-2F910": "2F910", "CJK COMPATIBILITY IDEOGRAPH-2F917": "2F917", - "CJK COMPATIBILITY IDEOGRAPH-2F91F": "2F91F", - "CJK COMPATIBILITY IDEOGRAPH-2F935": "2F935", - "CJK COMPATIBILITY IDEOGRAPH-2F93B": "2F93B", - "CJK COMPATIBILITY IDEOGRAPH-2F940": "2F940", - "CJK COMPATIBILITY IDEOGRAPH-2F942": "2F942", - "CJK COMPATIBILITY IDEOGRAPH-2F95C": "2F95C", + "CJK COMPATIBILITY IDEOGRAPH-2F918": "2F918", + "CJK COMPATIBILITY IDEOGRAPH-2F91A": "2F91A", + "CJK COMPATIBILITY IDEOGRAPH-2F927": "2F927", + "CJK COMPATIBILITY IDEOGRAPH-2F93D": "2F93D", + "CJK COMPATIBILITY IDEOGRAPH-2F944": "2F944", "CJK COMPATIBILITY IDEOGRAPH-2F961": "2F961", - "CJK COMPATIBILITY IDEOGRAPH-2F982": "2F982", - "CJK COMPATIBILITY IDEOGRAPH-2F98D": "2F98D", - "CJK COMPATIBILITY IDEOGRAPH-2F9A4": "2F9A4", - "CJK COMPATIBILITY IDEOGRAPH-2F9B1": "2F9B1", - "CJK COMPATIBILITY IDEOGRAPH-2F9BD": "2F9BD", - "CJK COMPATIBILITY IDEOGRAPH-2F9D5": "2F9D5", - "CJK COMPATIBILITY IDEOGRAPH-2F9DC": "2F9DC", - "CJK COMPATIBILITY IDEOGRAPH-2FA0C": "2FA0C", + "CJK COMPATIBILITY IDEOGRAPH-2F979": "2F979", + "CJK COMPATIBILITY IDEOGRAPH-2F994": "2F994", + "CJK COMPATIBILITY IDEOGRAPH-2F9C0": "2F9C0", + "CJK COMPATIBILITY IDEOGRAPH-2F9E0": "2F9E0", + "CJK COMPATIBILITY IDEOGRAPH-2F9E9": "2F9E9", + "CJK COMPATIBILITY IDEOGRAPH-2FA04": "2FA04", + "CJK COMPATIBILITY IDEOGRAPH-2FA06": "2FA06", + "CJK COMPATIBILITY IDEOGRAPH-2FA1B": "2FA1B", "CJK COMPATIBILITY IDEOGRAPH-2FA1C": "2FA1C", - "TAG SPACE": "E0020", - "TAG LATIN CAPITAL LETTER D": "E0044", - "TAG CIRCUMFLEX ACCENT": "E005E", + "TAG EQUALS SIGN": "E003D", + "TAG LATIN CAPITAL LETTER B": "E0042", "TAG RIGHT CURLY BRACKET": "E007D", - "VARIATION SELECTOR-34": "E0111", - "VARIATION SELECTOR-84": "E0143", - "VARIATION SELECTOR-98": "E0151", - "VARIATION SELECTOR-108": "E015B", - "VARIATION SELECTOR-112": "E015F", - "VARIATION SELECTOR-135": "E0176", - "VARIATION SELECTOR-178": "E01A1", - "VARIATION SELECTOR-228": "E01D3", - "VARIATION SELECTOR-251": "E01EA", - "": "FFFFD" + "VARIATION SELECTOR-17": "E0100", + "VARIATION SELECTOR-54": "E0125", + "VARIATION SELECTOR-115": "E0162", + "VARIATION SELECTOR-148": "E0183", + "VARIATION SELECTOR-170": "E0199", + "VARIATION SELECTOR-174": "E019D", + "VARIATION SELECTOR-177": "E01A0", + "VARIATION SELECTOR-212": "E01C3", + "VARIATION SELECTOR-250": "E01E9" }, "numerics": { "": "0000",