`};code.__getattribute__=function(self,attr){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($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");if($B.last(lines).startsWith(" ")){throw _b_.SyntaxError.$factory("unexpected EOF while parsing")}}if($.source.__class__&&$.source.__class__.__module__=="ast"){$B.imported._ast._validate($.source);$._ast=$.source;delete $.source;return $}var _ast,parser;if($B.parser_to_ast){try{var parser_mode=$.mode=="eval"?"eval":"file";parser=new $B.Parser($.source,filename,parser_mode);_ast=parser.parse()}catch(err){if($.mode=="single"){try{parser.tokens.next}catch(err2){var tokens=parser.tokens,tester=tokens[tokens.length-2];if(tester.type=="NEWLINE"&&$.flags&16384||tester.type=="DEDENT"&&$.flags&512){err.__class__=_b_.SyntaxError;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=parser.parse();$.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}}else{var root=$B.parser.create_root_node({src:$.source,filename:filename},module_name,module_name);root.mode=$.mode;root.parent_block=$B.builtins_scope;try{$B.parser.dispatch_tokens(root,$.source);_ast=root.ast()}catch(err){if($.mode=="single"&&root.token_reader.read()===undefined){let tokens=root.token_reader.tokens,tester=tokens[tokens.length-2];if(tester.type=="NEWLINE"&&$.flags&16384||tester.type=="DEDENT"&&$.flags&512){err.__class__=_b_.SyntaxError;err.args[0]="incomplete input"}}throw err}if($.mode=="single"&&_ast.body.length==1&&_ast.body[0]instanceof $B.ast.Expr){root=$B.parser.create_root_node({src:$.source,filename:filename},module_name,module_name);root.mode="eval";$.single_expression=true;root.parent_block=$B.builtins_scope;$B.parser.dispatch_tokens(root,$.source);_ast=root.ast()}delete $B.url2name[filename];if($.flags==$B.PyCF_ONLY_AST){$B.create_python_ast_classes();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;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.__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");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__,global_name="globals_"+__name__,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}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;frame.__file__=filename;frame.$f_trace=$B.enter_frame(frame);var _frame_obj=$B.frame_obj;frame.$lineno=1;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($B.parser_to_ast){if(!_ast){var _mode=mode=="eval"?"eval":"file";_ast=new $B.Parser(src,filename,_mode).parse()}}else{if(!_ast){var root=$B.parser.create_root_node(src,"",frame[0],frame[2],1);root.mode=mode;root.filename=filename;$B.parser.dispatch_tokens(root);_ast=root.ast()}}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,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 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)}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)}$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,3),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)};function in_mro(klass,attr){if(klass===undefined){return false}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 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(attr=="__doc__"&&klass[attr]===undefined){_get_builtins_doc();klass[attr]=$B.builtins_doc[klass.__name__]}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}}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(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.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=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.JSObj.$factory($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.JSObj.$factory(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)+"'")}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__=_b_.object.__hash__(obj)}}else{return $B.$call(hash_method)(obj)}};function _get_builtins_doc(){if($B.builtins_doc===undefined){var url=$B.brython_path;if(url.charAt(url.length-1)=="/"){url=url.substr(0,url.length-1)}url+="/builtins_docstrings.js";var f=_b_.open(url);eval(f.$content);for(var key in docs){if(_b_[key]){_b_[key].__doc__=docs[key]}}$B.builtins_doc=docs}}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.indexOf(cls)>-1){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,len){return{__class__:iterator_class,getitem:getitem,len:len,counter:-1}}));iterator_class.__next__=function(self){self.counter++;if(self.len!==null&&self.counter==self.len){throw _b_.StopIteration.$factory("")}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;try{len=len(obj)}catch(err){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+"' object is not iterable")}return iterator_class.$factory(gi,len)}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()")}return $B.$call(method)(obj)};_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))}var obj={__class__:map,args:iter_args,func:func};obj[Symbol.iterator]=function(){this.iters=[];for(var arg of this.args){this.iters.push(arg[Symbol.iterator]())}return this};obj.next=function(){var args=[];for(var iter of this.iters){var arg=iter.next();if(arg.done){return{done:true,value:null}}args.push(arg.value)}return{done:false,value:this.func.apply(null,args)}};return obj}));map.__iter__=function(self){self[Symbol.iterator]();return self};map.__next__=function(self){var args=[];for(var iter of self.iters){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 attr in $.kw.$jsobj){switch(attr){case"key":func=$.kw.$jsobj[attr];func=func===_b_.None?func:$B.$call(func);break;case"default":var default_value=$.kw.$jsobj[attr];has_default=true;break;default:throw _b_.TypeError.$factory("'"+attr+"' 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.is_none(kw.$jsobj.end)?"\n":kw.$jsobj.end,sep=$B.is_none(kw.$jsobj.sep)?" ":kw.$jsobj.sep,file=$B.is_none(kw.$jsobj.file)?$B.get_stdout():kw.$jsobj.file;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.__dict__===undefined){obj[attr]=value}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(){return false};$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")}if(size<0){size=self.$length-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;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 i=0,len=this.response.length;i63232){cp-=63232}bytes.push(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($ns.kw.$jsobj.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__,__globals__,__kwdefaults__,__doc__,arg_names,vararg,kwarg,co_argcount,co_filename,co_firstlineno,co_flags,co_freevars,co_kwonlyargcount,co_name,co_nlocals,co_posonlyargcount,co_qualname,co_varnames){f.$is_func=true;f.$infos={__module__:__module__,__defaults__:__defaults__,__globals__:__globals__,__kwdefaults__:__kwdefaults__,__doc__:__doc__,arg_names:arg_names,vararg:vararg,kwarg:kwarg};f.$infos.__name__=co_name;f.$infos.__qualname__=co_qualname;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_nlocals,co_posonlyargcount:co_posonlyargcount,co_qualname:co_qualname,co_varnames:co_varnames}};$B.make_function_defaults=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;for(let i=f.$infos.__code__.co_posonlyargcount;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 _b_.None};$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_function_defaults(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_function_defaults(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(var i=0;i=0;i--){array[customDest+i]=array[customCursor+i]}array[dest]=tmp[cursor2];return}var minGallop=this.minGallop;while(true){var 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(var 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(var 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(var 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.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}`};var traceback=$B.traceback=$B.make_class("traceback",(function(exc){var frame_obj=exc.$frame_obj;if(frame_obj===null){return _b_.None}if($B.$isinstance(exc,_b_.SyntaxError)){frame_obj=frame_obj.prev}var $linenums=$B.make_linenums(frame_obj);return{__class__:traceback,$stack:make_frames_stack(frame_obj),$linenums:$linenums,pos:0}}));traceback.__getattribute__=function(_self,attr){switch(attr){case"tb_frame":return _self.$stack[_self.pos];case"tb_lineno":return _self.$linenums[_self.pos];case"tb_lasti":return-1;case"tb_next":if(_self.pos<_self.$stack.length-1){_self.pos++;return _self}else{return _b_.None}case"stack":return _self.$stack;default:return _b_.object.__getattribute__(_self,attr)}};$B.set_func_names(traceback,"builtins");var frame=$B.frame=$B.make_class("frame",(function(frame_list){frame_list.__class__=frame;return frame_list}));frame.__delattr__=function(_self,attr){if(attr=="f_trace"){_self.$f_trace=_b_.None}};frame.__dir__=function(_self){return _b_.object.__dir__(frame).concat(["clear","f_back","f_builtins","f_code","f_globals","f_lasti","f_lineno","f_locals","f_trace","f_trace_lines","f_trace_opcodes"])};frame.__getattr__=function(_self,attr){if(attr=="f_back"){var frame_obj=$B.frame_obj;while(frame_obj!==null){if(frame_obj.frame===_self){break}frame_obj=frame_obj.prev}if(frame_obj.prev!==null){return frame.$factory(frame_obj.prev.frame)}return _b_.None}else if(attr=="clear"){return function(){}}else if(attr=="f_trace"){var locals=_self[1];if(_self.$f_trace===undefined){return _b_.None}return _self.$f_trace}console.log("no attr",attr,"for frame",_self);throw $B.attr_error(attr,_self)};frame.__setattr__=function(_self,attr,value){if(attr=="f_trace"){_self.$f_trace=value}};frame.__str__=frame.__repr__=function(_self){return""};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,in_ctx_manager){if(!js_exc.__class__){if(js_exc.$py_exc){return js_exc.$py_exc}var exc=_b_.JavascriptError.$factory(js_exc.__name__||js_exc.name);exc.$js_exc=js_exc;if($B.is_recursion_error(js_exc)){return _b_.RecursionError.$factory("too much recursion")}exc.__cause__=_b_.None;exc.__context__=_b_.None;exc.__suppress_context__=false;var $message=js_exc.message||"<"+js_exc+">";exc.args=_b_.tuple.$factory([$message]);exc.$py_error=true;js_exc.$py_exc=exc;$B.freeze(exc)}else{var 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__=[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"],_b_.RuntimeError);make_builtin_exception("IndentationError",_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){if(obj.$is_class){var msg=`type object '${obj.__name__}'`}else{var 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);return exc};var MAX_CANDIDATE_ITEMS=750,MAX_STRING_SIZE=40,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("$")));var 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_.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.__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_.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(var 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)}if(err.$positions!==undefined){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);console.log("in file_cache",Object.keys($B.file_cache).join("\n"))}}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])}}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(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){var suggestion=$B.offer_suggestions_for_name_error(err);if(suggestion!==_b_.None){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){var 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\nJavascript error\n"+err.$js_exc+"\n"+err.$js_exc.stack}return trace};$B.get_stderr=function(){if($B.imported.sys){return $B.imported.sys.stderr}return $B.imported._sys.stderr};$B.get_stdout=function(){if($B.imported.sys){return $B.imported.sys.stdout}return $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(self,attr,value){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(self,attr,value){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(self,other){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(self,attr,value){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(var i=start;i=start){return bytes.$factory([])}stop=Math.max(0,stop);for(var 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)){var 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(var 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(self,encoding,errors){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 start=$.start==-1?$.self.source.length-$.suffix.source.length:Math.min($.self.source.length-$.suffix.source.length,$.start);var end=$.end==-1?$.self.source.length:$.end;var res=true;for(var 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(var 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 res};bytes.splitlines=function(self){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=[],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{var 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(var 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]}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(var 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":for(var 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(var 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(var 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(var 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(var entry of set_iter_with_hash(other)){set_discard_entry(so,entry.item,entry.hash)}}else if($B.$isinstance(other,_b_.dict)){for(var entry of _b_.dict.$iter_items_with_hash(other)){set_discard_entry(so,entry.key,entry.hash)}}else{var iterator=$B.make_js_iterator(other);for(var key of iterator){set_discard_key(so,key)}}}const DISCARD_NOTFOUND=0,DISCARD_FOUND=1;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),iterator;if($B.$isinstance(other,[set,frozenset])){if(other.$used>so.$used){var tmp=so;so=other;other=tmp}for(var 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(var entry of _b_.dict.$iter_items_with_hash(other)){if(set_contains(so,entry.key,entry.hash)){set_add(result,entry.key,entry.hash)}}}else{var 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,protocol){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 check_version(s,version){if(s.$version!=version){throw _b_.RuntimeError.$factory("Set changed size during iteration")}}function set_make_items(so){var items=[];for(var hash in so.$store){items=items.concat(so.$store[hash])}return items}function make_hash_iter(obj,hash){let version=obj.$version,hashes=obj.$hashes[hash],len=hashes.length,i=0;const iterator={*[Symbol.iterator](){while(iset.__len__(other)){return false}for(var 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(var entry of _b_.dict.$iter_items_with_hash(self)){if(!set_lookkey(other,entry.key,entry.hash)){return false}}return true}else{var member_func=$B.member_func(other);for(var 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){var res=make_new_set(set);for(var item of items){if(item.constant){set_add(res,item.constant[0],item.constant[1])}else if(item.starred){for(var 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)};var singleton_id=Math.floor(Math.random()*Math.pow(2,40));function empty_frozenset(){var res=frozenset.__new__(frozenset);res.$id=singleton_id;return res}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 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 elts=filename.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($B.script_dir);if(ix===-1){console.log("bizarre",path,$B.script_dir)}else{path.splice(ix,1,...pythonpath)}}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,$package){var xhr=new XMLHttpRequest,fake_qs="?v="+(new Date).getTime(),res=null,mod_name=mod.__name__;var timer=_window.setTimeout((function(){xhr.abort()}),5e3);if($B.get_option("cache")){xhr.open("GET",url,false)}else{xhr.open("GET",url+fake_qs,false)}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("Error "+xhr.status+" means that Python module "+mod_name+" was 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;function import_js(mod,path){try{var module_contents=$download_module(mod,path,undefined)}catch(err){return null}run_js(module_contents,path,mod);return true}$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){var module_id="$locals_"+_module.__name__.replace(/\./g,"_");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 show_ns(){var kk=Object.keys(_window);for(var i=0,len=kk.length;i1){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))}var 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(var 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}try{for(var attr in mod){module[attr]=mod[attr]}module.__initializing__=false;$B.imported[module.__name__]=module;return{content:src,name:mod_name,imports:Object.keys(root.imports).join(",")}}catch(err){console.log(""+err+" "+" for module "+module.__name__);for(var 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,path){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_.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(var 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(self,spec){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{var 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 record=run_py(module_contents,modobj.__file__,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;var elts=mod_name.split(".");if(elts.length>1){elts.pop()}if($B.$options.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"),cursor=store.openCursor(),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 finder_cpython={__class__:_b_.type,__mro__:[_b_.object],__qualname__:"CPythonFinder",$infos:{__module__:"builtins",__name__:"CPythonFinder"},create_module:function(cls,spec){return _b_.None},exec_module:function(cls,modobj){console.log("exec PYthon module",modobj);var loader_state=modobj.__spec__.loader_state;var content=loader_state.content;delete modobj.__spec__["loader_state"];modobj.$is_package=loader_state.is_package;modobj.__file__=loader_state.__file__;$B.file_cache[modobj.__file__]=content;$B.url2file[modobj.__file__]=modobj.__name__;var mod_name=modobj.__name__;if($B.get_option("debug")>1){console.log("run Python code from CPython",mod_name)}run_py(content,modobj.__path__,modobj)},find_module:function(cls,name,path){return{__class__:Loader,load_module:function(name,path){var spec=cls.find_spec(cls,name,path);var mod=Module.$factory(name);$B.imported[name]=mod;mod.__spec__=spec;cls.exec_module(cls,mod)}}},find_spec:function(cls,fullname,path){console.log("finder cpython",fullname);var xhr=new XMLHttpRequest,url="/cpython_import?module="+fullname,result;xhr.open("GET",url,false);xhr.onreadystatechange=function(){if(this.readyState==4&&this.status==200){var data=JSON.parse(this.responseText);result=ModuleSpec.$factory({name:fullname,loader:cls,origin:"CPython",submodule_search_locations:data.is_package?[]:_b_.None,loader_state:{content:data.content},cached:_b_.None,parent:data.is_package?fullname:parent_package(fullname),has_location:_b_.False})}};xhr.send();return result}};$B.set_func_names(finder_cpython,"");for(var method in finder_cpython){if(typeof finder_cpython[method]=="function"){finder_cpython[method]=_b_.classmethod.$factory(finder_cpython[method])}}finder_cpython.$factory=function(){return{__class__:finder_cpython}};var StdlibStaticFinder=$B.make_class("StdlibStaticFinder",(function(){return{__class__:StdlibStaticFinder}}));StdlibStaticFinder.find_spec=function(self,fullname,path){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?[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(var 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(var 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=".";var 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,globals,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);alert()}if(mod_name=="_frozen_importlib_external"){var alias=aliases[mod_name]||mod_name;var imp=$B.$import_from("importlib",["_bootstrap_external"],{_bootstrap_external:alias},0,locals);var _bootstrap=$B.imported.importlib._bootstrap,_bootstrap_external=$B.imported.importlib["_bootstrap_external"];_bootstrap_external._set_bootstrap_module(_bootstrap);_bootstrap._bootstap_external=_bootstrap_external;var _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:"")}var parts=mod_name.split(".");if(mod_name[mod_name.length-1]=="."){parts.pop()}var norm_parts=[],prefix=true;for(var i=0,len=parts.length;i1){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;if(relative){var 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){var 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,CPython:finder_cpython};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 unicode_tables=$B.unicode_tables;$B.has_surrogate=function(s){for(var i=0;i=55296&&code<=56319){return true}}return false};var 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 codepoints=[],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){if(!Array.isArray(surrogates)){throw Error("not list")}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]=55296&&code<=56319){var v=65536;v+=(code&1023)<<10;v+=s.charCodeAt(i+1)&1023;cps.push(v);i++}else{cps.push(code)}}return s.codepoints=cps}str.__add__=function(_self,other){if(!$B.$isinstance(other,str)){try{return $B.$getattr(other,"__radd__")(_self)}catch(err){throw _b_.TypeError.$factory("Can't convert "+$B.class_name(other)+" to str implicitly")}}[_self,other]=to_string([_self,other]);var res=$B.String(_self+other);return res};str.__contains__=function(_self,item){if(!$B.$isinstance(item,str)){throw _b_.TypeError.$factory("'in ' requires "+"string as left operand, not "+$B.class_name(item))}[_self,item]=to_string([_self,item]);if(item.__class__===str||$B.$isinstance(item,str)){var nbcar=item.length}else{var nbcar=_b_.len(item)}if(nbcar==0){return true}var len=_self.length;if(len==0){return nbcar==0}for(var i=0,len=_self.length;i=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="",i=null;if(step>0){if(stop<=start){return""}for(var i=start;i=start){return""}for(var i=start;i>stop;i+=step){res+=_self[i]}}return $B.String(res)};var prefix=2,suffix=3,mask=2**32-1;str.$nb_str_hash_cache=0;function fnv(p){if(p.length==0){return 0}var x=prefix;x=(x^p[0]<<7)&mask;for(var i=0,len=p.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)}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 trailing_zeros=/(.*?)(0+)([eE].*)/,leading_zeros=/\.(0*)/,trailing_dot=/\.$/;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)+1}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)}`)}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 length=s.length,pos=0,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(self,attr,value){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(":")}var 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(_self){var last_arg=$B.last(arguments);if(last_arg.$nat=="mapping"){var mapping=last_arg.mapping,getitem=$B.$getattr(mapping,"__getitem__");var args=[];for(var i=0,len=arguments.length-1;i-1){var pos=parseInt(fmt.name),value=_b_.tuple.__getitem__($.$args,pos)}else{var 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(self){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};str.isalnum=function(){var $=$B.args("isalnum",1,{self:null},["self"],arguments,{},null,null),cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);for(var cat of["Ll","Lu","Lm","Lt","Lo","Nd","digits","numeric"]){if(!$B.in_unicode_category(cat,cp)){return false}}}return true};str.isalpha=function(){var $=$B.args("isalpha",1,{self:null},["self"],arguments,{},null,null),cp,_self=to_string($.self);for(var char of _self){cp=_b_.ord(char);for(var cat of["Ll","Lu","Lm","Lt","Lo"]){if(!$B.in_unicode_category(cat,cp)){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(self){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(self){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(self){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(self){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(self){var $=$B.args("lower",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);return _self.toLowerCase()};str.lstrip=function(self,x){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(var i=0,len=items.length;i0&&str.endswith(_self,suffix)){return _self.substr(0,_self.length-suffix.length)}return _self.substr(0)};function $re_escape(str){var specials="[.*+?|()$^";for(var i=0,len=specials.length;i-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{var elts=str.split(_self,old,count)}var res=_self,pos=-1;if(old.length==0){var 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(self,substr){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(self){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){var res=[];while(pos<_self.length&&_self.charAt(pos).search(/\s/)>-1){pos++}if(pos===_self.length-1){return[_self]}var 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 res.map($B.String)}else{sep=to_string(sep);var res=[],s="",seplen=sep.length;if(maxsplit==0){return[$.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 res.map($B.String)}};str.splitlines=function(self){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=[],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 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(self){var $=$B.args("upper",1,{self:null},["self"],arguments,{},null,null),_self=to_string($.self);return _self.toUpperCase()};str.zfill=function(self,width){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,errors){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,errors=$.errors}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.JSObj.$factory(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)=='"""'){var 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{var 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};var _chr=$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)}};var _ord=$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(var 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(var 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;i0){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)};function __newobj__(){var $=$B.args("__newobj__",0,{},[],arguments,{},"args",null),args=$.args;var res=args.slice(1);res.__class__=args[0];return res}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=function(self){return int_value(self)};int.denominator=function(self){return int.$factory(1)};int.imag=function(self){return int.$factory(0)};int.real=function(self){return self};for(var attr of["numerator","denominator","imag","real"]){int[attr].setter=function(x){return function(self,value){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(var 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("-")){var 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){var _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);if(match===null){res=0;var coef=1,digit;for(var char of _value){if(/\p{Nd}/u.test(char)){var cp=char.codePointAt(0);for(var 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);var res=0n,coef=1n,char;for(var 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 len_method(obj)>0}else{try{var res=bool_class?$B.$call(bool_method)(obj):$B.$call(bool_method)()}catch(err){throw err}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.$factory=function(){var $=$B.args("bool",1,{x:null},["x"],arguments,{x:false},null,null);return $B.$bool($.x,true)};bool.numerator=int.numerator;bool.denominator=int.denominator;bool.real=int.real;bool.imag=int.imag;_b_.bool=bool;$B.set_func_names(bool,"builtins")})(__BRYTHON__);(function($B){var _b_=$B.builtins;if($B.isWebWorker){var window=self}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 max_safe_divider=$B.max_int/9;var int_or_long=_b_.int.$int_or_long;var len=(Math.pow(2,53)-1+"").length-1;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=function(self){return self};long_int.denominator=function(self){return _b_.int.$factory(1)};long_int.imag=function(self){return _b_.int.$factory(0)};long_int.real=function(self){return 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(var i=0;iMIN_SAFE_INTEGER&&v0}};long_int.$factory=function(value,base){var is_digits=digits(base);for(var 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;var object=_b_.object;function $err(op,other){var msg="unsupported operand type(s) for "+op+": 'float' and '"+$B.class_name(other)+"'";throw _b_.TypeError.$factory(msg)}function float_value(obj){return obj.__class__===float?obj:fast_float(obj.value)}var float={__class__:_b_.type,__dir__: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=function(self){return self};float.denominator=function(self){return 1};float.imag=function(self){return 0};float.real=function(self){return 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=__BRYTHON__.MAX_VALUE,DBL_MAX_EXP=2**10,LONG_MIN=__BRYTHON__.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();var re_parts=[/^(?[+-])?(0x)?/,/(?[0-9a-fA-F]+)?/,/(?\.(?[0-9a-fA-F]+))?/,/(?p(?[+-])?(?\d+))?$/];var re=new RegExp(re_parts.map((r=>r.source)).join(""));var mo=re.exec(s);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")}var pos=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(var 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(var 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(var i=ndigits-1;i>key_digit;i--){x=16*x+HEX_DIGIT(i)}var 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"){var 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}if(fmt.precision!==undefined){var prec=fmt.precision;if(prec==0){return Math.round(value)+""}var res=$B.roundDownToFixed(value,prec),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"){var 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){var exp=res.length-1,exp=exp<10?"0"+exp:exp,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{var 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{var 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;i0?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){var mant=split_e[0],exp=split_e[1];if(exp.startsWith("-")){var 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){var 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)}var mant=int_part;if(dec_part.length>0){mant+="."+dec_part}return sign+mant+"e+"+exp}else if(x=="0"){var exp=0;while(exp3){var rest=y.substr(exp),exp=(exp+1).toString();while(rest.endsWith("0")){rest=rest.substr(0,res.length-1)}var 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(var op in ops){var 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(var op in $B.$comps){var 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 $FloatClass(value){return new Number(value)}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}};var fast_float_with_hash=function(value,hash_value){return{__class__:_b_.float,__hashvalue__:hash_value,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))}}}var klass=value.__class__,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 "+"number, not '"+$B.class_name(value)+"'")}var res=$B.$call(index_method)(value),klass=$B.get_class(res);if(klass===_b_.int){return fast_float(res)}else if(klass===$B.long_int){return $B.long_int.__float__(res)}else if(klass.__mro__.indexOf(_b_.int)>-1){var msg=`${$B.class_name(value)}.__index__ returned `+`non-int (type ${$B.class_name(res)}). 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(res)}throw _b_.TypeError.$factory("__index__ returned non-int"+` (type ${$B.class_name(res)})`)}var res=$B.$call(float_method)(value),klass=$B.get_class(res);if(klass!==_b_.float){if(klass.__mro__.indexOf(_b_.float)>-1){var 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.$FloatClass=$FloatClass;$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),NZERO=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.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.__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,max_repeat=2**30-1;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 default_precision=6,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,im=self.$imag.value,precision=parseInt(fmt.precision,10);if(type===undefined){type="r";default_precision=0;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,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}}var 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 hypot(){var $=$B.args("hypot",0,{},[],arguments,{},"args",null);return _b_.float.$factory(Math.hypot(...$.args))}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 r,p,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 r,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{var 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){var 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 str_hash=_b_.str.__hash__,$N=_b_.None;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_with_hash=function*(d){if(d.$all_str){for(var key in d.$strings){if(key!="$dict_strings"){yield{key:key,value:d.$strings[key]}}}}if(d.$jsobj){for(var key in d.$jsobj){if(!d.$exclude||!d.$exclude(key)){yield{key:key,value:d.$jsobj[key]}}}}else if(d.__class__===$B.jsobj_as_pydict){for(var key in d.obj){yield{key:key,value:d.obj[key]}}}else{var version=d.$version;for(var i=0,len=d._keys.length;i0};dict.__class_getitem__=function(cls,item){if(!Array.isArray(item)){item=[item]}return $B.GenericAlias.$factory(cls,item)};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);var 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{var 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.__init__=function(self,first,second){if(first===undefined){return _b_.None}if(second===undefined){if(!first.$kw&&$B.$isinstance(first,$B.JSObj)){for(var key in first){dict.$setitem(self,key,first[key])}return _b_.None}else if(first.$jsobj){self.$jsobj={};for(var attr in first.$jsobj){self.$jsobj[attr]=first.$jsobj[attr]}self.$all_str=false;return $N}else if(first[Symbol.iterator]){init_from_list(self,first);return $N}else if(first.__class__===$B.generator){init_from_list(self,first.js_gen);return $N}}var $=$B.args("dict",1,{self:null},["self"],arguments,{},"first","second");var args=$.first;if(args.length>1){throw _b_.TypeError.$factory("dict expected at most 1 argument"+", got 2")}else if(args.length==1){args=args[0];if(args.__class__===dict){for(var entry of dict.$iter_items_with_hash(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);var kiter=_b_.iter($B.$call(keys)());while(true){try{var key=_b_.next(kiter),value=gi(key);dict.__setitem__(self,key,value)}catch(err){if(err.__class__===_b_.StopIteration){break}throw err}}return $N}}if(!Array.isArray(args)){args=_b_.list.$factory(args)}init_from_list(self,args)}}for(var key in $.second.$jsobj){dict.$setitem(self,key,$.second.$jsobj[key])}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"{...}"}var res=[],key,value;for(var entry of dict.$iter_items_with_hash(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,protocol){return $B.fast_tuple([_b_.iter,$B.fast_tuple([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(self,key,value){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.$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 $N}else if(self.__class__===$B.jsobj_as_pydict){return $B.jsobj_as_pydict.__setitem__(self,key,value)}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 $N};dict.copy=function(self){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:$N},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_with_hash(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=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,protocol){return $B.fast_tuple([_b_.iter,$B.fast_tuple([Array.from(self.make_iter())])])};$B.set_func_names(dict_itemiterator,"builtins");dict.items=function(self){var $=$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=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,protocol){return $B.fast_tuple([_b_.iter,$B.fast_tuple([Array.from(self.make_iter())])])};$B.set_func_names(dict_keyiterator,"builtins");dict.keys=function(self){var $=$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){}var 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){var 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:$N},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(self){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(var 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.$JS2Py(x[attr]))}}}return d}$B.obj_dict=function(obj,exclude){var klass=obj.__class__||$B.get_class(obj);if(klass!==undefined&&klass.$native){throw $B.attr_error("__dict__",obj)}var res={__class__:dict,$jsobj:obj,$exclude:exclude||function(){return false}};return res};var jsobj_as_pydict=$B.jsobj_as_pydict=$B.make_class("jsobj_as_pydict",(function(jsobj){return{__class__:jsobj_as_pydict,obj:jsobj||{},new_keys:[],$version:0}}));jsobj_as_pydict.__contains__=function(self,key){if(self.new_keys.indexOf(key)>-1){return true}return self.obj[key]!==undefined};jsobj_as_pydict.__delitem__=function(self,key){jsobj_as_pydict.__getitem__(self,key);delete self.obj[key];var ix=self.new_keys.indexOf(key);if(ix>-1){self.new_keys.splice(ix,1)}};jsobj_as_pydict.__eq__=function(self,other){if(other.__class__!==jsobj_as_pydict&&!$B.$isinstance(other,_b_.dict)){return _b_.NotImplemented}var self1=$B.empty_dict(),other1=$B.empty_dict();dict.__init__(self1,jsobj_as_pydict.items(self));dict.__init__(other1,$B.get_class(other).items(other));return dict.__eq__(self1,other1)};jsobj_as_pydict.__ne__=function(self,other){var eq=jsobj_as_pydict.__eq__(self,other);return eq===_b_.NotImplemented?eq:!eq};jsobj_as_pydict.__getitem__=function(self,key){if(self.obj.hasOwnProperty(key)){return self.obj[key]}throw _b_.KeyError.$factory(key)};jsobj_as_pydict.__iter__=function(self){return _b_.iter(jsobj_as_pydict.keys(self))};jsobj_as_pydict.__len__=function(self){var len=0;for(var key in self.obj){len++}return len+self.new_keys.length};jsobj_as_pydict.__or__=function(self,other){if(!$B.$isinstance(other,[dict,jsobj_as_pydict])){return _b_.NotImplemented}var res=jsobj_as_pydict.copy(self);jsobj_as_pydict.update(res,other);return res};jsobj_as_pydict.__repr__=function(self){if($B.repr.enter(self)){return"{...}"}var res=[],items=_b_.list.$factory(jsobj_as_pydict.items(self));for(var item of items){res.push(_b_.repr(item[0])+": "+_b_.repr(item[1]))}$B.repr.leave(self);return"{"+res.join(", ")+"}"};jsobj_as_pydict.__setitem__=function(self,key,value){self.obj[key]=value};jsobj_as_pydict.clear=function(self){self.obj={};return _b_.None};jsobj_as_pydict.copy=function(self){var copy=jsobj_as_pydict.$factory();for(var key in self.obj){copy.obj[key]=self.obj[key]}return copy};jsobj_as_pydict.get=function(self,key,_default){_default=_default===undefined?_b_.None:_default;if(!self.obj.hasOwnProperty(key)){return _default}return self.obj[key]};jsobj_as_pydict.$iter_items=function*(self){for(var key in self.obj){yield $B.fast_tuple([key,self.obj[key]])}};jsobj_as_pydict.items=function(self){var items=Array.from(jsobj_as_pydict.$iter_items(self));return _b_.iter(items)};jsobj_as_pydict.keys=function(self){var items=Array.from(jsobj_as_pydict.$iter_items(self)),keys=items.map((x=>x[0]));return _b_.iter(keys)};jsobj_as_pydict.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;if(self.obj.hasOwnProperty(key)){var res=self.obj[key];delete self.obj[key];return res}else{if(_default!==missing){return _default}throw _b_.KeyError.$factory(key)}};jsobj_as_pydict.popitem=function(self){$B.check_nb_args_no_kw("popitem",1,arguments);for(var key in self.obj){var res=$B.fast_tuple([key,self.obj[key]]);delete self.obj[key];return res}throw _b_.KeyError.$factory("'popitem(): dictionary is empty'")};jsobj_as_pydict.update=function(self,other){var klass=$B.get_class(other),keys=$B.$call($B.$getattr(klass,"keys")),getitem;for(var key of $B.make_js_iterator(keys(other))){if(!getitem){getitem=$B.$call($B.$getattr(klass,"__getitem__"))}self.obj[key]=getitem(other,key)}return _b_.None};jsobj_as_pydict.values=function(self){var items=Array.from(jsobj_as_pydict.$iter_items(self)),values=items.map((x=>x[1]));return _b_.iter(values)};$B.set_func_names(jsobj_as_pydict,"builtins")})(__BRYTHON__);(function($B){var _b_=$B.builtins,object=_b_.object,getattr=$B.$getattr,isinstance=$B.$isinstance;function check_not_tuple(self,attr){if(self.__class__===tuple){throw $B.attr_error(attr,self)}}function $list(){return list.$factory.apply(null,arguments)}var list={__class__:_b_.type,__qualname__:"list",__mro__:[object],$is_class:true,$native:true,$match_sequence_pattern:true,__dir__: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(),is_js=other.$brython_class=="js";for(const item of other){res.push(is_js?$B.$JS2Py(item):item)}res.__brython__=true;if(isinstance(self,tuple)){res=tuple.$factory(res)}return res};list.__bool__=function(self){return list.__len__(self)>0};list.__class_getitem__=function(cls,item){if(!Array.isArray(item)){item=[item]}return $B.GenericAlias.$factory(cls,item)};list.__contains__=function(self,item){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)){var 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}var res=[],i=null,pos=0;if(step>0){if(stop>start){for(var i=start;istop;i+=step){if(self[i]!==undefined){res[pos++]=i}}res.reverse()}}var 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){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){var 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(var i=start;istart){return factory(res)}for(var 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($B.$iter($.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&&posbegin){var pivot=begin+Math.floor(Math.random()*(end-begin));pivot=$partition(arg,array,begin,end,pivot);$qsort(arg,array,begin,pivot);$qsort(arg,array,pivot+1,end)}}function $elts_class(self){if(self.length==0){return null}var cl=$B.get_class(self[0]),i=self.length;while(i--){if($B.get_class(self[i])!==cl){return false}}return cl}list.sort=function(self){var $=$B.args("sort",1,{self:null},["self"],arguments,{},null,"kw");check_not_tuple(self,"sort");var func=_b_.None,reverse=false,kw_args=$.kw;for(var key in kw_args.$jsobj){if(key=="key"){func=kw_args.$jsobj[key]}else if(key=="reverse"){reverse=kw_args.$jsobj[key]}else{throw _b_.TypeError.$factory("'"+key+"' is an invalid keyword argument for this function")}}if(self.length==0){return _b_.None}if(func!==_b_.None){func=$B.$call(func)}self.$cl=$elts_class(self);var cmp=null;function basic_cmp(a,b){return $B.rich_comp("__lt__",a,b)?-1:$B.rich_comp("__eq__",a,b)?0:1}function reverse_cmp(a,b){return basic_cmp(b,a)}if(func===_b_.None&&self.$cl===_b_.str){if(reverse){cmp=function(b,a){return $B.$AlphabeticalCompare(a,b)}}else{cmp=function(a,b){return $B.$AlphabeticalCompare(a,b)}}}else if(func===_b_.None&&self.$cl===_b_.int){if(reverse){cmp=function(b,a){return a-b}}else{cmp=function(a,b){return a-b}}}else{cmp=reverse?function(t1,t2){return basic_cmp(t2[0],t1[0])}:function(t1,t2){return basic_cmp(t1[0],t2[0])};if(func===_b_.None){cmp=reverse?reverse_cmp:basic_cmp;self.sort(cmp)}else{var temp=[],saved=self.slice();for(var i=0,len=self.length;i"};function make_args(args){var res=[args[0].js];for(var i=1,len=args.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(self,type,value,traceback){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}));var ag_closed={};$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;var object=_b_.object;var _window=globalThis;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()}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){var res=new Array(obj.length);for(var i=0,len=obj.length;ijsobj2pyobj(x))).catch($B.handle_error)}if(typeof jsobj==="function"){_this=_this===undefined?null:_this;if(_this===null){const pyobj=jsobj[PYOBJFCT];if(pyobj!==undefined){return pyobj}}else{const pyobjfcts=_this[PYOBJFCTS];if(pyobjfcts!==undefined){const pyobj=pyobjfcts.get(jsobj);if(pyobj!==undefined){return pyobj}}else{try{_this[PYOBJFCTS]=new Map}catch(err){}}}var res=function(){var args=new Array(arguments.length);for(var i=0,len=arguments.length;i-1){return pyobj}if([_b_.list,_b_.tuple].indexOf(klass)>-1){return pyobj.map(pyobj2jsobj)}if(klass===_b_.dict||_b_.issubclass(klass,_b_.dict)){var jsobj={};for(var entry of _b_.dict.$iter_items_with_hash(pyobj)){var key=entry.key;if(typeof key!=="string"){key=_b_.str.$factory(key)}if(typeof entry.value==="function"){entry.value.bind(jsobj)}jsobj[key]=pyobj2jsobj(entry.value)}return jsobj}if(klass===_b_.str){return pyobj.valueOf()}if(klass===$B.long_int){return pyobj.value}if(klass===_b_.float){return pyobj.value}if(klass===$B.function||klass===$B.method){if(pyobj.prototype&&pyobj.prototype.constructor===pyobj&&!pyobj.$is_func){return pyobj}if(pyobj.$is_async){const jsobj=function(){var res=pyobj.apply(null,arguments);return $B.coroutine.send(res)};pyobj[JSOBJ]=jsobj;jsobj[PYOBJ]=pyobj;return jsobj}var jsobj=function(){try{var args=new Array(arguments.length);for(var i=0;i`};$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)}}}};_self.$brython_events=_self.$brython_events||{};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)))}}return function(){var js_array=arguments[0],t=jsobj2pyobj(js_array),args=[t];return _b_.list[attr].apply(null,args)}};$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.__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.__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 $B.JSObj.$factory(_self[attr])}throw $B.attr_error(attr,_self)}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 $B.jsobj2pyobj(_self[i])};var js_array_iterator=$B.make_class("JSArray_iterator",(function(obj){return{__class__:js_array_iterator,it:obj[Symbol.iterator]()}}));js_array_iterator.__next__=function(_self){var v=_self.it.next();if(v.done){throw _b_.StopIteration.$factory("")}return $B.jsobj2pyobj(v.value)};$B.set_func_names(js_array_iterator,"builtins");js_array.__iter__=function(_self){return js_array_iterator.$factory(_self)};js_array.__repr__=function(_self){if($B.repr.enter(_self)){return"[...]"}var _r=new Array(_self.length),res;for(var i=0;i<_self.length;++i){_r[i]=_b_.str.$factory(_self[i])}res="["+_r.join(", ")+"]";$B.repr.leave(_self);return res};$B.set_func_names(js_array,"javascript");$B.get_jsobj_class=function(obj){var proto=Object.getPrototypeOf(obj);if(proto===null){return $B.JSObj}if(proto[Symbol.iterator]!==undefined){return $B.IterableJSObj}else if(Object.getOwnPropertyNames(proto).indexOf("length")>-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;i0)}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(var i=0;i<$DOMEventAttrs_W3C.length;i++){if(obj[$DOMEventAttrs_W3C[i]]===undefined){flag=false;break}}if(flag){return true}for(var i=0;i<$DOMEventAttrs_IE.length;i++){if(obj[$DOMEventAttrs_IE[i]]===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};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(self,attr){switch(attr){case"__repr__":case"__str__":return function(){return""};case"x":return $mouseCoords(self).x;case"y":return $mouseCoords(self).y;case"data":if(self.dataTransfer!==null&&self.dataTransfer!==undefined){return Clipboard.$factory(self.dataTransfer)}return $B.$JS2Py(self["data"]);case"target":if(self.target!==undefined){return DOMNode.$factory(self.target)}case"char":return String.fromCharCode(self.which);case"svgX":if(self.target instanceof SVGSVGElement){return Math.floor(dom2svg(self.target,$mouseCoords(self)).x)}throw _b_.AttributeError.$factory("event target is not an SVG "+"element");case"svgY":if(self.target instanceof SVGSVGElement){return Math.floor(dom2svg(self.target,$mouseCoords(self)).y)}throw _b_.AttributeError.$factory("event target is not an SVG "+"element")}var res=self[attr];if(res!==undefined){if(typeof res=="function"){var func=function(){var args=[];for(var i=0;i");function $EventsList(elt,evt,arg){this.elt=elt;this.evt=evt;if($B.$isinstance(arg,_b_.list)){this.callbacks=arg}else{this.callbacks=[arg]}this.remove=function(callback){var found=false;for(var i=0;i"};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(self){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){var res={__class__:Query,_keys:[],_values:{}};var qs=location.search.substr(1).split("&");if(location.search!=""){for(var 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){var 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{var 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=[],pos=0;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))}break}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(self,event){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 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 res};DOMNode.clear=function(self){var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null);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(self,selector){var $=$B.args("closest",2,{self:null,selector:null},["self","selector"],arguments,{},null,null);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 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){var result=self._values[key];if(result===undefined){return[]}return result};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="