/brython.js
JavaScript | 5400 lines | 5397 code | 0 blank | 3 comment | 721 complexity | 2b3b992a411831b336b4d525699e7589 MD5 | raw file
Possible License(s): BSD-3-Clause
Large files files are truncated, but you can click here to view the full file
- // brython.js www.brython.info
- // version 1.1.20130319-232656
- // version compiled from commented, indented source files at http://code.google.com/p/brython/
- __BRYTHON__=new Object()
- __BRYTHON__.__getattr__=function(attr){return this[attr]}
- __BRYTHON__.date=function(){
- if(arguments.length===0){return JSObject(new Date())}
- else if(arguments.length===1){return JSObject(new Date(arguments[0]))}
- else if(arguments.length===7){return JSObject(new Date(arguments[0],
- arguments[1]-1,arguments[2],arguments[3],
- arguments[4],arguments[5],arguments[6]))}
- }
- __BRYTHON__.has_local_storage=typeof(Storage)!=="undefined"
- if(__BRYTHON__.has_local_storage){
- __BRYTHON__.local_storage=function(){return JSObject(localStorage)}
- }
- __BRYTHON__.has_json=typeof(JSON)!=="undefined"
- __BRYTHON__.version_info=[1,1,"20130319-232656"]
- __BRYTHON__.path=[]
- function abs(obj){
- if(isinstance(obj,int)){return int(Math.abs(obj))}
- else if(isinstance(obj,float)){return float(Math.abs(obj.value))}
- else if('__abs__' in obj){return obj.__abs__()}
- else{throw TypeError("Bad operand type for abs(): '"+str(obj.__class__)+"'")}
- }
- function $alert(src){alert(str(src))}
- function all(iterable){
- while(true){
- try{
- var elt=next(iterable)
- if(!bool(elt)){return False}
- }catch(err){return True}
- }
- }
- function any(iterable){
- if(iterable.__item__===undefined){
- throw TypeError("'"+iterable.__class__.__name__+"' object is not iterable")
- }
- while(true){
- try{
- var elt=next(iterable)
- if(bool(elt)){return True}
- }catch(err){return False}
- }
- }
- function assert_raises(){
- var $ns=$MakeArgs('assert_raises',arguments,['exc','func'],{},'args','kw')
- var args=$ns['args']
- try{$ns['func'].apply(this,args)}
- catch(err){
- if(err.name!==$ns['exc']){
- throw AssertionError(
- "exception raised '"+err.name+"', expected '"+$ns['exc']+"'")
- }
- return
- }
- throw AssertionError("no exception raised, expected '"+$ns['exc']+"'")
- }
- function bool(obj){
- if(obj===null){return False}
- else if(obj===undefined){return False}
- else if(isinstance(obj,dict)){return obj.keys.length>0}
- else if(isinstance(obj,tuple)){return obj.length>0}
- else if(typeof obj==="boolean"){return obj}
- else if(typeof obj==="number" || typeof obj==="string"){
- if(obj){return true}else{return false}
- }else if('__bool__' in obj){return obj.__bool__()}
- else if('__len__' in obj){return obj.__len__()>0}
- return true
- }
- bool.__class__=$type
- bool.__name__='bool'
- bool.__str__=function(){return "<class 'bool'>"}
- bool.toString=bool.__str__
- bool.__hash__=function(){
- if(this.valueOf())return 1
- return 0
- }
- function $class(obj,info){
- this.obj=obj
- this.info=info
- this.__class__=Object
- this.toString=function(){return "<class '"+info+"'>"}
- }
- function $confirm(src){return confirm(src)}
- function $DictClass($keys,$values){
- var x=null
- var i=null
- this.iter=null
- this.__class__=dict
- this.$keys=$keys
- this.$values=$values
- }
- function dict(){
- if(arguments.length==0){return new $DictClass([],[])}
- else if(arguments.length===1 && isinstance(arguments[0],dict)){
- return arguments[0]
- }
- var $ns=$MakeArgs('dict',arguments,[],{},'args','kw')
- var args=$ns['args']
- var kw=$ns['kw']
- if(args.length>0){
- var iterable=args[0]
- var obj=new $DictClass([],[])
- for(var i=0;i<iterable.__len__();i++){
- var elt=iterable.__item__(i)
- obj.__setitem__(elt.__item__(0),elt.__item__(1))
- }
- return obj
- }else if(kw.$keys.length>0){
- return kw
- }
- }
- dict.__name__='dict'
- dict.toString=function(){return "<class 'dict'>"}
- dict.__add__=function(self,other){
- var msg="unsupported operand types for +:'dict' and "
- throw TypeError(msg+"'"+(str(other.__class__)|| typeof other)+"'")
- }
- dict.__class__=$type
- dict.__contains__=function(self,item){
- return self.$keys.__contains__(item)
- }
- dict.__delitem__=function(self,arg){
- for(var i=0;i<self.$keys.length;i++){
- if(arg.__eq__(self.$keys[i])){
- self.$keys.splice(i,1)
- self.$values.splice(i,1)
- return
- }
- }
- throw KeyError(str(arg))
- }
- dict.__eq__=function(self,other){
- if(other===undefined){
- return self===dict
- }
- if(!isinstance(other,dict)){return False}
- if(other.$keys.length!==self.$keys.length){return False}
- for(var i=0;i<self.$keys.length;i++){
- var key=self.$keys[i]
- for(j=0;j<other.$keys.length;j++){
- try{
- if(other.$keys[j].__eq__(key)){
- if(!other.$values[j].__eq__(self.$values[i])){
- return False
- }
- }
- }catch(err){void(0)}
- }
- }
- return True
- }
- dict.__getattr__=function(attr){
- if(this[attr]!==undefined){return this[attr]}
- else{throw AttributeError("'dict' object has no attribute '"+attr+"'")}
- }
- dict.__getitem__=function(self,arg){
- for(var i=0;i<self.$keys.length;i++){
- if(arg.__eq__(self.$keys[i])){return self.$values[i]}
- }
- throw KeyError(str(arg))
- }
- dict.__hash__=function(self){throw TypeError("unhashable type: 'dict'");}
- dict.__in__=function(self,item){return item.__contains__(self)}
- dict.__item__=function(self,i){return self.$keys[i]}
- dict.__len__=function(self){return self.$keys.length}
- dict.__ne__=function(self,other){return !dict.__eq__(self,other)}
- dict.__next__=function(self){
- if(self.iter==null){self.iter==0}
- if(self.iter<self.$keys.length){
- self.iter++
- return self.$keys[self.iter-1]
- }else{
- self.iter=null
- throw StopIteration()
- }
- }
- dict.__not_in__=function(self,item){return !(item.__contains__(self))}
- dict.__setitem__=function(self,key,value){
- for(var i=0;i<self.$keys.length;i++){
- try{
- if(key.__eq__(self.$keys[i])){
- self.$values[i]=value
- return
- }
- }catch(err){
- void(0)
- }
- }
- self.$keys.push(key)
- self.$values.push(value)
- }
- dict.__str__=function(self){
- if(self===undefined){return "<class 'dict'>"}
- if(self.$keys.length==0){return '{}'}
- var res="{",key=null,value=null,i=null
- var qesc=new RegExp('"',"g")
- for(var i=0;i<self.$keys.length;i++){
- if(typeof self.$keys[i]==="string"){key='"'+$escape_dq(self.$keys[i])+'"'}
- else{key=str(self.$keys[i])}
- if(typeof self.$values[i]==="string"){value='"'+$escape_dq(self.$values[i])+'"'}
- else{value=str(self.$values[i])}
- res +=key+':'+value+','
- }
- return res.substr(0,res.length-1)+'}'
- }
- dict.items=function(self){
- return new $iterator(zip(self.$keys,self.$values),"dict_items")
- }
- dict.keys=function(self){
- return new $iterator(self.$keys,"dict keys")
- }
- dict.update=function(self){
- var params=[]
- for(var i=1;i<arguments.length;i++){params.push(arguments[i])}
- var $ns=$MakeArgs('dict.update',params,[],{},'args','kw')
- var args=$ns['args']
- if(args.length>0 && isinstance(args[0],dict)){
- var other=args[0]
- for(var i=0;i<other.$keys.length;i++){
- dict.__setitem__(self,other.$keys[i],other.$values[i])
- }
- }
- var kw=$ns['kw']
- console.log('kw '+kw.__class__)
- var keys=list(kw.keys())
- for(var i=0;i<keys.__len__();i++){
- dict.__setitem__(self,keys[i],kw.__getitem__(keys[i]))
- }
- }
- dict.values=function(self){
- return new $iterator(self.$values,"dict values")
- }
- $DictClass.prototype.__class__=dict
- $DictClass.prototype.__getattr__=function(attr){
- if(attr==='__class__'){return this.__class__}
- if(dict[attr]===undefined){throw AttributeError("'dict' object has no attribute '"+attr+"'")}
- var obj=this
- var res=function(){
- var args=[obj]
- for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
- return dict[attr].apply(obj,args)
- }
- res.__str__=function(){return "<built-in method "+attr+" of dict object>"}
- return res
- }
- for(var attr in dict){
- if($DictClass.prototype[attr]===undefined){
- $DictClass.prototype[attr]=(function(attr){
- return function(){
- var args=[this]
- for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
- return dict[attr].apply(this,args)
- }
- })(attr)
- }
- }
- function dir(obj){
- var res=[]
- for(var attr in obj){res.push(attr)}
- res.sort()
- return res
- }
- function enumerate(iterator){
- var res=[]
- for(var i=0;i<iterator.__len__();i++){
- res.push([i,iterator.__item__(i)])
- }
- return res
- }
- function $eval(src){
- if(src===""){throw SyntaxError("unexpected EOF while parsing")}
- try{return eval(__BRYTHON__.py2js(src).to_js())}
- catch(err){
- if(err.py_error===undefined){throw RuntimeError(err.message)}
- if(document.$stderr){document.$stderr.__getattr__('write')(document.$stderr_buff+'\n')}
- else{err.message +=err.info;throw(err)}
- }
- }
- function exec(src){
- try{eval(__BRYTHON__.py2js(src).to_js())}
- catch(err){
- console.log(err)
- if(err.py_error===undefined){err=RuntimeError(err+'')}
- var trace=err.__name__+': '+err.message
- if(err.__name__=='SyntaxError'||err.__name__==='IndentationError'){
- trace +=err.info
- }
- if(document.$stderr){document.$stderr.__getattr__('write')(trace)}
- else{err.message +=err.info}
- throw err
- }
- }
- function filter(){
- if(arguments.length!=2){throw TypeError(
- "filter expected 2 arguments, got "+arguments.length)}
- var func=arguments[0],iterable=arguments[1]
- var res=[]
- for(var i=0;i<iterable.__len__();i++){
- if(func(iterable.__item__(i))){
- res.push(iterable.__item__(i))
- }
- }
- return res
- }
- function float(value){
- if(value===undefined){return new $FloatClass(0.0)}
- if(typeof value=="number" ||(typeof value=="string" && !isNaN(value))){
- return new $FloatClass(parseFloat(value))
- }
- if(isinstance(value,float))return value
- if(value=='inf')return new $FloatClass(Infinity)
- if(value=='-inf')return new $FloatClass(-Infinity)
- if(typeof value=='string' && value.toLowerCase()=='nan')return new $FloatClass(Number.NaN)
- throw ValueError("Could not convert to float(): '"+str(value)+"'")
- }
- float.__class__=$type
- float.__name__='float'
- float.toString=function(){return "<class 'float'>"}
- float.__hash__=function(){
- frexp=function(re){
- var ex=Math.floor(Math.log(re)/ Math.log(2))+ 1
- var frac=re / Math.pow(2, ex)
- return[frac, ex]
- }
- if(this.value===Infinity || this.value===-Infinity){
- if(this.value < 0.0)return -271828
- return 314159
- }else if(isNaN(this.value)){
- return 0
- }
- var r=frexp(this.value)
- r[0]*=Math.pow(2,31)
- hipart=int(r[0])
- r[0]=(r[0]- hipart)* Math.pow(2,31)
- var x=hipart + int(r[0])+(r[1]<< 15)
- return x & 0xFFFFFFFF
- }
- function $FloatClass(value){
- this.value=value
- this.__class__=float
- this.__hash__=float.__hash__
- }
- $FloatClass.prototype.toString=function(){
- var res=this.value+''
- if(res.indexOf('.')==-1){res+='.0'}
- return str(res)
- }
- $FloatClass.prototype.__class__=float
- $FloatClass.prototype.__bool__=function(){return bool(this.value)}
- $FloatClass.prototype.__floordiv__=function(other){
- if(isinstance(other,int)){
- if(other===0){throw ZeroDivisionError('division by zero')}
- else{return float(Math.floor(this.value/other))}
- }else if(isinstance(other,float)){
- if(!other.value){throw ZeroDivisionError('division by zero')}
- else{return float(Math.floor(this.value/other.value))}
- }else{throw TypeError(
- "unsupported operand type(s) for //: 'int' and '"+other.__class__+"'")
- }
- }
- $FloatClass.prototype.__getattr__=function(attr){
- if(this[attr]!==undefined){return this[attr]}
- else{throw AttributeError("'float' object has no attribute '"+attr+"'")}
- }
- $FloatClass.prototype.__hash__=float.__hash__
- $FloatClass.prototype.__in__=function(item){return item.__contains__(this)}
- $FloatClass.prototype.__not_in__=function(item){return !(item.__contains__(this))}
- $FloatClass.prototype.__str__=$FloatClass.prototype.toString
- $FloatClass.prototype.__truediv__=function(other){
- if(isinstance(other,int)){
- if(other===0){throw ZeroDivisionError('division by zero')}
- else{return float(this.value/other)}
- }else if(isinstance(other,float)){
- if(!other.value){throw ZeroDivisionError('division by zero')}
- else{return float(this.value/other.value)}
- }else{throw TypeError(
- "unsupported operand type(s) for //: 'int' and '"+other.__class__+"'")
- }
- }
- var $op_func=function(other){
- if(isinstance(other,int)){return float(this.value-other)}
- else if(isinstance(other,float)){return float(this.value-other.value)}
- else if(isinstance(other,bool)){
- var bool_value=0;
- if(other.valueOf())bool_value=1
- return float(this.value-bool_value)}
- else{throw TypeError(
- "unsupported operand type(s) for -: "+this.value+" (float) and '"+other.__class__+"'")
- }
- }
- $op_func +=''
- var $ops={'+':'add','-':'sub','*':'mul','%':'mod'}
- for($op in $ops){
- eval('$FloatClass.prototype.__'+$ops[$op]+'__ = '+$op_func.replace(/-/gm,$op))
- }
- var $comp_func=function(other){
- if(isinstance(other,int)){return this.value > other.valueOf()}
- else if(isinstance(other,float)){return this.value > other.value}
- else{throw TypeError(
- "unorderable types: "+this.__class__+'() > '+other.__class__+"()")
- }
- }
- $comp_func +=''
- var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le','==':'eq','!=':'ne'}
- for($op in $comps){
- eval("$FloatClass.prototype.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
- }
- var $notimplemented=function(other){
- throw TypeError(
- "unsupported operand types for OPERATOR: '"+this.__class__+"' and '"+other.__class__+"'")
- }
- $notimplemented +=''
- for($op in $operators){
- var $opfunc='__'+$operators[$op]+'__'
- if(!($opfunc in $FloatClass.prototype)){
- eval('$FloatClass.prototype.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
- }
- }
- function getattr(obj,attr,_default){
- if(obj.__getattr__!==undefined &&
- obj.__getattr__(attr)!==undefined){
- return obj.__getattr__(attr)
- }
- else if(_default !==undefined){return _default}
- else{throw AttributeError(
- "'"+str(obj.__class__)+"' object has no attribute '"+attr+"'")}
- }
- function hasattr(obj,attr){
- try{getattr(obj,attr);return True}
- catch(err){return False}
- }
- function hash(obj){
- if(isinstance(obj, int)){return obj.valueOf();}
- if(isinstance(obj, bool)){return int(obj);}
- if(obj.__hashvalue__ !==undefined){return obj.__hashvalue__;}
- if(obj.__hash__ !==undefined){
- obj.__hashvalue__=obj.__hash__()
- return obj.__hashvalue__
- }else{
- throw AttributeError(
- "'"+str(obj.__class__)+"' object has no attribute '__hash__'")
- }
- }
- function input(src){
- return prompt(src)
- }
- function int(value){
- if(value===undefined){return 0}
- else if(isinstance(value,int)){return value}
- else if(value===True){return 1}
- else if(value===False){return 0}
- else if(typeof value=="number" ||
- (typeof value=="string" && parseInt(value)!=NaN)){
- return parseInt(value)
- }else if(isinstance(value,float)){
- return parseInt(value.value)
- }else{throw ValueError(
- "Invalid literal for int() with base 10: '"+str(value)+"'"+value.__class__)
- }
- }
- int.__class__=$type
- int.__name__='int'
- int.toString=function(){return "<class 'int'>"}
- Number.prototype.__class__=int
- Number.prototype.__floordiv__=function(other){
- if(isinstance(other,int)){
- if(other==0){throw ZeroDivisionError('division by zero')}
- else{return Math.floor(this/other)}
- }else if(isinstance(other,float)){
- if(!other.value){throw ZeroDivisionError('division by zero')}
- else{return float(Math.floor(this/other.value))}
- }else{$UnsupportedOpType("//","int",other.__class__)}
- }
- Number.prototype.__getattr__=function(attr){
- if(this[attr]!==undefined){return this[attr]}
- throw AttributeError("'int' object has no attribute '"+attr+"'")
- }
- Number.prototype.__hash__=function(){return this.valueOf()}
- Number.prototype.__in__=function(item){return item.__contains__(this)}
- Number.prototype.__int__=function(){return this}
- Number.prototype.__mul__=function(other){
- var val=this.valueOf()
- if(isinstance(other,int)){return this*other}
- else if(isinstance(other,float)){return float(this*other.value)}
- else if(isinstance(other,bool)){
- var bool_value=0
- if(other.valueOf())bool_value=1
- return this*bool_value}
- else if(typeof other==="string"){
- var res=''
- for(var i=0;i<val;i++){res+=other}
- return res
- }else if(isinstance(other,[list,tuple])){
- var res=[]
- var $temp=other.slice(0,other.length)
- for(var i=0;i<val;i++){res=res.concat($temp)}
- if(isinstance(other,tuple)){res=tuple.apply(this,res)}
- return res
- }else{$UnsupportedOpType("*",int,other)}
- }
- Number.prototype.__not_in__=function(item){
- res=item.__contains__(this)
- return !res
- }
- Number.prototype.__pow__=function(other){
- if(typeof other==="number"){return int(Math.pow(this.valueOf(),other.valueOf()))}
- else{$UnsupportedOpType("//",int,other.__class__)}
- }
- Number.prototype.__setattr__=function(attr,value){throw AttributeError(
- "'int' object has no attribute "+attr+"'")}
- Number.prototype.__str__=function(){return this.toString()}
- Number.prototype.__truediv__=function(other){
- if(isinstance(other,int)){
- if(other==0){throw ZeroDivisionError('division by zero')}
- else{return float(this/other)}
- }else if(isinstance(other,float)){
- if(!other.value){throw ZeroDivisionError('division by zero')}
- else{return float(this/other.value)}
- }else{$UnsupportedOpType("//","int",other.__class__)}
- }
- var $op_func=function(other){
- if(isinstance(other,int)){
- var res=this.valueOf()-other.valueOf()
- if(isinstance(res,int)){return res}
- else{return float(res)}
- }
- else if(isinstance(other,float)){return float(this.valueOf()-other.value)}
- else if(isinstance(other,bool)){
- var bool_value=0
- if(other.valueOf())bool_value=1
- return this.valueOf()-bool_value}
- else{throw TypeError(
- "unsupported operand type(s) for -: "+this.value+" (float) and '"+str(other.__class__)+"'")
- }
- }
- $op_func +=''
- var $ops={'+':'add','-':'sub','%':'mod'}
- for($op in $ops){
- eval('Number.prototype.__'+$ops[$op]+'__ = '+$op_func.replace(/-/gm,$op))
- }
- var $comp_func=function(other){
- if(isinstance(other,int)){return this.valueOf()> other.valueOf()}
- else if(isinstance(other,float)){return this.valueOf()> other.value}
- else{throw TypeError(
- "unorderable types: "+str(this.__class__)+'() > '+str(other.__class__)+"()")}
- }
- $comp_func +=''
- var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le','==':'eq','!=':'ne'}
- for($op in $comps){
- eval("Number.prototype.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
- }
- var $notimplemented=function(other){
- throw TypeError(
- "unsupported operand types for OPERATOR: '"+str(this.__class__)+"' and '"+str(other.__class__)+"'")
- }
- $notimplemented +=''
- for($op in $operators){
- var $opfunc='__'+$operators[$op]+'__'
- if(!($opfunc in Number.prototype)){
- eval('Number.prototype.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
- }
- }
- function isinstance(obj,arg){
- if(obj===null){return arg===None}
- if(obj===undefined){return false}
- if(arg.constructor===Array){
- for(var i=0;i<arg.length;i++){
- if(isinstance(obj,arg[i])){return true}
- }
- return false
- }else{
- if(arg===int){
- return((typeof obj)=="number"||obj.constructor===Number)&&(obj.valueOf()%1===0)
- }
- if(arg===float){
- return((typeof obj=="number" && obj.valueOf()%1!==0))||
- (obj.__class__===float)
- }
- if(arg===str){return(typeof obj=="string")}
- if(arg===list){return(obj.constructor===Array)}
- if(obj.__class__!==undefined){return obj.__class__===arg}
- return obj.constructor===arg
- }
- }
- function iter(obj){
- if('__item__' in obj){
- obj.__counter__=0
- return obj
- }
- throw TypeError("'"+str(obj.__class__)+"' object is not iterable")
- }
- function $iterator(obj,info){
- this.__getattr__=function(attr){
- var res=this[attr]
- if(res===undefined){throw AttributeError(
- "'"+info+"' object has no attribute '"+attr+"'")}
- else{return res}
- }
- this.__len__=function(){return obj.__len__()}
- this.__item__=function(i){return obj.__item__(i)}
- this.__class__=new $class(this,info)
- this.toString=function(){return info+'('+obj.toString()+')'}
- }
- function len(obj){
- try{return obj.__len__()}
- catch(err){
- try{return obj.__getattr__('__len__')()}
- catch(err){
- throw TypeError("object of type '"+obj.__class__.__name__+"' has no len()")}
- }
- }
- function map(){
- var func=arguments[0],res=[],rank=0
- while(true){
- var args=[],flag=true
- for(var i=1;i<arguments.length;i++){
- var x=arguments[i].__item__(rank)
- if(x===undefined){flag=false;break}
- args.push(x)
- }
- if(!flag){break}
- res.push(func.apply(null,args))
- rank++
- }
- return res
- }
- function $extreme(args,op){
- if(op==='__gt__'){var $op_name="max"}
- else{var $op_name="min"}
- if(args.length==0){throw TypeError($op_name+" expected 1 argument, got 0")}
- var last_arg=args[args.length-1]
- var last_i=args.length-1
- var has_key=false
- if(isinstance(last_arg,$Kw)){
- if(last_arg.name==='key'){
- var func=last_arg.value
- has_key=true
- last_i--
- }else{throw TypeError($op_name+"() got an unexpected keyword argument")}
- }else{var func=function(x){return x}}
- if((has_key && args.length==2)||(!has_key && args.length==1)){
- var arg=args[0]
- var $iter=iter(arg)
- var res=null
- while(true){
- try{
- var x=next($iter)
- if(res===null || bool(func(x)[op](func(res)))){res=x}
- }catch(err){
- if(err.__name__=="StopIteration"){return res}
- throw err
- }
- }
- }else{
- var res=null
- for(var i=0;i<=last_i;i++){
- var x=args[i]
- if(res===null || bool(func(x)[op](func(res)))){res=x}
- }
- return res
- }
- }
- function max(){
- var args=[]
- for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
- return $extreme(args,'__gt__')
- }
- function min(){
- var args=[]
- for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
- return $extreme(args,'__lt__')
- }
- function next(obj){
- if('__item__' in obj){
- if(obj.__counter__===undefined){obj.__counter__=0}
- var res=obj.__item__(obj.__counter__)
- if(res!==undefined){obj.__counter__++;return res}
- throw StopIteration('')
- }
- throw TypeError("'"+str(obj.__class__)+"' object is not iterable")
- }
- function $not(obj){return !bool(obj)}
- function $ObjectClass(){
- this.__class__="<class 'object'>"
- }
- $ObjectClass.prototype.__getattr__=function(attr){
- if(attr in this){return this[attr]}
- else{throw AttributeError("object has no attribute '"+attr+"'")}
- }
- $ObjectClass.prototype.__delattr__=function(attr){delete this[attr]}
- $ObjectClass.prototype.__setattr__=function(attr,value){this[attr]=value}
- function object(){
- return new $ObjectClass()
- }
- object.__class__=$type
- object.__name__='object'
- object.__str__="<class 'object'>"
- object.__hash__=function(){
- document.$py_next_hash+=1;
- return document.$py_next_hash
- }
- $ObjectClass.prototype.__hash__=object.__hash__
- function $open(){
- var $ns=$MakeArgs('open',arguments,['file'],{'mode':'r','encoding':'utf-8'},'args','kw')
- for(var attr in $ns){eval('var '+attr+'=$ns["'+attr+'"]')}
- if(args.length>0){var mode=args[0]}
- if(args.length>1){var encoding=args[1]}
- if(isinstance(file,JSObject)){return new $OpenFile(file.js,mode,encoding)}
- }
- function $print(){
- var $ns=$MakeArgs('print',arguments,[],{},'args','kw')
- var args=$ns['args']
- var kw=$ns['kw']
- var end='\n'
- var res=''
- if(kw['end']!==undefined){end=kw['end']}
- for(var i=0;i<args.length;i++){
- res +=str(args[i])
- if(i<args.length-1){res +=' '}
- }
- res +=end
- document.$stdout.__getattr__('write')(res)
- }
- log=function(arg){console.log(arg)}
- function $prompt(text,fill){return prompt(text,fill || '')}
- function range(){
- var $ns=$MakeArgs('range',arguments,[],{},'args',null)
- var args=$ns['args']
- if(args.length>3){throw TypeError(
- "range expected at most 3 arguments, got "+args.length)
- }
- var start=0
- var stop=0
- var step=1
- if(args.length==1){stop=args[0]}
- else if(args.length>=2){
- start=args[0]
- stop=args[1]
- }
- if(args.length>=3){step=args[2]}
- if(step==0){throw ValueError("range() arg 3 must not be zero")}
- var res=[]
- if(step>0){
- for(var i=start;i<stop;i+=step){res.push(i)}
- }else if(step<0){
- for(var i=start;i>stop;i+=step){res.push(i)}
- }
- return res
- }
- function repr(obj){return obj.toString()}
- function reversed(seq){
- if(isinstance(seq,list)){seq.reverse();return seq}
- else if(isinstance(seq,str)){
- var res=''
- for(var i=seq.length-1;i>=0;i--){res+=seq.charAt(i)}
- return res
- }else{throw TypeError(
- "argument to reversed() must be a sequence")}
- }
- function round(arg,n){
- if(!isinstance(arg,[int,float])){
- throw TypeError("type "+str(arg.__class__)+" doesn't define __round__ method")
- }
- if(n===undefined){n=0}
- if(!isinstance(n,int)){throw TypeError(
- "'"+n.__class__+"' object cannot be interpreted as an integer")}
- var mult=Math.pow(10,n)
- var res=Number(Math.round(arg*mult)).__truediv__(mult)
- if(n==0){return int(res)}else{return float(res)}
- }
- function set(){
- var i=0
- if(arguments.length==0){return new $SetClass()}
- else if(arguments.length==1){
- var arg=arguments[0]
- if(isinstance(arg,set)){return arg}
- var obj=new $SetClass()
- try{
- for(var i=0;i<arg.__len__();i++){
- obj.items.push(arg.__getitem__(i))
- }
- return obj
- }catch(err){
- throw TypeError("'"+arg.__class__.__name__+"' object is not iterable")
- }
- }else{
- throw TypeError("set expected at most 1 argument, got "+arguments.length)
- }
- }
- set.__class__=$type
- set.__name__='set'
- set.toString=function(){return "<class 'set'>"}
- set.__hash__=function(){throw TypeError("unhashable type: 'set'");}
- function $SetClass(){
- var x=null
- var i=null
- this.iter=null
- this.__class__=set
- this.items=[]
- }
- $SetClass.prototype.toString=function(){
- var res="{"
- for(var i=0;i<this.items.length;i++){
- var x=this.items[i]
- if(isinstance(x,str)){res +="'"+x+"'"}
- else{res +=x.toString()}
- if(i<this.items.length-1){res +=','}
- }
- return res+'}'
- }
- $SetClass.prototype.__add__=function(other){
- return set(this.items.concat(other.items))
- }
- $SetClass.prototype.__class__=set
- $SetClass.prototype.__contains__=function(item){
- for(var i=0;i<this.items.length;i++){
- try{if(this.items[i].__eq__(item)){return True}
- }catch(err){void(0)}
- }
- return False
- }
- $SetClass.prototype.__eq__=function(other){
- if(isinstance(other,set)){
- if(other.items.length==this.items.length){
- for(var i=0;i<this.items.length;i++){
- if(this.__contains__(other.items[i])===False){
- return False
- }
- }
- return True
- }
- }
- return False
- }
- $SetClass.prototype.__getattr__=function(attr){
- if(this[attr]!==undefined){return this[attr]}
- else{throw AttributeError("'set' object has no attribute '"+attr+"'")}
- }
- $SetClass.prototype.__hash__=set.__hash__
- $SetClass.prototype.__in__=function(item){return item.__contains__(this)}
- $SetClass.prototype.__len__=function(){return int(this.items.length)}
- $SetClass.prototype.__item__=function(i){return this.items[i]}
- $SetClass.prototype.__ne__=function(other){return !(this.__eq__(other))}
- $SetClass.prototype.__not_in__=function(item){return !(item.__contains__(this))}
- $SetClass.prototype.__str__=$SetClass.prototype.toString
- $SetClass.prototype.add=function(item){
- var i=0
- for(i=0;i<this.items.length;i++){
- try{if(item.__eq__(this.items[i])){return}}
- catch(err){void(0)}
- }
- this.items.push(item)
- }
- function setattr(obj,attr,value){
- if(!isinstance(attr,str)){throw TypeError("setattr(): attribute name must be string")}
- obj[attr]=value
- }
- function $SliceClass(start,stop,step){
- this.__class__=slice
- this.start=start
- this.stop=stop
- this.step=step
- }
- function slice(){
- var $ns=$MakeArgs('slice',arguments,[],{},'args',null)
- var args=$ns['args']
- if(args.length>3){throw TypeError(
- "slice expected at most 3 arguments, got "+args.length)
- }
- var start=0
- var stop=0
- var step=1
- if(args.length==1){stop=args[0]}
- else if(args.length>=2){
- start=args[0]
- stop=args[1]
- }
- if(args.length>=3){step=args[2]}
- if(step==0){throw ValueError("slice step must not be zero")}
- return new $SliceClass(start,stop,step)
- }
- function sum(iterable,start){
- if(start===undefined){start=0}
- var res=0
- for(var i=start;i<iterable.__len__();i++){
- res=res.__add__(iterable.__item__(i))
- }
- return res
- }
- function $tuple(arg){return arg}
- function tuple(){
- var args=new Array(),i=0
- for(i=0;i<arguments.length;i++){args.push(arguments[i])}
- var obj=list(args)
- obj.__class__=tuple
- obj.toString=function(){
- var res=args.__str__()
- res='('+res.substr(1,res.length-2)
- if(obj.length===1){res+=','}
- return res+')'
- }
- obj.__hash__=function(){
- var x=0x345678
- for(var i=0;i < args.length;i++){
- var y=args[i].__hash__()
- x=(1000003 * x)^ y & 0xFFFFFFFF
- }
- return x
- }
- obj.__str__=obj.toString
- return obj
- }
- tuple.__class__=$type
- tuple.__name__='tuple'
- tuple.__str__=function(){return "<class 'tuple'>"}
- tuple.toString=tuple.__str__
- function zip(){
- var $ns=$MakeArgs('zip',arguments,[],{},'args','kw')
- var args=$ns['args']
- var kw=$ns['kw']
- var rank=0,res=[]
- while(true){
- var line=[],flag=true
- for(var i=0;i<args.length;i++){
- var x=args[i].__item__(rank)
- if(x===undefined){flag=false;break}
- line.push(x)
- }
- if(!flag){return res}
- res.push(line)
- rank++
- }
- }
- True=true
- False=false
- Boolean.prototype.__class__=bool
- Boolean.prototype.__eq__=function(other){
- if(this.valueOf()){return !!other}else{return !other}
- }
- Boolean.prototype.__getattr__=function(attr){
- if(this[attr]!==undefined){return this[attr]}
- else{throw AttributeError("'bool' object has no attribute '"+attr+"'")}
- }
- Boolean.prototype.__hash__=function(){
- if(this.valueOf())return 1
- return 0
- }
- Boolean.prototype.__mul__=function(other){
- if(this.valueOf())return other
- return 0
- }
- Boolean.prototype.__add__=function(other){
- if(this.valueOf())return other + 1
- return other
- }
- Boolean.prototype.toString=function(){
- if(this.valueOf())return "True"
- return "False"
- }
- Boolean.prototype.__str__=Boolean.prototype.toString
- function $NoneClass(){
- this.__class__=new $class(this,"NoneType")
- this.value=null
- this.__bool__=function(){return False}
- this.__eq__=function(other){return other===None}
- this.__getattr__=function(attr){
- if(this[attr]!==undefined){return this[attr]}
- else{throw AttributeError("'NoneType' object has no attribute '"+attr+"'")}
- }
- this.__hash__=function(){return 0}
- this.__ne__=function(other){return other!==None}
- this.__str__=function(){return 'None'}
- var comp_ops=['ge','gt','le','lt']
- for(var key in $comps){
- if(comp_ops.indexOf($comps[key])>-1){
- this['__'+$comps[key]+'__']=(function(k){
- return function(other){
- throw TypeError("unorderable types: NoneType() "+$comps[k]+" "+
- other.__class__.__name__)}
- })(key)
- }
- }
- for(var func in this){
- if(typeof this[func]==='function'){
- this[func].__str__=(function(f){
- return function(){return "<mthod-wrapper "+f+" of NoneType object>"}
- })(func)
- }
- }
- }
- None=new $NoneClass()
- Exception=function(msg){
- var err=Error()
- err.info=''
- if(document.$debug && msg.split('\n').length==1){
- var module=document.$line_info[1]
- var line_num=document.$line_info[0]
- var lines=document.$py_src[module].split('\n')
- err.info +="\nmodule '"+module+"' line "+line_num
- err.info +='\n'+lines[line_num-1]
- }
- err.message=msg + err.info
- err.args=tuple(msg.split('\n')[0])
- err.__str__=function(){return msg}
- err.toString=err.__str__
- err.__getattr__=function(attr){return this[attr]}
- err.__name__='Exception'
- err.__class__=Exception
- err.py_error=true
- __BRYTHON__.exception_stack.push(err)
- return err
- }
- Exception.__str__=function(){return "<class 'Exception'>"}
- Exception.__class__=$type
- function $make_exc(name){
- var $exc=(Exception+'').replace(/Exception/g,name)
- eval(name+'='+$exc)
- eval(name+'.__str__ = function(){return "<class '+"'"+name+"'"+'>"}')
- eval(name+'.__class__=$type')
- }
- var $errors=['AssertionError','AttributeError','EOFError','FloatingPointError',
- 'GeneratorExit','ImportError','IndexError','KeyError','KeyboardInterrupt',
- 'NameError','NotImplementedError','OSError','OverflowError','ReferenceError',
- 'RuntimeError','StopIteration','SyntaxError','IndentationError','TabError',
- 'SystemError','SystemExit','TypeError','UnboundLocalError','ValueError',
- 'ZeroDivisionError','IOError']
- for(var i=0;i<$errors.length;i++){$make_exc($errors[i])}
- list=function(){
- function $list(){
- var args=new Array()
- for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
- return new $ListClass(args)
- }
- function list(){
- if(arguments.length===0){return[]}
- else if(arguments.length>1){
- throw TypeError("list() takes at most 1 argument ("+arguments.length+" given)")
- }
- var res=[]
- list.__init__(res,arguments[0])
- return res
- }
- list.__add__=function(self,other){
- var res=self.valueOf().concat(other.valueOf())
- if(isinstance(self,tuple)){res=tuple.apply(self,res)}
- return res
- }
- list.__class__=$type
- list.__contains__=function(self,item){
- for(var i=0;i<self.length;i++){
- try{if(self[i].__eq__(item)){return true}
- }catch(err){void(0)}
- }
- return false
- }
- list.__delitem__=function(self,arg){
- if(isinstance(arg,int)){
- var pos=arg
- if(arg<0){pos=self.length+pos}
- if(pos>=0 && pos<self.length){
- self.splice(pos,1)
- return
- }
- else{throw IndexError('list index out of range')}
- }else if(isinstance(arg,slice)){
- var start=arg.start || 0
- var stop=arg.stop || self.length
- var step=arg.step || 1
- if(start<0){start=self.length+start}
- if(stop<0){stop=self.length+stop}
- var res=[],i=null
- if(step>0){
- if(stop>start){
- for(i=start;i<stop;i+=step){
- if(self[i]!==undefined){res.push(i)}
- }
- }
- }else{
- if(stop<start){
- for(i=start;i>stop;i+=step.value){
- if(self[i]!==undefined){res.push(i)}
- }
- res.reverse()
- }
- }
- for(var i=res.length-1;i>=0;i--){
- self.splice(res[i],1)
- }
- return
- }else{
- throw TypeError('list indices must be integer, not '+str(arg.__class__))
- }
- }
- list.__eq__=function(self,other){
- if(other===undefined){
- return self===list
- }
- if(isinstance(other,self.__class__)){
- if(other.length==self.length){
- for(var i=0;i<self.length;i++){
- if(!self[i].__eq__(other[i])){return False}
- }
- return True
- }
- }
- return False
- }
- list.__getattr__=function(attr){
- switch(attr){
- case '__class__':
- var res=function(){return list}
- res.__str__=list.__str__
- return res
- case '__name__':
- var res=function(){
- throw AttributeError(" 'list' object has no attribute '__name__'")
- }
- res.__str__=function(){return 'list'}
- return res
- default:
- return list[attr]
- }
- }
- list.__getitem__=function(self,arg){
- if(isinstance(arg,int)){
- var items=self.valueOf()
- var pos=arg
- if(arg<0){pos=items.length+pos}
- if(pos>=0 && pos<items.length){return items[pos]}
- else{
- throw IndexError('list index out of range')
- }
- }else if(isinstance(arg,slice)){
- var step=arg.step===None ? 1 : arg.step
- if(step>0){
- var start=arg.start===None ? 0 : arg.start
- var stop=arg.stop===None ? self.__len__(): arg.stop
- }else{
- var start=arg.start===None ? self.__len__()-1 : arg.start
- var stop=arg.stop===None ? 0 : arg.stop
- }
- if(start<0){start=int(self.length+start)}
- if(stop<0){stop=self.length+stop}
- var res=[],i=null,items=self.valueOf()
- if(step>0){
- if(stop<=start){return res}
- else{
- for(i=start;i<stop;i+=step){
- if(items[i]!==undefined){res.push(items[i])}
- }
- return res
- }
- }else{
- if(stop>=start){return res}
- else{
- for(i=start;i>=stop;i+=step){
- if(items[i]!==undefined){res.push(items[i])}
- }
- return res
- }
- }
- }else if(isinstance(arg,bool)){
- return self.__getitem__(int(arg))
- }else{
- throw TypeError('list indices must be integer, not '+str(arg.__class__))
- }
- }
- list.__hash__=function(self){throw TypeError("unhashable type: 'list'")}
- list.__in__=function(self,item){return item.__contains__(self)}
- list.__init__=function(self){
- while(self.__len__()>0){self.pop()}
- if(arguments.length===1){return}
- var arg=arguments[1]
- for(var i=0;i<arg.__len__();i++){self.push(arg.__item__(i))}
- }
- list.__item__=function(self,i){return self[i]}
- list.__len__=function(self){return self.length}
- list.__mul__=function(self,other){
- if(isinstance(other,int)){return other.__mul__(self)}
- else{throw TypeError("can't multiply sequence by non-int of type '"+other.__name+"'")}
- }
- list.__name__='list'
- list.__ne__=function(self,other){return !self.__eq__(other)}
- list.__next__=function(self){
- if(self.iter===null){self.iter=0}
- if(self.iter<self.valueOf().length){
- self.iter++
- return self.valueOf()[self.iter-1]
- }else{
- self.iter=null
- throw StopIteration('')
- }
- }
- list.__not_in__=function(self,item){return !item.__contains__(self)}
- list.__setitem__=function(self,arg,value){
- if(isinstance(arg,int)){
- var pos=arg
- if(arg<0){pos=self.length+pos}
- if(pos>=0 && pos<self.length){self[pos]=value}
- else{throw IndexError('list index out of range')}
- }else if(isinstance(arg,slice)){
- var start=arg.start===None ? 0 : arg.start
- var stop=arg.stop===None ? self.__len__(): arg.stop
- var step=arg.step===None ? 1 : arg.step
- if(start<0){start=self.length+start}
- if(stop<0){stop=self.length+stop}
- self.splice(start,stop-start)
- if(hasattr(value,'__item__')){
- var $temp=list(value)
- for(var i=$temp.length-1;i>=0;i--){
- self.splice(start,0,$temp[i])
- }
- }else{
- throw TypeError("can only assign an iterable")
- }
- }else{
- throw TypeError('list indices must be integer, not '+str(arg.__class__))
- }
- }
- list.__str__=function(self){
- if(self===undefined){return "<class 'list'>"}
- var res="[",items=self.valueOf()
- for(var i=0;i<self.length;i++){
- var x=self[i]
- if(isinstance(x,str)){res +="'"+x+"'"}
- else if(x['__str__']!==undefined){res +=x.__str__()}
- else{res +=x.toString()}
- if(i<self.length-1){res +=','}
- }
- return res+']'
- }
- list.append=function(self,other){self.push(other)}
- list.count=function(self,elt){
- var res=0
- for(var i=0;i<self.length;i++){
- if(self[i].__eq__(elt)){res++}
- }
- return res
- }
- list.extend=function(self,other){
- if(arguments.length!=2){throw TypeError(
- "extend() takes exactly one argument ("+arguments.length+" given)")}
- try{
- for(var i=0;i<other.__len__();i++){self.push(other.__item__(i))}
- }catch(err){
- throw TypeError("object is not iterable")
- }
- }
- list.index=function(self,elt){
- for(var i=0;i<self.length;i++){
- if(self[i].__eq__(elt)){return i}
- }
- throw ValueError(str(elt)+" is not in list")
- }
- list.insert=function(self,i,item){self.splice(i,0,item)}
- list.remove=function(self,elt){
- for(var i=0;i<self.length;i++){
- if(self[i].__eq__(elt)){
- self.splice(i,1)
- return
- }
- }
- throw ValueError(str(elt)+" is not in list")
- }
- list.pop=function(self,pos){
- if(pos===undefined){
- var res=self[self.length-1]
- self.splice(self.length-1,1)
- return res
- }else if(arguments.length==2){
- if(isinstance(pos,int)){
- var res=self[pos]
- self.splice(pos,1)
- return res
- }else{
- throw TypeError(pos.__class__+" object cannot be interpreted as an integer")
- }
- }else{
- throw TypeError("pop() takes at most 1 argument ("+(arguments.length-1)+' given)')
- }
- }
- list.reverse=function(self){
- for(var i=0;i<parseInt(self.length/2);i++){
- var buf=self[i]
- self[i]=self[self.length-i-1]
- self[self.length-i-1]=buf
- }
- }
- function $partition(arg,array,begin,end,pivot)
- {
- var piv=array[pivot]
- array.swap(pivot, end-1)
- var store=begin
- for(var ix=begin;ix<end-1;++ix){
- if(arg(array[ix]).__le__(arg(piv))){
- array.swap(store, ix)
- ++store
- }
- }
- array.swap(end-1, store)
- return store
- }
- Array.prototype.swap=function(a, b)
- {
- var tmp=this[a]
- this[a]=this[b]
- this[b]=tmp
- }
- function $qsort(arg,array, begin, end)
- {
- if(end-1>begin){
- 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)
- }
- }
- list.sort=function(self){
- var func=function(x){return x}
- var reverse=false
- for(var i=1;i<arguments.length;i++){
- var arg=arguments[i]
- if(isinstance(arg,$Kw)){
- if(arg.name==='key'){func=arg.value}
- else if(arg.name==='reverse'){reverse=arg.value}
- }
- }
- if(self.length==0){return}
- $qsort(func,self,0,self.length)
- if(reverse){list.reverse(self)}
- }
- list.toString=list.__str__
- function $ListClass(items){
- var x=null,i=null
- this.iter=null
- this.__class__=list
- this.items=items
- }
- for(var attr in list){
- if(typeof list[attr]==='function'){list[attr].__str__=function(){return "<list method "+attr+">"}}
- var func=(function(attr){
- return function(){
- var args=[this]
- for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
- return list[attr].apply(this,args)
- }
- })(attr)
- func.__str__=(function(attr){
- return function(){return "<method-wrapper '"+attr+"' of list object>"}
- })(attr)
- Array.prototype[attr]=func
- }
- Array.prototype.__class__=list
- Array.prototype.__getattr__=function(attr){
- if(attr==='__class__'){return this.__class__}
- if(list[attr]===undefined){
- throw AttributeError("'"+this.__class__.__name__+"' object has no attribute '"+attr+"'")
- }
- var obj=this
- var res=function(){
- var args=[obj]
- for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
- return list[attr].apply(obj,args)
- }
- res.__str__=function(){return "<built-in method "+attr+" of "+this.__class__.__name__+" object>"}
- return res
- }
- return list
- }()
- str=function(){
- function str(arg){
- if(arg===undefined){return '<undefined>'}
- else if(arg.__str__!==undefined){return arg.__str__()}
- else if(arg.__getattr__('__str__')!==undefined){
- return arg.__getattr__('__str__')()
- }else{return arg.toString()}
- }
- str.__name__='str'
- str.__str__=function(){return "<class 'str'>"}
- str.toString=str.__str__
- str.__add__=function(self,other){
- if(!(typeof other==="string")){
- try{return other.__radd__(self)}
- catch(err){throw TypeError(
- "Can't convert "+other.__class__+" to str implicitely")}
- }else{
- return self+other
- }
- }
- str.__class__=$type
- str.__contains__=function(self,item){
- if(!(typeof item==="string")){throw TypeError(
- "'in <string>' requires string as left operand, not "+item.__class__)}
- var nbcar=item.length
- for(var i=0;i<self.length;i++){
- if(self.substr(i,nbcar)==item){return True}
- }
- return False
- }
- str.__eq__=function(self,other){
- if(other===undefined){
- return self===str
- }
- return other===self.valueOf()
- }
- str.__getattr__=function(attr){return this[attr]}
- str.__getitem__=function(self,arg){
- if(isinstance(arg,int)){
- var pos=arg
- if(arg<0){pos=self.length+pos}
- if(pos>=0 && pos<self.length){return self.charAt(pos)}
- else{throw IndexError('string index out of range')}
- }else if(isinstance(arg,slice)){
- var step=arg.step===None ? 1 : arg.step
- if(step>0){
- var start=arg.start===None ? 0 : arg.start
- var stop=arg.stop===None ? self.__len__(): arg.stop
- }else{
- var start=arg.start===None ? self.__len__()-1 : arg.start
- var stop=arg.stop===None ? 0 : arg.stop
- }
- if(start<0){start=self.length+start}
- if(stop<0){stop=self.length+stop}
- var res='',i=null
- if(step>0){
- if(stop<=start){return ''}
- else{
- for(i=start;i<stop;i+=step){
- res +=self.charAt(i)
- }
- }
- }else{
- if(stop>=start){return ''}
- else{
- for(i=start;i>=stop;i+=step){
- res +=self.charAt(i)
- }
- }
- }
- return res
- }else if(isinstance(arg,bool)){
- return self.__getitem__(int(arg))
- }
- }
- str.__hash__=function(self){
- var hash=1
- for(var i=0;i < self.length;i++){
- hash=(101*hash + self.charCodeAt(i))& 0xFFFFFFFF
- }
- return hash
- }
- str.__in__=function(self,item){return item.__contains__(self.valueOf())}
- str.__item__=function(self,i){return self.charAt(i)}
- str.__len__=function(self){return self.length}
- str.__mod__=function(self,args){
- var flags=$List2Dict('#','0','-',' ','+')
- var ph=[]
- function format(s){
- var conv_flags='([#\\+\\- 0])*'
- var conv_types='[diouxXeEfFgGcrsa%]'
- var re=new RegExp('\\%(\\(.+\\))*'+conv_flags+'(\\*|\\d*)(\\.\\*|\\.\\d*)*(h|l|L)*('+conv_types+'){1}')
- var res=re.exec(s)
- this.is_format=true
- if(!res){this.is_format=false;return}
- this.src=res[0]
- if(res[1]){this.mapping_key=str(res[1].substr(1,res[1].length-2))}
- else{this.mapping_key=null}
- this.flag=res[2]
- this.min_width=res[3]
- this.precision=res[4]
- this.length_modifier=res[5]
- this.type=res[6]
- this.toString=function(){
- var res='type '+this.type+' key '+this.mapping_key+' min width '+this.min_width
- res +=' precision '+this.precision
- return res
- }
- this.format=function(src){
- if(this.mapping_key!==null){
- if(!isinstance(src,dict)){throw TypeError("format requires a mapping")}
- src=src.__getitem__(this.mapping_key)
- }
- if(this.type=="s"){return str(src)}
- else if(this.type=="i" || this.type=="d"){
- if(!isinstance(src,[int,float])){throw TypeError(
- "%"+this.type+" format : a number is required, not "+str(src.__class__))}
- return str(int(src))
- }else if(this.type=="f" || this.type=="F"){
- if(!isinstance(src,[int,float])){throw TypeError(
- "%"+this.type+" format : a number is required, not "+str(src.__class__))}
- return str(float(src))
- }
- }
- }
- var elts=[]
- var pos=0, start=0, nb_repl=0
- var val=self.valueOf()
- while(pos<val.length){
- if(val.charAt(pos)=='%'){
- var f=new format(val.substr(pos))
- if(f.is_format && f.type!=="%"){
- elts.push(val.substring(start,pos))
- elts.push(f)
- start=pos+f.src.length
- pos=start
- nb_repl++
- }else{pos++}
- }else{pos++}
- }
- elts.push(val.substr(start))
- if(!isinstance(args,tuple)){
- if(nb_repl>1){throw TypeError('not enough arguments for format string')}
- else{elts[1]=elts[1].format(args)}
- }else{
- if(nb_repl==args.length){
- for(var i=0;i<args.length;i++){
- var fmt=elts[1+2*i]
- elts[1+2*i]=fmt.format(args[i])
- }
- }else if(nb_repl<args.length){throw TypeError(
- "not all arguments converted during string formatting")
- }else{throw TypeError('not enough arguments for format string')}
- }
- var res=''
- for(var i=0;i<elts.length;i++){res+=elts[i]}
- res=res.replace(/%%/g,'%')
- return res
- }
- str.__mul__=function(self,other){
- if(!isinstance(other,int)){throw TypeError(
- "Can't multiply sequence by non-int of type '"+str(other.__class__)+"'")}
- $res=''
- for(var i=0;i<other;i++){$res+=self.valueOf()}
- return $res
- }
- str.__ne__=function(self,other){return other!==self.valueOf()}
- str.__next__=function(self){
- if(self.iter==null){self.iter==0}
- if(self.iter<self.value.length){
- self.iter++
- return str(self.value.charAt(self.iter-1))
- }else{
- self.iter=null
- throw StopIteration()
- }
- }
- str.__not_in__=function(self,item){return !item.__contains__(self.valueOf())}
- str.__setattr__=function(self,attr,value){setattr(self,attr,value)}
- self.__setitem__=function(self,attr,value){
- throw TypeError("'str' object does not support item assignment")
- }
- str.__str__=function(self){
- if(self===undefined){return "<class 'str'>"}
- else{return self.toString()}
- }
- var $comp_func=function(self,other){
- if(typeof other !=="string"){throw TypeError(
- "unorderable types: 'str' > "+other.__class__+"()")}
- return self > other
- }
- $comp_func +=''
- var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le'}
- for($op in $comps){
- eval("str.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
- }
- var $notimplemented=function(self,other){
- throw TypeError(
- "unsupported operand types for OPERATOR: '"+str(self.__class__)+"' and '"+str(other.__class__)+"'")
- }
- $notimplemented +=''
- for($op in $operators){
- var $opfunc='__'+$operators[$op]+'__'
- if(!($opfunc in str)){
- eval('str.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
- }
- }
- str.capitalize=function(self){
- if(self.length==0){return ''}
- return self.charAt(0).toUpperCase()+self.substr(1).toLowerCase()
- }
- str.center=function(self,width,fillchar){
- if(fillchar===undefined){fillchar=' '}else{fillchar=fillchar}
- if(width<=self.length){return self}
- else{
- var pad=parseInt((width-self.length)/2)
- res=''
- for(var i=0;i<pad;i++){res+=fillchar}
- res +=self
- for(var i=0;i<pad;i++){res+=fillchar}
- if(res.length<width){res +=fillchar}
- return res
- }
- }
- str.count=function(self,elt){
- if(!(typeof elt==="string")){throw TypeError(
- "Can't convert '"+str(elt.__class__)+"' object to str implicitly")}
- var res=0
- for(var i=0;i<self.length-elt.length+1;i++){
- if(self.substr(i,elt.length)===elt){res++}
- }
- return res
- }
- str.endswith=function(self){
- var args=[]
- for(var i=1;i<arguments.length;i++){args.push(arguments[i])}
- var $ns=$MakeArgs("str.endswith",args,['suffix'],
- {'start':null,'end':null},null,null)
- var suffixes=$ns['suffix']
- if(!isinstance(suffixes,tuple)){suffixes=[suffixes]}
- var start=$ns['start']|| 0
- var end=$ns['end']|| self.length-1
- var s=self.substr(start,end+1)
- for(var i=0;i<suffixes.length;i++){
- suffix=suffixes[i]
- if(suffix.length<=s.length &&
- s.substr(s.length-suffix.length)==suffix){return True}
- }
- return False
- }
- str.find=function(self){
- var $ns=$MakeArgs("str.find",arguments,['self','sub'],
- {'start':0,'end':self.length},null,null)
- var sub=$ns['sub'],start=$ns['start'],end=$ns['end']
- if(!isinstance(sub,str)){throw TypeError(
- "Can't convert '"+str(sub.__class__)+"' object to str implicitly")}
- if(!isinstance(start,int)||!isinstance(end,int)){throw TypeError(
- "slice indices must be integers or None or have an __index__ method")}
- var s=self.substring(start,end)
- var escaped=list("[.*+?|()$^")
- var esc_sub=''
- for(var i=0;i<sub.length;i++){
- if(escaped.indexOf(sub.charAt(i))>-1){esc_sub +='\\'}
- esc_sub +=sub.charAt(i)
- }
- var res=s.search(esc_sub)
- if(res==-1){return -1}
- else{return start+res}
- }
- str.index=function(self){
- var res=str.find.apply(self,arguments)
- if(res===-1){throw ValueError("substring not found")}
- else{return res}
- }
- str.join=function(self,iterable){
- if(!'__item__' in iterable){throw TypeError(
- "'"+str(iterable.__class__)+"' object is not iterable")}
- var res='',count=0
- for(var i=0;i<iterable.length;i++){
- var obj2=iterable.__getitem__(i)
- if(!isinstance(obj2,str)){throw TypeError(
- "sequence item "+count+": expected str instance, "+obj2.__class__+"found")}
- res +=obj2+self
- count++
- }
- if(count==0){return ''}
- res=res.substr(0,res.length-self.length)
- return res
- }
- str.lower=function(self){return self.toLowerCase()}
- str.lstrip=function(self,x){
- var pattern=null
- if(x==undefined){pattern="\\s*"}
- else{pattern="["+x+"]*"}
- var sp=new RegExp("^"+pattern)
- return self.replace(sp,"")
- }
- function $re_escape(str)
- {
- var specials="[.*+?|()$^"
- for(var i=0;i<specials.length;i++){
- var re=new RegExp('\\'+specials.charAt(i),'g')
- str=str.replace(re, "\\"+specials.charAt(i))
- }
- return str
- }
- str.replace=function(self,old,_new,count){
- if(count!==undefined){
- if(!isinstance(count,[int,float])){throw TypeError(
- "'"+str(count.__class__)+"' object cannot be interpreted as an integer")}
- var re=new RegExp($re_escape(old),'g')
- var res=self.valueOf()
- while(count>0){
- if(self.search(re)==-1){return res}
- res=res.replace(re,_new)
- count--
- }
- return res
- }else{
- var re=new RegExp($re_escape(old),"g")
- return self.replace(re,_new)
- }
- }
- str.rfind=function(self){
- var $ns=$MakeArgs("str.find",arguments,['self','sub'],
- {'start':0,'end':self.length},null,null)
- var sub=$ns['sub'],start=$ns['start'],end=$ns['end']
- if(!isinstance(sub,str)){throw TypeError(
- "Can't convert '"+str(sub.__class__)+"' object to str implicitly")}
- if(!isinstance(start,int)||!isinstance(end,int)){throw TypeError(
- "slice indices must be integers or None or have an __index__ method")}
- var s=self.substring(start,end)
- var reversed=''
- for(var i=s.length-1;i>=0;i--){reversed +=s.charAt(i)}
- var res=reversed.search(sub)
- if(res==-1){return -1}
- else{return start+s.length…
Large files files are truncated, but you can click here to view the full file