idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
43,400 | def getOid ( self ) : if self . _state & self . ST_CLEAN : return self . _oid else : raise SmiError ( '%s object not fully initialized' % self . __class__ . __name__ ) | Returns OID identifying MIB variable . |
43,401 | def getLabel ( self ) : if self . _state & self . ST_CLEAN : return self . _label else : raise SmiError ( '%s object not fully initialized' % self . __class__ . __name__ ) | Returns symbolic path to this MIB variable . |
43,402 | def addMibSource ( self , * mibSources ) : if self . _mibSourcesToAdd is None : self . _mibSourcesToAdd = mibSources else : self . _mibSourcesToAdd += mibSources return self | Adds path to repository to search PySNMP MIB files . |
43,403 | def loadMibs ( self , * modNames ) : if self . _modNamesToLoad is None : self . _modNamesToLoad = modNames else : self . _modNamesToLoad += modNames return self | Schedules search and load of given MIB modules . |
43,404 | def resolveWithMib ( self , mibViewController ) : if self . _state & self . ST_CLEAM : return self self . _args [ 0 ] . resolveWithMib ( mibViewController ) MibScalar , MibTableColumn = mibViewController . mibBuilder . importSymbols ( 'SNMPv2-SMI' , 'MibScalar' , 'MibTableColumn' ) if not isinstance ( self . _args [ 0 ] . getMibNode ( ) , ( MibScalar , MibTableColumn ) ) : if not isinstance ( self . _args [ 1 ] , AbstractSimpleAsn1Item ) : raise SmiError ( 'MIB object %r is not OBJECT-TYPE ' '(MIB not loaded?)' % ( self . _args [ 0 ] , ) ) self . _state |= self . ST_CLEAM return self if isinstance ( self . _args [ 1 ] , ( rfc1905 . UnSpecified , rfc1905 . NoSuchObject , rfc1905 . NoSuchInstance , rfc1905 . EndOfMibView ) ) : self . _state |= self . ST_CLEAM return self syntax = self . _args [ 0 ] . getMibNode ( ) . getSyntax ( ) try : self . _args [ 1 ] = syntax . clone ( self . _args [ 1 ] ) except PyAsn1Error as exc : raise SmiError ( 'MIB object %r having type %r failed to cast value ' '%r: %s' % ( self . _args [ 0 ] . prettyPrint ( ) , syntax . __class__ . __name__ , self . _args [ 1 ] , exc ) ) if rfc1902 . ObjectIdentifier ( ) . isSuperTypeOf ( self . _args [ 1 ] , matchConstraints = False ) : self . _args [ 1 ] = ObjectIdentity ( self . _args [ 1 ] ) . resolveWithMib ( mibViewController ) self . _state |= self . ST_CLEAM debug . logger & debug . FLAG_MIB and debug . logger ( 'resolved %r syntax is %r' % ( self . _args [ 0 ] , self . _args [ 1 ] ) ) return self | Perform MIB variable ID and associated value conversion . |
43,405 | def addVarBinds ( self , * varBinds ) : debug . logger & debug . FLAG_MIB and debug . logger ( 'additional var-binds: %r' % ( varBinds , ) ) if self . _state & self . ST_CLEAN : raise SmiError ( '%s object is already sealed' % self . __class__ . __name__ ) else : self . _additionalVarBinds . extend ( varBinds ) return self | Appends variable - binding to notification . |
43,406 | def resolveWithMib ( self , mibViewController ) : if self . _state & self . ST_CLEAN : return self self . _objectIdentity . resolveWithMib ( mibViewController ) self . _varBinds . append ( ObjectType ( ObjectIdentity ( v2c . apiTrapPDU . snmpTrapOID ) , self . _objectIdentity ) . resolveWithMib ( mibViewController ) ) SmiNotificationType , = mibViewController . mibBuilder . importSymbols ( 'SNMPv2-SMI' , 'NotificationType' ) mibNode = self . _objectIdentity . getMibNode ( ) varBindsLocation = { } if isinstance ( mibNode , SmiNotificationType ) : for notificationObject in mibNode . getObjects ( ) : objectIdentity = ObjectIdentity ( * notificationObject + self . _instanceIndex ) objectIdentity . resolveWithMib ( mibViewController ) objectType = ObjectType ( objectIdentity , self . _objects . get ( notificationObject , rfc1905 . unSpecified ) ) objectType . resolveWithMib ( mibViewController ) self . _varBinds . append ( objectType ) varBindsLocation [ objectIdentity ] = len ( self . _varBinds ) - 1 else : debug . logger & debug . FLAG_MIB and debug . logger ( 'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not ' 'loaded?)' % ( self . _objectIdentity , ) ) for varBinds in self . _additionalVarBinds : if not isinstance ( varBinds , ObjectType ) : varBinds = ObjectType ( ObjectIdentity ( varBinds [ 0 ] ) , varBinds [ 1 ] ) varBinds . resolveWithMib ( mibViewController ) if varBinds [ 0 ] in varBindsLocation : self . _varBinds [ varBindsLocation [ varBinds [ 0 ] ] ] = varBinds else : self . _varBinds . append ( varBinds ) self . _additionalVarBinds = [ ] self . _state |= self . ST_CLEAN debug . logger & debug . FLAG_MIB and debug . logger ( 'resolved %r into %r' % ( self . _objectIdentity , self . _varBinds ) ) return self | Perform MIB variable ID conversion and notification objects expansion . |
43,407 | def withValues ( cls , * values ) : class X ( cls ) : subtypeSpec = cls . subtypeSpec + constraint . SingleValueConstraint ( * values ) X . __name__ = cls . __name__ return X | Creates a subclass with discreet values constraint . |
43,408 | def withRange ( cls , minimum , maximum ) : class X ( cls ) : subtypeSpec = cls . subtypeSpec + constraint . ValueRangeConstraint ( minimum , maximum ) X . __name__ = cls . __name__ return X | Creates a subclass with value range constraint . |
43,409 | def withNamedValues ( cls , ** values ) : enums = set ( cls . namedValues . items ( ) ) enums . update ( values . items ( ) ) class X ( cls ) : namedValues = namedval . NamedValues ( * enums ) subtypeSpec = cls . subtypeSpec + constraint . SingleValueConstraint ( * values . values ( ) ) X . __name__ = cls . __name__ return X | Create a subclass with discreet named values constraint . |
43,410 | def withSize ( cls , minimum , maximum ) : class X ( cls ) : subtypeSpec = cls . subtypeSpec + constraint . ValueSizeConstraint ( minimum , maximum ) X . __name__ = cls . __name__ return X | Creates a subclass with value size constraint . |
43,411 | def withNamedBits ( cls , ** values ) : enums = set ( cls . namedValues . items ( ) ) enums . update ( values . items ( ) ) class X ( cls ) : namedValues = namedval . NamedValues ( * enums ) X . __name__ = cls . __name__ return X | Creates a subclass with discreet named bits constraint . |
43,412 | def loadModule ( self , modName , ** userCtx ) : for mibSource in self . _mibSources : debug . logger & debug . FLAG_BLD and debug . logger ( 'loadModule: trying %s at %s' % ( modName , mibSource ) ) try : codeObj , sfx = mibSource . read ( modName ) except IOError as exc : debug . logger & debug . FLAG_BLD and debug . logger ( 'loadModule: read %s from %s failed: ' '%s' % ( modName , mibSource , exc ) ) continue modPath = mibSource . fullPath ( modName , sfx ) if modPath in self . _modPathsSeen : debug . logger & debug . FLAG_BLD and debug . logger ( 'loadModule: seen %s' % modPath ) break else : self . _modPathsSeen . add ( modPath ) debug . logger & debug . FLAG_BLD and debug . logger ( 'loadModule: evaluating %s' % modPath ) g = { 'mibBuilder' : self , 'userCtx' : userCtx } try : exec ( codeObj , g ) except Exception : self . _modPathsSeen . remove ( modPath ) raise error . MibLoadError ( 'MIB module "%s" load error: ' '%s' % ( modPath , traceback . format_exception ( * sys . exc_info ( ) ) ) ) self . _modSeen [ modName ] = modPath debug . logger & debug . FLAG_BLD and debug . logger ( 'loadModule: loaded %s' % modPath ) break if modName not in self . _modSeen : raise error . MibNotFoundError ( 'MIB file "%s" not found in search path ' '(%s)' % ( modName and modName + ".py[co]" , ', ' . join ( [ str ( x ) for x in self . _mibSources ] ) ) ) return self | Load and execute MIB modules as Python code |
43,413 | def nextCmd ( snmpDispatcher , authData , transportTarget , * varBinds , ** options ) : def cbFun ( * args , ** kwargs ) : response [ : ] = args + ( kwargs . get ( 'nextVarBinds' , ( ) ) , ) options [ 'cbFun' ] = cbFun lexicographicMode = options . pop ( 'lexicographicMode' , True ) maxRows = options . pop ( 'maxRows' , 0 ) maxCalls = options . pop ( 'maxCalls' , 0 ) initialVarBinds = VB_PROCESSOR . makeVarBinds ( snmpDispatcher . cache , varBinds ) totalRows = totalCalls = 0 errorIndication , errorStatus , errorIndex , varBindTable = None , 0 , 0 , ( ) response = [ ] while True : if not varBinds : yield ( errorIndication , errorStatus , errorIndex , varBindTable and varBindTable [ 0 ] or [ ] ) return cmdgen . nextCmd ( snmpDispatcher , authData , transportTarget , * [ ( x [ 0 ] , Null ( '' ) ) for x in varBinds ] , ** options ) snmpDispatcher . transportDispatcher . runDispatcher ( ) errorIndication , errorStatus , errorIndex , varBindTable , varBinds = response if errorIndication : yield ( errorIndication , errorStatus , errorIndex , varBindTable and varBindTable [ 0 ] or [ ] ) return elif errorStatus : if errorStatus == 2 : errorStatus = errorStatus . clone ( 0 ) errorIndex = errorIndex . clone ( 0 ) yield ( errorIndication , errorStatus , errorIndex , varBindTable and varBindTable [ 0 ] or [ ] ) return else : varBindRow = varBindTable and varBindTable [ - 1 ] if not lexicographicMode : for idx , varBind in enumerate ( varBindRow ) : name , val = varBind if not isinstance ( val , Null ) : if initialVarBinds [ idx ] [ 0 ] . isPrefixOf ( name ) : break else : return for varBindRow in varBindTable : nextVarBinds = ( yield errorIndication , errorStatus , errorIndex , varBindRow ) if nextVarBinds : initialVarBinds = varBinds = VB_PROCESSOR . makeVarBinds ( snmpDispatcher . cache , nextVarBinds ) totalRows += 1 totalCalls += 1 if maxRows and totalRows >= maxRows : return if maxCalls and totalCalls >= maxCalls : return | Create a generator to perform one or more SNMP GETNEXT queries . |
43,414 | def registerContextEngineId ( self , contextEngineId , pduTypes , processPdu ) : for pduType in pduTypes : k = contextEngineId , pduType if k in self . _appsRegistration : raise error . ProtocolError ( 'Duplicate registration %r/%s' % ( contextEngineId , pduType ) ) self . _appsRegistration [ k ] = processPdu debug . logger & debug . FLAG_DSP and debug . logger ( 'registerContextEngineId: contextEngineId %r pduTypes ' '%s' % ( contextEngineId , pduTypes ) ) | Register application with dispatcher |
43,415 | def unregisterContextEngineId ( self , contextEngineId , pduTypes ) : if contextEngineId is None : contextEngineId , = self . mibInstrumController . mibBuilder . importSymbols ( '__SNMP-FRAMEWORK-MIB' , 'snmpEngineID' ) for pduType in pduTypes : k = contextEngineId , pduType if k in self . _appsRegistration : del self . _appsRegistration [ k ] debug . logger & debug . FLAG_DSP and debug . logger ( 'unregisterContextEngineId: contextEngineId %r pduTypes ' '%s' % ( contextEngineId , pduTypes ) ) | Unregister application with dispatcher |
43,416 | def sendNotification ( snmpEngine , authData , transportTarget , contextData , notifyType , * varBinds , ** options ) : def __cbFun ( snmpEngine , sendRequestHandle , errorIndication , errorStatus , errorIndex , varBinds , cbCtx ) : lookupMib , deferred = cbCtx if errorIndication : deferred . errback ( Failure ( errorIndication ) ) else : try : varBinds = VB_PROCESSOR . unmakeVarBinds ( snmpEngine . cache , varBinds , lookupMib ) except Exception as e : deferred . errback ( Failure ( e ) ) else : deferred . callback ( ( errorStatus , errorIndex , varBinds ) ) notifyName = LCD . configure ( snmpEngine , authData , transportTarget , notifyType , contextData . contextName ) def __trapFun ( deferred ) : deferred . callback ( ( 0 , 0 , [ ] ) ) varBinds = VB_PROCESSOR . makeVarBinds ( snmpEngine . cache , varBinds ) deferred = Deferred ( ) ntforg . NotificationOriginator ( ) . sendVarBinds ( snmpEngine , notifyName , contextData . contextEngineId , contextData . contextName , varBinds , __cbFun , ( options . get ( 'lookupMib' , True ) , deferred ) ) if notifyType == 'trap' : reactor . callLater ( 0 , __trapFun , deferred ) return deferred | Sends SNMP notification . |
43,417 | def nextCmd ( snmpEngine , authData , transportTarget , contextData , * varBinds , ** options ) : def __cbFun ( snmpEngine , sendRequestHandle , errorIndication , errorStatus , errorIndex , varBindTable , cbCtx ) : lookupMib , deferred = cbCtx if ( options . get ( 'ignoreNonIncreasingOid' , False ) and errorIndication and isinstance ( errorIndication , errind . OidNotIncreasing ) ) : errorIndication = None if errorIndication : deferred . errback ( Failure ( errorIndication ) ) else : try : varBindTable = [ VB_PROCESSOR . unmakeVarBinds ( snmpEngine . cache , varBindTableRow , lookupMib ) for varBindTableRow in varBindTable ] except Exception as e : deferred . errback ( Failure ( e ) ) else : deferred . callback ( ( errorStatus , errorIndex , varBindTable ) ) addrName , paramsName = LCD . configure ( snmpEngine , authData , transportTarget , contextData . contextName ) varBinds = VB_PROCESSOR . makeVarBinds ( snmpEngine . cache , varBinds ) deferred = Deferred ( ) cmdgen . NextCommandGenerator ( ) . sendVarBinds ( snmpEngine , addrName , contextData . contextEngineId , contextData . contextName , varBinds , __cbFun , ( options . get ( 'lookupMib' , True ) , deferred ) ) return deferred | Performs SNMP GETNEXT query . |
43,418 | def getBranch ( self , name , ** context ) : for keyLen in self . _vars . getKeysLens ( ) : subName = name [ : keyLen ] if subName in self . _vars : return self . _vars [ subName ] raise error . NoSuchObjectError ( name = name , idx = context . get ( 'idx' ) ) | Return a branch of this tree where the name OID may reside |
43,419 | def getNode ( self , name , ** context ) : if name == self . name : return self else : return self . getBranch ( name , ** context ) . getNode ( name , ** context ) | Return tree node found by name |
43,420 | def getNextNode ( self , name , ** context ) : try : nextNode = self . getBranch ( name , ** context ) except ( error . NoSuchInstanceError , error . NoSuchObjectError ) : return self . getNextBranch ( name , ** context ) else : try : return nextNode . getNextNode ( name , ** context ) except ( error . NoSuchInstanceError , error . NoSuchObjectError ) : try : return self . _vars [ self . _vars . nextKey ( nextNode . name ) ] except KeyError : raise error . NoSuchObjectError ( name = name , idx = context . get ( 'idx' ) ) | Return tree node next to name |
43,421 | def writeCommit ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: writeCommit(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY : { } } ) idx = context [ 'idx' ] if idx in instances [ self . ST_CREATE ] : self . createCommit ( varBind , ** context ) return if idx in instances [ self . ST_DESTROY ] : self . destroyCommit ( varBind , ** context ) return try : node = self . getBranch ( name , ** context ) except ( error . NoSuchInstanceError , error . NoSuchObjectError ) as exc : cbFun ( varBind , ** dict ( context , error = exc ) ) else : node . writeCommit ( varBind , ** context ) | Commit new value of the Managed Object Instance . |
43,422 | def readGet ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: readGet(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] if name == self . name : cbFun ( ( name , exval . noSuchInstance ) , ** context ) return acFun = context . get ( 'acFun' ) if acFun : if ( self . maxAccess not in ( 'readonly' , 'readwrite' , 'readcreate' ) or acFun ( 'read' , ( name , self . syntax ) , ** context ) ) : cbFun ( ( name , exval . noSuchInstance ) , ** context ) return ManagedMibObject . readGet ( self , varBind , ** context ) | Read Managed Object Instance . |
43,423 | def readGetNext ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: readGetNext(%s, %r)' % ( self , name , val ) ) ) acFun = context . get ( 'acFun' ) if acFun : if ( self . maxAccess not in ( 'readonly' , 'readwrite' , 'readcreate' ) or acFun ( 'read' , ( name , self . syntax ) , ** context ) ) : nextName = context . get ( 'nextName' ) if nextName : varBind = nextName , exval . noSuchInstance else : varBind = name , exval . endOfMibView cbFun = context [ 'cbFun' ] cbFun ( varBind , ** context ) return ManagedMibObject . readGetNext ( self , varBind , ** context ) | Read the next Managed Object Instance . |
43,424 | def createCommit ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: writeCommit(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY : { } } ) idx = context [ 'idx' ] if name in self . _vars : cbFun ( varBind , ** context ) return self . _vars [ name ] , instances [ self . ST_CREATE ] [ - idx - 1 ] = instances [ self . ST_CREATE ] [ idx ] , self . _vars . get ( name ) instances [ self . ST_CREATE ] [ idx ] . writeCommit ( varBind , ** context ) | Create Managed Object Instance . |
43,425 | def createCleanup ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: createCleanup(%s, %r)' % ( self , name , val ) ) ) instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY : { } } ) idx = context [ 'idx' ] self . branchVersionId += 1 instances [ self . ST_CREATE ] . pop ( - idx - 1 , None ) self . _vars [ name ] . writeCleanup ( varBind , ** context ) | Finalize Managed Object Instance creation . |
43,426 | def destroyCommit ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: destroyCommit(%s, %r)' % ( self , name , val ) ) ) instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY : { } } ) idx = context [ 'idx' ] try : instances [ self . ST_DESTROY ] [ - idx - 1 ] = self . _vars . pop ( name ) except KeyError : pass cbFun = context [ 'cbFun' ] cbFun ( varBind , ** context ) | Destroy Managed Object Instance . |
43,427 | def oidToValue ( self , syntax , identifier , impliedFlag = False , parentIndices = None ) : if not identifier : raise error . SmiError ( 'Short OID for index %r' % ( syntax , ) ) if hasattr ( syntax , 'cloneFromName' ) : return syntax . cloneFromName ( identifier , impliedFlag , parentRow = self , parentIndices = parentIndices ) baseTag = syntax . getTagSet ( ) . getBaseTag ( ) if baseTag == Integer . tagSet . getBaseTag ( ) : return syntax . clone ( identifier [ 0 ] ) , identifier [ 1 : ] elif IpAddress . tagSet . isSuperTagSetOf ( syntax . getTagSet ( ) ) : return syntax . clone ( '.' . join ( [ str ( x ) for x in identifier [ : 4 ] ] ) ) , identifier [ 4 : ] elif baseTag == OctetString . tagSet . getBaseTag ( ) : if impliedFlag : return syntax . clone ( tuple ( identifier ) ) , ( ) elif syntax . isFixedLength ( ) : l = syntax . getFixedLength ( ) return syntax . clone ( tuple ( identifier [ : l ] ) ) , identifier [ l : ] else : return syntax . clone ( tuple ( identifier [ 1 : identifier [ 0 ] + 1 ] ) ) , identifier [ identifier [ 0 ] + 1 : ] elif baseTag == ObjectIdentifier . tagSet . getBaseTag ( ) : if impliedFlag : return syntax . clone ( identifier ) , ( ) else : return syntax . clone ( identifier [ 1 : identifier [ 0 ] + 1 ] ) , identifier [ identifier [ 0 ] + 1 : ] elif baseTag == Bits . tagSet . getBaseTag ( ) : return syntax . clone ( tuple ( identifier [ 1 : identifier [ 0 ] + 1 ] ) ) , identifier [ identifier [ 0 ] + 1 : ] else : raise error . SmiError ( 'Unknown value type for index %r' % ( syntax , ) ) | Turn SMI table instance identifier into a value object . |
43,428 | def valueToOid ( self , value , impliedFlag = False , parentIndices = None ) : if hasattr ( value , 'cloneAsName' ) : return value . cloneAsName ( impliedFlag , parentRow = self , parentIndices = parentIndices ) baseTag = value . getTagSet ( ) . getBaseTag ( ) if baseTag == Integer . tagSet . getBaseTag ( ) : return int ( value ) , elif IpAddress . tagSet . isSuperTagSetOf ( value . getTagSet ( ) ) : return value . asNumbers ( ) elif baseTag == OctetString . tagSet . getBaseTag ( ) : if impliedFlag or value . isFixedLength ( ) : initial = ( ) else : initial = ( len ( value ) , ) return initial + value . asNumbers ( ) elif baseTag == ObjectIdentifier . tagSet . getBaseTag ( ) : if impliedFlag : return tuple ( value ) else : return ( len ( value ) , ) + tuple ( value ) elif baseTag == Bits . tagSet . getBaseTag ( ) : return ( len ( value ) , ) + value . asNumbers ( ) else : raise error . SmiError ( 'Unknown value type for index %r' % ( value , ) ) | Turn value object into SMI table instance identifier . |
43,429 | def announceManagementEvent ( self , action , varBind , ** context ) : name , val = varBind cbFun = context [ 'cbFun' ] if not self . _augmentingRows : cbFun ( varBind , ** context ) return instId = name [ len ( self . name ) + 1 : ] baseIndices = [ ] indices = [ ] for impliedFlag , modName , symName in self . _indexNames : mibObj , = mibBuilder . importSymbols ( modName , symName ) syntax , instId = self . oidToValue ( mibObj . syntax , instId , impliedFlag , indices ) if self . name == mibObj . name [ : - 1 ] : baseIndices . append ( ( mibObj . name , syntax ) ) indices . append ( syntax ) if instId : exc = error . SmiError ( 'Excessive instance identifier sub-OIDs left at %s: %s' % ( self , instId ) ) cbFun ( varBind , ** dict ( context , error = exc ) ) return if not baseIndices : cbFun ( varBind , ** context ) return count = [ len ( self . _augmentingRows ) ] def _cbFun ( varBind , ** context ) : count [ 0 ] -= 1 if not count [ 0 ] : cbFun ( varBind , ** context ) for modName , mibSym in self . _augmentingRows : mibObj , = mibBuilder . importSymbols ( modName , mibSym ) mibObj . receiveManagementEvent ( action , ( baseIndices , val ) , ** dict ( context , cbFun = _cbFun ) ) debug . logger & debug . FLAG_INS and debug . logger ( 'announceManagementEvent %s to %s' % ( action , mibObj ) ) | Announce mass operation on parent table s row . |
43,430 | def receiveManagementEvent ( self , action , varBind , ** context ) : baseIndices , val = varBind instId = ( ) for impliedFlag , modName , symName in self . _indexNames : mibObj , = mibBuilder . importSymbols ( modName , symName ) parentIndices = [ ] for name , syntax in baseIndices : if name == mibObj . name : instId += self . valueToOid ( syntax , impliedFlag , parentIndices ) parentIndices . append ( syntax ) if instId : debug . logger & debug . FLAG_INS and debug . logger ( 'receiveManagementEvent %s for suffix %s' % ( action , instId ) ) self . _manageColumns ( action , ( self . name + ( 0 , ) + instId , val ) , ** context ) | Apply mass operation on extending table s row . |
43,431 | def registerAugmentation ( self , * names ) : for name in names : if name in self . _augmentingRows : raise error . SmiError ( 'Row %s already augmented by %s::%s' % ( self . name , name [ 0 ] , name [ 1 ] ) ) self . _augmentingRows . add ( name ) return self | Register table extension . |
43,432 | def _manageColumns ( self , action , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: _manageColumns(%s, %s, %r)' % ( self , action , name , val ) ) ) cbFun = context [ 'cbFun' ] colLen = len ( self . name ) + 1 indexVals = { } instId = name [ colLen : ] indices = [ ] for impliedFlag , modName , symName in self . _indexNames : mibObj , = mibBuilder . importSymbols ( modName , symName ) syntax , instId = self . oidToValue ( mibObj . syntax , instId , impliedFlag , indices ) indexVals [ mibObj . name ] = syntax indices . append ( syntax ) count = [ len ( self . _vars ) ] if name [ : colLen ] in self . _vars : count [ 0 ] -= 1 def _cbFun ( varBind , ** context ) : count [ 0 ] -= 1 if not count [ 0 ] : cbFun ( varBind , ** context ) for colName , colObj in self . _vars . items ( ) : acFun = context . get ( 'acFun' ) if colName in indexVals : colInstanceValue = indexVals [ colName ] acFun = None elif name [ : colLen ] == colName : continue else : colInstanceValue = None actionFun = getattr ( colObj , action ) colInstanceName = colName + name [ colLen : ] actionFun ( ( colInstanceName , colInstanceValue ) , ** dict ( context , acFun = acFun , cbFun = _cbFun ) ) debug . logger & debug . FLAG_INS and debug . logger ( '_manageColumns: action %s name %s instance %s %svalue %r' % ( action , name , instId , name in indexVals and "index " or "" , indexVals . get ( name , val ) ) ) | Apply a management action on all columns |
43,433 | def _checkColumns ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: _checkColumns(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] if val != 1 : cbFun ( varBind , ** context ) return count = [ len ( self . _vars ) ] def _cbFun ( varBind , ** context ) : count [ 0 ] -= 1 name , val = varBind if count [ 0 ] >= 0 : exc = context . get ( 'error' ) if exc or not val . hasValue ( ) : count [ 0 ] = - 1 exc = error . InconsistentValueError ( msg = 'Inconsistent column %s: %s' % ( name , exc ) ) cbFun ( varBind , ** dict ( context , error = exc ) ) return if not count [ 0 ] : cbFun ( varBind , ** context ) return colLen = len ( self . name ) + 1 for colName , colObj in self . _vars . items ( ) : instName = colName + name [ colLen : ] colObj . readGet ( ( instName , None ) , ** dict ( context , cbFun = _cbFun ) ) debug . logger & debug . FLAG_INS and debug . logger ( '%s: _checkColumns: checking instance %s' % ( self , instName ) ) | Check the consistency of all columns . |
43,434 | def getIndicesFromInstId ( self , instId ) : if instId in self . _idToIdxCache : return self . _idToIdxCache [ instId ] indices = [ ] for impliedFlag , modName , symName in self . _indexNames : mibObj , = mibBuilder . importSymbols ( modName , symName ) try : syntax , instId = self . oidToValue ( mibObj . syntax , instId , impliedFlag , indices ) except PyAsn1Error as exc : debug . logger & debug . FLAG_INS and debug . logger ( 'error resolving table indices at %s, %s: %s' % ( self . __class__ . __name__ , instId , exc ) ) indices = [ instId ] instId = ( ) break indices . append ( syntax ) if instId : raise error . SmiError ( 'Excessive instance identifier sub-OIDs left at %s: %s' % ( self , instId ) ) indices = tuple ( indices ) self . _idToIdxCache [ instId ] = indices return indices | Return index values for instance identification |
43,435 | def getInstIdFromIndices ( self , * indices ) : try : return self . _idxToIdCache [ indices ] except TypeError : cacheable = False except KeyError : cacheable = True idx = 0 instId = ( ) parentIndices = [ ] for impliedFlag , modName , symName in self . _indexNames : if idx >= len ( indices ) : break mibObj , = mibBuilder . importSymbols ( modName , symName ) syntax = mibObj . syntax . clone ( indices [ idx ] ) instId += self . valueToOid ( syntax , impliedFlag , parentIndices ) parentIndices . append ( syntax ) idx += 1 if cacheable : self . _idxToIdCache [ indices ] = instId return instId | Return column instance identification from indices |
43,436 | def getInstNameByIndex ( self , colId , * indices ) : return self . name + ( colId , ) + self . getInstIdFromIndices ( * indices ) | Build column instance name from components |
43,437 | def getInstNamesByIndex ( self , * indices ) : instNames = [ ] for columnName in self . _vars . keys ( ) : instNames . append ( self . getInstNameByIndex ( * ( columnName [ - 1 ] , ) + indices ) ) return tuple ( instNames ) | Build column instance names from indices |
43,438 | def nextCmd ( snmpEngine , authData , transportTarget , contextData , * varBinds , ** options ) : def cbFun ( snmpEngine , sendRequestHandle , errorIndication , errorStatus , errorIndex , varBindTable , cbCtx ) : cbCtx [ 'errorIndication' ] = errorIndication cbCtx [ 'errorStatus' ] = errorStatus cbCtx [ 'errorIndex' ] = errorIndex cbCtx [ 'varBindTable' ] = varBindTable lexicographicMode = options . get ( 'lexicographicMode' , True ) ignoreNonIncreasingOid = options . get ( 'ignoreNonIncreasingOid' , False ) maxRows = options . get ( 'maxRows' , 0 ) maxCalls = options . get ( 'maxCalls' , 0 ) cbCtx = { } vbProcessor = CommandGeneratorVarBinds ( ) initialVars = [ x [ 0 ] for x in vbProcessor . makeVarBinds ( snmpEngine . cache , varBinds ) ] totalRows = totalCalls = 0 while True : previousVarBinds = varBinds if varBinds : cmdgen . nextCmd ( snmpEngine , authData , transportTarget , contextData , * [ ( x [ 0 ] , Null ( '' ) ) for x in varBinds ] , cbFun = cbFun , cbCtx = cbCtx , lookupMib = options . get ( 'lookupMib' , True ) ) snmpEngine . transportDispatcher . runDispatcher ( ) errorIndication = cbCtx [ 'errorIndication' ] errorStatus = cbCtx [ 'errorStatus' ] errorIndex = cbCtx [ 'errorIndex' ] if ignoreNonIncreasingOid and errorIndication and isinstance ( errorIndication , errind . OidNotIncreasing ) : errorIndication = None if errorIndication : yield ( errorIndication , errorStatus , errorIndex , varBinds ) return elif errorStatus : if errorStatus == 2 : errorStatus = errorStatus . clone ( 0 ) errorIndex = errorIndex . clone ( 0 ) yield ( errorIndication , errorStatus , errorIndex , varBinds ) return else : stopFlag = True varBinds = cbCtx [ 'varBindTable' ] and cbCtx [ 'varBindTable' ] [ 0 ] for col , varBind in enumerate ( varBinds ) : name , val = varBind if isinstance ( val , Null ) : varBinds [ col ] = previousVarBinds [ col ] [ 0 ] , endOfMibView if not lexicographicMode and not initialVars [ col ] . isPrefixOf ( name ) : varBinds [ col ] = previousVarBinds [ col ] [ 0 ] , endOfMibView if stopFlag and varBinds [ col ] [ 1 ] is not endOfMibView : stopFlag = False if stopFlag : return totalRows += 1 totalCalls += 1 else : errorIndication = errorStatus = errorIndex = None varBinds = [ ] initialVarBinds = ( yield errorIndication , errorStatus , errorIndex , varBinds ) if initialVarBinds : varBinds = initialVarBinds initialVars = [ x [ 0 ] for x in vbProcessor . makeVarBinds ( snmpEngine . cache , varBinds ) ] if maxRows and totalRows >= maxRows : return if maxCalls and totalCalls >= maxCalls : return | Creates a generator to perform one or more SNMP GETNEXT queries . |
43,439 | def _storeAccessContext ( snmpEngine ) : execCtx = snmpEngine . observer . getExecutionContext ( 'rfc3412.receiveMessage:request' ) return { 'securityModel' : execCtx [ 'securityModel' ] , 'securityName' : execCtx [ 'securityName' ] , 'securityLevel' : execCtx [ 'securityLevel' ] , 'contextName' : execCtx [ 'contextName' ] , 'pduType' : execCtx [ 'pdu' ] . getTagSet ( ) } | Copy received message metadata while it lasts |
43,440 | def _getManagedObjectsInstances ( self , varBinds , ** context ) : rspVarBinds = context [ 'rspVarBinds' ] varBindsMap = context [ 'varBindsMap' ] rtrVarBinds = [ ] for idx , varBind in enumerate ( varBinds ) : name , val = varBind if ( exval . noSuchObject . isSameTypeWith ( val ) or exval . noSuchInstance . isSameTypeWith ( val ) ) : varBindsMap [ len ( rtrVarBinds ) ] = varBindsMap . pop ( idx , idx ) rtrVarBinds . append ( varBind ) else : rspVarBinds [ varBindsMap . pop ( idx , idx ) ] = varBind if rtrVarBinds : snmpEngine = context [ 'snmpEngine' ] def callLater ( * args ) : snmpEngine . transportDispatcher . unregisterTimerCbFun ( callLater ) mgmtFun = context [ 'mgmtFun' ] mgmtFun ( * varBinds , ** context ) snmpEngine . transportDispatcher . registerTimerCbFun ( callLater , 0.01 ) else : return rspVarBinds | Iterate over Managed Objects fulfilling SNMP query . |
43,441 | def clone ( self , value = univ . noValue , ** kwargs ) : cloned = univ . Choice . clone ( self , ** kwargs ) if value is not univ . noValue : if isinstance ( value , NetworkAddress ) : value = value . getComponent ( ) elif not isinstance ( value , IpAddress ) : value = IpAddress ( value ) try : tagSet = value . tagSet except AttributeError : raise PyAsn1Error ( 'component value %r has no tag set' % ( value , ) ) cloned . setComponentByType ( tagSet , value ) return cloned | Clone this instance . |
43,442 | def _defaultErrorHandler ( varBinds , ** context ) : errors = context . get ( 'errors' ) if errors : err = errors [ - 1 ] raise err [ 'error' ] | Raise exception on any error if user callback is missing |
43,443 | def readMibObjects ( self , * varBinds , ** context ) : if 'cbFun' not in context : context [ 'cbFun' ] = self . _defaultErrorHandler self . flipFlopFsm ( self . FSM_READ_VAR , * varBinds , ** context ) | Read Managed Objects Instances . |
43,444 | def readNextMibObjects ( self , * varBinds , ** context ) : if 'cbFun' not in context : context [ 'cbFun' ] = self . _defaultErrorHandler self . flipFlopFsm ( self . FSM_READ_NEXT_VAR , * varBinds , ** context ) | Read Managed Objects Instances next to the given ones . |
43,445 | def writeMibObjects ( self , * varBinds , ** context ) : if 'cbFun' not in context : context [ 'cbFun' ] = self . _defaultErrorHandler self . flipFlopFsm ( self . FSM_WRITE_VAR , * varBinds , ** context ) | Create destroy or modify Managed Objects Instances . |
43,446 | def bulkCmd ( snmpDispatcher , authData , transportTarget , nonRepeaters , maxRepetitions , * varBinds , ** options ) : def _cbFun ( snmpDispatcher , stateHandle , errorIndication , rspPdu , _cbCtx ) : if not cbFun : return if errorIndication : cbFun ( errorIndication , pMod . Integer ( 0 ) , pMod . Integer ( 0 ) , None , cbCtx = cbCtx , snmpDispatcher = snmpDispatcher , stateHandle = stateHandle ) return errorStatus = pMod . apiBulkPDU . getErrorStatus ( rspPdu ) errorIndex = pMod . apiBulkPDU . getErrorIndex ( rspPdu ) varBindTable = pMod . apiBulkPDU . getVarBindTable ( reqPdu , rspPdu ) errorIndication , nextVarBinds = pMod . apiBulkPDU . getNextVarBinds ( varBindTable [ - 1 ] , errorIndex = errorIndex ) if options . get ( 'lookupMib' ) : varBindTable = [ VB_PROCESSOR . unmakeVarBinds ( snmpDispatcher . cache , vbs ) for vbs in varBindTable ] nextStateHandle = pMod . getNextRequestID ( ) nextVarBinds = cbFun ( errorIndication , errorStatus , errorIndex , varBindTable , cbCtx = cbCtx , snmpDispatcher = snmpDispatcher , stateHandle = stateHandle , nextStateHandle = nextStateHandle , nextVarBinds = nextVarBinds ) if not nextVarBinds : return pMod . apiBulkPDU . setRequestID ( reqPdu , nextStateHandle ) pMod . apiBulkPDU . setVarBinds ( reqPdu , nextVarBinds ) return snmpDispatcher . sendPdu ( authData , transportTarget , reqPdu , cbFun = _cbFun ) if authData . mpModel < 1 : raise error . PySnmpError ( 'GETBULK PDU is only supported in SNMPv2c and SNMPv3' ) lookupMib , cbFun , cbCtx = [ options . get ( x ) for x in ( 'lookupMib' , 'cbFun' , 'cbCtx' ) ] if lookupMib : varBinds = VB_PROCESSOR . makeVarBinds ( snmpDispatcher . cache , varBinds ) pMod = api . PROTOCOL_MODULES [ authData . mpModel ] reqPdu = pMod . GetBulkRequestPDU ( ) pMod . apiBulkPDU . setDefaults ( reqPdu ) pMod . apiBulkPDU . setNonRepeaters ( reqPdu , nonRepeaters ) pMod . apiBulkPDU . setMaxRepetitions ( reqPdu , maxRepetitions ) pMod . apiBulkPDU . setVarBinds ( reqPdu , varBinds ) return snmpDispatcher . sendPdu ( authData , transportTarget , reqPdu , cbFun = _cbFun ) | Initiate SNMP GETBULK query over SNMPv2c . |
43,447 | def save ( self ) : if self . mode in ( "wb+" , 'rb+' ) : if not self . is_open : raise IOError ( "file closed" ) self . write_reference_properties ( ) self . manager . write_objects ( ) | Writes current changes to disk and flushes modified objects in the AAFObjectManager |
43,448 | def close ( self ) : self . save ( ) self . manager . remove_temp ( ) self . cfb . close ( ) self . is_open = False self . f . close ( ) | Close the file . A closed file cannot be read or written any more . |
43,449 | def run_apidoc ( _ ) : import os dirname = os . path . dirname ( __file__ ) ignore_paths = [ os . path . join ( dirname , '../../aaf2/model' ) , ] argv = [ '--force' , '--no-toc' , '--separate' , '--module-first' , '--output-dir' , os . path . join ( dirname , 'api' ) , os . path . join ( dirname , '../../aaf2' ) , ] + ignore_paths from sphinx . ext import apidoc apidoc . main ( argv ) | This method is required by the setup method below . |
43,450 | def from_dict ( self , d ) : self . length = d . get ( "length" , 0 ) self . instanceHigh = d . get ( "instanceHigh" , 0 ) self . instanceMid = d . get ( "instanceMid" , 0 ) self . instanceLow = d . get ( "instanceLow" , 0 ) material = d . get ( "material" , { 'Data1' : 0 , 'Data2' : 0 , 'Data3' : 0 , 'Data4' : [ 0 for i in range ( 8 ) ] } ) self . Data1 = material . get ( 'Data1' , 0 ) self . Data2 = material . get ( 'Data2' , 0 ) self . Data3 = material . get ( 'Data3' , 0 ) self . Data4 = material . get ( "Data4" , [ 0 for i in range ( 8 ) ] ) self . SMPTELabel = d . get ( "SMPTELabel" , [ 0 for i in range ( 12 ) ] ) | Set MobID from a dict |
43,451 | def to_dict ( self ) : material = { 'Data1' : self . Data1 , 'Data2' : self . Data2 , 'Data3' : self . Data3 , 'Data4' : list ( self . Data4 ) } return { 'material' : material , 'length' : self . length , 'instanceHigh' : self . instanceHigh , 'instanceMid' : self . instanceMid , 'instanceLow' : self . instanceLow , 'SMPTELabel' : list ( self . SMPTELabel ) } | MobID representation as dict |
43,452 | def wave_infochunk ( path ) : with open ( path , 'rb' ) as file : if file . read ( 4 ) != b"RIFF" : return None data_size = file . read ( 4 ) if file . read ( 4 ) != b"WAVE" : return None while True : chunkid = file . read ( 4 ) sizebuf = file . read ( 4 ) if len ( sizebuf ) < 4 or len ( chunkid ) < 4 : return None size = struct . unpack ( b'<L' , sizebuf ) [ 0 ] if chunkid [ 0 : 3 ] != b"fmt" : if size % 2 == 1 : seek = size + 1 else : seek = size file . seek ( size , 1 ) else : return bytearray ( b"RIFF" + data_size + b"WAVE" + chunkid + sizebuf + file . read ( size ) ) | Returns a bytearray of the WAVE RIFF header and fmt chunk for a WAVEDescriptor Summary |
43,453 | def pop ( self ) : entry = self parent = self . parent root = parent . child ( ) dir_per_sector = self . storage . sector_size // 128 max_dirs_entries = self . storage . dir_sector_count * dir_per_sector count = 0 if root . dir_id == entry . dir_id : parent . child_id = None else : while True : if count > max_dirs_entries : raise CompoundFileBinaryError ( "max dir entries limit reached" ) if entry < root : if root . left_id == entry . dir_id : root . left_id = None break root = root . left ( ) else : if root . right_id == entry . dir_id : root . right_id = None break root = root . right ( ) count += 1 left = entry . left ( ) right = entry . right ( ) if parent . dir_id in self . storage . children_cache : del self . storage . children_cache [ parent . dir_id ] [ entry . name ] if left : del self . storage . children_cache [ parent . dir_id ] [ left . name ] if right : del self . storage . children_cache [ parent . dir_id ] [ right . name ] if left is not None : parent . add_child ( left ) if right is not None : parent . add_child ( right ) self . left_id = None self . right_id = None self . parent = None | remove self from binary search tree |
43,454 | def remove ( self , path ) : entry = self . find ( path ) if not entry : raise ValueError ( "%s does not exists" % path ) if entry . type == 'root storage' : raise ValueError ( "can no remove root entry" ) if entry . type == "storage" and not entry . child_id is None : raise ValueError ( "storage contains children" ) entry . pop ( ) if entry . type == "stream" : self . free_fat_chain ( entry . sector_id , entry . byte_size < self . min_stream_max_size ) self . free_dir_entry ( entry ) | Removes both streams and storage DirEntry types from file . storage type entries need to be empty dirs . |
43,455 | def rmtree ( self , path ) : for root , storage , streams in self . walk ( path , topdown = False ) : for item in streams : self . free_fat_chain ( item . sector_id , item . byte_size < self . min_stream_max_size ) self . free_dir_entry ( item ) for item in storage : self . free_dir_entry ( item ) root . child_id = None self . remove ( path ) | Removes directory structure similar to shutil . rmtree . |
43,456 | def listdir_dict ( self , path = None ) : if path is None : path = self . root root = self . find ( path ) if root is None : raise ValueError ( "unable to find dir: %s" % str ( path ) ) if not root . isdir ( ) : raise ValueError ( "can only list storage types" ) children = self . children_cache . get ( root . dir_id , None ) if children is not None : return children child = root . child ( ) result = { } if not child : self . children_cache [ root . dir_id ] = result return result dir_per_sector = self . sector_size // 128 max_dirs_entries = self . dir_sector_count * dir_per_sector stack = deque ( [ child ] ) count = 0 while stack : current = stack . pop ( ) result [ current . name ] = current count += 1 if count > max_dirs_entries : raise CompoundFileBinaryError ( "corrupt folder structure" ) left = current . left ( ) if left : stack . append ( left ) right = current . right ( ) if right : stack . append ( right ) self . children_cache [ root . dir_id ] = result return result | Return a dict containing the DirEntry objects in the directory given by path with name of the dir as key . |
43,457 | def makedir ( self , path , class_id = None ) : return self . create_dir_entry ( path , dir_type = 'storage' , class_id = class_id ) | Create a storage DirEntry name path |
43,458 | def makedirs ( self , path ) : root = "" assert path . startswith ( '/' ) p = path . strip ( '/' ) for item in p . split ( '/' ) : root += "/" + item if not self . exists ( root ) : self . makedir ( root ) return self . find ( path ) | Recursive storage DirEntry creation function . |
43,459 | def move ( self , src , dst ) : src_entry = self . find ( src ) if src_entry is None : raise ValueError ( "src path does not exist: %s" % src ) if dst . endswith ( '/' ) : dst += src_entry . name if self . exists ( dst ) : raise ValueError ( "dst path already exist: %s" % dst ) if dst == '/' or src == '/' : raise ValueError ( "cannot overwrite root dir" ) split_path = dst . strip ( '/' ) . split ( '/' ) dst_basename = split_path [ - 1 ] dst_dirname = '/' + '/' . join ( split_path [ : - 1 ] ) dst_entry = self . find ( dst_dirname ) if dst_entry is None : raise ValueError ( "src path does not exist: %s" % dst_dirname ) if not dst_entry . isdir ( ) : raise ValueError ( "dst dirname cannot be stream: %s" % dst_dirname ) src_entry . pop ( ) src_entry . parent = None src_entry . name = dst_basename dst_entry . add_child ( src_entry ) self . children_cache [ dst_entry . dir_id ] [ src_entry . name ] = src_entry return src_entry | Moves DirEntry from src to dst |
43,460 | def open ( self , path , mode = 'r' ) : entry = self . find ( path ) if entry is None : if mode == 'r' : raise ValueError ( "stream does not exists: %s" % path ) entry = self . create_dir_entry ( path , 'stream' , None ) else : if not entry . isfile ( ) : raise ValueError ( "can only open stream type DirEntry's" ) if mode == 'w' : logging . debug ( "stream: %s exists, overwriting" % path ) self . free_fat_chain ( entry . sector_id , entry . byte_size < self . min_stream_max_size ) entry . sector_id = None entry . byte_size = 0 entry . class_id = None elif mode == 'rw' : pass s = Stream ( self , entry , mode ) return s | Open stream returning Stream object |
43,461 | def add2set ( self , pid , key , value ) : prop = self . property_entries [ pid ] current = prop . objects . get ( key , None ) current_local_key = prop . references . get ( key , None ) if current and current is not value : current . detach ( ) if current_local_key is None : prop . references [ key ] = prop . next_free_key prop . next_free_key += 1 prop . objects [ key ] = value if prop . parent . dir : ref = prop . index_ref_name ( key ) dir_entry = prop . parent . dir . get ( ref ) if dir_entry is None : dir_entry = prop . parent . dir . makedir ( ref ) if value . dir != dir_entry : value . attach ( dir_entry ) prop . mark_modified ( ) | low level add to StrongRefSetProperty |
43,462 | def histogram_info ( self ) -> dict : return { 'support_atoms' : self . support_atoms , 'atom_delta' : self . atom_delta , 'vmin' : self . vmin , 'vmax' : self . vmax , 'num_atoms' : self . atoms } | Return extra information about histogram |
43,463 | def sample ( self , histogram_logits ) : histogram_probs = histogram_logits . exp ( ) atoms = self . support_atoms . view ( 1 , 1 , self . atoms ) return ( histogram_probs * atoms ) . sum ( dim = - 1 ) . argmax ( dim = 1 ) | Sample from a greedy strategy with given q - value histogram |
43,464 | def download ( self ) : if not os . path . exists ( self . data_path ) : pathlib . Path ( self . data_path ) . mkdir ( parents = True , exist_ok = True ) if not os . path . exists ( self . text_path ) : http = urllib3 . PoolManager ( cert_reqs = 'CERT_REQUIRED' , ca_certs = certifi . where ( ) ) with open ( self . text_path , 'wt' ) as fp : request = http . request ( 'GET' , self . url ) content = request . data . decode ( 'utf8' ) fp . write ( content ) if not os . path . exists ( self . processed_path ) : with open ( self . text_path , 'rt' ) as fp : content = fp . read ( ) alphabet = sorted ( set ( content ) ) index_to_character = { idx : c for idx , c in enumerate ( alphabet , 1 ) } character_to_index = { c : idx for idx , c in enumerate ( alphabet , 1 ) } content_encoded = np . array ( [ character_to_index [ c ] for c in content ] , dtype = np . uint8 ) data_dict = { 'alphabet' : alphabet , 'index_to_character' : index_to_character , 'character_to_index' : character_to_index , 'content_encoded' : content_encoded } with open ( self . processed_path , 'wb' ) as fp : torch . save ( data_dict , fp ) else : with open ( self . processed_path , 'rb' ) as fp : data_dict = torch . load ( fp ) return data_dict | Make sure data file is downloaded and stored properly |
43,465 | def explained_variance ( returns , values ) : exp_var = 1 - torch . var ( returns - values ) / torch . var ( returns ) return exp_var . item ( ) | Calculate how much variance in returns do the values explain |
43,466 | def create ( model_config , path , num_workers , batch_size , augmentations = None , tta = None ) : if not os . path . isabs ( path ) : path = model_config . project_top_dir ( path ) train_path = os . path . join ( path , 'train' ) valid_path = os . path . join ( path , 'valid' ) train_ds = ImageDirSource ( train_path ) val_ds = ImageDirSource ( valid_path ) return TrainingData ( train_ds , val_ds , num_workers = num_workers , batch_size = batch_size , augmentations = augmentations , ) | Create an ImageDirSource with supplied arguments |
43,467 | def reset_weights ( self ) : self . input_block . reset_weights ( ) self . backbone . reset_weights ( ) self . q_head . reset_weights ( ) | Initialize weights to reasonable defaults |
43,468 | def result ( self ) : return { k : torch . stack ( v ) for k , v in self . accumulants . items ( ) } | Concatenate accumulated tensors |
43,469 | def resolve_parameters ( self , func , extra_env = None ) : parameter_list = [ ( k , v . default == inspect . Parameter . empty ) for k , v in inspect . signature ( func ) . parameters . items ( ) ] extra_env = extra_env if extra_env is not None else { } kwargs = { } for parameter_name , is_required in parameter_list : if parameter_name in extra_env : kwargs [ parameter_name ] = self . instantiate_from_data ( extra_env [ parameter_name ] ) continue if parameter_name in self . instances : kwargs [ parameter_name ] = self . instances [ parameter_name ] continue if parameter_name in self . environment : kwargs [ parameter_name ] = self . instantiate_by_name ( parameter_name ) continue if is_required : funcname = f"{inspect.getmodule(func).__name__}.{func.__name__}" raise RuntimeError ( "Required argument '{}' cannot be resolved for function '{}'" . format ( parameter_name , funcname ) ) return kwargs | Resolve parameter dictionary for the supplied function |
43,470 | def resolve_and_call ( self , func , extra_env = None ) : kwargs = self . resolve_parameters ( func , extra_env = extra_env ) return func ( ** kwargs ) | Resolve function arguments and call them possibily filling from the environment |
43,471 | def instantiate_from_data ( self , object_data ) : if isinstance ( object_data , dict ) and 'name' in object_data : name = object_data [ 'name' ] module = importlib . import_module ( name ) return self . resolve_and_call ( module . create , extra_env = object_data ) if isinstance ( object_data , dict ) and 'factory' in object_data : factory = object_data [ 'factory' ] module = importlib . import_module ( factory ) params = self . resolve_parameters ( module . create , extra_env = object_data ) return GenericFactory ( module . create , params ) elif isinstance ( object_data , dict ) : return { k : self . instantiate_from_data ( v ) for k , v in object_data . items ( ) } elif isinstance ( object_data , list ) : return [ self . instantiate_from_data ( x ) for x in object_data ] elif isinstance ( object_data , Variable ) : return object_data . resolve ( self . parameters ) else : return object_data | Instantiate object from the supplied data additional args may come from the environment |
43,472 | def render_configuration ( self , configuration = None ) : if configuration is None : configuration = self . environment if isinstance ( configuration , dict ) : return { k : self . render_configuration ( v ) for k , v in configuration . items ( ) } elif isinstance ( configuration , list ) : return [ self . render_configuration ( x ) for x in configuration ] elif isinstance ( configuration , Variable ) : return configuration . resolve ( self . parameters ) else : return configuration | Render variables in configuration object but don t instantiate anything |
43,473 | def is_provided ( self , name ) : if name in self . _storage : return True elif name in self . _providers : return True elif name . startswith ( 'rollout:' ) : rollout_name = name [ 8 : ] else : return False | Capability check if evaluator provides given value |
43,474 | def get ( self , name ) : if name in self . _storage : return self . _storage [ name ] elif name in self . _providers : value = self . _storage [ name ] = self . _providers [ name ] ( self ) return value elif name . startswith ( 'rollout:' ) : rollout_name = name [ 8 : ] value = self . _storage [ name ] = self . rollout . batch_tensor ( rollout_name ) return value else : raise RuntimeError ( f"Key {name} is not provided by this evaluator" ) | Return a value from this evaluator . |
43,475 | def create ( model_config , batch_size , normalize = True , num_workers = 0 , augmentations = None ) : path = model_config . data_dir ( 'mnist' ) train_dataset = datasets . MNIST ( path , train = True , download = True ) test_dataset = datasets . MNIST ( path , train = False , download = True ) augmentations = [ ToArray ( ) ] + ( augmentations if augmentations is not None else [ ] ) if normalize : train_data = train_dataset . train_data mean_value = ( train_data . double ( ) / 255 ) . mean ( ) . item ( ) std_value = ( train_data . double ( ) / 255 ) . std ( ) . item ( ) augmentations . append ( Normalize ( mean = mean_value , std = std_value , tags = [ 'train' , 'val' ] ) ) augmentations . append ( ToTensor ( ) ) return TrainingData ( train_dataset , test_dataset , num_workers = num_workers , batch_size = batch_size , augmentations = augmentations ) | Create a MNIST dataset normalized |
43,476 | def reset ( self , configuration : dict ) -> None : self . clean ( 0 ) self . backend . store_config ( configuration ) | Whenever there was anything stored in the database or not purge previous state and start new training process from scratch . |
43,477 | def load ( self , train_info : TrainingInfo ) -> ( dict , dict ) : last_epoch = train_info . start_epoch_idx model_state = torch . load ( self . checkpoint_filename ( last_epoch ) ) hidden_state = torch . load ( self . checkpoint_hidden_filename ( last_epoch ) ) self . checkpoint_strategy . restore ( hidden_state ) train_info . restore ( hidden_state ) return model_state , hidden_state | Resume learning process and return loaded hidden state dictionary |
43,478 | def clean ( self , global_epoch_idx ) : if self . cleaned : return self . cleaned = True self . backend . clean ( global_epoch_idx ) self . _make_sure_dir_exists ( ) for x in os . listdir ( self . model_config . checkpoint_dir ( ) ) : match = re . match ( 'checkpoint_(\\d+)\\.data' , x ) if match : idx = int ( match [ 1 ] ) if idx > global_epoch_idx : os . remove ( os . path . join ( self . model_config . checkpoint_dir ( ) , x ) ) match = re . match ( 'checkpoint_hidden_(\\d+)\\.data' , x ) if match : idx = int ( match [ 1 ] ) if idx > global_epoch_idx : os . remove ( os . path . join ( self . model_config . checkpoint_dir ( ) , x ) ) match = re . match ( 'checkpoint_best_(\\d+)\\.data' , x ) if match : idx = int ( match [ 1 ] ) if idx > global_epoch_idx : os . remove ( os . path . join ( self . model_config . checkpoint_dir ( ) , x ) ) | Clean old checkpoints |
43,479 | def checkpoint ( self , epoch_info : EpochInfo , model : Model ) : self . clean ( epoch_info . global_epoch_idx - 1 ) self . _make_sure_dir_exists ( ) torch . save ( model . state_dict ( ) , self . checkpoint_filename ( epoch_info . global_epoch_idx ) ) hidden_state = epoch_info . state_dict ( ) self . checkpoint_strategy . write_state_dict ( hidden_state ) torch . save ( hidden_state , self . checkpoint_hidden_filename ( epoch_info . global_epoch_idx ) ) if epoch_info . global_epoch_idx > 1 and self . checkpoint_strategy . should_delete_previous_checkpoint ( epoch_info . global_epoch_idx ) : prev_epoch_idx = epoch_info . global_epoch_idx - 1 os . remove ( self . checkpoint_filename ( prev_epoch_idx ) ) os . remove ( self . checkpoint_hidden_filename ( prev_epoch_idx ) ) if self . checkpoint_strategy . should_store_best_checkpoint ( epoch_info . global_epoch_idx , epoch_info . result ) : best_checkpoint_idx = self . checkpoint_strategy . current_best_checkpoint_idx if best_checkpoint_idx is not None : os . remove ( self . checkpoint_best_filename ( best_checkpoint_idx ) ) torch . save ( model . state_dict ( ) , self . checkpoint_best_filename ( epoch_info . global_epoch_idx ) ) self . checkpoint_strategy . store_best_checkpoint_idx ( epoch_info . global_epoch_idx ) self . backend . store ( epoch_info . result ) | When epoch is done we persist the training state |
43,480 | def _persisted_last_epoch ( self ) -> int : epoch_number = 0 self . _make_sure_dir_exists ( ) for x in os . listdir ( self . model_config . checkpoint_dir ( ) ) : match = re . match ( 'checkpoint_(\\d+)\\.data' , x ) if match : idx = int ( match [ 1 ] ) if idx > epoch_number : epoch_number = idx return epoch_number | Return number of last epoch already calculated |
43,481 | def _make_sure_dir_exists ( self ) : filename = self . model_config . checkpoint_dir ( ) pathlib . Path ( filename ) . mkdir ( parents = True , exist_ok = True ) | Make sure directory exists |
43,482 | def clip_gradients ( batch_result , model , max_grad_norm ) : if max_grad_norm is not None : grad_norm = torch . nn . utils . clip_grad_norm_ ( filter ( lambda p : p . requires_grad , model . parameters ( ) ) , max_norm = max_grad_norm ) else : grad_norm = 0.0 batch_result [ 'grad_norm' ] = grad_norm | Clip gradients to a given maximum length |
43,483 | def sample_trajectories ( self , rollout_length , batch_info ) -> Trajectories : indexes = self . backend . sample_batch_trajectories ( rollout_length ) transition_tensors = self . backend . get_trajectories ( indexes , rollout_length ) return Trajectories ( num_steps = rollout_length , num_envs = self . backend . num_envs , environment_information = None , transition_tensors = { k : torch . from_numpy ( v ) for k , v in transition_tensors . items ( ) } , rollout_tensors = { } ) | Sample batch of trajectories and return them |
43,484 | def conjugate_gradient_method ( matrix_vector_operator , loss_gradient , nsteps , rdotr_tol = 1e-10 ) : x = torch . zeros_like ( loss_gradient ) r = loss_gradient . clone ( ) p = loss_gradient . clone ( ) rdotr = torch . dot ( r , r ) for i in range ( nsteps ) : Avp = matrix_vector_operator ( p ) alpha = rdotr / torch . dot ( p , Avp ) x += alpha * p r -= alpha * Avp new_rdotr = torch . dot ( r , r ) betta = new_rdotr / rdotr p = r + betta * p rdotr = new_rdotr if rdotr < rdotr_tol : break return x | Conjugate gradient algorithm |
43,485 | def line_search ( self , model , rollout , original_policy_loss , original_policy_params , original_parameter_vec , full_step , expected_improvement_full ) : current_parameter_vec = original_parameter_vec . clone ( ) for idx in range ( self . line_search_iters ) : stepsize = 0.5 ** idx new_parameter_vec = current_parameter_vec + stepsize * full_step v2p ( new_parameter_vec , model . policy_parameters ( ) ) with torch . no_grad ( ) : policy_params = model . policy ( rollout . batch_tensor ( 'observations' ) ) policy_entropy = torch . mean ( model . entropy ( policy_params ) ) kl_divergence = torch . mean ( model . kl_divergence ( original_policy_params , policy_params ) ) new_loss = self . calc_policy_loss ( model , policy_params , policy_entropy , rollout ) actual_improvement = original_policy_loss - new_loss expected_improvement = expected_improvement_full * stepsize ratio = actual_improvement / expected_improvement if kl_divergence . item ( ) > self . mak_kl * 1.5 : continue elif ratio < expected_improvement : continue else : return True , ratio , actual_improvement , new_loss , kl_divergence v2p ( original_parameter_vec , model . policy_parameters ( ) ) return False , torch . tensor ( 0.0 ) , torch . tensor ( 0.0 ) , torch . tensor ( 0.0 ) , torch . tensor ( 0.0 ) | Find the right stepsize to make sure policy improves |
43,486 | def fisher_vector_product ( self , vector , kl_divergence_gradient , model ) : assert not vector . requires_grad , "Vector must not propagate gradient" dot_product = vector @ kl_divergence_gradient double_gradient = torch . autograd . grad ( dot_product , model . policy_parameters ( ) , retain_graph = True ) fvp = p2v ( x . contiguous ( ) for x in double_gradient ) return fvp + vector * self . cg_damping | Calculate product Hessian |
43,487 | def value_loss ( self , model , observations , discounted_rewards ) : value_outputs = model . value ( observations ) value_loss = 0.5 * F . mse_loss ( value_outputs , discounted_rewards ) return value_loss | Loss of value estimator |
43,488 | def calc_policy_loss ( self , model , policy_params , policy_entropy , rollout ) : actions = rollout . batch_tensor ( 'actions' ) advantages = rollout . batch_tensor ( 'advantages' ) fixed_logprobs = rollout . batch_tensor ( 'action:logprobs' ) model_logprobs = model . logprob ( actions , policy_params ) advantages = ( advantages - advantages . mean ( ) ) / ( advantages . std ( ) + 1e-8 ) policy_loss = - advantages * torch . exp ( model_logprobs - fixed_logprobs ) return policy_loss . mean ( ) - policy_entropy * self . entropy_coef | Policy gradient loss - calculate from probability distribution |
43,489 | def shuffled_batches ( self , batch_size ) : if batch_size >= self . size : yield self else : batch_splits = math_util . divide_ceiling ( self . size , batch_size ) indices = list ( range ( self . size ) ) np . random . shuffle ( indices ) for sub_indices in np . array_split ( indices , batch_splits ) : yield Transitions ( size = len ( sub_indices ) , environment_information = None , transition_tensors = { k : v [ sub_indices ] for k , v in self . transition_tensors . items ( ) } ) | Generate randomized batches of data |
43,490 | def to_transitions ( self ) -> 'Transitions' : return Transitions ( size = self . num_steps * self . num_envs , environment_information = [ ei for l in self . environment_information for ei in l ] if self . environment_information is not None else None , transition_tensors = { name : tensor_util . merge_first_two_dims ( t ) for name , t in self . transition_tensors . items ( ) } , extra_data = self . extra_data ) | Convert given rollout to Transitions |
43,491 | def shuffled_batches ( self , batch_size ) : if batch_size >= self . num_envs * self . num_steps : yield self else : rollouts_in_batch = batch_size // self . num_steps batch_splits = math_util . divide_ceiling ( self . num_envs , rollouts_in_batch ) indices = list ( range ( self . num_envs ) ) np . random . shuffle ( indices ) for sub_indices in np . array_split ( indices , batch_splits ) : yield Trajectories ( num_steps = self . num_steps , num_envs = len ( sub_indices ) , environment_information = None , transition_tensors = { k : x [ : , sub_indices ] for k , x in self . transition_tensors . items ( ) } , rollout_tensors = { k : x [ sub_indices ] for k , x in self . rollout_tensors . items ( ) } , ) | Generate randomized batches of data - only sample whole trajectories |
43,492 | def episode_information ( self ) : return [ info . get ( 'episode' ) for infolist in self . environment_information for info in infolist if 'episode' in info ] | List of information about finished episodes |
43,493 | def forward_state ( self , sequence , state = None ) : if state is None : state = self . zero_state ( sequence . size ( 0 ) ) data = self . input_block ( sequence ) state_outputs = [ ] for idx in range ( len ( self . recurrent_layers ) ) : layer_length = self . recurrent_layers [ idx ] . state_dim current_state = state [ : , : , : layer_length ] state = state [ : , : , layer_length : ] data , new_h = self . recurrent_layers [ idx ] ( data , current_state ) if self . dropout_layers : data = self . dropout_layers [ idx ] ( data ) state_outputs . append ( new_h ) output_data = self . output_activation ( self . output_layer ( data ) ) concatenated_hidden_output = torch . cat ( state_outputs , dim = 2 ) return output_data , concatenated_hidden_output | Forward propagate a sequence through the network accounting for the state |
43,494 | def loss_value ( self , x_data , y_true , y_pred ) : y_pred = y_pred . view ( - 1 , y_pred . size ( 2 ) ) y_true = y_true . view ( - 1 ) . to ( torch . long ) return F . nll_loss ( y_pred , y_true ) | Calculate a value of loss function |
43,495 | def initialize_training ( self , training_info : TrainingInfo , model_state = None , hidden_state = None ) : if model_state is None : self . model . reset_weights ( ) else : self . model . load_state_dict ( model_state ) | Prepare for training |
43,496 | def run_epoch ( self , epoch_info : EpochInfo , source : 'vel.api.Source' ) : epoch_info . on_epoch_begin ( ) lr = epoch_info . optimizer . param_groups [ - 1 ] [ 'lr' ] print ( "|-------- Epoch {:06} Lr={:.6f} ----------|" . format ( epoch_info . global_epoch_idx , lr ) ) self . train_epoch ( epoch_info , source ) epoch_info . result_accumulator . freeze_results ( 'train' ) self . validation_epoch ( epoch_info , source ) epoch_info . result_accumulator . freeze_results ( 'val' ) epoch_info . on_epoch_end ( ) | Run full epoch of learning |
43,497 | def train_epoch ( self , epoch_info , source : 'vel.api.Source' , interactive = True ) : self . train ( ) if interactive : iterator = tqdm . tqdm ( source . train_loader ( ) , desc = "Training" , unit = "iter" , file = sys . stdout ) else : iterator = source . train_loader ( ) for batch_idx , ( data , target ) in enumerate ( iterator ) : batch_info = BatchInfo ( epoch_info , batch_idx ) batch_info . on_batch_begin ( ) self . train_batch ( batch_info , data , target ) batch_info . on_batch_end ( ) iterator . set_postfix ( loss = epoch_info . result_accumulator . intermediate_value ( 'loss' ) ) | Run a single training epoch |
43,498 | def validation_epoch ( self , epoch_info , source : 'vel.api.Source' ) : self . eval ( ) iterator = tqdm . tqdm ( source . val_loader ( ) , desc = "Validation" , unit = "iter" , file = sys . stdout ) with torch . no_grad ( ) : for batch_idx , ( data , target ) in enumerate ( iterator ) : batch_info = BatchInfo ( epoch_info , batch_idx ) batch_info . on_validation_batch_begin ( ) self . feed_batch ( batch_info , data , target ) batch_info . on_validation_batch_end ( ) | Run a single evaluation epoch |
43,499 | def feed_batch ( self , batch_info , data , target ) : data , target = data . to ( self . device ) , target . to ( self . device ) output , loss = self . model . loss ( data , target ) batch_info [ 'data' ] = data batch_info [ 'target' ] = target batch_info [ 'output' ] = output batch_info [ 'loss' ] = loss return loss | Run single batch of data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.